/* === New work item form — right drawer ===
   Types + terminal states + optional stage pipelines per spec §7/§8.
   Editors and admins can create; the item is owned by its owner field
   (defaults to the signed-in user), which is what scopes editor permissions. */

const WORK_TYPES = {
  "product":             { terminal: "published",       stages: ["development / kickoff / research plan", "drafting", "peer review", "QC (data / fact check)", "content edit", "approvals (SD/GR/Legal)", "copyedit", "review synthesis"] },
  "event":               { terminal: "held",            stages: ["development / kickoff", "approvals (SD/GR/Legal)", "preparation", "post-event reporting"] },
  "convening":           { terminal: "held",            stages: ["development / kickoff", "approvals (SD/GR/Legal)", "preparation", "post-event reporting"] },
  "survey":              { terminal: "fielded/weighted", stages: ["development / research plan", "focus groups / IDIs", "pretesting", "fielding", "validation / weighting"] },
  "TA engagement":       { terminal: "complete",        stages: null },
  "transition/handoff":  { terminal: "committed",       stages: null },
};

function nextWorkId() {
  const nums = window.WORK_ITEMS.map((w) => parseInt((w.id || "").replace(/\D/g, ""), 10)).filter((n) => !isNaN(n));
  return "W-" + String((nums.length ? Math.max(...nums) : 0) + 1).padStart(3, "0");
}

