/* review.jsx: the real Review module (Membership Strategy Audit).
 * A three-step form posts to /club/review; an n8n workflow scrapes the club's website and
 * Facebook page and has Claude write the report, which comes back as Markdown. This file
 * lists the club's reports, shows progress while one runs, and renders the Markdown.
 * Exposes window.CCReview; shell.jsx mounts it on the Review page when not in demo mode.
 */
(function () {
  const h = React.createElement;
  const API = window.ClubcraftApi;

  /* ---------- Markdown -> safe HTML (headings, bold, lists, tables, quotes, rules) ---------- */
  const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  const inline = (s) => esc(s).replace(/\*\*(.+?)\*\*/g, "<b>$1</b>").replace(/(^|[\s(])\*(?!\s)(.+?)\*(?=[\s).,;:]|$)/g, "$1<i>$2</i>").replace(/`(.+?)`/g, "<code>$1</code>");
  function markdown(md) {
    const lines = md.replace(/\r/g, "").split("\n");
    const out = [];
    let i = 0, list = null;
    const close = () => { if (list) { out.push("</" + list + ">"); list = null; } };
    while (i < lines.length) {
      const l = lines[i];
      let m;
      if (/^\s*\|.+\|\s*$/.test(l)) {
        close();
        const rows = [];
        while (i < lines.length && /^\s*\|.+\|\s*$/.test(lines[i])) { rows.push(lines[i].trim().slice(1, -1).split("|").map((c) => c.trim())); i++; }
        const body = rows.filter((r) => !r.every((c) => /^:?-{2,}:?$/.test(c)));
        out.push("<div class=\"cc-rv-table\"><table><thead><tr>" + body[0].map((c) => "<th>" + inline(c) + "</th>").join("") + "</tr></thead><tbody>"
          + body.slice(1).map((r) => "<tr>" + r.map((c) => "<td>" + inline(c) + "</td>").join("") + "</tr>").join("") + "</tbody></table></div>");
        continue;
      }
      if ((m = /^(#{1,4})\s+(.*)$/.exec(l))) { close(); const n = Math.min(4, m[1].length + 1); out.push("<h" + n + ">" + inline(m[2]) + "</h" + n + ">"); }
      else if (/^\s*---+\s*$/.test(l)) { close(); out.push("<hr>"); }
      else if ((m = /^>\s?(.*)$/.exec(l))) { close(); out.push("<blockquote>" + inline(m[1]) + "</blockquote>"); }
      else if ((m = /^\s*[-*•]\s+(.*)$/.exec(l))) { if (list !== "ul") { close(); out.push("<ul>"); list = "ul"; } out.push("<li>" + inline(m[1]) + "</li>"); }
      else if ((m = /^\s*\d+[.)]\s+(.*)$/.exec(l))) { if (list !== "ol") { close(); out.push("<ol>"); list = "ol"; } out.push("<li>" + inline(m[1]) + "</li>"); }
      else if (!l.trim()) close();
      else { close(); out.push("<p>" + inline(l) + "</p>"); }
      i++;
    }
    close();
    return out.join("\n");
  }

  /* ---------- the form ---------- */
  const EMPTY = {
    location: "", club_type: "rotary", active_members: "", website: "", facebook: "", instagram: "", community_type: "", club_vibe: "", meeting_format: "", meeting_time: "",
    age_breakdown: { "65_plus": "", "40_to_65": "", under_40: "" }, membership_tenure: "", members_joined_2_years: "", reasons_joined: "", members_left_2_years: "", reasons_left: "",
    key_challenges: "", primary_interests: "", upcoming_projects: "", projects_that_dont_work: ""
  };
  const STEPS = ["About your club", "Your members", "Goals and projects"];
  const draftKey = (clubId) => "cc_review_form_" + clubId;
  const loadDraft = (clubId) => { try { return { ...EMPTY, ...JSON.parse(localStorage.getItem(draftKey(clubId)) || "{}") }; } catch (e) { return { ...EMPTY }; } };

  function Form({ clubId, onStarted, runNote, canRun }) {
    const [step, setStep] = React.useState(0);
    const [f, setF] = React.useState(() => 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 } })) });
    const ok = [!!f.location.trim(), true, true][step];
    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/review", { form: f }, { 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, "Run a Review"), h("span", { className: "cc-pill quiet" }, "Step " + (step + 1) + " of 3: " + STEPS[step])),
      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" },
          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("label", { className: "cc-field" }, "Website (optional)", h("input", { placeholder: "https://", ...bind("website") }), h("span", { className: "cc-hint" }, "We read the public pages to see what a stranger sees.")),
        h("label", { className: "cc-field" }, "Facebook page (optional)", h("input", { placeholder: "https://www.facebook.com/yourclub", ...bind("facebook") }), h("span", { className: "cc-hint" }, "We look at your latest posts. Public pages only.")),
        h("label", { className: "cc-field" }, "Instagram account (optional)", h("input", { placeholder: "https://www.instagram.com/yourclub", ...bind("instagram") }), h("span", { className: "cc-hint" }, "We look at your profile and latest posts. Public accounts only.")),
        h("label", { className: "cc-field" }, "Your community", h("input", { placeholder: "For example: coastal town, many retirees, growing young families", ...bind("community_type") })),
        h("label", { className: "cc-field" }, "Club feel, in a sentence", h("input", { placeholder: "For example: friendly, informal, project-focused", ...bind("club_vibe") })),
        h("div", { className: "cc-grid2" },
          h("label", { className: "cc-field" }, "How you meet", h("input", { placeholder: "In person, online or hybrid; dinner or breakfast", ...bind("meeting_format") })),
          h("label", { className: "cc-field" }, "When you meet", h("input", { placeholder: "For example: Tuesdays 6:30pm", ...bind("meeting_time") })))),
      step === 1 && h("div", null,
        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" }, "How long have people been members?", h("input", { placeholder: "For example: 6 under 3 years, 15 for 3 to 10, 17 over 10", ...bind("membership_tenure") })),
        h("div", { className: "cc-grid2" },
          h("label", { className: "cc-field" }, "Joined in the last two years", h("input", { type: "number", min: "0", ...bind("members_joined_2_years") })),
          h("label", { className: "cc-field" }, "Left in the last two years", h("input", { type: "number", min: "0", ...bind("members_left_2_years") }))),
        h("label", { className: "cc-field" }, "Why did people join?", h("textarea", { rows: 2, ...bind("reasons_joined") })),
        h("label", { className: "cc-field" }, "Why did people leave?", h("textarea", { rows: 2, ...bind("reasons_left") }))),
      step === 2 && h("div", null,
        h("label", { className: "cc-field" }, "Your biggest challenges", h("textarea", { rows: 3, ...bind("key_challenges") })),
        h("label", { className: "cc-field" }, "What the club most wants to achieve", h("textarea", { rows: 3, ...bind("primary_interests") })),
        h("label", { className: "cc-field" }, "Projects coming up", h("textarea", { rows: 2, ...bind("upcoming_projects") })),
        h("label", { className: "cc-field" }, "Projects or ideas that have not worked", h("textarea", { rows: 2, ...bind("projects_that_dont_work") })),
        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(step - 1) }, "Back"),
        step < 2
          ? h("button", { className: "cc-btn primary", disabled: !ok, onClick: () => setStep(step + 1) }, "Next")
          : h("button", { className: "cc-btn primary lg", disabled: busy || !canRun, onClick: go }, busy ? "Starting…" : "Run my Review")));
  }

  /* ---------- Word export (docx library loaded on first use) ---------- */
  function loadDocx() {
    if (window.docx) return Promise.resolve();
    return new Promise((res, rej) => {
      const s = document.createElement("script");
      s.src = "https://cdn.jsdelivr.net/npm/docx@8.5.0/build/index.umd.min.js";
      s.onload = res;
      s.onerror = () => rej(new Error("Could not load the Word export. Check your connection and try again."));
      document.head.appendChild(s);
    });
  }
  async function downloadWord(markdownText, club) {
    await loadDocx();
    const brand = getComputedStyle(document.documentElement).getPropertyValue("--b-primary").trim().replace("#", "");
    const doc = window.CCReviewDocx.build(window.docx, markdownText, { club, 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 = ("Membership Strategy Audit - " + (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);
  }

  /* ---------- a report ---------- */
  function Report({ clubId, club, id, onBack, onChanged }) {
    const [wordBusy, setWordBusy] = React.useState(false);
    const [r, setR] = React.useState(null);
    const [err, setErr] = React.useState(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.status === "running") { wasRunning = true; t = setTimeout(load, 8000); }
        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 html = React.useMemo(() => (r && r.markdown ? markdown(r.markdown) : ""), [r && r.markdown]);
    return h("div", null,
      h("button", { className: "cc-link", onClick: onBack }, "← All reports"),
      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 Review is being written. We are reading your website, Facebook page and Instagram account, then putting the report together. This usually takes about five minutes. You can leave this page; the report will be in your list when it is 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 Review could not be completed. Your credits were returned.")),
      r && r.status === "done" && h("section", { className: "cc-card cc-rv" },
        h("div", { className: "cc-card-h" }, h("h2", null, r.title), h("div", { className: "cc-row", style: { marginTop: 0 } },
          h("button", { className: "cc-btn sm", disabled: wordBusy, onClick: () => { setWordBusy(true); setErr(null); downloadWord(r.markdown, club).catch((e) => setErr(e.message)).finally(() => setWordBusy(false)); } }, wordBusy ? "Preparing…" : "Download Word"),
          h("button", { className: "cc-btn sm ghost", onClick: () => window.print() }, "Print"))),
        h("div", { className: "cc-rv-body", dangerouslySetInnerHTML: { __html: html } }),
        h("p", { className: "cc-ex-foot" }, "Prepared by Clubcraft Review. This report is written by AI from your answers and your public website, Facebook page and Instagram account. Please check it with your club leadership before you share it.")));
  }

  /* ---------- the Review page ---------- */
  function ReviewApp({ clubId, clubInfo, onGo, onChanged }) {
    const access = clubInfo.me.access.Review;
    const a = (clubInfo.allowances || {}).Review || {};
    const [list, setList] = React.useState(null);
    const [view, setView] = React.useState(null);           // null = list, "new", or a report id
    const [err, setErr] = React.useState(null);
    const load = React.useCallback(() => API.call("GET", "/club/reports?module=Review", null, { club: clubId }).then((r) => setList(r.reports)).catch((e) => setErr(e.message)), [clubId]);
    React.useEffect(() => { setList(null); setView(null); if (access) load(); }, [clubId]);
    if (!access) return h("div", { className: "cc-note" }, "Ask a club admin for access to Review.");
    const running = (list || []).some((r) => r.status === "running");
    const trialRun = a.state === "available" || a.state === "used" || a.state === "ended";
    const canRun = access === "edit" && !running && (a.state === "credits" || a.state === "available");
    const runNote = a.state === "credits" ? "This Review uses 1 of your " + a.runsLeft + " Review runs available this month (AI credits)."
      : a.state === "available" ? "This is your free Review." : "";
    let why = "";
    if (access !== "edit") why = "You can read your club's reports. Edit access to Review is needed to run a new one.";
    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 free Review has been used. Choose a plan to run more.";
    else if (a.state === "ended") why = "Your trial has ended. Choose a plan to run a new Review.";
    if (view && view !== "new") return h(Report, { clubId, club: clubInfo.club.name, id: view, onChanged, onBack: () => { setView(null); load(); } });
    if (view === "new") return h("div", null, h("button", { className: "cc-link", onClick: () => setView(null) }, "← All reports"),
      h(Form, { clubId, canRun, runNote, onStarted: (r) => { 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 Reviews"),
          access === "edit" && h("button", { className: "cc-btn primary", disabled: !canRun, onClick: () => setView("new") }, running ? "A Review is running" : "Run a Review")),
        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 Reviews yet. A Review reads your website and Facebook page and what you tell us about your members, then writes a strategy audit with a 90-day plan."),
        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" : "Running"))))));
  }

  window.CCReview = ReviewApp;
})();
