/* toast.jsx — on-brand toast notifications (matches the confirm modal).

   Usage (anywhere):
     toast.success("Event deleted");
     toast.error("Delete failed — " + err.message);
     toast("Saved", { type: "info", duration: 2000 });

   Mount <ToastHost /> once near the app root. */

let _add = null;   // wired up by the mounted ToastHost
let _id = 0;

function toast(message, opts = {}) {
  const t = {
    id: ++_id,
    message,
    type: opts.type || "info",
    duration: opts.duration != null ? opts.duration : 2800,
  };
  if (_add) _add(t);
  return t.id;
}
toast.success = (m, o = {}) => toast(m, { ...o, type: "success" });
toast.error = (m, o = {}) => toast(m, { duration: 4500, ...o, type: "error" });
toast.info = (m, o = {}) => toast(m, { ...o, type: "info" });

function ToastHost() {
  const [items, setItems] = useState([]);

  useEffect(() => {
    _add = (t) => {
      setItems((prev) => [...prev, t]);
      if (t.duration > 0) {
        setTimeout(() => setItems((prev) => prev.filter((x) => x.id !== t.id)), t.duration);
      }
    };
    return () => { _add = null; };
  }, []);

  function dismiss(id) { setItems((prev) => prev.filter((x) => x.id !== id)); }

  if (!items.length) return null;
  return (
    <div className="toast-host">
      {items.map((t) => (
        <div key={t.id} className={cx("toast", t.type)} onClick={() => dismiss(t.id)} role="status">
          <span className="toast-icon">
            {I(t.type === "success" ? "check" : t.type === "error" ? "alert" : "spark", { size: 15 })}
          </span>
          <span className="toast-msg">{t.message}</span>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { toast, ToastHost });