function NewWorkForm({ onClose, onCreated }) {
  const me = window.Store.session();
  const [title, setTitle] = React.useState("");
  const [type, setType] = React.useState("product");
  const [owner, setOwner] = React.useState(me ? me.name : "");
  const [milestones, setMilestones] = React.useState([]);
  const [oda, setOda] = React.useState([]);
  const [state, setState] = React.useState("");
  const [due, setDue] = React.useState("");
  const [firmness, setFirmness] = React.useState("estimated");
  const [status, setStatus] = React.useState("development");
  const [useStages, setUseStages] = React.useState(true);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const spec = WORK_TYPES[type];
  const odaIds = window.ODA.flatMap((o) => [o.id, ...o.deliverables.map((d) => d.id)]);
  const toggle = (list, setList, id) =>
    setList(list.includes(id) ? list.filter((x) => x !== id) : [...list, id]);

  async function create() {
    if (!title.trim()) { setErr("A title is required."); return; }
    setBusy(true); setErr(null);
    const id = nextWorkId();
    const stages = useStages && spec.stages ? spec.stages : null;
    const data = {
      id, title: title.trim(), type,
      milestones, oda,
      state: state.trim() || null,
      owner: owner.trim() || (me ? me.name : "?"),
      status: status.trim() || "development",
      stages: stages,
      stageStatus: stages ? stages.map((_, i) => (i === 0 ? "current" : "todo")) : null,
      stuckSince: null,
      due: due.trim() || "TBD",
      firmness,
      terminal: spec.terminal,
      completedDate: null,
      twoWeekNote: null,
    };
    try {
      await window.Store.commit({ entityType: "work", entityId: id, action: "create", patch: data, note: "created" });
      onCreated && onCreated(id);
      onClose();
    } catch (e) {
      setErr(String(e.message || e));
    } finally {
      setBusy(false);
    }
  }

  const input = {
    width: "100%", padding: "7px 10px", borderRadius: 4, border: "1px solid var(--border)",
    background: "var(--surface-2)", font: "500 13px/1.3 var(--sans)", outline: "none",
  };

  return (
    <>
      <div className="scrim is-open" onClick={onClose}></div>
      <aside className="side-panel is-open">
        <div className="side-panel__head">
          <button className="side-panel__close" onClick={onClose} title="Close">
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M3 3 L11 11 M11 3 L3 11" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" /></svg>
          </button>
          <div className="side-panel__eyebrow">New work item · {nextWorkId()}</div>
          <div className="side-panel__title" style={{ fontSize: 19 }}>Create work item</div>
        </div>

        <div className="side-panel__section">
          <h4>Basics</h4>
          <div className="eyebrow" style={{ marginBottom: 4 }}>Title</div>
          <input style={input} value={title} onChange={(e) => setTitle(e.target.value)} autoFocus
                 placeholder="e.g. OR auto-IRA participation brief" />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 12 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 4 }}>Type</div>
              <select style={input} value={type} onChange={(e) => setType(e.target.value)}>
                {Object.keys(WORK_TYPES).map((t) => <option key={t} value={t}>{t}</option>)}
              </select>
              <div className="mono faint" style={{ fontSize: 10, marginTop: 4 }}>done = "{spec.terminal}"</div>
            </div>
            <div>
              <div className="eyebrow" style={{ marginBottom: 4 }}>Owner</div>
              <input style={input} value={owner} onChange={(e) => setOwner(e.target.value)} />
            </div>
          </div>
          {spec.stages ? (
            <label className="row" style={{ gap: 6, marginTop: 12, fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-2)", cursor: "pointer", userSelect: "none" }}>
              <input type="checkbox" checked={useStages} onChange={(e) => setUseStages(e.target.checked)} />
              Use the standard {type} stage pipeline ({spec.stages.length} stages)
            </label>
          ) : null}
        </div>

        <div className="side-panel__section">
          <h4>Ladders up to</h4>
          <div className="eyebrow" style={{ marginBottom: 6 }}>Milestones</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
            {window.MILESTONES.map((m) => (
              <button key={m.id} type="button" onClick={() => toggle(milestones, setMilestones, m.id)}
                className={`chip ${milestones.includes(m.id) ? "chip--navy" : "chip--ghost"}`}
                title={m.title} style={{ cursor: "pointer" }}>
                {m.id}
              </button>
            ))}
          </div>
          <div className="eyebrow" style={{ margin: "12px 0 6px" }}>ODA nodes</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
            {odaIds.map((id) => (
              <button key={id} type="button" onClick={() => toggle(oda, setOda, id)}
                className={`chip ${oda.includes(id) ? "chip--navy" : "chip--ghost"}`}
                style={{ cursor: "pointer" }}>
                {id}
              </button>
            ))}
          </div>
          <div style={{ marginTop: 12 }}>
            <div className="eyebrow" style={{ marginBottom: 4 }}>Jurisdiction (optional)</div>
            <input style={{ ...input, width: 120, fontFamily: "var(--mono)" }} value={state}
                   onChange={(e) => setState(e.target.value.toUpperCase())} placeholder="e.g. OR" maxLength={2} />
          </div>
        </div>

        <div className="side-panel__section">
          <h4>Dates & status</h4>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 4 }}>Due date</div>
              <input style={{ ...input, fontFamily: "var(--mono)", fontSize: 12 }} value={due}
                     onChange={(e) => setDue(e.target.value)} placeholder="Sep 30, 2026 (or TBD)" />
            </div>
            <div>
              <div className="eyebrow" style={{ marginBottom: 4 }}>Firmness</div>
              <select style={input} value={firmness} onChange={(e) => setFirmness(e.target.value)}>
                <option value="estimated">estimated — soft</option>
                <option value="quoted">quoted — shared externally</option>
                <option value="locked">locked — committed</option>
              </select>
            </div>
          </div>
          <div style={{ marginTop: 12 }}>
            <div className="eyebrow" style={{ marginBottom: 4 }}>Current status</div>
            <input style={input} value={status} onChange={(e) => setStatus(e.target.value)} />
          </div>
        </div>

        <div className="side-panel__section" style={{ borderBottom: 0 }}>
          {err ? (
            <div style={{ marginBottom: 12, padding: "8px 12px", borderRadius: 4, background: "var(--red-bg)", color: "var(--red)", fontSize: 12 }}>{err}</div>
          ) : null}
          <div className="row" style={{ gap: 8 }}>
            <button className="btn btn--primary" disabled={busy || !title.trim()} onClick={create}>
              {busy ? "Creating…" : "Create work item"}
            </button>
            <button className="btn btn--ghost" onClick={onClose}>Cancel</button>
          </div>
        </div>
      </aside>
    </>
  );
}

Object.assign(window, { NewWorkForm });
