/* ============ UI primitives ============ */
const { useState, useEffect, useRef, useCallback, useMemo, createContext, useContext } = React;

/* ---------- Toast ---------- */
const ToastCtx = createContext(null);
function ToastProvider({ children }) {
  const [toasts, setToasts] = useState([]);
  const push = useCallback((msg, kind = "") => {
    const id = Math.random().toString(36).slice(2);
    setToasts(t => [...t, { id, msg, kind }]);
    setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), 2600);
  }, []);
  return (
    <ToastCtx.Provider value={push}>
      {children}
      <div className="toast-wrap">
        {toasts.map(t => <div key={t.id} className={"toast " + (t.kind||"")}>{t.msg}</div>)}
      </div>
    </ToastCtx.Provider>
  );
}
function useToast() { return useContext(ToastCtx); }

/* ---------- Sheet (bottom modal) ---------- */
function Sheet({ open, onClose, title, children }) {
  useEffect(() => {
    if (!open) return;
    const onKey = e => { if (e.key === "Escape") onClose && onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="sheet-backdrop" onClick={onClose}>
      <div className="sheet" onClick={e => e.stopPropagation()}>
        <div className="grip" />
        {title ? <h3>{title}</h3> : null}
        {children}
      </div>
    </div>
  );
}

/* ---------- Confirm dialog (as sheet) ---------- */
function useConfirm() {
  const [state, setState] = useState({ open:false, title:"", body:"", resolve:null, danger:false, okLabel:"OK" });
  const confirm = useCallback((opts) => {
    return new Promise(resolve => {
      setState({ open:true, title: opts.title || "確認", body: opts.body || "", danger: !!opts.danger, okLabel: opts.okLabel || "OK", resolve });
    });
  }, []);
  const node = state.open ? (
    <Sheet open={true} onClose={() => { state.resolve && state.resolve(false); setState(s => ({...s, open:false})); }} title={state.title}>
      <p style={{margin:"4px 2px 16px", color:"var(--ink-2)", fontSize:14}}>{state.body}</p>
      <div className="row-2">
        <button className="btn secondary" onClick={() => { state.resolve && state.resolve(false); setState(s => ({...s, open:false})); }}>キャンセル</button>
        <button className={"btn " + (state.danger ? "danger" : "primary")} onClick={() => { state.resolve && state.resolve(true); setState(s => ({...s, open:false})); }}>{state.okLabel}</button>
      </div>
    </Sheet>
  ) : null;
  return { confirm, node };
}

window.UIP = { ToastProvider, useToast, Sheet, useConfirm };
