# Alert

## Introduction

The Alert component is a feedback component used to communicate important information, success messages, warnings, errors, and more to users. It is based on Joy UI Alert and uses a variety of colors and variants to visually distinguish the importance and nature of a message. It is used to clearly communicate system notifications, form validation results, task completion states, and similar feedback.

```tsx
<Alert
  content="Alert Content"
  variant="solid"
/>
```

| Field          | Description | Default         |
| -------------- | ----------- | --------------- |
| title          | —           | —               |
| content        | —           | "Alert Content" |
| variant        | —           | "solid"         |
| color          | —           | —               |
| size           | —           | —               |
| invertedColors | —           | —               |
| startDecorator | —           | —               |
| actions        | —           | —               |

## Usage

```tsx
import { Alert } from '@ceed/cds';

function MyComponent() {
  return (
    <div>
      {/* Basic alert */}
      <Alert content="이것은 기본 알림입니다." />

      {/* Success message */}
      <Alert
        color="success"
        title="저장 완료"
        content="문서가 성공적으로 저장되었습니다."
        startDecorator={<CheckCircleIcon />}
      />

      {/* Error message */}
      <Alert
        color="danger"
        title="오류 발생"
        content="파일 업로드에 실패했습니다. 다시 시도해주세요."
        startDecorator={<ErrorIcon />}
        actions={<Button size="sm">다시 시도</Button>}
      />
    </div>
  );
}
```

## Examples

### Basic Usage

The most basic Alert usage.

```tsx
<Alert
  content="Alert Content"
  variant="solid"
/>
```

### Colors

You can distinguish message types through various colors.

```tsx
<div
    style={{
      display: "flex",
      flexDirection: "column",
      gap: "5px"
    }}
  >
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        gap: "5px"
      }}
    >
      <Alert {...props} color="primary" variant="plain" />
      <Alert {...props} color="neutral" variant="plain" />
      <Alert {...props} color="danger" variant="plain" />
      <Alert {...props} color="success" variant="plain" />
      <Alert {...props} color="warning" variant="plain" />
    </div>
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        gap: "5px"
      }}
    >
      <Alert {...props} color="primary" variant="soft" />
      <Alert {...props} color="neutral" variant="soft" />
      <Alert {...props} color="danger" variant="soft" />
      <Alert {...props} color="success" variant="soft" />
      <Alert {...props} color="warning" variant="soft" />
    </div>
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        gap: "5px"
      }}
    >
      <Alert {...props} color="primary" variant="solid" />
      <Alert {...props} color="neutral" variant="solid" />
      <Alert {...props} color="danger" variant="solid" />
      <Alert {...props} color="success" variant="solid" />
      <Alert {...props} color="warning" variant="solid" />
    </div>
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        gap: "5px"
      }}
    >
      <Alert {...props} color="primary" variant="outlined" />
      <Alert {...props} color="neutral" variant="outlined" />
      <Alert {...props} color="danger" variant="outlined" />
      <Alert {...props} color="success" variant="outlined" />
      <Alert {...props} color="warning" variant="outlined" />
    </div>
  </div>
```

- **primary**: General informational message
- **success**: Success or completion message
- **warning**: Caution or warning message
- **danger**: Error or risk message
- **neutral**: Neutral message

### With Start Decorator

You can add an icon or another element before the message.

```tsx
<Alert
  content="Alert Content"
  variant="solid"
  startDecorator={<AccountCircle />}
/>
```

### With Title

You can structure the message by adding a title.

```tsx
<Alert
  content="Alert Content"
  variant="solid"
  title="Alert Title"
/>
```

### With Actions

You can add actions the user can take.

```tsx
<Alert
  content="Alert Content"
  variant="solid"
  actions={<Button>Action</Button>}
/>
```

### Complete Alert

A complete Alert containing all elements.

```tsx
<Alert
  content="Alert Content"
  variant="solid"
  startDecorator={<AccountCircle />}
  title="Alert Title"
  actions={<Button>Action</Button>}
/>
```

## Common Use Cases

### Form Validation

Used to display form validation results.

```tsx
function LoginForm() {
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);

  const handleSubmit = async (formData) => {
    try {
      await login(formData);
      setSuccess(true);
      setError('');
    } catch (err) {
      setError(err.message);
      setSuccess(false);
    }
  };

  return (
    <Stack spacing={3}>
      {error && (
        <Alert
          color="danger"
          title="로그인 실패"
          content={error}
          startDecorator={<ErrorIcon />}
          actions={
            <Button size="sm" variant="plain" onClick={() => setError('')}>
              닫기
            </Button>
          }
        />
      )}

      {success && <Alert color="success" content="로그인이 완료되었습니다." startDecorator={<CheckCircleIcon />} />}

      <form onSubmit={handleSubmit}>{/* Form fields */}</form>
    </Stack>
  );
}
```

### System Notifications

Used to display system status or notifications.

