import { useEffect } from 'react';
import type { LucideIcon } from 'lucide-react';
import { CheckCircle2, XCircle, Info, X } from 'lucide-react';
import { useToastStore, type ToastKind } from '../store/useToastStore';

const ICONS: Record<ToastKind, LucideIcon> = {
  success: CheckCircle2,
  error: XCircle,
  info: Info,
};

const ACCENT: Record<ToastKind, string> = {
  success: 'text-green',
  error: 'text-red',
  info: 'text-accent',
};

/**
 * Fixed top-right toast stack. Ethos spec: notifications stack top-right.
 * Supports optional action (e.g. "Undo") and auto-dismiss.
 */
export function Toaster() {
  const toasts = useToastStore((s) => s.toasts);
  const dismiss = useToastStore((s) => s.dismiss);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && toasts.length > 0) {
        dismiss(toasts[toasts.length - 1].id);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [toasts, dismiss]);

  if (toasts.length === 0) return null;

  return (
    <div
      className="fixed top-14 right-4 z-50 flex flex-col gap-2 w-[min(20rem,calc(100vw-2rem))]"
      role="region"
      aria-label="Notifications"
      aria-live="polite"
    >
      {toasts.map((t) => {
        const Icon = ICONS[t.kind];
        return (
          <div
            key={t.id}
            className="flex items-start gap-2.5 rounded-md border border-border bg-bg1 p-3 shadow-lg shadow-black/40 animate-rise"
            role="status"
          >
            <Icon size={16} className={`mt-0.5 flex-none ${ACCENT[t.kind]}`} />
            <div className="min-w-0 flex-1 text-sm text-text">{t.message}</div>
            {t.action && (
              <button
                onClick={() => { t.action?.onClick(); dismiss(t.id); }}
                className="flex-none text-xs font-semibold text-accent hover:text-accent-h"
              >
                {t.action.label}
              </button>
            )}
            <button
              onClick={() => dismiss(t.id)}
              aria-label="Dismiss notification"
              className="flex-none rounded p-0.5 text-muted hover:text-text hover:bg-surface0"
            >
              <X size={12} />
            </button>
          </div>
        );
      })}
    </div>
  );
}
