/* === New milestone form — admin only ===
   Numeric milestones carry an explicit target (progress auto-computes with a
   human override); qualitative ones are hand-rated RAG with a required
   rationale when non-green (spec §3). New milestones start green. */

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

function NewMilestoneForm({ onClose }) {
  const [title, setTitle] = React.useState("");
  const [kind, setKind] = React.useState("numeric");
  const [target, setTarget] = React.useState(1);
  const [unit, setUnit] = React.useState("");
  const [secondaryTarget, setSecondaryTarget] = React.useState("");
  const [secondaryLabel, setSecondaryLabel] = React.useState("");
  const [oda, setOda] = React.useState([]);
  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 odaIds = window.ODA.flatMap((o) => [o.id, ...o.deliverables.map((d) => d.id)]);
  const toggle = (id) => setOda(oda.includes(id) ? oda.filter((x) => x !== id) : [...oda, id]);

  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",
  };

  async function create() {
    if (!title.trim()) { setErr("The milestone text is required — use the board language verbatim."); return; }
    setBusy(true); setErr(null);
    const id = nextMilestoneId();
    const isNumeric = kind === "numeric";
    const data = {
      id, glyph: isNumeric ? "⊕" : "◇", kind,
      title: title.trim(),
      oda, rag: "green", rationale: null, workItems: 0, note: null,
      ...(isNumeric ? {
        current: 0, target: Math.max(1, Number(target) || 1), unit: unit.trim() || "count",
        ...(secondaryTarget ? {
          secondaryCurrent: 0, secondaryTarget: Number(secondaryTarget),
          secondaryLabel: secondaryLabel.trim() || "secondary",
        } : {}),
      } : {}),
    };
    try {
      await window.Store.commit({ entityType: "milestone", entityId: id, action: "create", patch: data, note: "created" });
      onClose();
    } catch (e) { setErr(String(e.message || e)); }
    finally { setBusy(false); }
  }

  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 milestone · {nextMilestoneId()}</div>
          <div className="side-panel__title" style={{ fontSize: 19 }}>Create milestone</div>
        </div>

        <div className="side-panel__section">
          <div className="eyebrow" style={{ marginBottom: 4 }}>Milestone text (board language, verbatim)</div>
          <textarea rows={3} style={{ ...input, resize: "vertical", lineHeight: 1.4 }} value={title} autoFocus
                    onChange={(e) => setTitle(e.target.value)}
                    placeholder="e.g. ≥6 states introduce auto-enrollment program legislation; assist ≥3 enacted" />
          <div style={{ marginTop: 12 }}>
            <div className="eyebrow" style={{ marginBottom: 6 }}>Kind</div>
            <div className="row" style={{ gap: 8 }}>
              {[["numeric", "⊕ Numeric — counted target"], ["qualitative", "◇ Qualitative — hand-rated"]].map(([k, label]) => (
                <button key={k} type="button" onClick={() => setKind(k)}
                  className="btn" style={kind === k ? { background: "var(--navy)", color: "white", borderColor: "var(--navy)" } : null}>
                  {label}
                </button>
              ))}
            </div>
          </div>
          {kind === "numeric" ? (
            <div style={{ marginTop: 12 }}>
              <div style={{ display: "grid", gridTemplateColumns: "90px 1fr", gap: 12 }}>
                <div>
                  <div className="eyebrow" style={{ marginBottom: 4 }}>Target</div>
                  <input type="number" min="1" style={{ ...input, fontFamily: "var(--mono)" }} value={target} onChange={(e) => setTarget(e.target.value)} />
                </div>
                <div>
                  <div className="eyebrow" style={{ marginBottom: 4 }}>Unit label</div>
                  <input style={input} value={unit} onChange={(e) => setUnit(e.target.value)} placeholder="e.g. states introduced" />
                </div>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "90px 1fr", gap: 12, marginTop: 10 }}>
                <div>
                  <div className="eyebrow" style={{ marginBottom: 4 }}>2nd target</div>
                  <input type="number" min="1" style={{ ...input, fontFamily: "var(--mono)" }} value={secondaryTarget}
                         onChange={(e) => setSecondaryTarget(e.target.value)} placeholder="—" />
                </div>
                <div>
                  <div className="eyebrow" style={{ marginBottom: 4 }}>2nd label (optional)</div>
                  <input style={input} value={secondaryLabel} onChange={(e) => setSecondaryLabel(e.target.value)} placeholder="e.g. assist enacted" />
                </div>
              </div>
            </div>
          ) : null}
        </div>

        <div className="side-panel__section">
          <div className="eyebrow" style={{ marginBottom: 6 }}>Linked ODA nodes (one or more)</div>
          {odaIds.length ? (
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
              {odaIds.map((id) => (
                <button key={id} type="button" onClick={() => toggle(id)}
                  className={`chip ${oda.includes(id) ? "chip--navy" : "chip--ghost"}`} style={{ cursor: "pointer" }}>
                  {id}
                </button>
              ))}
            </div>
          ) : (
            <div className="muted" style={{ fontSize: 12 }}>No ODA tree loaded — import it in Admin, then link milestones. (Links can be added later by editing.)</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 milestone"}
            </button>
            <button className="btn btn--ghost" onClick={onClose}>Cancel</button>
          </div>
        </div>
      </aside>
    </>
  );
}

Object.assign(window, { NewMilestoneForm });