```tsx
function SystemStatus() {
  return (
    <Stack spacing={2}>
      <Alert
        color="success"
        title="시스템 정상"
        content="모든 서비스가 정상적으로 작동하고 있습니다."
        startDecorator={<CheckCircleIcon />}
      />

      <Alert
        color="warning"
        title="예정된 점검"
        content="오늘 밤 12시부터 2시까지 시스템 점검이 예정되어 있습니다."
        startDecorator={<WarningIcon />}
        actions={
          <Button size="sm" variant="plain">
            자세히 보기
          </Button>
        }
      />

      <Alert
        color="danger"
        title="서비스 장애"
        content="결제 서비스에 일시적인 장애가 발생했습니다."
        startDecorator={<ErrorIcon />}
        actions={
          <Stack direction="row" spacing={1}>
            <Button size="sm" variant="plain">
              새로고침
            </Button>
            <Button size="sm" variant="solid" color="danger">
              고객센터
            </Button>
          </Stack>
        }
      />
    </Stack>
  );
}
```

### Data Processing Status

Used to display data processing status.

```tsx
function DataProcessingStatus({ status, progress, onCancel, onRetry }) {
  const getAlertProps = () => {
    switch (status) {
      case 'processing':
        return {
          color: 'primary',
          title: '데이터 처리 중',
          content: `진행률: ${progress}%`,
          startDecorator: <CircularProgress size="sm" />,
          actions: (
            <Button size="sm" onClick={onCancel}>
              취소
            </Button>
          ),
        };
      case 'completed':
        return {
          color: 'success',
          title: '처리 완료',
          content: '모든 데이터가 성공적으로 처리되었습니다.',
          startDecorator: <CheckCircleIcon />,
        };
      case 'failed':
        return {
          color: 'danger',
          title: '처리 실패',
          content: '데이터 처리 중 오류가 발생했습니다.',
          startDecorator: <ErrorIcon />,
          actions: (
            <Button size="sm" onClick={onRetry}>
              다시 시도
            </Button>
          ),
        };
      default:
        return null;
    }
  };

  const alertProps = getAlertProps();

  return alertProps ? <Alert {...alertProps} /> : null;
}
```

### Feature Announcements

Used to display new feature announcements or important notices.

```tsx
function FeatureAnnouncement() {
  const [dismissed, setDismissed] = useState(false);

  if (dismissed) return null;

  return (
    <Alert
      color="primary"
      title="🎉 새로운 기능 출시"
      content="이제 문서를 팀원들과 실시간으로 공동 편집할 수 있습니다!"
      startDecorator={<NewReleasesIcon />}
      actions={
        <Stack direction="row" spacing={1}>
          <Button size="sm" variant="soft">
            자세히 보기
          </Button>
          <Button size="sm" variant="plain" onClick={() => setDismissed(true)}>
            닫기
          </Button>
        </Stack>
      }
    />
  );
}
```

### Permission Requests

Used to guide permission requests or settings changes.

```tsx
function PermissionAlert() {
  return (
    <Stack spacing={2}>
      <Alert
        color="warning"
        title="알림 권한 필요"
        content="중요한 업데이트를 놓치지 않으려면 브라우저 알림을 허용해주세요."
        startDecorator={<NotificationsIcon />}
        actions={
          <Stack direction="row" spacing={1}>
            <Button size="sm" variant="solid" color="warning">
              허용
            </Button>
            <Button size="sm" variant="plain">
              나중에
            </Button>
          </Stack>
        }
      />

      <Alert
        color="neutral"
        title="쿠키 사용 안내"
        content="이 웹사이트는 사용자 경험 개선을 위해 쿠키를 사용합니다."
        startDecorator={<InfoIcon />}
        actions={
          <Button size="sm" variant="outlined">
            설정
          </Button>
        }
      />
    </Stack>
  );
}
```

### Inline Messages

Messages displayed inline within form fields or specific sections.

```tsx
function InlineMessages() {
  return (
    <Stack spacing={3}>
      <FormControl>
        <FormLabel>비밀번호</FormLabel>
        <Input type="password" />
        <Alert
          size="sm"
          color="warning"
          content="비밀번호는 최소 8자 이상이어야 합니다."
          startDecorator={<WarningIcon />}
          variant="soft"
        />
      </FormControl>

      <FormControl>
        <FormLabel>이메일 주소</FormLabel>
        <Input type="email" />
        <Alert
          size="sm"
          color="success"
          content="사용 가능한 이메일 주소입니다."
          startDecorator={<CheckIcon />}
          variant="soft"
        />
      </FormControl>
    </Stack>
  );
}
```

### Dismissible Alerts

An implementation example of Alerts that users can dismiss.

