// Global toast notification system
// Usage from anywhere: window.__toast('success'|'error'|'warning', 'message')

const ToastSystem = () => {
  const [toasts, setToasts] = React.useState([]);

  const dismiss = React.useCallback((id) => {
    setToasts(t => t.filter(x => x.id !== id));
  }, []);

  React.useEffect(() => {
    window.__toast = (type, message, duration = 4500) => {
      const id = Date.now() + Math.random();
      setToasts(t => [...t, { id, type, message }]);
      if (duration > 0) setTimeout(() => dismiss(id), duration);
    };
    return () => { delete window.__toast; };
  }, [dismiss]);

  if (!toasts.length) return null;

  const iconMap = {
    success: <Icon name="check"  size={14} strokeWidth={2.4} />,
    error:   <Icon name="close"  size={14} strokeWidth={2}   />,
    warning: <span style={{ fontWeight: 800, fontSize: 14, lineHeight: 1 }}>!</span>,
  };

  return (
    <div className="toast-stack" role="region" aria-label="Notifications">
      {toasts.map(t => (
        <div key={t.id} className={`toast toast-${t.type}`} role={t.type === 'error' ? 'alert' : 'status'}>
          <span className="toast-ico" aria-hidden="true">{iconMap[t.type]}</span>
          <span className="toast-msg">{t.message}</span>
          <button className="toast-x" onClick={() => dismiss(t.id)} aria-label="Dismiss">
            <Icon name="close" size={11} />
          </button>
        </div>
      ))}
    </div>
  );
};

window.ToastSystem = ToastSystem;
