import './alert.css';
import type { AlertThickness } from '../types';

export type AlertVariant =
  | 'primary'
  | 'secondary'
  | 'success'
  | 'danger'
  | 'warning'
  | 'info'
  | 'light'
  | 'dark'
  /** @deprecated use `danger` */
  | 'error';

export type AlertProps = {
  variant?: AlertVariant;
  message?: string;
  title?: string;
  dismissible?: boolean;
  showIcon?: boolean;
  icon?: string;
  /** Border + padding emphasis (compact vs comfortable). */
  thickness?: AlertThickness;
  onClose?: () => void;
};

function normalizeVariant(v: AlertVariant): Exclude<AlertVariant, 'error'> {
  return v === 'error' ? 'danger' : v;
}

function defaultIcon(variant: Exclude<AlertVariant, 'error'>): string {
  switch (variant) {
    case 'success':
      return '✓';
    case 'warning':
      return '⚠';
    case 'danger':
      return '✕';
    case 'primary':
    case 'secondary':
    case 'light':
    case 'dark':
    case 'info':
    default:
      return 'ℹ';
  }
}

export function Alert({
  variant = 'info',
  message = '',
  title,
  dismissible = false,
  showIcon = true,
  icon,
  thickness = 'normal',
  onClose,
}: AlertProps) {
  const v = normalizeVariant(variant);

  return (
    <div
      className={['ccl-alert', `ccl-alert--${v}`, `ccl-alert--thick-${thickness}`].filter(Boolean).join(' ')}
      role="alert"
    >
      <div className="ccl-alert__content">
        {showIcon ? <span className="ccl-alert__icon">{icon ?? defaultIcon(v)}</span> : null}
        <div className="ccl-alert__text">
          {title ? <h4 className="ccl-alert__title">{title}</h4> : null}
          <span className="ccl-alert__message">{message}</span>
        </div>
      </div>
      {dismissible ? (
        <button type="button" className="ccl-alert__close" aria-label="Close" onClick={() => onClose?.()}>
          <svg className="ccl-alert__close-icon" viewBox="0 0 16 16" aria-hidden focusable="false">
            <path
              d="M2.146 2.146a.5.5 0 0 1 .708 0L8 7.293l5.146-5.147a.5.5 0 0 1 .708.708L8.707 8l5.147 5.146a.5.5 0 0 1-.708.708L8 8.707l-5.146 5.147a.5.5 0 0 1-.708-.708L7.293 8 2.146 2.854a.5.5 0 0 1 0-.708z"
              fill="currentColor"
            />
          </svg>
        </button>
      ) : null}
    </div>
  );
}
