/* comms.jsx: the real Comms module (a marketing campaign plan for an event).
 * A two-step form posts to /club/comms; 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 Comms example in previews.jsx (the Social Planner's Week Planner, Table and Board
 * views). Members with edit access can tick weeks done and reword a week's topic; that progress is saved with
 * the plan (POST /club/reports/:id/comms-state). A plan can be downloaded as Word, sent to Tasks as weekly jobs,
 * handed to Calendar, or planned again with changed answers. A finished Events plan arrives through
 * window.CCCommsHandoff ({report_id}, set in events.jsx); an idea chosen in Ideas arrives the same way ({idea}, set in ideas.jsx).
 * Exposes window.CCComms; shell.jsx mounts it on the Comms page when not in demo mode.
 */
(function () {
  const h = React.createElement;
  const API = window.ClubcraftApi;

  /* What the member chose to promote: an Events plan ({report_id}) or an idea ({idea}). Kept for the session only. */
  window.CCCommsHandoff = {
    set(x) { try { sessionStorage.setItem("cc_comms_handoff", JSON.stringify(x)); } catch (e) { /* private window */ } },
    get() { try { return JSON.parse(sessionStorage.getItem("cc_comms_handoff") || "null"); } catch (e) { return null; } },
    clear() { try { sessionStorage.removeItem("cc_comms_handoff"); } catch (e) { /* none */ } }
  };
  /* Dates for the Calendar module to pick up: {source_type, source_id, name, items:[{title, date, end, notes}], at}, dates as
   * YYYY-MM-DD. Comms only offers "Add to Calendar" once window.CCCalendar exists (the Calendar page is still a preview),
   * so the button never leads to a page that ignores it. The Calendar module reads and clears this when it opens. */
  window.CCCalendarHandoff = window.CCCalendarHandoff || {
    set(x) { try { sessionStorage.setItem("cc_calendar_handoff", JSON.stringify(x)); } catch (e) { /* private window */ } },
    get() { try { return JSON.parse(sessionStorage.getItem("cc_calendar_handoff") || "null"); } catch (e) { return null; } },
    clear() { try { sessionStorage.removeItem("cc_calendar_handoff"); } catch (e) { /* none */ } }
  };

  const CHANNELS = ["Facebook", "Instagram", "LinkedIn", "Member emails", "Club website", "Local newspaper", "Posters and flyers", "Word of mouth"];
  const WEEK_CHOICES = [[4, "4 weeks"], [6, "6 weeks"], [8, "8 weeks"], [10, "10 weeks"]];
  const PILLARS = {
    event: { label: "About the Event", color: "#17458F", bg: "#E7EEF8" },
    impact: { label: "Community Impact", color: "#0E7490", bg: "#DEF1F4" },
    involved: { label: "How to Get Involved", color: "#6D28D9", bg: "#EDE7FB" },
    story: { label: "Stories", color: "#C2410C", bg: "#FAE7DB" }
  };
  const EMPTY = { source_id: "", event_name: "", description: "", event_date: "", venue: "", location: "", active_members: "", attendance: "", cause: "", goal: "", audiences: "", channels: ["Facebook", "Member emails"], existing: "", voice: "", constraints: "", campaign_weeks: 6 };
  const draftKey = (clubId) => "cc_comms_form_" + clubId;
  const DAY = 86400000;
  const fmtShort = (d) => d.toLocaleDateString(CCIntl.locale(), { day: "numeric", month: "short" });

  /* The club's basics come from the Review form (kept in the browser), then from the last Comms answers. */
  const loadDraft = (clubId) => {
    let rv = {}, d = {};
    try { rv = JSON.parse(localStorage.getItem("cc_review_form_" + clubId) || "{}"); } catch (e) { /* none */ }
    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, location: d.location || rv.location || "", active_members: rv.active_members || "", channels: Array.isArray(d.channels) && d.channels.length ? d.channels : EMPTY.channels, existing: d.existing || "", voice: d.voice || "", constraints: d.constraints || "" };
  };
  /* A finished Events run turned into the form's starting answers. */
  const fromEvents = (run) => {
    const p = run.plan || {}, f = run.form || {};
    return { source_id: "events:" + run.id, event_name: (p.event && p.event.name) || f.event_name || run.title, description: f.description || "", event_date: f.event_date || "", venue: f.venue || "", attendance: f.attendance == null ? "" : f.attendance, cause: f.cause || (p.purpose && p.purpose.cause) || "", location: f.location || "", active_members: f.active_members || "" };
  };
  /* An idea chosen in Ideas turned into the form's starting answers. */
  const fromIdea = (i) => ({ event_name: i.name || i.title || "", description: String(i.summary || "").slice(0, 500) });
  const iso = (d) => d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
  /* A week's first day: the event date counted back by the weeks out (negative = after the event). */
  const startOf = (eventDate, wk) => (eventDate && /^\d{4}-\d{2}-\d{2}$/.test(eventDate) ? new Date(new Date(eventDate + "T00:00:00").getTime() - wk.weeks_out * 7 * DAY) : null);
  const weekLabel = (wk, i) => (wk.weeks_out < 0 ? "After" : "Week " + (i + 1));
  const outLabel = (n) => (n > 1 ? n + " weeks out" : n === 1 ? "1 week out" : n === 0 ? "Event week" : "After the event");

  /* ---------- the form ---------- */
  function Form({ clubId, initial, eventRuns, onStarted, runNote, canRun }) {
    const handoff = React.useMemo(() => window.CCCommsHandoff.get(), []);
    const [step, setStep] = React.useState(0);
    const [f, setF] = React.useState(() => {
      if (initial) return { ...EMPTY, ...loadDraft(clubId), ...initial, attendance: initial.attendance === "" ? "" : initial.attendance };
      const base = loadDraft(clubId);
      if (handoff && handoff.idea) return { ...base, ...fromIdea(handoff.idea) };
      const run = handoff && eventRuns.find((r) => r.id === String(handoff.report_id));
      return run ? { ...base, ...fromEvents(run) } : base;
    });
    const ideaName = !initial && handoff && handoff.idea ? (handoff.idea.name || handoff.idea.title) : "";
    const [pick, setPick] = React.useState(() => (f.source_id ? f.source_id.split(":")[1] : ""));
    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 = (rid) => {
      setPick(rid);
      const run = eventRuns.find((r) => r.id === rid);
      if (!run) { setF((x) => ({ ...x, source_id: "" })); return; }
      setF((x) => ({ ...x, ...fromEvents(run), location: fromEvents(run).location || x.location, active_members: fromEvents(run).active_members || x.active_members }));
    };
    const toggleChannel = (c) => setF((x) => ({ ...x, channels: x.channels.includes(c) ? x.channels.filter((k) => k !== c) : x.channels.concat(c) }));
    async function go() {
      setBusy(true); setErr(null);
      try {
        try { localStorage.setItem(draftKey(clubId), JSON.stringify({ location: f.location, channels: f.channels, existing: f.existing, voice: f.voice, constraints: f.constraints })); } catch (e) { /* private window */ }
        const r = await API.call("POST", "/club/comms", { form: f }, { club: clubId });
        window.CCCommsHandoff.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 a marketing plan"), h("span", { className: "cc-pill quiet" }, "Step " + (step + 1) + " of 2: " + (step ? "The campaign" : "The event"))),
      step === 0 && h("div", null,
        ideaName && h("div", { className: "cc-note trial cc-handoff", role: "status" }, h("div", null, h("b", null, "Starting from the idea: " + ideaName), h("p", null, "Add the date and venue if you have them, then tell Comms who to reach."))),
        eventRuns.length > 0 && h("label", { className: "cc-field" }, "Start from one of your Events plans (optional)",
          h("select", { value: pick, onChange: (e) => choose(e.target.value) },
            h("option", { value: "" }, "No, I will describe the event"),
            eventRuns.map((r) => h("option", { key: r.id, value: r.id }, (r.plan && r.plan.event && r.plan.event.name) || r.title)))),
        f.source_id && h("div", { className: "cc-note trial cc-handoff", role: "status" }, h("div", null, h("b", null, "Building on your Events plan"), h("p", null, "The promotion steps and success measure in that plan are used, so the two fit together."))),
        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("label", { className: "cc-field" }, "What must the campaign achieve?", h("textarea", { rows: 2, placeholder: "For example: sell all 12 tables three days before the night, and find four sponsors", ...bind("goal") })),
        h("label", { className: "cc-field" }, "Who do you want to reach?", h("textarea", { rows: 2, placeholder: "For example: members and families, local businesses, schools and sports clubs", ...bind("audiences") })),
        h("fieldset", { className: "cc-field cc-cm-channels" }, h("legend", null, "Where can you post or send things?"),
          h("div", { className: "cc-ex-chips" }, CHANNELS.map((c) => h("button", { key: c, type: "button", className: f.channels.includes(c) ? "on" : "", "aria-pressed": f.channels.includes(c), onClick: () => toggleChannel(c) }, c)))),
        h("div", { className: "cc-grid2" },
          h("label", { className: "cc-field" }, "How long should the campaign run?", h("select", { value: f.campaign_weeks, onChange: (e) => set("campaign_weeks", Number(e.target.value)) }, WEEK_CHOICES.map(([n, l]) => h("option", { key: n, value: n }, l)))),
          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 do you already have?", h("textarea", { rows: 2, placeholder: "For example: a Facebook page with 400 followers, a monthly member email, last year's photos", ...bind("existing") })),
        h("label", { className: "cc-field" }, "Voice and style (optional)", h("input", { placeholder: "For example: warm, a bit cheeky, no jargon", ...bind("voice") })),
        h("label", { className: "cc-field" }, "Anything that limits you", h("textarea", { rows: 2, placeholder: "For example: no paid ads, one person looks after social media", ...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 || f.channels.length === 0, 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 || ""), key: label }, h("span", null, label), h("b", null, value), note && h("small", null, note));
  const PillarChip = ({ p }) => h("span", { className: "cc-sp-pillar", style: { color: PILLARS[p].color, background: PILLARS[p].bg } }, PILLARS[p].label);

  async function downloadWord(plan, state, club, title, eventDate) {
    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.CCCommsDocx.build(window.docx, plan, state, { club, title, date, eventDate, 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 = ("Marketing plan - " + ((plan.campaign && plan.campaign.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, canCalendar, canSocial, onBack, onRerun, onChanged, onGo }) {
    const [wordBusy, setWordBusy] = React.useState(false);
    const [r, setR] = React.useState(null);
    const [state, setState] = React.useState({ done: [], topics: {} });
    const [view, setView] = React.useState("table");
    const [saveNote, setSaveNote] = React.useState("");
    const [err, setErr] = React.useState(null);
    const [sent, setSent] = React.useState(null);        // the Tasks project made from this plan
    const [sendBusy, setSendBusy] = React.useState(false);
    const [socialBusy, setSocialBusy] = 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: [], topics: {}, ...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 + "/comms-state", next, { club: clubId })
            .then(() => setSaveNote("Saved"))
            .catch((e) => { setSaveNote(""); setErr(e.message); });
        }, 700);
        return next;
      });
    };
    const toggleDone = (wid) => change((s) => ({ ...s, done: s.done.includes(wid) ? s.done.filter((k) => k !== wid) : s.done.concat(wid) }));
    const setTopic = (wid, v) => change((s) => ({ ...s, topics: { ...s.topics, [wid]: v } }));

    const plan = r && r.plan;
    // Saves any pending change first, so finished weeks 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 + "/comms-state", state, { club: clubId }); }
        setSent(await API.call("POST", "/club/reports/" + id + "/comms-to-tasks", {}, { club: clubId }));
      } catch (e) { setErr(e.message); }
      setSendBusy(false);
    };
    // Makes a Social campaign from this plan (once): its weeks, topics and pillars become the Week Planner, with the planned number of posts.
    const toSocial = async () => {
      setSocialBusy(true); setErr(null);
      try {
        const list = await API.call("GET", "/club/social", null, { club: clubId });
        const have = (list.campaigns || []).find((c) => c.commsReportId === id);
        if (!have) {
          const reworded = { ...plan, weeks: plan.weeks.map((w) => ({ ...w, topic: (state.topics && state.topics[w.id]) || w.topic })) };
          const name = (plan.campaign && plan.campaign.name) || r.title;
          const seed = window.CCSocialSeed.fromCommsPlan(reworded, r.event_date, name);
          await API.call("POST", "/club/social", { name, config: seed.config, weeks: seed.weeks, posts: seed.posts, commsReportId: id }, { club: clubId });
          window.dispatchEvent(new Event("cc-club-changed"));
        }
        onGo && onGo("social");
      } catch (e) { setErr(e.message); }
      setSocialBusy(false);
    };
    const word = () => { setWordBusy(true); setErr(null); downloadWord(plan, state, club, r.title, r.event_date).catch((e) => setErr(e.message)).finally(() => setWordBusy(false)); };
    // One calendar item per week (its first day to its last) plus the event itself, for the Calendar module to pick up.
    const toCalendar = () => {
      const items = plan.weeks.slice().sort((a, b) => b.weeks_out - a.weeks_out).map((w, i) => {
        const s = startOf(r.event_date, w);
        const topic = state.topics[w.id] ? state.topics[w.id] : w.topic;
        return { title: "Marketing " + weekLabel(w, i).toLowerCase() + ": " + PILLARS[w.pillar].label, date: iso(s), end: iso(new Date(s.getTime() + 6 * DAY)), notes: topic + (w.reference ? " (" + w.reference + ")" : "") };
      });
      items.push({ title: (plan.campaign && plan.campaign.name) || r.title, date: r.event_date, end: r.event_date, notes: "The event", kind: "Event" });
      window.CCCalendarHandoff.set({ source_type: "Comms", source_id: id, name: (plan.campaign && plan.campaign.name) || r.title, items, at: Date.now() });
      onGo && onGo("mod:Calendar");
    };
    let body = null;
    if (plan) {
      const weeks = plan.weeks.slice().sort((a, b) => b.weeks_out - a.weeks_out);
      const topicOf = (w) => (state.topics[w.id] != null && state.topics[w.id] !== "" ? state.topics[w.id] : w.topic);
      const posts = weeks.reduce((a, w) => a + w.posts, 0);
      const doneN = weeks.filter((w) => state.done.includes(w.id)).length;
      const first = weeks.length ? startOf(r.event_date, weeks[0]) : null;
      const range = (w) => { const s = startOf(r.event_date, w); return s ? fmtShort(s) + " to " + fmtShort(new Date(s.getTime() + 6 * DAY)) : outLabel(w.weeks_out); };
      const tick = (w) => { const d = state.done.includes(w.id); return canEdit
        ? h("button", { type: "button", className: "cc-btn sm" + (d ? " primary" : ""), "aria-pressed": d, onClick: () => toggleDone(w.id) }, d ? "✓ Done" : "Mark done")
        : h("span", { className: "cc-pill " + (d ? "ok" : "quiet") }, d ? "Done" : "To do"); };
      const topicCell = (w) => (canEdit
        ? h("textarea", { className: "cc-cm-topic", rows: 3, maxLength: 320, "aria-label": "Topic and angle for " + range(w), value: topicOf(w), onChange: (e) => setTopic(w.id, e.target.value) })
        : h("span", null, topicOf(w)));
      body = h("div", { className: "cc-ex" },
        h("div", { className: "cc-ex-head" }, h("div", null, h("h2", null, (plan.campaign && plan.campaign.name) || r.title), h("p", null, plan.campaign && plan.campaign.event_when ? "Event: " + plan.campaign.event_when : "")),
          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"),
            canCalendar && window.CCCalendar && r.event_date && h("button", { className: "cc-btn sm", title: "Show the campaign weeks and the event date on the club calendar", onClick: toCalendar }, "Add to Calendar"),
            canEdit && canSocial && window.CCSocialSeed && h("button", { className: "cc-btn sm primary", disabled: socialBusy, title: "Make a Social campaign from this plan: the weeks, topics and pillars become the Week Planner", onClick: toSocial }, socialBusy ? "Creating…" : "Create the social posts"),
            canEdit && canTasks && h("button", { className: "cc-btn sm primary", disabled: sendBusy, title: "Make a Tasks project from the weekly planner", onClick: sendToTasks }, sendBusy ? "Sending…" : "Send to Tasks"),
            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 + " weekly jobs" + (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")),
        plan.summary && h("div", { className: "cc-ex-note" }, plan.summary),
        h("div", { className: "cc-ex-stats" },
          h(Stat, { label: "Weeks", value: String(weeks.length), note: first ? "starts " + fmtShort(first) : "dates follow the event date" }),
          h(Stat, { label: "Posts planned", value: String(posts) }),
          h(Stat, { label: "Channels", value: String(plan.channels.length) }),
          h(Stat, { label: "Weeks done", value: doneN + " of " + weeks.length, tone: doneN === weeks.length ? "good" : "" })),
        h("div", { className: "cc-ex-purpose" },
          h("div", null, h("span", null, "The goal"), h("b", null, plan.goal || "Not stated")),
          h("div", null, h("span", null, "Who we want to reach"), h("b", null, plan.audiences.map((a) => a.who).join(", "))),
          h("div", null, h("span", null, "Channels"), h("b", null, plan.channels.map((c) => c.name).join(", "))),
          h("div", null, h("span", null, "Voice"), h("b", null, plan.voice || "Not stated"))),
        h("div", { className: "cc-ex-cols" },
          h(Panel, { title: "Who we are talking to" }, h("table", { className: "cc-ex-table" }, h("tbody", null, plan.audiences.map((a) => h("tr", { key: a.id }, h("td", null, h("b", null, a.who)), h("td", null, a.message)))))),
          h(Panel, { title: "Channels" }, h("table", { className: "cc-ex-table" }, h("tbody", null, plan.channels.map((c) => h("tr", { key: c.id }, h("td", null, h("b", null, c.name), c.frequency && h("div", { className: "cc-muted sm" }, c.frequency)), h("td", null, c.role))))))),
        h(Panel, { title: "Content pillars", aside: h("small", { className: "cc-muted" }, "Each week leads with one pillar") },
          h("div", { className: "cc-cm-pillars" }, plan.pillars.map((p) => h("div", { key: p.key }, h(PillarChip, { p: p.key }), p.focus && h("p", null, p.focus))))),
        h("div", { className: "cc-sp" },
          h("div", { className: "cc-sp-bar" },
            h("div", null, h("h3", null, "Week Planner"), h("p", null, weeks.length + " weeks  ·  " + posts + " posts" + (canEdit ? "  ·  edit a topic or mark a week done" : ""))),
            h("div", { className: "cc-sp-seg" }, h("button", { className: view === "table" ? "on" : "", onClick: () => setView("table") }, "Table"), h("button", { className: view === "board" ? "on" : "", onClick: () => setView("board") }, "Board"))),
          view === "table"
            ? h("div", { className: "cc-sp-table", role: "table", "aria-label": "Week planner" },
              h("div", { className: "head", role: "row" }, ["Week", "Dates", "Pillar", "Topic and angle", "Reference", "Posts", "Done"].map((t) => h("div", { key: t }, t))),
              weeks.map((w, i) => h("div", { className: "row" + (state.done.includes(w.id) ? " cc-cm-done" : ""), role: "row", key: w.id },
                h("div", null, h("b", null, weekLabel(w, i))), h("div", { className: "muted" }, range(w)), h("div", null, h(PillarChip, { p: w.pillar })),
                h("div", null, topicCell(w)), h("div", { className: "ref" }, w.reference), h("div", null, w.posts + (w.posts === 1 ? " post" : " posts")), h("div", null, tick(w)))))
            : h("div", { className: "cc-sp-board" }, weeks.map((w, i) => h("div", { className: "card" + (state.done.includes(w.id) ? " cc-cm-done" : ""), key: w.id },
              h("div", { className: "h" }, h("div", null, h("b", null, weekLabel(w, i)), h("small", null, range(w))), h(PillarChip, { p: w.pillar })),
              h("div", { className: "b" }, h("span", { className: "lab" }, "Topic and angle"), topicCell(w), h("span", { className: "lab" }, "Reference"), h("p", { className: "ref" }, w.reference), h("small", null, w.posts + (w.posts === 1 ? " post" : " posts") + " planned")),
              h("div", { className: "f" }, tick(w)))))),
        plan.key_messages.length > 0 && h(Panel, { title: "Key messages", aside: h("small", { className: "cc-muted" }, "Lines every post can draw on") }, h("ul", { className: "cc-ex-after" }, plan.key_messages.map((m, n) => h("li", { key: n }, m)))),
        h("div", { className: "cc-ex-cols" },
          plan.measures.length > 0 && h(Panel, { title: "How you will know it worked" }, h("table", { className: "cc-ex-table" }, h("tbody", null, plan.measures.map((m, n) => h("tr", { key: n }, h("td", null, h("b", null, m.what)), h("td", null, m.target)))))),
          plan.watch_outs.length > 0 && h(Panel, { title: "Get these right before posting" }, h("ul", { className: "cc-ex-after" }, plan.watch_outs.map((m, n) => h("li", { key: n }, m))))),
        plan.next_step && h("p", { className: "cc-muted" }, plan.next_step),
        h("p", { className: "cc-ex-foot" }, "Prepared by Clubcraft Comms. This plan is written by AI from your answers. Targets and timing are guides. Please check facts, names and any local rules with your club leadership before you publish."));
    }
    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 Comms page ---------- */
  function CommsApp({ clubId, clubInfo, onGo, onChanged }) {
    const access = clubInfo.me.access.Comms;
    const a = (clubInfo.allowances || {}).Comms || {};
    const [list, setList] = React.useState(null);
    const [eventRuns, setEventRuns] = React.useState(null);  // null until loaded, so a hand-off can wait for it
    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=Comms", null, { club: clubId }).then((r) => setList(r.reports)).catch((e) => setErr(e.message)), [clubId]);
    React.useEffect(() => {
      setList(null); setEventRuns(null);
      setView(null);
      if (!access) return;
      load();
      // Finished Events plans, so a campaign can start from one. Not everyone can read Events, so ignore a refusal.
      API.call("GET", "/club/reports?module=Events", null, { club: clubId }).then(async (r) => {
        const done = (r.reports || []).filter((x) => x.status === "done").slice(0, 5);
        const runs = await Promise.all(done.map((x) => API.call("GET", "/club/reports/" + x.id, null, { club: clubId }).then((y) => (y.report.plan ? { id: x.id, title: x.title, plan: y.report.plan, form: y.report.form } : null)).catch(() => null)));
        setEventRuns(runs.filter(Boolean));
      }).catch(() => setEventRuns([]));
    }, [clubId]);
    // An Events plan waiting from the Events page opens the form straight away, once the plans have loaded.
    React.useEffect(() => {
      if (eventRuns && access === "edit" && window.CCCommsHandoff.get()) setView("new");
    }, [eventRuns]);
    if (!access) return h("div", { className: "cc-note" }, "Ask a club admin for access to Comms.");
    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 Comms. A plan removes the limit." : "";
    let why = "";
    if (access !== "edit") why = "You can read your club's plans. Edit access to Comms 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 Comms 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 marketing 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", canCalendar: clubInfo.me.access.Calendar === "edit", canSocial: clubInfo.me.access.Social === "edit", onGo, onRerun: rerun, onChanged, onBack: () => { setView(null); load(); } });
    if (view === "new") return h("div", null, h("button", { className: "cc-link", onClick: () => { setInitial(null); window.CCCommsHandoff.clear(); setView(null); } }, "← All plans"),
      h(Form, { clubId, initial, eventRuns: eventRuns || [], 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 marketing plans"),
          access === "edit" && h("button", { className: "cc-btn primary", disabled: !canRun, onClick: () => { setInitial(null); setView("new"); } }, running ? "A plan is being written" : "Make a marketing 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 Events plan, or describe an event, and Comms writes a campaign plan: who to reach, what to say, which channels to use and a week-by-week planner."),
        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.CCComms = CommsApp;
})();
