import { useToast } from '../../context/ToastContext';
import type { ToastLevel } from '../../context/ToastContext';
import './ToastStack.css';

const LEVEL_LABEL: Record<ToastLevel, string> = {
  info: 'INFO',
  success: 'OK',
  warn: 'WARN',
  error: 'ERROR',
};

export default function ToastStack() {
  const { toasts, dismissToast, clearAllToasts } = useToast();

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

  return (
    <div className="toast-stack" role="region" aria-label="Notifications" data-testid="toast-stack">
      {toasts.length > 1 && (
        <button
          type="button"
          className="toast-clear-all"
          onClick={clearAllToasts}
          aria-label="Clear all notifications"
        >
          Clear all
        </button>
      )}
      <ul className="toast-list">
        {toasts.map((toast) => (
          <li key={toast.id} className={`toast-item toast-${toast.level}`} role="status">
            <div className="toast-body">
              <span className="toast-level font-tech">{LEVEL_LABEL[toast.level]}</span>
              <div className="toast-text">
                <span className="toast-message">{toast.message}</span>
                {toast.detail ? <span className="toast-detail">{toast.detail}</span> : null}
              </div>
            </div>
            <button
              type="button"
              className="toast-dismiss"
              onClick={() => dismissToast(toast.id)}
              aria-label="Dismiss notification"
            >
              ×
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}
