// Reusable admin primitives
const { useState: useStateA, useEffect: useEffectA, useMemo: useMemoA, useRef: useRefA } = React;

// Inline-editable text cell. Click to edit, Enter to commit, Esc to cancel.
function EditableCell({ value, onChange, placeholder = "—", multiline = false, format = "text" }) {
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState(value ?? "");
  const ref = React.useRef(null);

  React.useEffect(() => { if (!editing) setDraft(value ?? ""); }, [value, editing]);
  React.useEffect(() => { if (editing && ref.current) { ref.current.focus(); ref.current.select?.(); } }, [editing]);

  const commit = () => {
    setEditing(false);
    if (draft !== (value ?? "")) onChange(draft);
  };
  const cancel = () => { setDraft(value ?? ""); setEditing(false); };

  if (editing) {
    if (multiline) {
      return (
        <textarea ref={ref} value={draft} onChange={e => setDraft(e.target.value)}
          onBlur={commit}
          onKeyDown={e => { if (e.key === "Escape") cancel(); if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) commit(); }}
          style={{ width: "100%", minHeight: 80, padding: "6px 8px", border: "2px solid var(--accent)", background: "var(--paper)", font: "inherit", color: "var(--ink)", resize: "vertical", lineHeight: 1.5 }} />
      );
    }
    return (
      <input ref={ref} type={format === "number" ? "number" : format === "date" ? "date" : "text"}
        value={draft} onChange={e => setDraft(e.target.value)}
        onBlur={commit}
        onKeyDown={e => { if (e.key === "Escape") cancel(); if (e.key === "Enter") commit(); }}
        style={{ width: "100%", padding: "4px 8px", border: "2px solid var(--accent)", background: "var(--paper)", font: "inherit", color: "var(--ink)" }} />
    );
  }

  return (
    <span
      className={"cell-edit" + ((value == null || value === "") ? " muted" : "")}
      tabIndex={0}
      onClick={() => setEditing(true)}
      onKeyDown={e => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); setEditing(true); } }}
      title="点击编辑">
      {(value == null || value === "") ? placeholder : String(value)}
    </span>
  );
}

// Inline-editable select
function EditableSelect({ value, options, onChange }) {
  return (
    <select className="cell-select" value={value || ""} onChange={e => onChange(e.target.value)}>
      {options.map(o => {
        const [v, l] = Array.isArray(o) ? o : [o, o];
        return <option key={v} value={v}>{l}</option>;
      })}
    </select>
  );
}

// Tag editor: comma-separated
function EditableTags({ value, onChange }) {
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState((value || []).join(", "));
  React.useEffect(() => setDraft((value || []).join(", ")), [value]);

  const commit = () => {
    const next = draft.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
    setEditing(false);
    onChange(next);
  };

  if (editing) {
    return (
      <input autoFocus value={draft} onChange={e => setDraft(e.target.value)}
        onBlur={commit}
        onKeyDown={e => { if (e.key === "Enter") commit(); if (e.key === "Escape") setEditing(false); }}
        style={{ width: "100%", padding: "4px 8px", border: "2px solid var(--accent)", background: "var(--paper)", font: "inherit", color: "var(--ink)" }} />
    );
  }
  return (
    <span onClick={() => setEditing(true)} className="cell-edit" tabIndex={0}
      style={{ display: "inline-flex", flexWrap: "wrap", gap: 4, cursor: "text" }}>
      {(value || []).length === 0
        ? <span style={{ color: "var(--muted)", fontStyle: "italic" }}>添加标签…</span>
        : (value || []).map(t => <span key={t} className="chip" style={{ fontSize: 10.5, padding: "1px 8px" }}>{t}</span>)
      }
    </span>
  );
}

// Drawer
function Drawer({ open, onClose, title, subtitle, children, footer, width = 620 }) {
  if (!open) return null;
  return (
    <>
      <div className="admin-drawer-back" onClick={onClose}></div>
      <aside className="admin-drawer" style={{ width }}>
        <div className="admin-drawer-head">
          <div>
            <h3 className="serif" style={{ fontSize: 22, color: "var(--ink)", lineHeight: 1.2 }}>{title}</h3>
            {subtitle && <div className="mono" style={{ fontSize: 10.5, color: "var(--muted)", letterSpacing: ".1em", marginTop: 6 }}>{subtitle}</div>}
          </div>
          <button className="btn btn-ghost btn-sm" onClick={onClose}>关闭 ✕</button>
        </div>
        <div className="admin-drawer-body">{children}</div>
        {footer && <div style={{ padding: "14px 24px", borderTop: "1px solid var(--rule)", background: "var(--paper-2)", display: "flex", gap: 10, justifyContent: "flex-end" }}>{footer}</div>}
      </aside>
    </>
  );
}

// Simple confirm
function useConfirm() {
  return (msg) => window.confirm(msg);
}

Object.assign(window, { EditableCell, EditableSelect, EditableTags, Drawer, useConfirm });
