/* ideas.jsx: the real Ideas module (event ideas that suit the club).
 * A two-step form posts to /club/ideas; an n8n workflow has Claude write six ideas as JSON, which
 * comes back through the shared report routes. This file lists the club's runs, shows progress
 * while one runs, and draws the ideas as cards (same look as the Ideas example in previews.jsx).
 * Ideas can be shortlisted (kept on the run), downloaded as Word, handed to Events (window.CCHandoff,
 * read by events.jsx, which starts a plan from the idea), or re-run with changed answers.
 * Exposes window.CCIdeas; shell.jsx mounts it on the Ideas page when not in demo mode.
 */
(function () {
  const h = React.createElement;
  const API = window.ClubcraftApi;

  /* The idea a member chose to plan. events.jsx reads it (the shape follows the source_type / source_id design:
   * the plan points back at the idea it came from through the run's parent_report_id). Kept for the session only. */
  window.CCHandoff = {
    set(x) { try { sessionStorage.setItem("cc_handoff", JSON.stringify(x)); } catch (e) { /* private window */ } },
    get() { try { return JSON.parse(sessionStorage.getItem("cc_handoff") || "null"); } catch (e) { return null; } },
    clear() { try { sessionStorage.removeItem("cc_handoff"); } catch (e) { /* none */ } }
  };

  const GOALS = [["mix", "A mix of all three"], ["funds", "Raise funds"], ["members", "Find members"], ["community", "Serve the community"]];
  const EMPTY = {
    location: "", club_type: "rotary", active_members: "", age_breakdown: { "65_plus": "", "40_to_65": "", under_40: "" },
    goal: "mix", primary_cause: "", budget: "", success_metrics: "", target_audience: "", local_resources: "", past_events: "", constraints: "", exclude: "", timing: "", use_review: true
  };
  const EXCLUDE_PICKS = ["Raffles or gambling", "Events serving alcohol", "Fun runs and walks", "Auctions", "Door-to-door or street collections", "Anything outdoors"];
  const addPick = (cur, p) => (String(cur || "").toLowerCase().includes(p.toLowerCase()) ? cur : (cur ? cur.replace(/[,\s]+$/, "") + ", " : "") + p);
  const draftKey = (clubId) => "cc_ideas_form_" + clubId;
  // The Review form already holds the club's basics: start from those, then from the last Ideas answers.
  const loadDraft = (clubId) => {
    let rv = {}, id = {};
    try { rv = JSON.parse(localStorage.getItem("cc_review_form_" + clubId) || "{}"); } catch (e) { /* none */ }
    try { id = JSON.parse(localStorage.getItem(draftKey(clubId)) || "{}"); } catch (e) { /* none */ }
    const basics = {};
    ["location", "club_type", "active_members", "age_breakdown"].forEach((k) => { if (rv[k] != null && rv[k] !== "") basics[k] = rv[k]; });
    return { ...EMPTY, ...basics, ...id, age_breakdown: { ...EMPTY.age_breakdown, ...(basics.age_breakdown || {}), ...(id.age_breakdown || {}) } };
  };

  /* ---------- the form ---------- */
  function Form({ clubId, hasReview, rotary, initial, onStarted, runNote, canRun }) {
    const [step, setStep] = React.useState(0);
    const [f, setF] = React.useState(() => (initial
      ? { ...loadDraft(clubId), ...initial, age_breakdown: { ...EMPTY.age_breakdown, ...(initial.age_breakdown || {}) }, club_type: String(initial.club_type || "rotary").toLowerCase() }
      : loadDraft(clubId)));
    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 age = (k) => ({ type: "number", min: "0", value: f.age_breakdown[k], onChange: (e) => setF((x) => ({ ...x, age_breakdown: { ...x.age_breakdown, [k]: e.target.value } })) });
    async function go() {
      setBusy(true); setErr(null);
      try {
        try { localStorage.setItem(draftKey(clubId), JSON.stringify(f)); } catch (e) { /* private window */ }
        const r = await API.call("POST", "/club/ideas", { form: { ...f, use_review: hasReview && f.use_review } }, { club: clubId });
        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, "Get event ideas"), h("span", { className: "cc-pill quiet" }, "Step " + (step + 1) + " of 2: " + (step ? "What you want" : "About your club"))),
      step === 0 && h("div", null,
        h("label", { className: "cc-field" }, "Where is your club based?", h("input", { placeholder: "Suburb or town, state", ...bind("location") })),
        h("div", { className: "cc-grid2" },
          rotary && h("label", { className: "cc-field" }, "Club type", h("select", { ...bind("club_type") }, h("option", { value: "rotary" }, "Rotary club"), h("option", { value: "rotaract" }, "Rotaract club"))),
          h("label", { className: "cc-field" }, "Active members", h("input", { type: "number", min: "0", ...bind("active_members") }))),
        h("div", { className: "cc-label", style: { marginTop: 8 } }, "Roughly how many members are in each age group?"),
        h("div", { className: "cc-grid2" },
          h("label", { className: "cc-field" }, "Under 40", h("input", { ...age("under_40") })),
          h("label", { className: "cc-field" }, "40 to 65", h("input", { ...age("40_to_65") }))),
        h("label", { className: "cc-field" }, "65 and over", h("input", { ...age("65_plus") })),
        h("label", { className: "cc-field" }, "What is around you that a club could use?", h("textarea", { rows: 3, placeholder: "For example: a footy club, two primary schools, a Bunnings, a weekly market, a foreshore with walking tracks", ...bind("local_resources") })),
        h("label", { className: "cc-field" }, "Events you have run before", h("textarea", { rows: 3, placeholder: "What worked, and what did not. We will not suggest the same again.", ...bind("past_events") })),
        hasReview && h("label", { className: "cc-check" }, h("input", { type: "checkbox", checked: !!f.use_review, onChange: (e) => set("use_review", e.target.checked) }), " Use my latest Review to sharpen the ideas")),
      step === 1 && h("div", null,
        h("label", { className: "cc-field" }, "What do you want most from an event?", h("select", { ...bind("goal") }, GOALS.map(([v, l]) => h("option", { key: v, value: v }, l)))),
        h("label", { className: "cc-field" }, "The cause or project it supports (optional)", h("input", { placeholder: "For example: the local reading program, or polio eradication", ...bind("primary_cause") })),
        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") })),
          h("label", { className: "cc-field" }, "When are you thinking?", h("input", { placeholder: "For example: autumn, or within three months", ...bind("timing") }))),
        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_metrics") })),
        h("label", { className: "cc-field" }, "Who do you want to reach?", h("input", { placeholder: "For example: young families, local businesses", ...bind("target_audience") })),
        h("label", { className: "cc-field" }, "Anything that limits you", h("textarea", { rows: 2, placeholder: "For example: few volunteers, no weekend availability, no venue", ...bind("constraints") })),
        h("label", { className: "cc-field" }, "Events your club is not interested in", h("textarea", { rows: 2, placeholder: "We will not suggest these, or anything like them", ...bind("exclude") })),
        h("div", { className: "cc-ex-chips", "aria-label": "Quick picks for events to leave out" }, EXCLUDE_PICKS.map((p) =>
          h("button", { key: p, type: "button", onClick: () => set("exclude", addPick(f.exclude, p)) }, "+ " + p))),
        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.location.trim(), onClick: () => setStep(1) }, "Next")
          : h("button", { className: "cc-btn primary lg", disabled: busy || !canRun, onClick: go }, busy ? "Starting…" : "Get my ideas")));
  }

  /* ---------- the ideas ---------- */
  const EFFORT = ["Low", "Medium", "High"];
  function Idea({ i, saved, canSave, canComms, onSave, onPlan, onComms }) {
    return h("article", { className: "cc-ex-idea" + (saved ? " saved" : "") },
      h("div", { className: "top" }, h("span", { className: "tags" }, h("span", { className: "cc-pill quiet" }, i.category), i.focus && h("span", { className: "cc-pill trial" }, i.focus)),
        i.fit != null && h("span", { className: "fit", title: "How well this fits your club" }, h("b", null, i.fit), "fit")),
      h("h3", null, i.name || i.title),
      h("p", { className: "why" }, i.summary),
      h("dl", null,
        i.audience && h("div", null, h("dt", null, "Who comes"), h("dd", null, i.audience)),
        i.cost && h("div", null, h("dt", null, "Costs about"), h("dd", null, i.cost)),
        i.outcome && h("div", null, h("dt", null, "Could bring"), h("dd", null, i.outcome)),
        h("div", null, h("dt", null, "Effort"), h("dd", null,
          h("span", { className: "dots", "aria-label": EFFORT[i.effort - 1] + " effort" }, [1, 2, 3].map((n) => h("i", { key: n, className: n <= i.effort ? "on" : "" }))),
          " " + EFFORT[i.effort - 1] + (i.people ? ", " + i.people + " people" : ""))),
        i.timing && h("div", null, h("dt", null, "Best time"), h("dd", null, i.timing))),
      i.why && h("p", { className: "cc-ex-fit" }, h("b", null, "Why it suits you: "), i.why),
      i.first_step && h("p", { className: "cc-ex-fit" }, h("b", null, "First step: "), i.first_step),
      i.local && h("p", { className: "cc-ex-local" }, h("b", null, "Check locally: "), i.local),
      i.local_evidence && h("p", { className: "cc-ex-fit" }, h("b", null, "What we found nearby: "), i.local_evidence),
      i.clash && h("p", { className: "cc-ex-fit" }, h("b", null, "Other events nearby: "), i.clash),
      i.sources && i.sources.length > 0 && h("p", { className: "cc-ex-local" }, h("b", null, "Sources: "),
        i.sources.map((u, n) => h("span", { key: n }, n ? ", " : "", h("a", { href: u, target: "_blank", rel: "noopener noreferrer" }, u.replace(/^https?:\/\/(www\.)?/, "").split("/")[0])))),
      h("div", { className: "cc-row", style: { marginTop: 10 } },
        canSave && h("button", { className: "cc-btn sm" + (saved ? " on" : ""), "aria-pressed": !!saved, onClick: () => onSave(i.id, !saved) }, saved ? "★ Shortlisted" : "☆ Shortlist"),
        h("button", { className: "cc-btn sm primary", onClick: () => onPlan(i) }, "Plan this in Events"),
        canComms && h("button", { className: "cc-btn sm", title: "Write a marketing plan for this idea in Comms", onClick: () => onComms(i) }, "Plan the marketing")));
  }

  async function downloadWord(res, club, title, only) {
    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.CCIdeasDocx.build(window.docx, res, { club, title, date, only, 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 = ((only ? "Shortlisted event ideas - " : "Event ideas - ") + (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, canSave, canComms, onBack, onGo, onRerun, onChanged }) {
    const [r, setR] = React.useState(null);
    const [err, setErr] = React.useState(null);
    const [cat, setCat] = React.useState("All");
    const [wordBusy, setWordBusy] = React.useState(false);
    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.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); };
    }, [id, clubId]);
    const res = r && r.ideas;
    const saved = (r && r.shortlist) || [];
    const cats = res ? ["All"].concat([...new Set(res.ideas.map((i) => i.category))], saved.length ? ["Shortlisted"] : []) : [];
    const shown = res ? res.ideas.filter((i) => cat === "All" || (cat === "Shortlisted" ? saved.includes(i.id) : i.category === cat)) : [];
    const save = (ideaId, on) => {
      const before = r.shortlist || [];
      setErr(null);
      setR((x) => ({ ...x, shortlist: on ? [...before.filter((k) => k !== ideaId), ideaId] : before.filter((k) => k !== ideaId) }));
      API.call("POST", "/club/reports/" + id + "/shortlist", { idea: ideaId, on }, { club: clubId })
        .then((x) => setR((y) => ({ ...y, shortlist: x.shortlist })))
        .catch((e) => { setErr(e.message); setR((x) => ({ ...x, shortlist: before })); });
      if (!on && cat === "Shortlisted" && before.length <= 1) setCat("All");
    };
    // Hand the idea to Events, which opens its form with the idea filled in.
    const plan = (i) => {
      window.CCHandoff.set({ source_type: "idea", source_id: id + ":" + i.id, report_id: id, idea_id: i.id, name: i.name || i.title, title: 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, at: Date.now() });
      onGo && onGo("mod:Events");
    };
    // Hand the idea to Comms, which opens its form with the idea filled in.
    const market = (i) => {
      window.CCCommsHandoff.set({ idea: { name: i.name || i.title, summary: i.summary, category: i.category, timing: i.timing, first_step: i.first_step }, at: Date.now() });
      onGo && onGo("mod:Comms");
    };
    const word = (only) => { setWordBusy(true); setErr(null); downloadWord(res, club, r.title, only).catch((e) => setErr(e.message)).finally(() => setWordBusy(false)); };
    return h("div", null,
      h("button", { className: "cc-link", onClick: onBack }, "← All ideas"),
      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 ideas are being written. This usually takes a minute or two. You can leave this page; they 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 || "Ideas could not be completed. Your credits were returned.")),
      r && r.status === "done" && !res && h("section", { className: "cc-card" }, h("div", { className: "cc-err", role: "alert" }, "These ideas could not be read. Please run Ideas again.")),
      res && h("div", { className: "cc-ex" },
        h("div", { className: "cc-ex-head" }, h("div", null, h("h2", null, r.title), h("p", null, res.ideas.length + " ideas, ranked by how well they fit your club.")),
          h("div", { className: "cc-ex-actions" },
            h("button", { className: "cc-btn sm", disabled: wordBusy, onClick: () => word(null) }, wordBusy ? "Preparing…" : "Download Word"),
            saved.length > 0 && h("button", { className: "cc-btn sm", disabled: wordBusy, onClick: () => word(saved) }, "Word: shortlist (" + saved.length + ")"),
            h("button", { className: "cc-btn sm ghost", onClick: () => window.print() }, "Print"),
            canSave && r.form && h("button", { className: "cc-btn sm ghost", title: "Change your answers and get a new set of ideas (uses another run)", onClick: () => onRerun(r.form) }, "Run again with changes"))),
        res.summary && h("div", { className: "cc-ex-note" }, res.summary),
        res.research_note && h("p", { className: "cc-muted" }, h("b", null, "Local research: "), res.research_note),
        h("div", { className: "cc-ex-chips", role: "tablist", "aria-label": "Filter ideas" }, cats.map((c) => h("button", { key: c, role: "tab", "aria-selected": cat === c, className: cat === c ? "on" : "", onClick: () => setCat(c) }, c))),
        h("div", { className: "cc-ex-cards" }, shown.map((i) => h(Idea, { key: i.id, i, saved: saved.includes(i.id), canSave, canComms: canComms && !!window.CCCommsHandoff, onSave: save, onPlan: plan, onComms: market }))),
        res.next_step && h("p", { className: "cc-muted" }, res.next_step),
        h("p", { className: "cc-ex-foot" }, "Prepared by Clubcraft Ideas. These ideas are written by AI from your answers. Costs and returns are estimates. Please check them, and any local rules, with your club leadership before you commit.")));
  }

  /* ---------- the Ideas page ---------- */
  function IdeasApp({ clubId, clubInfo, onGo, onChanged }) {
    const access = clubInfo.me.access.Ideas;
    const a = (clubInfo.allowances || {}).Ideas || {};
    const [list, setList] = React.useState(null);
    const [hasReview, setHasReview] = React.useState(false);
    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 ("run again with changes")
    const levels = (clubInfo.brand && clubInfo.brand.levels) || [];
    const rotary = levels.some((l) => /rotar/i.test(l.name));   // the same test the server uses
    const [err, setErr] = React.useState(null);
    const load = React.useCallback(() => API.call("GET", "/club/reports?module=Ideas", null, { club: clubId }).then((r) => setList(r.reports)).catch((e) => setErr(e.message)), [clubId]);
    React.useEffect(() => {
      setList(null); setView(null); setHasReview(false);
      if (!access) return;
      load();
      // A finished Review can sharpen the ideas. Not everyone can read Reviews, so ignore a refusal.
      API.call("GET", "/club/reports?module=Review", null, { club: clubId }).then((r) => setHasReview((r.reports || []).some((x) => x.status === "done"))).catch(() => {});
    }, [clubId]);
    if (!access) return h("div", { className: "cc-note" }, "Ask a club admin for access to Ideas.");
    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 + " Ideas runs available this month (AI credits)."
      : a.state === "available" ? "This is your trial run of Ideas. A plan removes the limit." : "";
    let why = "";
    if (access !== "edit") why = "You can read your club's ideas. Edit access to Ideas is needed to get 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 run of Ideas has been used. Choose a plan to get more.";
    else if (a.state === "ended") why = "Your trial has ended. Choose a plan to get new ideas.";
    const rerun = (form) => { setInitial(form); setView("new"); };
    if (view && view !== "new") return h(Result, { clubId, club: clubInfo.club.name, id: view, canSave: access === "edit", canComms: clubInfo.me.access.Comms === "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 ideas"),
      h(Form, { clubId, hasReview, rotary, initial, 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 ideas"),
          access === "edit" && h("button", { className: "cc-btn primary", disabled: !canRun, onClick: () => { setInitial(null); setView("new"); } }, running ? "Ideas are being written" : "Get event ideas")),
        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 ideas yet. Tell us about your club and what you want from an event, and Ideas suggests six that suit you, with rough costs and what each could bring in."),
        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.CCIdeas = IdeasApp;
})();