```tsx
function DismissibleAlerts() {
  const [alerts, setAlerts] = useState([
    { id: 1, type: 'info', message: '새로운 메시지가 도착했습니다.' },
    { id: 2, type: 'warning', message: '계정 보안을 위해 비밀번호를 변경해주세요.' },
    { id: 3, type: 'success', message: '프로필이 성공적으로 업데이트되었습니다.' },
  ]);

  const dismissAlert = (id) => {
    setAlerts((prev) => prev.filter((alert) => alert.id !== id));
  };

  return (
    <Stack spacing={2}>
      {alerts.map((alert) => (
        <Alert
          key={alert.id}
          color={getAlertColor(alert.type)}
          content={alert.message}
          startDecorator={getAlertIcon(alert.type)}
          actions={
            <IconButton size="sm" variant="plain" onClick={() => dismissAlert(alert.id)}>
              <CloseIcon />
            </IconButton>
          }
        />
      ))}
    </Stack>
  );
}
```

## Props and Customization

### Content Types

Alert supports various forms of content.

```tsx
// Plain text
<Alert content="간단한 메시지" />

// React element
<Alert
  content={
    <div>
      <strong>중요:</strong> 이 작업은 되돌릴 수 없습니다.
      <Link href="/help">도움말 보기</Link>
    </div>
  }
/>

// Separate title and content
<Alert
  title="업데이트 완료"
  content="애플리케이션이 최신 버전으로 업데이트되었습니다."
/>
```

### Variants

Provides various visual styles.

```tsx
<Stack spacing={2}>
  <Alert variant="solid" color="primary" content="Solid 변형" />
  <Alert variant="soft" color="primary" content="Soft 변형" />
  <Alert variant="outlined" color="primary" content="Outlined 변형" />
  <Alert variant="plain" color="primary" content="Plain 변형" />
</Stack>
```

### Sizes

You can adjust the Alert size.

```tsx
<Stack spacing={2}>
  <Alert size="sm" content="Small Alert" />
  <Alert size="md" content="Medium Alert (기본값)" />
  <Alert size="lg" content="Large Alert" />
</Stack>
```

### Custom Styling

You can apply custom styles using the `sx` prop.

```tsx
<Alert
  content="커스텀 스타일 Alert"
  sx={{
    borderRadius: 'xl',
    boxShadow: 'lg',
    '&:hover': {
      transform: 'translateY(-2px)',
      transition: 'transform 0.2s ease',
    },
  }}
/>
```

## Accessibility

The Alert component provides the following accessibility features:

### ARIA Attributes

Appropriate ARIA attributes are applied automatically.

- `role="alert"`: For important messages that should be announced to the user immediately
- `aria-live="polite"`: For less urgent messages

### Keyboard Navigation

Action buttons inside an Alert can be navigated by keyboard.

### Screen Reader Support

The title and content are structured appropriately for screen readers.

```tsx
<Alert
  title="오류 발생"
  content="입력하신 정보를 다시 확인해주세요."
  startDecorator={<ErrorIcon aria-hidden="true" />}
  actions={<Button aria-label="오류 메시지 닫기">닫기</Button>}
/>
```

## Best Practices

1. **Use appropriate colors**: Use colors that match the nature of the message.

```tsx
// ✅ Good example
<Alert color="success" content="저장 완료" />
<Alert color="danger" content="오류 발생" />
<Alert color="warning" content="주의 필요" />

// ❌ Bad example
<Alert color="success" content="오류 발생" /> // Incorrect color
```

2. **Clear messaging**: Write clear messages that are easy for users to understand.

```tsx
// ✅ Clear message
<Alert
  color="danger"
  title="업로드 실패"
  content="파일이 너무 큽니다. 10MB 이하의 파일을 선택해주세요."
/>

// ❌ Vague message
<Alert content="오류가 발생했습니다." />
```

3. **Appropriate actions**: Provide the next step the user can take.

```tsx
<Alert
  color="warning"
  content="세션이 곧 만료됩니다."
  actions={
    <Button size="sm" onClick={extendSession}>
      연장
    </Button>
  }
/>
```

4. **Avoid overuse**: Do not show too many Alerts at the same time.

5. **Auto-dismiss**: Implement temporary messages so they dismiss automatically.

```tsx
function AutoDismissAlert() {
  const [visible, setVisible] = useState(true);

  useEffect(() => {
    const timer = setTimeout(() => {
      setVisible(false);
    }, 5000);

    return () => clearTimeout(timer);
  }, []);

  if (!visible) return null;

  return <Alert color="success" content="저장이 완료되었습니다." startDecorator={<CheckIcon />} />;
}
```

## Performance Considerations

1. **Conditional rendering**: Render Alerts only when needed.

2. **Memoization**: Consider memoizing complex Alert content.

```tsx
const alertContent = useMemo(() => <ComplexAlertContent data={data} />, [data]);

<Alert content={alertContent} />;
```

3. **Batch handling**: Manage multiple Alerts efficiently.

Alert is a core component for communicating with users. With appropriate colors, clear messaging, and useful actions, it can provide an excellent user experience.
