/* events.jsx: the real Events module (turn an idea into a delivery plan).
 * A two-step form posts to /club/events; an n8n workflow has Claude write the plan as JSON, which comes back
 * through the shared report routes. This file lists the club's plans, shows progress while one is written,
 * and draws the plan like the Events example in previews.jsx. Members with edit access can tick milestones,
 * mark checks covered, put names against volunteer roles and enter actual amounts; that progress is saved
 * with the plan (POST /club/reports/:id/plan-state). The plan can be downloaded as Word, or planned again
 * with changed answers. An idea chosen in Ideas arrives through window.CCHandoff (set in ideas.jsx).
 * Exposes window.CCEvents; shell.jsx mounts it on the Events page when not in demo mode.
 */
(function () {
  const h = React.createElement;
  const API = window.ClubcraftApi;

  const EMPTY = { idea: null, source_id: "", event_name: "", description: "", event_date: "", venue: "", location: "", active_members: "", attendance: "", budget_limit: "", cause: "", success: "", volunteers: "", constraints: "" };
  const draftKey = (clubId) => "cc_events_form_" + clubId;
  const money = (n) => CCIntl.money(Math.round(Number(n) || 0));
  const COL = ["#0f8a8a", "#7a52c7", "#d2603a", "#2f7d4f", "#b0457a", "#3a6fb0", "#9a6a08", "#5a6b7a"];
  const ini = (n) => n.split(/\s+/).map((w) => w[0]).join("").slice(0, 2).toUpperCase();
  const colOf = (n) => COL[[...n].reduce((a, c) => a + c.charCodeAt(0), 0) % COL.length];

  /* The club's basics come from the Review form (kept in the browser), then from the last Events answers. */
  const loadBasics = (clubId) => {
    let rv = {};
    try { rv = JSON.parse(localStorage.getItem("cc_review_form_" + clubId) || "{}"); } catch (e) { /* none */ }
    const b = {};
    ["location", "active_members"].forEach((k) => { if (rv[k] != null && rv[k] !== "") b[k] = rv[k]; });
    return b;
  };
  const loadDraft = (clubId) => {
    let d = {};
    try { d = JSON.parse(localStorage.getItem(draftKey(clubId)) || "{}"); } catch (e) { /* none */ }
    // The event itself is never carried over; only the club's own facts are.
    return { ...EMPTY, ...loadBasics(clubId), location: d.location || loadBasics(clubId).location || "", volunteers: d.volunteers || "", constraints: d.constraints || "" };
  };

  /* ---------- the form ---------- */
  function Form({ clubId, initial, ideaRuns, onStarted, runNote, canRun }) {
    const handoff = React.useMemo(() => window.CCHandoff && window.CCHandoff.get(), []);
    const [step, setStep] = React.useState(0);
    const [f, setF] = React.useState(() => {
      if (initial) return { ...EMPTY, ...loadDraft(clubId), ...initial, idea: initial.idea || null, source_id: initial.source_id || "", attendance: initial.attendance === "" ? "" : initial.attendance };
      const base = loadDraft(clubId);
      if (handoff) return { ...base, idea: handoff, source_id: handoff.source_id || "", event_name: handoff.name || "", description: handoff.summary || "", attendance: "" };
      return base;
    });
    const [pick, setPick] = React.useState("");
    const [busy, setBusy] = React.useState(false);
    const [err, setErr] = React.useState(null);
    const set = (k, v) => setF((x) => ({ ...x, [k]: v }));
    const bind = (k) => ({ value: f[k], onChange: (e) => set(k, e.target.value) });
    const choose = (val) => {
      setPick(val);
      if (!val) { setF((x) => ({ ...x, idea: null, source_id: "" })); return; }
      const [rid, iid] = val.split(":");
      const run = ideaRuns.find((r) => r.id === rid), i = run && run.ideas.find((k) => k.id === iid);
      if (!i) return;
      setF((x) => ({ ...x, idea: { name: i.name || i.title, summary: i.summary, category: i.category, cost: i.cost, outcome: i.outcome, timing: i.timing, people: i.people, first_step: i.first_step, local: i.local }, source_id: val, event_name: i.name || i.title, description: i.summary }));
    };
    async function go() {
      setBusy(true); setErr(null);
      try {
        try { localStorage.setItem(draftKey(clubId), JSON.stringify({ location: f.location, volunteers: f.volunteers, constraints: f.constraints })); } catch (e) { /* private window */ }
        const idea = f.idea ? { name: f.idea.name, summary: f.idea.summary, category: f.idea.category, cost: f.idea.cost, outcome: f.idea.outcome, timing: f.idea.timing, people: f.idea.people, first_step: f.idea.first_step, local: f.idea.local } : null;
        const r = await API.call("POST", "/club/events", { form: { ...f, idea } }, { club: clubId });
        if (window.CCHandoff) window.CCHandoff.clear();
        onStarted(r.report);
      } catch (e) { setErr(e.message); setBusy(false); }
    }
    return h("section", { className: "cc-card" },
      h("div", { className: "cc-card-h" }, h("h2", null, "Make an event plan"), h("span", { className: "cc-pill quiet" }, "Step " + (step + 1) + " of 2: " + (step ? "Money and people" : "The event"))),
      step === 0 && h("div", null,
        f.idea
          ? h("div", { className: "cc-note trial cc-handoff", role: "status" },
            h("div", null, h("b", null, "Starting from the idea: " + f.idea.name), h("p", null, f.idea.summary), f.idea.cost && h("p", { className: "cc-muted" }, "Idea estimate: costs about " + f.idea.cost + (f.idea.outcome ? ", could bring " + f.idea.outcome : "") + ".")),
            h("button", { className: "cc-btn sm", type: "button", onClick: () => { if (window.CCHandoff) window.CCHandoff.clear(); setPick(""); setF((x) => ({ ...x, idea: null, source_id: "" })); } }, "Plan something else"))
          : ideaRuns.length > 0 && h("label", { className: "cc-field" }, "Start from one of your Ideas (optional)",
            h("select", { value: pick, onChange: (e) => choose(e.target.value) },
              h("option", { value: "" }, "No, I will describe the event"),
              ideaRuns.map((r) => h("optgroup", { key: r.id, label: r.title }, r.ideas.map((i) => h("option", { key: r.id + ":" + i.id, value: r.id + ":" + i.id }, (r.shortlist.includes(i.id) ? "★ " : "") + (i.name || i.title)))))
            )),
        h("label", { className: "cc-field" }, "Event name", h("input", { placeholder: "Include the full club name, for example Rotary Club of Example Bay Trivia Night", ...bind("event_name") })),
        h("label", { className: "cc-field" }, "What is the event?", h("textarea", { rows: 3, placeholder: "A line or two: what happens, who comes, and what it is for", ...bind("description") })),
        h("div", { className: "cc-grid2" },
          h("label", { className: "cc-field" }, "Date (if you have one)", h("input", { type: "date", ...bind("event_date") })),
          h("label", { className: "cc-field" }, "Expected guests", h("input", { type: "number", min: "0", ...bind("attendance") }))),
        h("label", { className: "cc-field" }, "Venue (if you have one)", h("input", { placeholder: "For example: Example Bay Community Hall", ...bind("venue") })),
        h("label", { className: "cc-field" }, "Where is your club based?", h("input", { placeholder: "Suburb or town, state", ...bind("location") }))),
      step === 1 && h("div", null,
        h("div", { className: "cc-grid2" },
          h("label", { className: "cc-field" }, "Money the club can spend up front", h("input", { placeholder: "For example: up to $2,000", ...bind("budget_limit") })),
          h("label", { className: "cc-field" }, "Active members", h("input", { type: "number", min: "0", ...bind("active_members") }))),
        h("label", { className: "cc-field" }, "The cause or project it supports", h("input", { placeholder: "For example: the local reading program", ...bind("cause") })),
        h("label", { className: "cc-field" }, "What would success look like?", h("textarea", { rows: 2, placeholder: "For example: $3,000 raised, and three guests who ask about joining", ...bind("success") })),
        h("label", { className: "cc-field" }, "Volunteers you can count on", h("textarea", { rows: 2, placeholder: "For example: about 12 members, plus the Rotaract club", ...bind("volunteers") })),
        h("label", { className: "cc-field" }, "Anything that limits you", h("textarea", { rows: 2, placeholder: "For example: no weekend availability, hall is booked until March", ...bind("constraints") })),
        h("div", { className: "cc-note trial" }, runNote)),
      err && h("div", { className: "cc-err", role: "alert" }, err),
      h("div", { className: "cc-row between" },
        h("button", { className: "cc-btn ghost", disabled: step === 0 || busy, onClick: () => setStep(0) }, "Back"),
        step === 0
          ? h("button", { className: "cc-btn primary", disabled: !f.event_name.trim() || !f.location.trim(), onClick: () => setStep(1) }, "Next")
          : h("button", { className: "cc-btn primary lg", disabled: busy || !canRun, onClick: go }, busy ? "Starting…" : "Make my plan")));
  }

  /* ---------- the plan ---------- */
  const Panel = ({ title, aside, children }) => h("section", { className: "cc-ex-panel" }, (title || aside) && h("div", { className: "cc-ex-ph" }, title && h("h3", null, title), aside), children);
  const Stat = ({ label, value, note, tone }) => h("div", { className: "cc-ex-stat " + (tone || "") }, h("span", null, label), h("b", null, value), note && h("small", null, note));
  const Av = ({ name }) => h("span", { className: "cc-ex-av", style: { background: colOf(name), width: 26, height: 26, fontSize: 11 }, title: name }, ini(name));

  function RoleRow({ role, names, canEdit, onAdd, onRemove }) {
    const [v, setV] = React.useState("");
    const add = () => { const n = v.trim(); if (n) { onAdd(n); setV(""); } };
    return h("div", { className: "cc-ev-role" },
      h("div", null, h("b", null, role.role), h("span", { className: "cc-muted sm" }, names.length + " of " + role.need), role.duties && h("div", { className: "cc-muted sm" }, role.duties)),
      h("div", { className: "cc-ev-who" },
        h("div", { className: "faces" }, names.map((n) => h("span", { key: n, className: "cc-ev-chip" }, h(Av, { name: n }), n, canEdit && h("button", { type: "button", "aria-label": "Remove " + n, onClick: () => onRemove(n) }, "×"))),
          Array.from({ length: Math.max(0, role.need - names.length) }).map((_, i) => h("span", { key: i, className: "cc-ex-open", title: "Still needed" }, "+"))),
        canEdit && h("span", { className: "cc-ev-add" },
          h("input", { value: v, placeholder: "Add a name", "aria-label": "Add a volunteer to " + role.role, maxLength: 40, onChange: (e) => setV(e.target.value), onKeyDown: (e) => { if (e.key === "Enter") { e.preventDefault(); add(); } } }),
          h("button", { className: "cc-btn sm", type: "button", disabled: !v.trim(), onClick: add }, "Add"))));
  }

  async function downloadWord(plan, state, club, title) {
    await window.CCReviewDocx.load();
    const brand = getComputedStyle(document.documentElement).getPropertyValue("--b-primary").trim().replace("#", "");
    const date = new Date().toLocaleDateString(CCIntl.locale(), { day: "numeric", month: "long", year: "numeric" });
    const doc = window.CCEventsDocx.build(window.docx, plan, state, { club, title, date, brandHex: /^[0-9a-fA-F]{6}$/.test(brand) ? brand : undefined });
    const blob = await window.docx.Packer.toBlob(doc);
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = ("Event plan - " + ((plan.event && plan.event.name) || club || "club") + " - " + new Date().toISOString().slice(0, 10) + ".docx").replace(/[\/:*?"<>|]/g, "");
    document.body.appendChild(a); a.click(); a.remove();
    setTimeout(() => URL.revokeObjectURL(a.href), 10000);
  }

  function Result({ clubId, club, id, canEdit, canTasks, canComms, canCalendar, onBack, onRerun, onChanged, onGo }) {
    const [r, setR] = React.useState(null);
    const [state, setState] = React.useState({ done: [], checks: [], roles: {}, actual: {} });
    const [saveNote, setSaveNote] = React.useState("");
    const [err, setErr] = React.useState(null);
    const [wordBusy, setWordBusy] = React.useState(false);
    const [sent, setSent] = React.useState(null);        // the Tasks project made from this plan
    const [sendBusy, setSendBusy] = React.useState(false);
    const [onCal, setOnCal] = React.useState(null);       // what was put on the calendar from this plan
    const [calBusy, setCalBusy] = React.useState(false);
    const timer = React.useRef(null);
    React.useEffect(() => {
      let stop = false, t, wasRunning = false;
      const load = () => API.call("GET", "/club/reports/" + id, null, { club: clubId }).then((x) => {
        if (stop) return; setR(x.report);
        if (x.report.state) setState({ done: [], checks: [], roles: {}, actual: {}, ...x.report.state });
        if (x.report.status === "running") { wasRunning = true; t = setTimeout(load, 6000); }
        else if (wasRunning && onChanged) onChanged();   // finished or failed (refunded): refresh the allowance
      }).catch((e) => !stop && setErr(e.message));
      load();
      return () => { stop = true; clearTimeout(t); clearTimeout(timer.current); };
    }, [id, clubId]);

    // Any change is saved a moment later, as one whole record of progress (last save wins).
    const change = (fn) => {
      if (!canEdit) return;
      setState((s) => {
        const next = fn(s);
        clearTimeout(timer.current);
        setSaveNote("Saving…");
        timer.current = setTimeout(() => {
          API.call("POST", "/club/reports/" + id + "/plan-state", next, { club: clubId })
            .then(() => setSaveNote("Saved"))
            .catch((e) => { setSaveNote(""); setErr(e.message); });
        }, 700);
        return next;
      });
    };
    const toggle = (key, val) => change((s) => ({ ...s, [key]: s[key].includes(val) ? s[key].filter((k) => k !== val) : s[key].concat(val) }));
    const addName = (rid, n) => change((s) => ({ ...s, roles: { ...s.roles, [rid]: (s.roles[rid] || []).includes(n) ? (s.roles[rid] || []) : (s.roles[rid] || []).concat(n) } }));
    const delName = (rid, n) => change((s) => ({ ...s, roles: { ...s.roles, [rid]: (s.roles[rid] || []).filter((k) => k !== n) } }));
    const setActual = (lid, v) => change((s) => { const a = { ...s.actual }; if (v === "") delete a[lid]; else a[lid] = v; return { ...s, actual: a }; });

    const plan = r && r.plan;
    // Saves any pending tick first, so finished steps arrive in Tasks as complete.
    const sendToTasks = async () => {
      setSendBusy(true); setErr(null);
      try {
        if (canEdit) { clearTimeout(timer.current); await API.call("POST", "/club/reports/" + id + "/plan-state", state, { club: clubId }); }
        setSent(await API.call("POST", "/club/reports/" + id + "/send-to-tasks", {}, { club: clubId }));
      } catch (e) { setErr(e.message); }
      setSendBusy(false);
    };
    const sendToCalendar = async () => {
      setCalBusy(true); setErr(null);
      try { setOnCal(await API.call("POST", "/club/reports/" + id + "/send-to-calendar", {}, { club: clubId })); } catch (e) { setErr(e.message); }
      setCalBusy(false);
    };
    const word = () => { setWordBusy(true); setErr(null); downloadWord(plan, state, club, r.title).catch((e) => setErr(e.message)).finally(() => setWordBusy(false)); };
    let body = null;
    if (plan) {
      const inc = plan.budget.income, exp = plan.budget.expenses;
      const anyActual = Object.keys(state.actual).length > 0;
      const sum = (lines, useActual) => lines.reduce((a, l) => a + (useActual && state.actual[l.id] != null && state.actual[l.id] !== "" ? Number(state.actual[l.id]) : l.amount), 0);
      const ti = sum(inc, false), te = sum(exp, false), tai = sum(inc, true), tae = sum(exp, true);
      const need = plan.roles.reduce((a, x) => a + x.need, 0);
      const have = plan.roles.reduce((a, x) => a + Math.min(x.need, (state.roles[x.id] || []).length), 0);
      const doneN = plan.milestones.filter((m) => state.done.includes(m.id)).length;
      const line = (l) => h("tr", { key: l.id }, h("td", null, l.item, l.note && h("div", { className: "cc-muted sm" }, l.note)), h("td", { className: "n" }, money(l.amount)),
        h("td", { className: "n" }, canEdit
          ? h("input", { className: "cc-ev-amt", type: "number", min: "0", step: "1", "aria-label": "Actual amount for " + l.item, value: state.actual[l.id] == null ? "" : state.actual[l.id], onChange: (e) => setActual(l.id, e.target.value) })
          : state.actual[l.id] != null ? money(state.actual[l.id]) : ""));
      body = h("div", { className: "cc-ex" },
        h("div", { className: "cc-ex-head" }, h("div", null, h("h2", null, plan.event.name || r.title), h("p", null, [plan.event.when, plan.event.venue, plan.event.guests].filter(Boolean).join(", "))),
          h("div", { className: "cc-ex-actions" },
            saveNote && h("span", { className: "cc-muted sm", role: "status" }, saveNote),
            h("button", { className: "cc-btn sm", disabled: wordBusy, onClick: word }, wordBusy ? "Preparing…" : "Download Word"),
            h("button", { className: "cc-btn sm ghost", onClick: () => window.print() }, "Print"),
            canEdit && canTasks && h("button", { className: "cc-btn sm primary", disabled: sendBusy, title: "Make a Tasks project from this timeline", onClick: sendToTasks }, sendBusy ? "Sending…" : "Send to Tasks"),
            canEdit && canCalendar && window.CCCalendar && h("button", { className: "cc-btn sm", disabled: calBusy, title: "Put the event and the dated steps on the club calendar", onClick: sendToCalendar }, calBusy ? "Adding…" : "Add to Calendar"),
            canComms && window.CCCommsHandoff && h("button", { className: "cc-btn sm", title: "Write a marketing plan for this event in Comms", onClick: () => { window.CCCommsHandoff.set({ report_id: id, at: Date.now() }); onGo && onGo("mod:Comms"); } }, "Build the marketing plan"),
            canEdit && r.form && h("button", { className: "cc-btn sm ghost", title: "Change your answers and get a new plan (uses another run)", onClick: () => onRerun(r.form) }, "Plan again with changes"))),
        sent && h("div", { className: "cc-note trial", role: "status" }, sent.existing ? "This plan is already in Tasks as " : "Sent to Tasks as ", h("b", null, sent.name), sent.existing ? "." : " (" + sent.tasks + " tasks" + (sent.dated ? ", " + sent.dated + " with due dates" : ", no due dates because the plan has no event date") + "). ", h("button", { className: "cc-link", onClick: () => onGo && onGo("tasks") }, "Open Tasks")),
        onCal && h("div", { className: "cc-note trial", role: "status" }, "Put " + onCal.added + " dates on the calendar" + (onCal.replaced ? " (replacing the earlier " + onCal.replaced + ")" : "") + (onCal.undated ? ". " + onCal.undated + " steps have no fixed timing, so they are left off" : "") + ". ", h("button", { className: "cc-link", onClick: () => onGo && onGo("mod:Calendar") }, "Open Calendar")),
        plan.summary && h("div", { className: "cc-ex-note" }, plan.summary),
        h("div", { className: "cc-ex-stats" },
          h(Stat, { label: "Expected income", value: money(ti) }),
          h(Stat, { label: "Expected costs", value: money(te) }),
          h(Stat, { label: "Expected profit", value: money(ti - te), tone: ti - te >= 0 ? "good" : "warn", note: ti > 0 ? Math.round(100 * (ti - te) / ti) + "% of income" : "" }),
          h(Stat, { label: "Volunteers", value: have + " of " + need, tone: have >= need ? "good" : "warn", note: have >= need ? "All roles filled" : (need - have) + " places still open" }),
          h(Stat, { label: "Timeline", value: doneN + " of " + plan.milestones.length, note: "steps done" })),
        h(Panel, { title: "Purpose and success" }, h("div", { className: "cc-ex-purpose" },
          h("div", null, h("span", null, "The cause"), h("b", null, plan.purpose.cause || "Not stated")),
          h("div", null, h("span", null, "Budget limit"), h("b", null, plan.purpose.budget_limit || "Not stated")),
          h("div", null, h("span", null, "Success looks like"), h("b", null, plan.purpose.success || "Not stated")))),
        h("div", { className: "cc-ex-cols" },
          h(Panel, { title: "Timeline", aside: canEdit && h("small", { className: "cc-muted" }, "Tick a step when it is done") },
            h("ol", { className: "cc-ex-time" }, plan.milestones.map((m) => {
              const d = state.done.includes(m.id);
              return h("li", { key: m.id, className: d ? "done" : "" },
                canEdit ? h("button", { type: "button", className: "dot cc-ev-dot", "aria-pressed": d, "aria-label": (d ? "Mark not done: " : "Mark done: ") + m.task, onClick: () => toggle("done", m.id) }, d ? "✓" : "")
                  : h("span", { className: "dot", "aria-hidden": "true" }, d ? "✓" : ""),
                h("div", null, h("b", null, m.when), h("span", null, m.task), m.role && h("span", { className: "cc-muted sm" }, " (" + m.role + ")")));
            }))),
          h(Panel, { title: "Budget", aside: h("small", { className: "cc-muted" }, canEdit ? "Enter actual amounts as they come in" : "Planned and actual") },
            h("table", { className: "cc-ex-table" },
              h("thead", null, h("tr", null, h("th", null, "Item"), h("th", { className: "n" }, "Planned"), h("th", { className: "n" }, "Actual"))),
              h("tbody", null,
                h("tr", { className: "sec" }, h("td", { colSpan: 3 }, "Money in")), inc.map(line),
                h("tr", { className: "sec" }, h("td", { colSpan: 3 }, "Money out")), exp.map(line),
                h("tr", { className: "tot" }, h("td", null, "Profit"), h("td", { className: "n" }, money(ti - te)), h("td", { className: "n" }, anyActual ? money(tai - tae) : "")))),
            plan.budget.note && h("p", { className: "cc-muted sm" }, plan.budget.note))),
        h(Panel, { title: "Volunteer roles", aside: canEdit && h("small", { className: "cc-muted" }, "Put names against each role") },
          h("div", { className: "cc-ex-roles" }, plan.roles.map((x) => h(RoleRow, { key: x.id, role: x, names: state.roles[x.id] || [], canEdit, onAdd: (n) => addName(x.id, n), onRemove: (n) => delName(x.id, n) })))),
        h("div", { className: "cc-ex-cols" },
          plan.checks.length > 0 && h(Panel, { title: "Check before you commit", aside: canEdit && h("small", { className: "cc-muted" }, "Mark each when you have confirmed it") },
            h("ul", { className: "cc-ex-check" }, plan.checks.map((c) => {
              const ok = c.status === "covered" || state.checks.includes(c.id);
              return h("li", { key: c.id },
                canEdit && c.status !== "covered"
                  ? h("button", { type: "button", className: "cc-rag " + (ok ? "g" : "a") + " cc-ev-rag", "aria-pressed": ok, onClick: () => toggle("checks", c.id) }, h("i", { "aria-hidden": "true" }, ok ? "✓" : "!"), ok ? "Covered" : "To check")
                  : h("span", { className: "cc-rag " + (ok ? "g" : "a") }, h("i", { "aria-hidden": "true" }, ok ? "✓" : "!"), ok ? "Covered" : "To check"),
                h("div", null, h("b", null, c.title), h("span", null, c.detail)));
            }))),
          plan.risks.length > 0 && h(Panel, { title: "If things go wrong" },
            h("table", { className: "cc-ex-table" }, h("tbody", null, plan.risks.map((x, n) => h("tr", { key: n }, h("td", null, h("b", null, x.risk), h("div", { className: "cc-muted sm" }, x.response))))))),),
        plan.promotion.length > 0 && h(Panel, { title: "Promotion" },
          h("table", { className: "cc-ex-table" }, h("tbody", null, plan.promotion.map((p, n) => h("tr", { key: n }, h("td", { className: "when" }, p.when), h("td", null, p.channel), h("td", null, p.message)))))),
        plan.logistics.length > 0 && h(Panel, { title: "Logistics" },
          h("table", { className: "cc-ex-table" }, h("tbody", null, plan.logistics.map((l, n) => h("tr", { key: n }, h("td", null, h("b", null, l.item)), h("td", null, l.detail)))))),
        plan.after.length > 0 && h(Panel, { title: "After the event" }, h("ul", { className: "cc-ex-after" }, plan.after.map((a, n) => h("li", { key: n }, a)))),
        plan.next_step && h("p", { className: "cc-muted" }, plan.next_step),
        h("p", { className: "cc-ex-foot" }, "Prepared by Clubcraft Events. This plan is written by AI from your answers. Costs and timing are estimates. Please check them, and any local rules, with your club leadership before you commit."));
    }
    return h("div", null,
      h("button", { className: "cc-link", onClick: onBack }, "← All plans"),
      err && h("div", { className: "cc-err", role: "alert" }, err),
      !r && !err && h("p", { className: "cc-muted" }, "Loading…"),
      r && r.status === "running" && h("section", { className: "cc-card" }, h("div", { className: "cc-card-h" }, h("h2", null, r.title)),
        h("p", null, "Your plan is being written. This usually takes a minute or two. You can leave this page; it will be in your list when ready."),
        h("div", { className: "cc-bar", role: "progressbar", "aria-label": "Working" }, h("span", { style: { width: "60%" } }))),
      r && r.status === "failed" && h("section", { className: "cc-card" }, h("div", { className: "cc-card-h" }, h("h2", null, r.title)),
        h("div", { className: "cc-err", role: "alert" }, r.error || "The plan could not be completed. Your credits were returned.")),
      r && r.status === "done" && !plan && h("section", { className: "cc-card" }, h("div", { className: "cc-err", role: "alert" }, "This plan could not be read. Please make it again.")),
      body);
  }

  /* ---------- the Events page ---------- */
  function EventsApp({ clubId, clubInfo, onGo, onChanged }) {
    const access = clubInfo.me.access.Events;
    const a = (clubInfo.allowances || {}).Events || {};
    const [list, setList] = React.useState(null);
    const [ideaRuns, setIdeaRuns] = React.useState([]);
    const [view, setView] = React.useState(null);           // null = list, "new", or a report id
    const [initial, setInitial] = React.useState(null);     // answers to start the form from ("plan again with changes")
    const [err, setErr] = React.useState(null);
    const load = React.useCallback(() => API.call("GET", "/club/reports?module=Events", null, { club: clubId }).then((r) => setList(r.reports)).catch((e) => setErr(e.message)), [clubId]);
    React.useEffect(() => {
      setList(null); setIdeaRuns([]);
      // An idea waiting from the Ideas page opens the form straight away.
      setView(window.CCHandoff && window.CCHandoff.get() && access === "edit" ? "new" : null);
      if (!access) return;
      load();
      // Finished Ideas runs, so a plan can start from any of their ideas. Not everyone can read Ideas, so ignore a refusal.
      API.call("GET", "/club/reports?module=Ideas", null, { club: clubId }).then(async (r) => {
        const done = (r.reports || []).filter((x) => x.status === "done").slice(0, 3);
        const runs = await Promise.all(done.map((x) => API.call("GET", "/club/reports/" + x.id, null, { club: clubId }).then((y) => (y.report.ideas ? { id: x.id, title: x.title, ideas: y.report.ideas.ideas, shortlist: y.report.shortlist || [] } : null)).catch(() => null)));
        setIdeaRuns(runs.filter(Boolean));
      }).catch(() => {});
    }, [clubId]);
    if (!access) return h("div", { className: "cc-note" }, "Ask a club admin for access to Events.");
    const running = (list || []).some((r) => r.status === "running");
    const canRun = access === "edit" && !running && (a.state === "credits" || a.state === "available");
    const runNote = a.state === "credits" ? "This uses 1 of your " + a.runsLeft + " AI runs available this month (AI credits)."
      : a.state === "available" ? "This is your trial plan in Events. A plan removes the limit." : "";
    let why = "";
    if (access !== "edit") why = "You can read your club's plans. Edit access to Events is needed to make new ones.";
    else if (a.state === "nocredits") why = "You have used this month's AI credits. They renew each month, or a club admin can buy a top-up (My club, AI allowance).";
    else if (a.state === "used") why = "Your trial plan in Events has been used. Choose a plan to make more.";
    else if (a.state === "ended") why = "Your trial has ended. Choose a plan to make new event plans.";
    const rerun = (form) => { setInitial(form); setView("new"); };
    if (view && view !== "new") return h(Result, { clubId, club: clubInfo.club.name, id: view, canEdit: access === "edit", canTasks: clubInfo.me.access.Tasks === "edit", canComms: clubInfo.me.access.Comms === "edit", canCalendar: clubInfo.me.access.Calendar === "edit", onGo, onRerun: rerun, onChanged, onBack: () => { setView(null); load(); } });
    if (view === "new") return h("div", null, h("button", { className: "cc-link", onClick: () => { setInitial(null); setView(null); } }, "← All plans"),
      h(Form, { clubId, initial, ideaRuns, canRun, runNote, onStarted: (r) => { setInitial(null); setView(r.id); onChanged && onChanged(); } }));
    return h("div", null,
      err && h("div", { className: "cc-err", role: "alert" }, err),
      h("section", { className: "cc-card" },
        h("div", { className: "cc-card-h" }, h("h2", null, "Your event plans"),
          access === "edit" && h("button", { className: "cc-btn primary", disabled: !canRun, onClick: () => { setInitial(null); setView("new"); } }, running ? "A plan is being written" : "Make an event plan")),
        why && h("div", { className: "cc-note warn" }, why),
        !list && !err && h("p", { className: "cc-muted" }, "Loading…"),
        list && !list.length && h("p", { className: "cc-muted" }, "No plans yet. Choose an idea from Ideas, or describe an event, and Events writes a plan with a timeline, budget, volunteer roles, checks and follow-up."),
        list && list.length > 0 && h("ul", { className: "cc-rv-list" }, list.map((r) =>
          h("li", { key: r.id }, h("button", { className: "cc-link", onClick: () => setView(r.id) }, r.title),
            h("span", { className: "cc-pill " + (r.status === "done" ? "ok" : r.status === "failed" ? "bad" : "trial") }, r.status === "done" ? "Ready" : r.status === "failed" ? "Failed" : "Writing"))))));
  }

  window.CCEvents = EventsApp;
})();
