// overlays.jsx — Dialog, DropdownMenu, Popover, Toast, Alert
const { useState: useStateO, useRef: useRefO, useEffect: useEffectO, createContext, useContext } = React;

/* ---------- Dialog ---------- */
function Dialog({ open, onClose, title, desc, children, footer }) {
  useEffectO(() => {
    if (!open) return;
    const h = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", h);
    return () => document.removeEventListener("keydown", h);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="overlay" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
      <div className="dialog" role="dialog" aria-modal="true" style={{ position: "relative" }}>
        <div className="dialog-close"><Button variant="ghost" size="sm" icon="x" onClick={onClose} /></div>
        <div className="dialog-pad">
          <div className="dialog-header">
            {title && <div className="dialog-title">{title}</div>}
            {desc && <div className="dialog-desc">{desc}</div>}
          </div>
          {children}
          {footer && <div className="dialog-footer">{footer}</div>}
        </div>
      </div>
    </div>
  );
}

/* ---------- DropdownMenu ---------- */
function DropdownMenu({ trigger, children, align = "left", width = 200 }) {
  const [open, setOpen] = useStateO(false);
  const ref = useRefO(null);
  useOutside(ref, () => setOpen(false));
  return (
    <div ref={ref} style={{ position: "relative", display: "inline-flex" }}>
      <span onClick={() => setOpen((o) => !o)}>{trigger}</span>
      {open && (
        <div className="menu" style={{ top: "calc(100% + 6px)", [align]: 0, minWidth: width }} onClick={() => setOpen(false)}>
          {children}
        </div>
      )}
    </div>
  );
}
function MenuItem({ icon, shortcut, danger, children, onClick }) {
  return (
    <div className={"menu-item" + (danger ? " danger" : "")} onClick={onClick}>
      {icon && <Icon name={icon} />}<span>{children}</span>{shortcut && <span className="shortcut">{shortcut}</span>}
    </div>
  );
}
function MenuLabel({ children }) { return <div className="menu-label">{children}</div>; }
function MenuSep() { return <div className="menu-sep" />; }

/* ---------- Popover ---------- */
function Popover({ trigger, children, align = "left", width = 260 }) {
  const [open, setOpen] = useStateO(false);
  const ref = useRefO(null);
  useOutside(ref, () => setOpen(false));
  return (
    <div ref={ref} style={{ position: "relative", display: "inline-flex" }}>
      <span onClick={() => setOpen((o) => !o)}>{trigger}</span>
      {open && <div className="popover" style={{ top: "calc(100% + 8px)", [align]: 0, width }}>{children}</div>}
    </div>
  );
}

/* ---------- Alert ---------- */
function Alert({ variant = "brand", title, children }) {
  const icons = { brand: "info", destructive: "alert-triangle", success: "check-circle", info: "info" };
  return (
    <div className={"alert alert-" + variant}>
      <Icon name={icons[variant] || "info"} />
      <div>
        {title && <div className="alert-title">{title}</div>}
        {children && <div className="alert-desc">{children}</div>}
      </div>
    </div>
  );
}

/* ---------- Toast system ---------- */
const ToastCtx = createContext(null);
function ToastProvider({ children }) {
  const [toasts, setToasts] = useStateO([]);
  const push = (t) => {
    const id = Math.random().toString(36).slice(2);
    setToasts((cur) => [...cur, { ...t, id }]);
    setTimeout(() => dismiss(id), t.duration || 3800);
  };
  const dismiss = (id) => {
    setToasts((cur) => cur.map((x) => (x.id === id ? { ...x, out: true } : x)));
    setTimeout(() => setToasts((cur) => cur.filter((x) => x.id !== id)), 240);
  };
  return (
    <ToastCtx.Provider value={push}>
      {children}
      <div className="toast-region">
        {toasts.map((t) => (
          <div key={t.id} className={"toast" + (t.out ? " out" : "")}>
            <Icon name={t.icon || "check-circle"} />
            <div style={{ flex: 1 }}>
              <div className="toast-title">{t.title}</div>
              {t.desc && <div className="toast-desc">{t.desc}</div>}
            </div>
            <Button variant="ghost" size="sm" icon="x" onClick={() => dismiss(t.id)} />
          </div>
        ))}
      </div>
    </ToastCtx.Provider>
  );
}
function useToast() { return useContext(ToastCtx); }

Object.assign(window, { Dialog, DropdownMenu, MenuItem, MenuLabel, MenuSep, Popover, Alert, ToastProvider, useToast });
