// =============================================================================
// TOAST — global notifications (window.rvlToast)
// =============================================================================

let _id = 0;
let _listeners = [];
let _toasts = [];

function emit() {
  for (const l of _listeners) l(_toasts);
}

window.rvlToast = {
  show(type, msg, ms = 2800) {
    const id = ++_id;
    _toasts = [..._toasts, { id, type, msg }];
    emit();
    setTimeout(() => {
      _toasts = _toasts.filter(t => t.id !== id);
      emit();
    }, ms);
  },
  success(msg, ms) { this.show("success", msg, ms); },
  error(msg, ms)   { this.show("error", msg, ms); },
  info(msg, ms)    { this.show("info", msg, ms); },
};

function ToastHost() {
  const [toasts, setToasts] = useState([]);
  useEffect(() => {
    const l = (next) => setToasts([...next]);
    _listeners.push(l);
    return () => { _listeners = _listeners.filter(x => x !== l); };
  }, []);

  if (!toasts.length) return null;

  const colors = {
    success: "#16a34a",
    error: "#b21e2e",
    info: "#0ea5e9",
  };
  const icons = { success: "✓", error: "⚠", info: "ℹ" };

  return ReactDOM.createPortal(
    <div style={{
      position: "fixed", top: 24, right: 24, zIndex: 10000,
      display: "flex", flexDirection: "column", gap: 8,
      pointerEvents: "none",
    }}>
      {toasts.map(t => (
        <div key={t.id} style={{
          padding: "12px 18px", borderRadius: 10,
          background: colors[t.type] || colors.info,
          color: "#fff", fontWeight: 600, fontSize: 14,
          boxShadow: "0 8px 24px rgba(0,0,0,.18)",
          display: "flex", alignItems: "center", gap: 10,
          animation: "toastIn .2s ease-out",
          pointerEvents: "auto",
        }} role="status" aria-live="polite">
          <span>{icons[t.type] || icons.info}</span>
          <span>{t.msg}</span>
        </div>
      ))}
      <style>{`
        @keyframes toastIn { from { opacity: 0; transform: translateY(-8px); } to { opacity: 1; transform: translateY(0); } }
      `}</style>
    </div>,
    document.body
  );
}

window.ToastHost = ToastHost;
