/* shell.jsx: everything around the Tasks board. Version s31, 2026-11-07 19:30.
 *   signed out   → no ?org= (and none remembered): the Clubcraft welcome with the organisation chooser;
 *                  ?org=<slug> → that organisation's branded welcome; an ?invite= shows the inviting club.
 *                  The organisation is remembered (cc_org) so it survives the hosted sign-up round trip.
 *   no club yet  → find your club: search, ask to join, set it up (14-day trial), or "club not listed"
 *   in a club    → branded top bar (club switcher, Tasks | Club | Delivio tabs)
 *     Tasks      → the Project Planner board (app.jsx) for that club
 *     Club       → trial, Your Current Modules; admins: plan (band and bundle),
 *                  join requests, members, invitations, club branding (if enabled)
 *     Delivio    → super admins: requests needing Delivio, organisations and branding
 * The look comes from the club's brand (cc_api resolves it up the organisation levels).
 */
(function () {
  const API = window.ClubcraftApi;
  const h = React.createElement;
  const ABOUT = !!new URLSearchParams(location.search).get("about");
  const MODULES = ["Review", "Ideas", "Events", "Tasks", "Comms", "Social"];
  const DEMO = !!(window.CCDemo && window.CCDemo.on);
  const pk = (k) => (DEMO ? "demo_" : "") + k;
  const store = {
    get: (k) => { try { return localStorage.getItem(pk(k)); } catch (e) { return null; } },
    set: (k, v) => { try { v == null ? localStorage.removeItem(pk(k)) : localStorage.setItem(pk(k), v); } catch (e) {} }
  };
  // The organisation comes from the join link (?org=<slug>, e.g. app.clubcraft.org/?org=rotary). There is no default: without
  // one (and none remembered from an earlier visit) people choose their organisation first. Remembered so the hosted sign-up,
  // which returns to /app/ without the query, still lands on the same organisation.
  const ORG = (function () {
    const q = (new URLSearchParams(location.search).get("org") || "").toLowerCase();
    if (/^[a-z0-9-]{1,60}$/.test(q)) { store.set("cc_org", q); return q; }
    return store.get("cc_org") || "";
  })();

  (function keepInvite() {   // kept through the sign-in round trip
    const t = new URLSearchParams(location.search).get("invite");
    if (t) { store.set("cc_invite", t); history.replaceState(null, "", location.pathname + (ORG ? "?org=" + ORG : "")); }
  })();

  /* ---------------- brand ---------------- */
  const VARS = { primary: "--b-primary", primaryDeep: "--b-primary-deep", accent: "--b-accent", wash: "--b-wash", bg: "--b-bg", surface: "--b-surface", ink: "--b-ink", muted: "--b-muted", line: "--b-line" };
  function applyBrand(brand) {
    if (!brand) return;
    const r = document.documentElement.style, t = brand.tokens || {};
    Object.entries(VARS).forEach(([k, v]) => { if (t[k]) r.setProperty(v, t[k]); });
    if (t.font) r.setProperty("--b-font", `"${t.font}", system-ui, -apple-system, "Segoe UI", sans-serif`);
    if (t.display) r.setProperty("--b-display", `"${t.display}", system-ui, -apple-system, "Segoe UI", sans-serif`);
  }
  function Logo({ brand, size = 34 }) {
    const t = (brand && brand.tokens) || {};
    if (brand && brand.logoUrl) return <img className="cc-logo" src={brand.logoUrl} alt="" style={{ height: size }} />;
    if (t.mark === "rotary-wheel") return <img className="cc-logo" src="rotary-wheel.svg" alt="" style={{ height: size, width: size }} />;
    // Clubcraft Portal mark (B1, 2026-11-13), small version from Platform Strategy/design-system/assets/logo
    return <img className="cc-logo" src="clubcraft-mark.svg?v=1" alt="" style={{ height: size, width: size }} />;
  }

  /* ---------------- small pieces ---------------- */
  function Card({ children, className, title, aside }) {
    return <section className={"cc-card " + (className || "")}>{(title || aside) && <div className="cc-card-h">{title && <h2>{title}</h2>}{aside}</div>}{children}</section>;
  }
  function Err({ e }) { return e ? <div className="cc-err" role="alert">{e}</div> : null; }
  const pill = (status) => ({ active: ["Active", "ok"], lapsed: ["Lapsed", "warn"], not_joined: ["Not joined", "quiet"] }[status] || [status, "quiet"]);
  const money = (n) => CCIntl.money(n);
  const fmtDate = (t) => (t ? new Date(t).toLocaleDateString(CCIntl.locale(), { day: "numeric", month: "short", year: "numeric" }) : "");
  const fileToDataUrl = (f) => new Promise((ok, no) => { const r = new FileReader(); r.onload = () => ok(r.result); r.onerror = no; r.readAsDataURL(f); });

  const ICON = {
    Review: <path d="M9 4h6M8 3h8a1 1 0 0 1 1 1v1h1.5A1.5 1.5 0 0 1 20 6.5v13A1.5 1.5 0 0 1 18.5 21h-13A1.5 1.5 0 0 1 4 19.5v-13A1.5 1.5 0 0 1 5.5 5H7V4a1 1 0 0 1 1-1Zm0 10 2.5 2.5L16 11" />,
    Ideas: <path d="M9 18h6M10 21h4M12 3a6 6 0 0 0-3.5 10.9c.6.4 1 1.1 1 1.8V16h5v-.3c0-.7.4-1.4 1-1.8A6 6 0 0 0 12 3Z" />,
    Events: <path d="M7 3v3M17 3v3M4 9h16M5.5 5h13A1.5 1.5 0 0 1 20 6.5v12a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 4 18.5v-12A1.5 1.5 0 0 1 5.5 5Zm3 8h3v3h-3z" />,
    Tasks: <path d="M4 5h4v14H4zM10 5h4v9h-4zM16 5h4v6h-4z" />,
    Comms: <path d="M4 10v4a1 1 0 0 0 1 1h2l5 4V5L7 9H5a1 1 0 0 0-1 1Zm12-1a4 4 0 0 1 0 6m2.5-8.5a7.5 7.5 0 0 1 0 11" />,
    Social: <path d="M8.6 13.5 15.4 17.5M15.4 6.5 8.6 10.5M18 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM6 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6Zm12 7a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z" />
  };
  Object.assign(ICON, {
    Calendar: <path d="M7 3v3M17 3v3M4 9h16M5.5 5h13A1.5 1.5 0 0 1 20 6.5v12a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 4 18.5v-12A1.5 1.5 0 0 1 5.5 5Zm2.5 7h2v2H8zm4 0h2v2h-2zm4 0h2v2h-2z" />,
    Members: <path d="M3 6h18v12H3zM8 11a2 2 0 1 0 0-4 2 2 0 0 0 0 4zM5.5 16a2.5 2.5 0 0 1 5 0M13 9h5M13 13h4" />,
    Contacts: <path d="M9 11a3 3 0 1 0 0-6 3 3 0 0 0 0 6Zm-5 8a5 5 0 0 1 10 0M16 11a2.5 2.5 0 1 0 0-5M17 14a4.5 4.5 0 0 1 3.5 5" />,
    Finances: <path d="M12 3v18M16.5 7.5H10a2.7 2.7 0 0 0 0 5.4h4a2.7 2.7 0 0 1 0 5.4H7.5" />
  });
  const ModIcon = ({ m }) => <svg className="cc-micon" viewBox="0 0 24 24" aria-hidden="true">{ICON[m]}</svg>;
  const MOD_INFO = {
    Review: "A membership strategy audit built from what you tell us about your club. Shows strengths and gaps, who to attract, and a 90-day plan.",
    Ideas: "Fundraising and event ideas that suit your club’s size, members and community, with rough budgets and what success looks like.",
    Events: "Turns a chosen idea into a full plan: timeline, budget, volunteer roles, promotion and follow-up.",
    Tasks: "A shared task board for projects and events. Everyone can see who is doing what, and what is overdue.",
    Comms: "A marketing plan for the club: who to reach, what to say, and which channels to use.",
    Social: "Writes, designs and schedules posts for Facebook, Instagram and LinkedIn from your club’s events and news."
  };
  Object.assign(MOD_INFO, {
    Calendar: "One shared calendar for everything the club is doing. Add dates yourself, send them from your plans, keep personal entries private, and follow it from your phone.",
    Members: "Your register of members: who belongs, which type, whether they are paid up and when they renew. Import a spreadsheet, record fees, and see how many members count towards your club's price.",
    Contacts: "Everyone connected to your club in one list: members appear automatically, and you add sponsors, suppliers and others, with custom fields and mailing consent.",
    Finances: "Book-keeping for your club: start free with Zoho Books, or step up to Standard for bank feeds and more. Coming soon."
  });


  /* ---------------- landing (no organisation chosen) ---------------- */
  // Where the website's "Start free trial" lands (app.clubcraft.org with no ?org=), at ?about=1, and when ?org= names an
  // organisation that does not exist. Step 1 is choosing the organisation, matching the website's three steps.
  const ORG_REQUEST = "mailto:support@clubcraft.org?subject=" + encodeURIComponent("Please add my organisation to Clubcraft")
    + "&body=" + encodeURIComponent("Organisation name:\nOur club:\nWhere we are:\nYour name and role:\n");
  function OrgChooser() {
    const [orgs, setOrgs] = React.useState(null);
    React.useEffect(() => { API.call("GET", "/orgs", null, { anon: true }).then((r) => setOrgs(r.orgs)).catch(() => setOrgs([])); }, []);
    return (
      <Card title="1. Choose your organisation">
        {!orgs && <p className="cc-muted">Loading...</p>}
        {orgs && orgs.length > 0 && <>
          <p className="cc-muted sm" style={{ marginTop: 0 }}>Pick the organisation your club belongs to. Your club gets its branding, and you can then find your club.</p>
          <div className="cc-orgcards">{orgs.map((o) => (
            <a key={o.slug} className="cc-orgcard" href={"?org=" + o.slug} style={o.primary ? { borderTopColor: o.primary } : null}>
              {o.logoUrl ? <img src={o.logoUrl} alt="" style={{ height: 44, maxWidth: 160, objectFit: "contain" }} /> : <Logo size={44} />}
              <b>{o.name}</b><span className="cc-muted sm">Choose {o.name}</span>
            </a>))}</div>
        </>}
        <p className="cc-muted sm">Organisation not listed? <a href={ORG_REQUEST}>Ask us to add it</a> and we will set it up for you, usually within 2 working days.</p>
      </Card>
    );
  }
  function Landing({ notFound, signedIn }) {
    const STEPS = [
      ["1", "Choose your organisation", "Pick it from the list. If it isn't there yet, ask us and we'll set it up for you."],
      ["2", "Find your club and start your free trial", "Create an account, find your club and set it up as its first admin. Every app for 14 days, nothing to pay today."],
      ["3", "Bring in your members and start planning", "Import your member list, then use the guided forms to find a project idea, plan it and tell the community."]
    ];
    return (
      <div className="cc-page cc-hero-bg"><div className="cc-wrap" style={{ maxWidth: 880 }}>
        <div className="cc-welcome" style={{ maxWidth: "none" }}>
          <div className="cc-welcome-top"><Logo size={48} /><div>
            <div className="cc-welcome-k">{notFound ? "We could not find that organisation" : "Welcome to Clubcraft"}</div>
            <h1>Grow your club. Keep your members.</h1>
          </div></div>
          <p>Get seen in your community, run projects people want to join, and give members a reason to come back every week.</p>
          <div className="cc-row">
            {signedIn ? <a className="cc-btn primary lg" href="./">Open Clubcraft</a> : <button className="cc-btn lg" onClick={API.signIn}>Sign in</button>}
            <a className="cc-btn lg ghost" href="?demo=1">Look around the example club</a>
          </div>
        </div>

        <OrgChooser />

        <Card title="How it starts">
          <ol className="cc-journey">{STEPS.map(([n, head, text]) => <li key={n}><span className="cc-jn" aria-hidden="true">{n}</span><div className="cc-jb"><div className="cc-jh"><b>{head}</b></div><p>{text}</p></div></li>)}</ol>
        </Card>

        <Card title="What is inside">
          <div className="cc-landmods">{MODULES.map((m) => <div key={m}><ModIcon m={m} /><b>{m}</b><p className="cc-muted sm">{MOD_INFO[m]}</p></div>)}</div>
        </Card>
        <div className="cc-powered">Powered by Clubcraft</div>
      </div></div>
    );
  }

  /* ---------------- signed out ---------------- */
  function SignedOut() {
    const [ctx, setCtx] = React.useState(null);
    React.useEffect(() => {
      const token = store.get("cc_invite");
      const p = token
        ? API.call("GET", "/invitations/preview?token=" + encodeURIComponent(token), null, { anon: true }).then((r) => ({ invite: r }))
        : API.call("GET", "/orgs/" + ORG, null, { anon: true }).then((r) => ({ org: r }));
      p.then((c) => { applyBrand((c.invite || c.org).brand); setCtx(c); }).catch(() => setCtx({}));
    }, []);
    if (!ctx) return <div className="cc-page center"><p className="cc-muted">Loading…</p></div>;
    if (!ctx.invite && !ctx.org) return <Landing notFound={true} />;
    const brand = (ctx.invite || ctx.org || {}).brand;
    return (
      <div className="cc-page center cc-hero-bg">
        <div className="cc-welcome">
          <div className="cc-welcome-top"><Logo brand={brand} size={48} /><div>
            <div className="cc-welcome-k">{ctx.invite ? "You're invited" : "Welcome"}</div>
            <h1>{ctx.invite ? ctx.invite.club.name : ctx.org ? "Clubcraft for " + (brand.labels.global || ctx.org.org.name) : "Welcome to Clubcraft"}</h1>
          </div></div>
          <p>{ctx.invite ? "Sign in, or create an account with the email address the invitation was sent to." : "Plan projects, run reviews and promote your club in one place. Sign in to your club, or create an account to find it and join."}</p>
          <div className="cc-row">
            <button className="cc-btn primary lg" onClick={API.signIn}>Sign in</button>
            <button className="cc-btn lg" onClick={API.signUp}>Create an account</button>
          </div>
          {!ctx.invite && <p className="cc-muted sm"><a href="?demo=1">Look around the example club, no sign-in needed</a> &middot; <a href="?about=1">Not your organisation? Choose another</a></p>}
          {!ctx.invite && <div className="cc-welcome-mods">{MODULES.map((m) => <span key={m}><ModIcon m={m} />{m}</span>)}</div>}
          <div className="cc-powered">Powered by Clubcraft</div>
        </div>
      </div>
    );
  }

  /* ---------------- find, join or set up a club ---------------- */
  function FindClub({ me, onDone, onCancel }) {
    const [org, setOrg] = React.useState(null);
    const [q, setQ] = React.useState("");
    const [res, setRes] = React.useState(null);
    const [err, setErr] = React.useState(null);
    const [pick, setPick] = React.useState(null);
    const [form, setForm] = React.useState({});
    const [busy, setBusy] = React.useState(false);
    React.useEffect(() => { API.call("GET", "/orgs/" + ORG, null, { anon: true }).then((o) => { setOrg(o); applyBrand(o.brand); }).catch((e) => setErr(e.message)); }, []);
    React.useEffect(() => {
      if (q.trim().length < 4) { setRes(null); return; }
      const t = setTimeout(() => {
        API.call("GET", "/orgs/" + ORG + "/clubs?q=" + encodeURIComponent(q.trim()), null, { anon: true }).then((r) => { setRes(r); setErr(null); }).catch((e) => setErr(e.message));
      }, 300);
      return () => clearTimeout(t);
    }, [q]);
    async function submit() {
      setBusy(true); setErr(null);
      try {
        if (pick.mode === "join") setPick({ ...pick, mode: "sent", result: await API.call("POST", "/clubs/" + pick.club.id + "/join-requests", { roleInClub: form.role, message: form.message }) });
        else if (pick.mode === "start") { const r = await API.call("POST", "/clubs/" + pick.club.id + "/start", { secondAdminEmail: form.admin2 || undefined, country: form.country || CCIntl.country(), timezone: form.timezone || undefined }); onDone(r.clubId, r.secondAdminInvite); }
        else if (pick.mode === "notlisted") {
          await API.call("POST", "/club-add-requests", { orgSlug: ORG, districtId: form.district || undefined, clubName: form.clubName, name: me.user.name, email: me.user.email, role: form.role, note: form.note }, { anon: true });
          setPick({ mode: "listedsent" });
        }
      } catch (e) { setErr(e.message); } finally { setBusy(false); }
    }
    const f = (k) => ({ value: form[k] || "", onChange: (e) => setForm({ ...form, [k]: e.target.value }) });
    const L = org ? org.brand.labels : { area: "District" };
    const trial = org && org.trial;
    const groups = {};
    (res ? res.clubs : []).forEach((c) => { (groups[c.district || "Other"] = groups[c.district || "Other"] || []).push(c); });

    if (pick && pick.mode === "sent") {
      const r = pick.result;
      return <div className="cc-page center"><Card className="narrow">
        <h1>Request sent</h1>
        <p>We've sent your request to the {r.admins === 1 ? "admin" : r.admins + " admins"} of <b>{pick.club.name}</b>. You'll get access once one of them approves it.</p>
        {r.lapsed && <div className="cc-note">This club's subscription has lapsed. The admins have been asked to renew.</div>}
        <p className="cc-muted sm">If nobody answers within 5 working days, Clubcraft support will follow up with the club.</p>
        <div className="cc-row"><button className="cc-btn" onClick={() => onDone(null)}>Done</button></div>
      </Card></div>;
    }
    if (pick && pick.mode === "listedsent") return <div className="cc-page center"><Card className="narrow"><h1>Thanks</h1><p>Clubcraft support will check the club and email you, usually within 2 working days.</p><div className="cc-row"><button className="cc-btn" onClick={() => { setPick(null); setForm({}); }}>Back to search</button></div></Card></div>;
    if (pick) {
      const title = pick.mode === "join" ? "Join " + pick.club.name : pick.mode === "start" ? "Set up " + pick.club.name : "Ask for your club to be added";
      return <div className="cc-page center"><Card className="narrow">
        {pick.club && <div className="cc-label">{pick.club.district}</div>}
        <h1>{title}</h1>
        {pick.mode === "join" && <>
          {pick.club.status === "lapsed" && <div className="cc-note">This club's subscription has lapsed. We'll ask its admins to renew.</div>}
          <label className="cc-field">Your role in the club<select {...f("role")}><option value="">Choose…</option>{["Member", "President", "Secretary", "Membership Director", "Treasurer", "Other board member"].map((x) => <option key={x}>{x}</option>)}</select></label>
          <label className="cc-field">Message to the club admins (optional)<textarea rows="3" {...f("message")} /></label>
        </>}
        {pick.mode === "start" && <>
          {trial && <div className="cc-trialbox">
            <b>Free {trial.days}-day trial, every app</b>
            <ul><li>The {trial.bundleName} bundle for up to {trial.upTo} members, with as many logins as you like</li><li>One run each of Review, Ideas, Events and Comms</li><li>One Tasks project and one Social campaign</li><li>No card needed. Choose a plan any time; after {trial.days} days your work stays readable until you do.</li></ul>
          </div>}
          <p className="cc-muted">You'll be the club's first admin.</p>
          <label className="cc-field">Where is your club?<select value={form.country || CCIntl.country()} onChange={(e) => setForm({ ...form, country: e.target.value, timezone: "" })} aria-label="Country">{Object.values(window.CCCountries.COUNTRIES).map((c) => <option key={c.code} value={c.code}>{c.name}</option>)}</select>
            <span className="cc-hint">This sets your currency, time zone, date style and the tax wording on your invoices. You can change the time zone later; the country and currency are fixed once you pay, so tell us if it's wrong.</span></label>
          <label className="cc-field">Time zone<select value={form.timezone || window.CCCountries.country(form.country || CCIntl.country()).defaultZone} onChange={(e) => setForm({ ...form, timezone: e.target.value })} aria-label="Time zone">{window.CCCountries.country(form.country || CCIntl.country()).zones.map(([id, label]) => <option key={id} value={id}>{label}</option>)}</select></label>
          {(() => { const dz = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone; } catch (e) { return null; } })(), cc = window.CCCountries.country(form.country || CCIntl.country()), cur = form.timezone || cc.defaultZone;
            return dz && dz !== cur ? <p className="cc-hint">Your device is on {dz.replace(/_/g, " ")} time, but we have set your club's time zone to {cur.replace(/_/g, " ")}, from the country you chose. {cc.zones.some(([id]) => id === dz) && <button type="button" className="cc-link" onClick={() => setForm({ ...form, timezone: dz })}>Use {dz.replace(/_/g, " ")} instead</button>}</p> : null; })()}
          <label className="cc-field">Second admin's email (recommended)<input type="email" placeholder="president@yourclub.org" {...f("admin2")} /><span className="cc-hint">Clubs change people every year. A second admin keeps the club running if you step down.</span></label>
        </>}
        {pick.mode === "notlisted" && <>
          <label className="cc-field">Club name<input {...f("clubName")} /></label>
          <label className="cc-field">{L.area}<select {...f("district")}><option value="">Not sure</option>{(org ? org.districts : []).map((d) => <option key={d.id} value={d.id}>{d.name}</option>)}</select></label>
          <label className="cc-field">Your role<input {...f("role")} /></label>
          <label className="cc-field">Anything we should know<textarea rows="3" {...f("note")} /></label>
        </>}
        <Err e={err} />
        <div className="cc-row between"><button className="cc-btn ghost" onClick={() => { setPick(null); setErr(null); }}>Back</button>
          <button className="cc-btn primary" disabled={busy || (pick.mode === "notlisted" && !(form.clubName || "").trim())} onClick={submit}>{busy ? "Sending…" : pick.mode === "join" ? "Send request" : pick.mode === "start" ? "Start free trial" : "Send to Clubcraft support"}</button></div>
      </Card></div>;
    }
    return (
      <div className="cc-page"><div className="cc-wrap">
        <div className="cc-pagehead"><div>
          <div className="cc-label">{org ? org.org.name : "Clubcraft"}</div>
          <h1>Find your club</h1>
          <p className="cc-muted">Search for your club to join it, or set it up with a free {trial ? trial.days : 14}-day trial.</p>
        </div>{onCancel && <button className="cc-btn" onClick={onCancel}>Back to my club</button>}</div>
        {me.pendingRequests && me.pendingRequests.length > 0 && <div className="cc-note">Waiting for approval: {me.pendingRequests.map((p) => p.clubName).join(", ")}.</div>}
        <Card>
          <label className="cc-search"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" /></svg>
            <input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder="Club name or town (at least 4 letters)" aria-label="Club name or town" /></label>
          <Err e={err} />
          {res && res.clubs.length === 0 && <div className="cc-empty">No club matches "{q}". Check the spelling, or ask for your club to be added.</div>}
          {Object.keys(groups).sort().map((d) => (
            <div className="cc-group" key={d}><div className="cc-group-h">{d}</div>
              {groups[d].map((c) => {
                const [pl, tone] = pill(c.status);
                const sub = c.status === "active" ? `${c.admins} admin${c.admins === 1 ? "" : "s"}` : c.status === "lapsed" ? "Subscription not renewed" : "Not on Clubcraft yet";
                return <div className="cc-hit" key={c.id}>
                  <div><div className="cc-hit-n">{c.name}</div><div className="cc-muted sm">{sub}</div></div>
                  <span className={"cc-pill " + tone}>{pl}</span>
                  <button className={"cc-btn sm" + (c.status === "not_joined" ? " primary" : "")} onClick={() => { setForm({}); setPick({ club: c, mode: c.status === "not_joined" ? "start" : "join" }); }}>{c.status === "not_joined" ? "Start free trial" : "Ask to join"}</button>
                </div>;
              })}
            </div>
          ))}
          <p className="cc-muted sm" style={{ marginTop: 14 }}>Club not listed? <button className="cc-link" onClick={() => { setForm({}); setPick({ mode: "notlisted" }); }}>Ask for it to be added</button></p>
        </Card>
      </div></div>
    );
  }

  /* ---------------- Allowances: what each app allows right now ---------------- */
  // `a` comes from /club `allowances[module]`: { unit, state, limit, used }.
  // state: available | used | ended | unlimited | locked.
  const plural = (n, u) => n + " " + u + (n === 1 ? "" : "s");
  function allow(m, a) {
    if (!a) return null;
    const u = a.unit;
    if (a.state === "credits") return { tone: "ok", short: a.runsLeft + " left", text: m === "Review" ? "Free with your plan. Each Review uses AI credits; about " + plural(a.runsLeft, "run") + " left this month." : "Included in your plan. Each run uses AI credits; about " + plural(a.runsLeft, "run") + " left this month." };
    if (a.state === "nocredits") return { tone: "warn", short: "No credits", text: "This month's AI credits are used up. They renew each month, or a club admin can buy a top-up (My club, AI allowance)." };
    if (a.state === "unlimited") return { tone: "ok", short: "", text: "Included in your plan." };
    if (a.state === "locked") return { tone: "quiet", short: "", text: "Not part of your plan." };
    if (a.state === "readonly") return { tone: "warn", short: "Read-only", text: "No longer in your plan. Your work stays readable until " + fmtDate(a.until) + ", then " + m + " switches off unless you add it back." };
    if (a.state === "ended") return { tone: "bad", short: "Ended", text: m === "Review" ? "Your trial has ended. You can still read your results." : "Your trial has ended. What you made stays readable." };
    const left = a.limit - a.used;
    if (a.state === "used") return { tone: "warn", short: "Used", text: m === "Review" ? "Your trial run is used. You can read the results. Review is free with any plan, using your AI credits." : "You have used the " + u + " included in your trial. A plan removes the limit." };
    return { tone: "good", short: left + " left", text: "Your trial includes " + plural(left, u) + "." + (m === "Review" ? " Review is free with any plan, using your AI credits." : "") };
  }

  function AppsTable({ allowances, access, isAdmin, onPlan, onOpen }) {
    return (
      <Card title="Your apps" className="cc-modcard">
        <div className="cc-apps" role="table" aria-label="Your apps">
          {MODULES.map((m) => {
            const a = allowances && allowances[m], t = allow(m, a), can = !!access[m];
            const stuck = a && (a.state === "used" || a.state === "ended" || a.state === "locked" || a.state === "nocredits" || a.state === "readonly");
            return (
              <div className="cc-app" role="row" key={m}>
                <ModIcon m={m} />
                <div className="cc-app-t"><b>{m}</b><span>{t ? t.text : MOD_INFO[m]}</span></div>
                {t && t.short && <span className={"cc-pill " + (t.tone === "good" ? "ok" : t.tone === "bad" ? "bad" : t.tone)}>{t.short}</span>}
                <div className="cc-app-act">
                  {can && <button className="cc-btn sm primary" onClick={() => onOpen(m)}>Open</button>}
                  {stuck && (isAdmin ? <button className="cc-btn sm" onClick={onPlan}>{a.state === "nocredits" ? "Plan and AI" : a.state === "readonly" ? "Add it back" : "Choose a plan"}</button> : <span className="cc-muted sm">Ask your club admin</span>)}
                  {!can && !stuck && <button className="cc-btn sm" onClick={() => onOpen(m)}>See what it does</button>}
                </div>
              </div>
            );
          })}
          {TOOLS.map((m) => (
            <div className="cc-app" role="row" key={m}>
              <ModIcon m={m} />
              <div className="cc-app-t"><b>{m}</b><span>{MOD_INFO[m]}</span></div>
              <span className={"cc-pill " + (m === "Finances" ? "trial" : "ok")}>{TOOL_TAG[m]}</span>
              <div className="cc-app-act"><button className="cc-btn sm primary" onClick={() => onOpen(m)}>Open</button></div>
            </div>
          ))}
        </div>
        <p className="cc-muted sm" style={{ marginTop: 10 }}><span className="cc-free-badge xs">FREE</span> Review is free with any paid plan. Each run uses AI credits.</p>
      </Card>
    );
  }

  /* ---------------- My second time zone ---------------- */
  // Club time stays the real clock. A member can add a second zone to read times in as well (travelling, or a member who lives elsewhere).
  const saveSecond = (clubId, zone) => API.call("PUT", "/club/me/second-zone", { zone }, { club: clubId });
  function SecondZoneCard({ clubId, club, onSaved }) {
    const cur = club.me.secondZone || "", clubZone = (club.club.region || {}).timezone;
    const [v, setV] = React.useState(cur), [note, setNote] = React.useState(null);
    const dz = CCIntl.deviceZone();
    async function save(next) {
      setV(next); setNote(null);
      try { await saveSecond(clubId, next || null); CCIntl.setSecond(next || null); setNote(CCIntl.t("second.saved")); onSaved && onSaved(); } catch (e) { setNote(CCIntl.t("second.not_saved", { error: e.message })); }
    }
    const opts = CCIntl.allZones();
    return (
      <Card title={CCIntl.t("second.title")}>
        <p className="cc-muted sm" style={{ marginTop: 0 }}>{CCIntl.t("second.intro", { zone: CCIntl.zoneName(clubZone) })}</p>
        <label className="cc-field">{CCIntl.t("second.also")}
          <select value={v} onChange={(e) => save(e.target.value)} aria-label={CCIntl.t("second.aria")}>
            <option value="">{CCIntl.t("second.club_only", { zone: CCIntl.zoneName(clubZone) })}</option>
            <option value="device">{dz ? CCIntl.t("second.device_named", { zone: CCIntl.zoneName(dz) }) : CCIntl.t("second.device")}</option>
            {opts.map(([id, label]) => <option key={id} value={id}>{label}</option>)}
            {v && v !== "device" && !opts.some(([id]) => id === v) && <option value={v}>{v}</option>}
          </select></label>
        {note && <span className="cc-muted sm" role="status">{note}</span>}
      </Card>
    );
  }
  // Always shown while a person is working from another zone: says club time is the real clock and where the brackets come from.
  function WorkingFromStrip({ clubInfo, onChange }) {
    const clubZone = (clubInfo.club.region || {}).timezone, z = CCIntl.workingFrom(clubZone);
    if (!z || !clubZone) return null;
    return <div className="cc-attn info" role="status"><span>{CCIntl.t("working.strip", { club: CCIntl.zoneName(clubZone), zone: CCIntl.zoneName(z) })}</span><button className="cc-btn sm ghost" onClick={onChange}>{CCIntl.t("working.change")}</button></div>;
  }
  // Shown once when the device is in a different zone from the club and no second zone is set: offers it, never switches it on by itself.
  function TravelBanner({ clubInfo, clubId, onSaved }) {
    const dz = CCIntl.deviceZone(), clubZone = (clubInfo.club.region || {}).timezone;
    const key = "cc_travel_" + clubId + "_" + (dz || ""), [hidden, setHidden] = React.useState(!!store.get(key)), [done, setDone] = React.useState(false);
    // After "Yes" the club info reloads with the zone set, so the question disappears: say what changed and where to see it.
    if (done) return <div className="cc-attn info" role="status"><span>{CCIntl.t("travel.done", { zone: CCIntl.zoneName(dz) })}</span><button className="cc-btn sm ghost" onClick={() => setDone(false)}>{CCIntl.t("travel.ok")}</button></div>;
    if (hidden || !dz || !clubZone || clubInfo.me.secondZone || dz === clubZone) return null;
    try { const now = Date.now(); if (CCIntl.zoneOffset(now, dz) === CCIntl.zoneOffset(now, clubZone)) return null; } catch (e) { return null; }
    const no = () => { store.set(key, "1"); setHidden(true); };
    return (
      <div className="cc-attn info" role="status">
        <span>{CCIntl.t("travel.msg", { device: CCIntl.zoneName(dz), club: CCIntl.zoneName(clubZone) })}</span>
        <span className="cc-row" style={{ marginTop: 0 }}>
          <button className="cc-btn sm primary" onClick={async () => { try { await saveSecond(clubId, "device"); CCIntl.setSecond("device"); setDone(true); onSaved && onSaved(); } catch (e) { no(); } }}>{CCIntl.t("travel.yes")}</button>
          <button className="cc-btn sm ghost" onClick={no}>{CCIntl.t("travel.no")}</button>
        </span>
      </div>
    );
  }

  /* One short line on every screen when something needs attention (dismiss for the day). */
  function AttentionBanner({ clubInfo, isAdmin, onPlan }) {
    const key = "cc_dismiss_" + clubInfo.club.id, today = new Date().toDateString();
    const [hidden, setHidden] = React.useState(store.get(key) === today);
    const t = clubInfo.trial, al = clubInfo.allowances || {};
    const stuck = MODULES.filter((m) => al[m] && (al[m].state === "used"));
    let msg = null, tone = "info";
    if (t && t.expired) { msg = CCIntl.t("trial.ended"); tone = "bad"; }
    else if (t && !t.unlimited && t.daysLeft <= 3) { msg = CCIntl.t("trial.ends_soon", { days: plural(t.daysLeft, "day") }); tone = "warn"; }
    else if (stuck.length) { msg = CCIntl.t(stuck.length === 1 ? "trial.limit.one" : "trial.limit.many", { apps: stuck.join(", ") }); tone = "warn"; }
    if (!msg || (hidden && !(t && t.expired))) return null;
    return (
      <div className={"cc-attn " + tone} role="status">
        <span>{msg} {isAdmin ? "" : CCIntl.t("trial.ask_admin")}</span>
        <span className="cc-row" style={{ marginTop: 0 }}>
          {isAdmin && <button className="cc-btn sm primary" onClick={onPlan}>{CCIntl.t("action.choose_plan")}</button>}
          {!(t && t.expired) && <button className="cc-btn sm ghost" onClick={() => { store.set(key, today); setHidden(true); }}>{CCIntl.t("action.dismiss")}</button>}
        </span>
      </div>
    );
  }

  /* ---------------- Seats and access (admins) ---------------- */
  // How many members count towards the club's price band (from the Members register). Display only: nothing is billed from it yet.
  function MemberBand({ reg, onGo }) {
    if (!reg) return null;
    const T = CCIntl.t;
    const b = reg.band, pct = b ? Math.min(100, Math.round(100 * reg.counting / b.upTo)) : 100;
    return (
      <Card title={T("band.title")} aside={<button className="cc-btn sm" onClick={() => onGo && onGo("mod:Members")}>{T("band.open")}</button>}>
        {!reg.started ? <p className="cc-muted">{T("band.not_started")}</p> : <>
          <div className="cc-lic">
            <div><b>{reg.counting}</b><span>{T(reg.counting === 1 ? "band.counts.one" : "band.counts.many")}</span></div>
            <div><b>{b ? T("band.up_to", { n: b.upTo }) : T("band.over_max")}</b><span>{b ? T("band.price_hint", { price: CCIntl.money(window.CCPricing.bandPrice((window.CCPricing.BANDS.find((x) => x.upTo === b.upTo) || {}).code, CCIntl.currency())) }) : T("band.your_band")}</span></div>
            {b && <div><b>{reg.spare}</b><span>{T(reg.spare === 1 ? "band.spare.one" : "band.spare.many")}</span></div>}
          </div>
          {b && <div className="cc-bar" role="img" aria-label={T("band.bar", { counting: reg.counting, upTo: b.upTo })}><span style={{ width: pct + "%" }} /></div>}
          {reg.nearTop && <div className="cc-note trial">{T("band.near_top", { next: reg.next.upTo })}</div>}
          {reg.contactUs && <div className="cc-note trial">{T("band.contact_us", { over: reg.over })}</div>}
        </>}
        <p className="cc-muted sm">{T("band.footnote")}</p>
      </Card>
    );
  }

  function SeatsAccess({ c, onAssign, onPlan, choosing }) {
    const T = CCIntl.t;
    const plan = c.plan, trial = c.trial, sub = c.licences.subscription, reg = c.register || {};
    return (
      <Card title={T("yourplan.title")} className="cc-seats" aside={<span className="cc-row" style={{ marginTop: 0 }}><HelpLink />{!choosing && <button className="cc-btn sm" onClick={onPlan}>{sub && !trial ? T("action.change_plan") : T("action.choose_plan")}</button>}</span>}>
        <div className="cc-lic">
          <div><b>{plan.bundleName}{plan.addon ? " + " + plan.addon : ""}</b><span>{trial ? T("yourplan.bundle.trial") : plan.live ? (plan.addon ? T("yourplan.bundle.addon") : T("yourplan.bundle.live")) : T("yourplan.bundle.none")}</span></div>
          <div><b>{plan.upTo ? T("band.up_to", { n: plan.upTo }) : T("yourplan.band.not_set")}</b><span>{reg.started ? T("yourplan.band.counting", { counting: reg.counting }) : T("yourplan.band.label")}</span></div>
          {trial ? <div><b>{T("yourplan.trial")}</b><span>{trial.expired ? T("yourplan.trial.ended") : T("yourplan.trial.ends", { date: fmtDate(trial.endsAt) })}</span></div>
            : sub && <div><b>{sub.billingPeriod === "month" ? T("yourplan.monthly") : T("yourplan.yearly")}</b><span>{sub.termEndAt ? T("yourplan.renews", { date: fmtDate(sub.termEndAt) }) : T("yourplan.billing")}{sub.aiPack !== "none" ? " · " + T("yourplan.ai", { pack: sub.aiPack }) : ""}{plan.assoc ? " · " + T("yourplan.assoc") : ""}</span></div>}
        </div>
        <div className="cc-free-sub">
          <div className="cc-free-h"><span className="cc-free-badge sm">{T("yourplan.free_badge")}</span><div><b>{T("yourplan.free_h")}</b><p>{T("yourplan.free_p")}</p></div></div>
          <div className="cc-free-grid">{MODULES.concat(TOOLS).map((m) => {
            const ro = plan.readOnly && plan.readOnly[m];
            return <div key={m} className={plan.apps.includes(m) ? "" : "cc-off"}><ModIcon m={m} /><span>{m}</span><small>{m === plan.addon ? T("yourplan.app.addon") : plan.apps.includes(m) ? T("yourplan.app.in") : ro ? T("yourplan.app.readonly", { date: fmtDate(ro) }) : T("yourplan.app.out")}</small></div>;
          })}</div>
          <button className="cc-btn sm" onClick={onAssign}>{T("yourplan.open_access")}</button>
        </div>
      </Card>
    );
  }

  /* ---------------- How licensing works (pop-up) ---------------- */
  // Short guide to docs/billing-rules.md. The FAQ link goes live when the FAQ exists.
  const FAQ_URL = null;
  function HelpLink({ label = "How licensing works" }) {
    const [open, setOpen] = React.useState(false);
    React.useEffect(() => {
      if (!open) return;
      const esc = (e) => { if (e.key === "Escape") setOpen(false); };
      document.addEventListener("keydown", esc);
      return () => document.removeEventListener("keydown", esc);
    }, [open]);
    return <>
      <button type="button" className="cc-link cc-help" onClick={() => setOpen(true)}><span aria-hidden="true">?</span>{label}</button>
      {open && <div className="cc-modal-bg" onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}>
        <div className="cc-modal" role="dialog" aria-modal="true" aria-labelledby="cc-help-h">
          <div className="cc-modal-h"><h2 id="cc-help-h">How licensing works</h2><button type="button" className="cc-x" aria-label="Close" onClick={() => setOpen(false)} autoFocus>×</button></div>
          <div className="cc-modal-b">
            <h3>One price for the club</h3>
            <p>There are <b>no seats</b>. Everyone in your club can log in. You pay one price, set by how many members are on your register (the <b>band</b>) and which <b>bundle</b> of apps you choose.</p>
            <h3>Bundles</h3>
            <p><b>Core</b> runs the club: Members, Contacts, Calendar and Review. <b>Grow</b> adds the planners and the to-do lists: Ideas, Events, Comms and Tasks. <b>Complete</b> adds Social and Finances. A bigger bundle costs a little more each month, and a little more again for clubs of 500 members or more.</p>
            <h3>Adding one app to Core</h3>
            <p>On Core you can add <b>one</b> app on its own, for example Tasks or Finances. If you want two or more, a bundle works out cheaper and the plan screen shows you the difference.</p>
            <h3>Dropping an app</h3>
            <p>If you move to a smaller bundle, or your trial ends on a plan without an app you used, that app stays <b>readable for 60 days</b> so you can look back at your work or copy it. After that it switches off until you add it back. Nothing is deleted.</p>
            <h3>Who can do what</h3>
            <p>On the <b>Access</b> page, a club admin sets each person to <b>Admin</b>, <b>Edit</b> or <b>View</b> in each app, or switches an app off for them. You can have several admins.</p>
            <h3>Yearly or monthly</h3>
            <p><b>Yearly</b> is the listed price and is paid up front. <b>Monthly</b> costs 25% more (the yearly price divided by 0.8). You can move from monthly to yearly at any time; yearly moves to monthly at renewal.</p>
            <h3>Associations and service clubs</h3>
            <p>Incorporated associations and service clubs get <b>20% off</b>. Enter your association or club number when you choose a plan.</p>
            <p>{CCIntl.taxNote()}</p>
            <h3>Changing your plan</h3>
            <p>A step up (a bigger band or bundle) is charged for the rest of your current month or year, so everything renews on <b>one date</b>. On a yearly plan more than 6 months old, the whole plan renews for 12 months from today instead, with credit for the unused time. A smaller plan takes effect at your next renewal, with no part refunds.</p>
            <h3>Your band and growing</h3>
            <p>Active, grace, life and honorary members count once each. Going a little over your band is allowed for 30 days before the next band applies.</p>
            <h3>Free Review and trial</h3>
            <p>Every club gets <b>1 free Review</b>. New clubs also get a 14-day trial of the Complete bundle for up to 25 members; after it ends, everything stays readable until you choose a plan.</p>
            <h3>AI allowance</h3>
            <p>Every plan includes a monthly AI allowance for Reviews, plans and Social posts. Any plan can add a monthly <b>AI pack</b>. If you run out part-way through a month, a club admin can buy a one-off <b>top-up</b> (1,000 credits); top-ups are used after the monthly allowance and last 12 months.</p>
            <p>The number of posts or plans shown for each pack is <b>an estimate only</b>. It depends on how many drafts, rewrites and pictures your club asks for.</p>
            <p>Small helpers, such as a picture brief or help writing a campaign's set-up text, are free and don't use credits.</p>
          </div>
          <div className="cc-modal-f">{FAQ_URL ? <a className="cc-link" href={FAQ_URL} target="_blank" rel="noopener">Read the FAQ</a> : <span className="cc-muted sm">FAQ coming soon</span>}<button type="button" className="cc-btn" onClick={() => setOpen(false)}>Close</button></div>
        </div>
      </div>}
    </>;
  }

  /* ---------------- Who gets the association rate (pop-up) ---------------- */
  function AssocHelp({ off }) {
    const [open, setOpen] = React.useState(false);
    React.useEffect(() => {
      if (!open) return;
      const esc = (e) => { if (e.key === "Escape") setOpen(false); };
      document.addEventListener("keydown", esc);
      return () => document.removeEventListener("keydown", esc);
    }, [open]);
    return <>
      <button type="button" className="cc-link cc-help" onClick={() => setOpen(true)}><span aria-hidden="true">?</span>{CCIntl.t("assoc.link")}</button>
      {open && <div className="cc-modal-bg" onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}>
        <div className="cc-modal" role="dialog" aria-modal="true" aria-labelledby="cc-assoc-h">
          <div className="cc-modal-h"><h2 id="cc-assoc-h">{CCIntl.t("assoc.title")}</h2><button type="button" className="cc-x" aria-label={CCIntl.t("assoc.close")} onClick={() => setOpen(false)} autoFocus>×</button></div>
          <div className="cc-modal-b">
            <p>{CCIntl.t("assoc.intro", { off: off })}</p>
            <h3>{CCIntl.t("assoc.yes_h")}</h3>
            <ul><li>{CCIntl.t("assoc.yes1")}</li><li>{CCIntl.t("assoc.yes2")}</li><li>{CCIntl.t("assoc.yes3")}</li></ul>
            <h3>{CCIntl.t("assoc.no_h")}</h3>
            <ul><li>{CCIntl.t("assoc.no1")}</li><li>{CCIntl.t("assoc.no2")}</li></ul>
            <p>{CCIntl.t("assoc.number")}</p>
          </div>
          <div className="cc-modal-f"><button type="button" className="cc-btn primary" onClick={() => setOpen(false)}>{CCIntl.t("assoc.close")}</button></div>
        </div>
      </div>}
    </>;
  }

  /* ---------------- plan chooser ---------------- */
  // One price per club: a member band plus a bundle, 20% off for associations, yearly the cheaper way to pay.
  // The sums come from POST /club/quote (lib/pricing.js, docs/billing-rules.md); the card prices use the same engine in the browser (pricing-lib.js).
  function PlanChooser({ clubId, club, onSaved, onCancel }) {
    const trial = club.trial, plan = club.plan, reg = club.register || {};
    const [cat, setCat] = React.useState(null);
    const [band, setBand] = React.useState(null);
    const [bundle, setBundle] = React.useState("grow");
    const [addon, setAddon] = React.useState(null);
    const [assoc, setAssoc] = React.useState(false);
    const [assocNumber, setAssocNumber] = React.useState("");
    const [ai, setAi] = React.useState("none");
    const [period, setPeriod] = React.useState("year");
    const [q, setQ] = React.useState(null);
    const [review, setReview] = React.useState(false);
    const [busy, setBusy] = React.useState(false);
    const [err, setErr] = React.useState(null);
    const sub = club.licences && club.licences.subscription;
    const live = !trial && plan && plan.live && plan.band;
    React.useEffect(() => {
      API.call("GET", "/plans", null, { anon: true }).then((c) => {
        setCat(c);
        const need = c.bands.find((b) => b.upTo >= (reg.counting || 0)) || c.bands[c.bands.length - 1];
        setBand(live ? plan.band : need.code);
        if (live) { setBundle(plan.bundle); setAddon(plan.addon || null); setAssoc(!!plan.assoc); setAi((sub && sub.aiPack) || "none"); setPeriod((sub && sub.billingPeriod) || c.defaultPeriod); }
        else setPeriod(c.defaultPeriod || "year");
      }).catch((e) => setErr(e.message));
    }, []);

    const body = { band, bundle, addon: bundle === "core" ? addon : null, assoc, assocNumber, aiPack: ai, billingPeriod: period };
    const bodyKey = JSON.stringify(body);
    React.useEffect(() => {
      if (!cat || !band) return;
      let on = true;
      const t = setTimeout(() => {
        API.call("POST", "/club/quote", body, { club: clubId }).then((r) => { if (on) { setQ(r); setErr(null); } }).catch((e) => on && setErr(e.message));
      }, 250);
      return () => { on = false; clearTimeout(t); };
    }, [bodyKey, !!cat]);
    if (!cat || !band) return <Err e={err} />;

    const PR = window.CCPricing;
    const currency = CCIntl.currency();     // the club's own price list (provisional for every currency but AUD)
    const lineFor = (b) => PR.lines({ period, band, bundle: b, assoc, aiPack: "none", currency })[0];
    const perMonth = (b) => { const l = lineFor(b); return period === "year" ? l.amount / 12 : l.amount; };
    const per = period === "year" ? "/yr" : "/mth";
    const bandObj = cat.bands.find((b) => b.code === band);
    const needBand = cat.bands.find((b) => b.upTo >= (reg.counting || 0));
    const tooSmall = needBand && bandObj.upTo < needBand.upTo;
    const bundleName = (code) => (cat.bundles.find((b) => b.code === code) || {}).name;
    async function save() {
      setBusy(true); setErr(null);
      try {
        const r = await API.call("POST", "/club/checkout", { ...body, returnUrl: window.location.href.split("#")[0] + "#/admin" }, { club: clubId });
        if (r.live && r.url) { window.location.href = r.url; return; }   // live billing: Zoho takes the payment, then the webhook activates the plan
        const when = r.appliedNowInTest ? " Live billing will apply this at your renewal; test mode applied it now." : "";
        onSaved(`Plan saved: ${money(r.dueToday)} due today, then ${money(r.recurring)} ${period === "year" ? "a year" : "a month"}, ${CCIntl.exTax()} (test mode, no payment taken).${when}`);
      } catch (e) { setErr(e.message); } finally { setBusy(false); }
    }
    const T = CCIntl.t;
    const kindNote = q && ({
      add: T("plan.kind.add", { term: T("term." + (q.period === "year" ? "year" : "month")) }), add_restart: T("plan.kind.add_restart"),
      upgrade: T("plan.kind.upgrade." + (q.period === "year" ? "year" : "month")), to_yearly: T("plan.kind.to_yearly"), downgrade: T("plan.kind.downgrade"),
      swap: T("plan.kind.swap"), at_renewal: T("plan.kind.at_renewal"), none: T("plan.kind.none")
    })[q.kind];
    const lineName = (l) => (l.key === "ai" ? T("plan.line.ai") : l.key === "addon" ? T("plan.line.addon", { app: l.app }) : T("plan.line.bundle", { bundle: l.bundleName, upTo: l.upTo }));
    // Rough number of finished Social posts (caption, a picture and a couple of rewrites) a month of AI credits covers. An estimate only.
    const POST_UNITS = 30;
    const aiUnits = cat.aiUnits || { included: 200, starter: 500, plus: 1000 };
    const postsFor = (pack) => { const n = Math.floor((aiUnits.included + (pack === "none" ? 0 : aiUnits[pack] || 0)) / POST_UNITS); return n >= 10 ? Math.floor(n / 5) * 5 : n; };
    const addonMonthly = (app) => PR.cents(PR.addonPrice(app, band, currency) * (assoc ? 1 - cat.assocOff : 1) * (period === "year" ? 1 : 1 / cat.monthlyDivisor));
    const cur = q && q.currentLines || [];

    if (review && q) {
      const table = (title, ls, recurring, pd, note, tone) => (
        <div className="cc-rev-col"><div className={"cc-band " + tone}>{title}</div>
          {ls.length ? <table><tbody>{ls.map((l) => <tr key={l.key}><td>{lineName(l)}</td><td className="q">{l.key === "ai" ? (l.aiPack === "starter" ? "Starter" : "Plus") : l.key === "addon" ? "Add-on" : ""}</td><td className="num">{money(l.amount)}</td></tr>)}</tbody>
            <tfoot><tr><td colSpan="2">Total</td><td className="num">{money(recurring)}{pd === "month" ? "/mth" : "/yr"}</td></tr></tfoot></table>
            : <p className="cc-muted sm">{note}</p>}
        </div>);
      return (
        <div className="cc-chooser">
          <div className="cc-row between" style={{ marginTop: 0 }}><h3 className="cc-rev-h">Review your order</h3><HelpLink /></div>
          <div className="cc-rev">
            {table("Current plan", cur, q.currentRecurring, q.currentPeriod, trial ? "Free trial: nothing bought yet." : "No plan yet.", "cur")}
            {table("New plan", q.lines, q.recurring, q.period, "", "tot")}
          </div>
          <div className="cc-sum cc-rev-sum">
            <div><span>New {q.period === "year" ? "yearly" : "monthly"} total</span><span className="num">{money(q.recurring)}{q.period === "month" ? "/mth" : "/yr"}</span></div>
            {assoc && <div className="save"><span>Association discount</span><span>{Math.round(cat.assocOff * 100)}% off</span></div>}
            {(q.kind === "add" || (q.kind === "upgrade" && q.period === "month")) && <div className="bill"><span>Charge for the rest of this {q.period === "year" ? "term" : "month"}</span><span className="num">{money(q.charges.reduce((a, c) => a + c.amount, 0))}</span></div>}
            {q.credit > 0 && <div className="save"><span>Credit ({q.creditWhy})</span><span className="num">−{money(q.credit)}</span></div>}
            <div className="due"><span>Due today</span><span className="num">{money(q.dueToday)}</span></div>
            <div className="bill"><span>{q.effectiveAt ? "Takes effect" : "Renews"}</span><span>{fmtDate(q.effectiveAt || q.renewsAt)}</span></div>
            <p className="cc-hint">{CCIntl.taxNote()}</p>
            {kindNote && <p className="cc-hint">{kindNote}</p>}
          </div>
          {q.losing && q.losing.length > 0 && <div className="cc-note warn">{q.losing.join(", ")} {q.losing.length === 1 ? "is" : "are"} not in this plan. {q.losing.length === 1 ? "It stays" : "They stay"} readable for {q.graceDays || 60} days{q.effectiveAt ? " after the change takes effect" : ""}, then switch off until added back. Nothing is deleted.</div>}
          <Err e={err} />
          <div className="cc-row between">
            <button className="cc-btn ghost" onClick={() => setReview(false)}>Back to edit</button>
            <button className="cc-btn primary" disabled={busy || cat.checkout === "unavailable"} onClick={save}>{busy ? (cat.checkout === "live" ? "Opening payment page…" : "Saving…") : cat.checkout === "test" ? "Confirm and continue to payment (test)" : "Continue to payment"}</button>
          </div>
          <p className="cc-muted sm" style={{ textAlign: "right" }}>{cat.checkout === "test" ? "Test mode: no card and no payment. Confirming saves the plan." : ""}</p>
        </div>
      );
    }
    return (
      <div className="cc-chooser">
        <div className="cc-row between" style={{ marginTop: 0 }}><span className="cc-muted sm">Pick how many members you have, then a bundle. Everyone in the club can log in, whatever the band.</span><HelpLink /></div>
        <div className="cc-period" role="radiogroup" aria-label="Billing period">
          <button role="radio" aria-checked={period === "year"} className={period === "year" ? "on" : ""} onClick={() => setPeriod("year")}>Yearly <span className="cc-save">Save {cat.monthlyExtra ? Math.round((1 - 1 / (1 + cat.monthlyExtra / 100)) * 100) : 20}%</span></button>
          <button role="radio" aria-checked={period === "month"} className={period === "month" ? "on" : ""} onClick={() => setPeriod("month")}>Monthly</button>
        </div>
        <label className="cc-field">Members in your club
          <select value={band} onChange={(e) => setBand(e.target.value)} aria-label="Member band">
            {cat.bands.map((b, i) => <option key={b.code} value={b.code}>{i === 0 ? "Up to " : `${cat.bands[i - 1].upTo + 1} to `}{b.upTo} members</option>)}
          </select>
          <span className="cc-hint">{reg.started ? `${reg.counting} members count now (active, grace, life and honorary).` : "Start your register in Members to see your count."} Over {cat.bands[cat.bands.length - 1].upTo}? Contact Clubcraft for a quote.</span>
        </label>
        {tooSmall && <div className="cc-note warn">Your {reg.counting} members need the up to {needBand.upTo} band or bigger.</div>}
        <div className="cc-plans">{cat.bundles.map((b) => {
          const on = bundle === b.code;
          return (
            <button type="button" key={b.code} className={"cc-plan" + (on ? " on" : "") + (b.code === "complete" ? " best" : "")} aria-pressed={on} onClick={() => setBundle(b.code)}>
              <div className="cc-plan-top"><span className="cc-plan-l">{b.name}</span>{b.code === "complete" && <span className="cc-plan-star">{CCIntl.t("plan.popular")}</span>}</div>
              <span className="cc-plan-d">{CCIntl.t("plan.bundle." + b.code)}</span>
              <span className="cc-chips">{(b.code === "core" ? b.apps : b.adds).map((m) => <span key={m}>{b.code === "core" ? m : "+ " + m}</span>)}</span>
              <span className="cc-plan-p">{money(perMonth(b.code))}<small>/mth {CCIntl.exTax()}</small></span>
              <span className="cc-plan-sub">{period === "year" ? `billed yearly (${money(lineFor(b.code).amount)})` : "billed monthly"}</span>
            </button>
          );
        })}</div>
        <p className="cc-hint cc-extax"><b>{CCIntl.taxNote()}</b></p>
        {bundle === "core" && cat.addons && <div className="cc-field">
          <label>Add one app to Core (optional)
            <select value={addon || ""} onChange={(e) => setAddon(e.target.value || null)} aria-label="Add one app to Core">
              <option value="">No add-on</option>
              {Object.keys(cat.addons).map((app) => <option key={app} value={app}>{app} · {money(addonMonthly(app))}/mth</option>)}
            </select>
          </label>
          <span className="cc-hint">Core can have one extra app on its own. Two or more cost more than a bundle.</span>
          {q && q.bundleInstead && q.bundleInstead.moreMonthly <= 15 && <div className="cc-note">
            <b>{q.bundleInstead.bundleName}</b> adds {q.bundleInstead.extraApps.join(", ")} for {money(q.bundleInstead.moreMonthly)} more a month{period === "year" ? " (yearly rate)" : ""}.{" "}
            <button type="button" className="cc-link" onClick={() => { setBundle(q.bundleInstead.bundle); setAddon(null); }}>Switch to {q.bundleInstead.bundleName}</button>
          </div>}
        </div>}
        <div className="cc-field">
          <label className="cc-radio"><input type="checkbox" checked={assoc} onChange={(e) => setAssoc(e.target.checked)} /><span><b>Incorporated association or service club: {Math.round(cat.assocOff * 100)}% off</b><span className="cc-hint">Enter your association or club number so we can check it.</span></span></label>
          <AssocHelp off={Math.round(cat.assocOff * 100)} />
          {assoc && <input value={assocNumber} placeholder="Association or club number" aria-label="Association or club number" onChange={(e) => setAssocNumber(e.target.value)} />}
        </div>
        <div className="cc-grid2">
          <div>
            <div className="cc-field" role="radiogroup" aria-label="Monthly AI pack">Monthly AI pack (optional)
              {[["none", "Included allowance", 0], ["starter", "AI Starter", PR.aiPackPrice("starter", currency)], ["plus", "AI Plus", PR.aiPackPrice("plus", currency)]].map(([v, t, c]) => (
                <label key={v} className={"cc-radio" + (ai === v ? " on" : "")}><input type="radio" name="ai" checked={ai === v} onChange={() => setAi(v)} /><span><b>{t}{c ? " · " + money(PR.cents(c * (assoc ? 1 - cat.assocOff : 1) * (period === "year" ? 1 : 1 / cat.monthlyDivisor))) + "/mth" : ""}</b><span className="cc-hint">Roughly {postsFor(v)} Social posts a month with a picture each{v === "none" ? ", or 4 Reviews" : ""}</span></span></label>
              ))}
              <p className="cc-hint"><b>These are estimates only.</b> The real number depends on how many drafts, rewrites and pictures your club asks for, and on any Reviews or plans run in the same month. If you run short, a club admin can buy a one-off top-up ({(cat.topup && cat.topup.units || 1000).toLocaleString(CCIntl.locale())} credits for {money(PR.topupPrice(assoc, currency))} {CCIntl.exTax()}, lasting {(cat.topup && cat.topup.months) || 12} months).</p>
            </div>
          </div>
          <div className="cc-sum" aria-live="polite">
            {!q ? <div><span className="cc-muted">{CCIntl.t("plan.working")}</span></div> : <>
              {q.lines.map((l) => <div key={l.key}><span>{lineName(l)}</span><span className="num">{money(l.amount)}</span></div>)}
              <div className="tot"><span>{period === "year" ? "Per year" : "Per month"}</span><span className="num">{money(q.recurring)}</span></div>
              {period === "year" && <div className="bill"><span>Works out at</span><span className="num">{money(q.recurring / 12)}/mth</span></div>}
              {q.credit > 0 && <div className="save"><span>Credit ({q.creditWhy})</span><span className="num">−{money(q.credit)}</span></div>}
              <div className="due"><span>Due today</span><span className="num">{money(q.dueToday)}</span></div>
              <div className="bill"><span>{q.effectiveAt ? "Takes effect" : "Renews"}</span><span>{fmtDate(q.effectiveAt || q.renewsAt)}</span></div>
              <p className="cc-hint">{CCIntl.taxNote(q.recurring)}</p>
              {kindNote && <p className="cc-hint">{kindNote}</p>}
            </>}
          </div>
        </div>
        {q && q.problems && q.problems.map((p) => <div key={p} className="cc-note warn">{p}</div>)}
        <Err e={err} />
        <div className="cc-row between">
          <span className="cc-muted sm">{cat.checkout === "test" ? CCIntl.t("plan.testmode.save") : cat.checkout === "live" ? "You will pay securely on our payment page, then return here." : CCIntl.t("plan.payment.soon")}</span>
          <span className="cc-row" style={{ marginTop: 0 }}>{onCancel && <button className="cc-btn ghost" onClick={onCancel}>Cancel</button>}
            <button className="cc-btn primary" disabled={busy || !q || (q.problems && q.problems.length > 0) || q.kind === "none" || cat.checkout === "unavailable"} onClick={() => setReview(true)}>Review order</button></span>
        </div>
      </div>
    );
  }

  /* ---------------- Club tab ---------------- */
  function ClubPanel({ clubId, view, onChanged, asMember, onGo, planSignal }) {
    const [c, setC] = React.useState(null);
    const [reqs, setReqs] = React.useState(null);
    const [choice, setChoice] = React.useState({});
    const [err, setErr] = React.useState(null);
    const [msg, setMsg] = React.useState(null);
    const [inv, setInv] = React.useState({ email: "", scope: "club" });
    const [choosing, setChoosing] = React.useState(!!(window.CCDemo && window.CCDemo.chooser));      // ?demo=1&chooser=1 opens the plan chooser, so it can be linked to
    const [confirmRemove, setConfirmRemove] = React.useState(null);
    const [buying, setBuying] = React.useState(false);
    const membersRef = React.useRef(null), planRef = React.useRef(null);
    const call = (m, p, b) => API.call(m, p, b, { club: clubId });
    async function load() {
      try {
        const club = await call("GET", "/club");
        setC(club); applyBrand(club.brand);
        if (club.me.isAdmin) setReqs((await call("GET", "/club/join-requests")).requests);
      } catch (e) { setErr(e.message); }
    }
    React.useEffect(() => { load(); }, [clubId]);
    async function act(fn, ok) {
      setErr(null); setMsg(null);
      try { const r = await fn(); if (ok) setMsg(typeof ok === "function" ? ok(r) : ok); await load(); onChanged && onChanged(); }
      catch (e) { setErr(e.message); }
    }
    async function buyTopup() {
      setBuying(true);
      await act(() => call("POST", "/club/topup"), (r) => `Top-up added: ${r.units.toLocaleString(CCIntl.locale())} AI credits, ${money(r.price)} ${CCIntl.exTax()}, lasting to ${fmtDate(r.expiresAt)} (test mode, no payment taken).`);
      setBuying(false);
    }
    React.useEffect(() => { if (planSignal) setChoosing(true); }, [planSignal]);
    React.useEffect(() => { if (choosing && c) setTimeout(() => planRef.current && planRef.current.scrollIntoView({ behavior: "smooth" }), 200); }, [choosing, !!c]);
    if (!c) return <div className="cc-page"><div className="cc-wrap"><Err e={err} />{!err && <p className="cc-muted">Loading…</p>}</div></div>;
    const L = c.brand.labels;
    const isAdmin = c.me.isAdmin && !asMember;
    const goPlan = () => { setChoosing(true); if (view !== "admin" && onGo) onGo("admin"); setTimeout(() => planRef.current && planRef.current.scrollIntoView({ behavior: "smooth" }), 120); };
    const showChooser = isAdmin && choosing;
    return (
      <div className="cc-page"><div className="cc-wrap">
        <div className="cc-pagehead"><div><div className="cc-label">{view === "admin" ? "Club admin" : "Your club"}</div><h1>{view === "admin" ? "Plan, people and settings" : c.club.name}</h1></div></div>
        <Err e={err} />{msg && <div className="cc-note ok">{msg}</div>}

        {c.trial && c.trial.expired && <div className={"cc-trial over"}>
          <div><b>{c.trial.expired ? "Your free trial has ended" : `Free trial · ${c.trial.daysLeft} day${c.trial.daysLeft === 1 ? "" : "s"} left`}</b>
            <span>{c.trial.expired ? "Everything stays readable. Choose a plan to keep working." : `Every app, as many logins as you like, for up to ${c.trial.upTo} members. One Tasks project, one Social campaign, one run of each report.`}</span></div>
          {isAdmin && <button className="cc-btn primary" onClick={goPlan}>Choose a plan</button>}
        </div>}

        {view !== "admin" && <div className="cc-grid2 top">
          <AppsTable allowances={c.allowances} access={c.me.access} isAdmin={isAdmin} onPlan={goPlan} onOpen={(m) => onGo && onGo("open:" + m)} />
          <Card title="AI allowance" className="cc-aicard">
            <div className="cc-ai"><div className="cc-bar" role="img" aria-label={c.aiPercentUsed + "% used"}><span style={{ width: c.aiPercentUsed + "%" }} /></div><b>{c.aiPercentUsed}% used this month</b></div>
            <p className="cc-muted sm">Reviews, plans and Social posts use the club's AI allowance. It resets each month. Top-ups are used after it runs out and last {(c.aiTopups && c.aiTopups.months) || 12} months.</p>
            {c.aiTopups && c.aiTopups.units > 0 && <p className="sm"><b>{c.aiTopups.units.toLocaleString(CCIntl.locale())} top-up credits left</b>{c.aiTopups.expiresAt ? <span className="cc-muted"> · the oldest run out {fmtDate(c.aiTopups.expiresAt)}</span> : null}</p>}
            {isAdmin && c.aiTopups && <button className="cc-btn sm" disabled={buying} onClick={buyTopup}>{buying ? "Buying…" : `Buy a top-up: ${c.aiTopups.size.toLocaleString(CCIntl.locale())} credits for ${money(c.aiTopups.price)} ${CCIntl.exTax()}`}</button>}
          </Card>
        </div>}

        {view !== "admin" && <SecondZoneCard clubId={clubId} club={c} onSaved={() => { load(); onChanged && onChanged(); }} />}

        {isAdmin && view === "admin" && <>
          <SeatsAccess c={c} choosing={showChooser} onPlan={goPlan} onAssign={() => onGo && onGo("access")} />
          <MemberBand reg={c.register} onGo={onGo} />

          {showChooser && <div ref={planRef}><Card title={c.licences.subscription && !c.trial ? "Change plan" : "Choose a plan"}>
            <PlanChooser clubId={clubId} club={c} onCancel={() => setChoosing(false)} onSaved={(m) => { setChoosing(false); setMsg(m); load(); onChanged && onChanged(); }} />
          </Card></div>}

          <Card title="Requests to join" aside={reqs && reqs.length > 0 && <span className="cc-pill warn">{reqs.length} waiting</span>}>
            {(!reqs || reqs.length === 0) && <p className="cc-muted">No one is waiting.</p>}
            {(reqs || []).map((r) => {
              return <div className="cc-req" key={r.id}>
                <div><b>{r.name}</b> · {r.roleInClub || "Member"}<div className="cc-muted sm">{r.email}{r.message ? " · \"" + r.message + "\"" : ""}{r.status === "escalated" ? " · sent to Clubcraft support" : ""}</div></div>
                <div className="cc-req-act">
                  <button className="cc-btn sm primary" onClick={() => act(() => call("POST", `/club/join-requests/${r.id}/decide`, { decision: "approve" }), r.name + " approved. Set what they can do on the Access page.")}>Approve</button>
                  <button className="cc-btn sm ghost" onClick={() => act(() => call("POST", `/club/join-requests/${r.id}/decide`, { decision: "decline" }), "Declined.")}>Decline</button>
                </div>
              </div>;
            })}
          </Card>

          <div ref={membersRef}><Card title="Members">
            <p className="cc-muted sm cc-intro">Make someone a <b>club admin</b> here (Admin in every app, plus plan, people and settings). What each person can do in each app is set on the <button type="button" className="cc-link" onClick={() => onGo && onGo("access")}>Access page</button>. To add someone new, use <i>Invite someone</i> below.</p>
            <div className="cc-table"><table>
              <thead><tr><th>Name</th><th>Club admin</th><th /></tr></thead>
              <tbody>{c.members.filter((m) => m.status !== "removed").map((m) => (
                <tr key={m.userId}>
                  <td><b>{m.name}</b>{m.isGuest && <span className="cc-pill quiet">Guest</span>}<div className="cc-muted sm">{m.email}</div></td>
                  <td><input type="checkbox" aria-label={"Admin: " + m.name} checked={m.isAdmin} onChange={(e) => act(() => call("PATCH", "/club/members/" + m.userId, { isAdmin: e.target.checked }), "Admin rights updated.")} /></td>
                  <td>{confirmRemove === m.userId
                    ? <span className="cc-row" style={{ marginTop: 0 }}><button className="cc-btn sm danger" onClick={() => { setConfirmRemove(null); act(() => call("PATCH", "/club/members/" + m.userId, { status: "removed" }), m.name + " removed."); }}>Remove {m.name.split(" ")[0]}</button><button className="cc-btn sm ghost" onClick={() => setConfirmRemove(null)}>Keep</button></span>
                    : <button className="cc-btn sm ghost" onClick={() => setConfirmRemove(m.userId)}>Remove</button>}</td>
                </tr>))}</tbody>
            </table></div>
          </Card></div>

          <Card title="Invite someone">
            <p className="cc-muted sm cc-intro">Send a link to join the club. New members start with your club defaults; change them on the Access page. A <b>Club admin</b> can manage the plan, members and requests, like you.</p>
            <div className="cc-inv">
              <input type="email" placeholder="name@example.com" aria-label="Email" value={inv.email} onChange={(e) => setInv({ ...inv, email: e.target.value })} />
              <select value={inv.scope} aria-label="Role" onChange={(e) => setInv({ ...inv, scope: e.target.value })}><option value="club">Club member</option><option value="club_admin">Club admin</option></select>
              <button className="cc-btn primary" disabled={!inv.email} onClick={() => act(() => call("POST", "/club/invitations", inv), (r) => "Invitation created. Until email is set up, send them this link: " + location.origin + location.pathname + r.acceptPath.replace("/join", ""))}>Create invitation</button>
            </div>
          </Card>

          <ClubRegion club={c} call={call} act={act} />
          {c.canEditBranding && <ClubBranding club={c} call={call} act={act} />}
        </>}
      </div></div>
    );
  }

  /* Where the club is: country and currency are fixed (Delivio changes them); the club admin sets time zone, date style and the registration number. */
  const LOCALES = [["en-AU", "Australian (5 March 2026)"], ["en-NZ", "New Zealand (5 March 2026)"], ["en-GB", "British (5 March 2026)"], ["en-CA", "Canadian"], ["en-US", "American (March 5, 2026)"]];
  function ClubRegion({ club, call, act }) {
    const r = club.club.region || {};
    const [tz, setTz] = React.useState(r.timezone), [loc, setLoc] = React.useState(r.locale), [tid, setTid] = React.useState(r.taxId || ""), [cty, setCty] = React.useState(r.country);
    const sub = club.licences && club.licences.subscription, paid = !!(sub && sub.status !== "trial");     // the server decides; this only hides the picker
    const pickCountry = (code) => { const d = window.CCCountries.defaultsFor(code); setCty(code); setTz(d.timezone); setLoc(d.locale); };
    const admin = club.me && club.me.isAdmin;
    const [note, setNote] = React.useState(null);        // shown next to Save, because the page-level message can be out of sight
    async function save() {
      setNote({ bad: false, text: "Saving…" });
      try { await call("PUT", "/club/region", { ...(cty !== r.country ? { country: cty } : {}), timezone: tz, locale: loc, taxId: tid }); setNote({ bad: false, text: "Saved. Dates, times and spelling now follow these settings." }); await act(async () => {}); }
      catch (e) { setNote({ bad: true, text: "Not saved: " + (e.message || "something went wrong") }); }
    }
    return (
      <Card title="Where your club is">
        <div className="cc-lic">
          <div><b>{r.countryName}</b><span>country</span></div>
          <div><b>{r.currency}</b><span>currency your plan is in</span></div>
          <div><b>{r.tax && r.tax.name}</b><span>{r.tax && r.tax.included ? "included in prices" : "added to prices where it applies"}</span></div>
        </div>
        {admin ? <>
          {!paid && <label className="cc-field">Country and currency<select value={cty} onChange={(e) => pickCountry(e.target.value)} aria-label="Country">{Object.values(window.CCCountries.COUNTRIES).map((c) => <option key={c.code} value={c.code}>{c.name} ({c.currency})</option>)}</select>
            <span className="cc-hint">Where your club is based, not where you are today. You can change this until your club pays for its first plan; prices on the Plan screen follow the currency.</span></label>}
          {paid && <p className="cc-muted sm">Your plan is billed in {r.currency}, so the country and currency are fixed. Contact Clubcraft support to move them.</p>}
          {(() => { const dz = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone; } catch (e) { return null; } })(); return dz && dz !== tz && !CCIntl.allZones().some(([id]) => id === dz && id === tz) ? <p className="cc-note trial">Your device is on {dz.replace(/_/g, " ")} time. Your club's time zone is set to {tz.replace(/_/g, " ")}. <button type="button" className="cc-link" onClick={() => setTz(dz)} disabled={!CCIntl.allZones().some(([id]) => id === dz)}>Use {dz.replace(/_/g, " ")} instead</button></p> : null; })()}
          <div className="cc-grid2">
            <label className="cc-field">Time zone<select value={tz} onChange={(e) => setTz(e.target.value)}>{CCIntl.allZones().map(([id, label]) => <option key={id} value={id}>{label}</option>)}{!CCIntl.allZones().some(([id]) => id === tz) && <option value={tz}>{tz}</option>}</select></label>
            <label className="cc-field">Dates and spelling<select value={loc} onChange={(e) => setLoc(e.target.value)}>{LOCALES.map(([id, label]) => <option key={id} value={id}>{label}</option>)}</select></label>
          </div>
          <label className="cc-field">{({ ABN: "ABN#", NZBN: "NZBN#", EIN: "EIN#", BN: "BN#", CHARITY: "VAT# or charity number" })[r.taxIdType] || r.taxIdLabel || "Registration number"} (optional, shown on your invoices)<input value={tid} placeholder={r.taxIdExample} onChange={(e) => setTid(e.target.value)} /></label>
          <div className="cc-row"><button className="cc-btn sm primary" onClick={save}>Save</button>{note && <span className={"cc-note " + (note.bad ? "bad" : "ok")} role="status" style={{ margin: 0 }}>{note.text}</span>}</div>
          <p className="cc-muted sm">To change the country or currency, contact Clubcraft support.</p>
        </> : <p className="cc-muted sm">Time zone {r.timezone}. A club admin can change it.</p>}
      </Card>
    );
  }

  function ClubBranding({ club, call, act }) {
    const [accent, setAccent] = React.useState(club.club.brandAccent || club.brand.tokens.accent);
    return (
      <Card title="Club branding">
        <p className="cc-muted sm">Your {club.brand.labels.global} brand stays the same. You can add your club's logo and one accent colour.</p>
        <div className="cc-row" style={{ alignItems: "center" }}>
          <Logo brand={club.brand} size={44} />
          <label className="cc-btn sm">Upload logo<input type="file" accept="image/png,image/jpeg,image/webp,image/svg+xml" hidden onChange={async (e) => { const f = e.target.files[0]; if (f) act(async () => call("PUT", "/club/branding", { logo: await fileToDataUrl(f) }), "Logo updated."); }} /></label>
          <label className="cc-colour">Accent <input type="color" value={accent} onChange={(e) => setAccent(e.target.value)} /></label>
          <button className="cc-btn sm primary" onClick={() => act(() => call("PUT", "/club/branding", { accent }), "Accent saved.")}>Save accent</button>
          <button className="cc-btn sm ghost" onClick={() => act(() => call("PUT", "/club/branding", { accent: null, removeLogo: true }), "Club branding reset.")}>Reset</button>
        </div>
      </Card>
    );
  }

  /* ---------------- Delivio tab ---------------- */
  function OpsPanel() {
    const [view, setView] = React.useState(store.get("cc_ops_view") || "requests");
    const go = (v) => { setView(v); store.set("cc_ops_view", v); };
    return (
      <div className="cc-page"><div className="cc-wrap">
        <div className="cc-pagehead"><div><div className="cc-label">Delivio · super admin</div><h1>Operations</h1></div>
          <nav className="cc-subtabs"><button className={view === "requests" ? "on" : ""} onClick={() => go("requests")}>Requests</button><button className={view === "brand" ? "on" : ""} onClick={() => go("brand")}>Organisations and branding</button></nav></div>
        {view === "requests" ? <OpsRequests /> : <OpsBranding />}
      </div></div>
    );
  }

  function OpsRequests() {
    const [d, setD] = React.useState(null);
    const [err, setErr] = React.useState(null);
    const [msg, setMsg] = React.useState(null);
    const [dist, setDist] = React.useState({});
    const [orgDistricts, setOrgDistricts] = React.useState({});
    const [templates, setTemplates] = React.useState([]);
    const [newOrg, setNewOrg] = React.useState(null);
    const slugOf = (n) => n.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
    async function load() {
      try {
        const o = await API.call("GET", "/ops/overview"); setD(o);
        const b = await API.call("GET", "/ops/brand");
        setOrgDistricts(Object.fromEntries(b.organisations.map((x) => [x.id, x.districts])));
        setTemplates(b.templates);
      } catch (e) { setErr(e.message); }
    }
    React.useEffect(() => { load(); }, []);
    async function act(fn, ok) { setErr(null); setMsg(null); try { await fn(); setMsg(ok); await load(); } catch (e) { setErr(e.message); } }
    const linkFor = (slug) => location.origin + location.pathname + "?org=" + slug;
    const copyLink = (slug) => { try { navigator.clipboard.writeText(linkFor(slug)); setMsg("Link copied: " + linkFor(slug)); } catch (e) { setMsg(linkFor(slug)); } };
    if (!d) return <><Err e={err} />{!err && <p className="cc-muted">Loading…</p>}</>;
    const ago = (ms) => (!ms ? "never" : Math.round((Date.now() - ms) / 86400000) + " days ago");
    const first = (n) => (n ? n.split(" ")[0] : "them");
    return <>
      <Err e={err} />{msg && <div className="cc-note ok">{msg}</div>}
      <Card title="Join requests nobody has answered" aside={d.overdueJoinRequests.length > 0 && <span className="cc-pill warn">{d.overdueJoinRequests.length} overdue</span>}>
        <p className="cc-muted sm">No club admin replied within 5 working days. Often an admin has left and nobody updated Clubcraft.</p>
        {d.overdueJoinRequests.length === 0 && <p className="cc-muted">Nothing overdue.</p>}
        {d.overdueJoinRequests.map((r) => (
          <div className="cc-req" key={r.id}>
            <div><b>{r.club}</b> <span className={"cc-pill " + pill(r.clubStatus)[1]}>{pill(r.clubStatus)[0]}</span>
              <div className="cc-muted sm">{r.district} · {r.requester} ({r.requesterEmail}) · waiting about {r.waitingDays} working days</div>
              <div className="cc-muted sm">Admins: {r.admins.length ? r.admins.map((a) => a.name + " (last signed in " + ago(a.lastSeenAt) + ")").join("; ") : "none"}</div></div>
            <div className="cc-req-act">
              <button className="cc-btn sm primary" onClick={() => act(() => API.call("POST", "/ops/join-requests/" + r.id + "/resolve", { action: "make_admin" }), r.requester + " is now an admin of " + r.club + ".")}>Make {first(r.requester)} an admin</button>
              <button className="cc-btn sm" onClick={() => act(() => API.call("POST", "/ops/join-requests/" + r.id + "/resolve", { action: "contacted" }), "The club has another 5 working days.")}>Contacted the club</button>
              <button className="cc-btn sm ghost" onClick={() => act(() => API.call("POST", "/ops/join-requests/" + r.id + "/resolve", { action: "close" }), "Request closed.")}>Close</button>
            </div>
          </div>
        ))}
      </Card>
      <Card title="Clubs asking to be added" aside={d.clubAddRequests.length > 0 && <span className="cc-pill warn">{d.clubAddRequests.length} new</span>}>
        {d.clubAddRequests.length === 0 && <p className="cc-muted">No new requests.</p>}
        {d.clubAddRequests.map((a) => {
          const chosen = dist[a.id] !== undefined ? dist[a.id] : (a.districtId || "");
          return <div className="cc-req" key={a.id}>
            <div><b>{a.clubName}</b><div className="cc-muted sm">{a.name} ({a.email}){a.role ? ", " + a.role : ""}{a.note ? " · " + a.note : ""}</div></div>
            <div className="cc-req-act">
              <select value={chosen} onChange={(e) => setDist({ ...dist, [a.id]: e.target.value })}><option value="">No district</option>{(orgDistricts[a.orgId] || []).map((x) => <option key={x.id} value={x.id}>{x.name}</option>)}</select>
              <button className="cc-btn sm primary" onClick={() => act(() => API.call("POST", "/ops/club-add-requests/" + a.id, { action: "add", districtId: chosen || undefined }), a.clubName + " added. Email " + a.email + " to say they can now set it up.")}>Add club</button>
              <button className="cc-btn sm" onClick={() => act(() => API.call("POST", "/ops/club-add-requests/" + a.id, { action: "duplicate" }), "Marked as a duplicate.")}>Duplicate</button>
              <button className="cc-btn sm ghost" onClick={() => act(() => API.call("POST", "/ops/club-add-requests/" + a.id, { action: "decline" }), "Declined.")}>Decline</button>
            </div>
          </div>;
        })}
      </Card>
      <Card title="Organisations" aside={<button className="cc-btn sm" onClick={() => setNewOrg(newOrg ? null : { name: "", slug: "", slugEdited: false, brandTemplateId: "", districts: "" })}>{newOrg ? "Cancel" : "Add organisation"}</button>}>
        {newOrg && <div className="cc-tpled">
          <label className="cc-field">Organisation name<input value={newOrg.name} onChange={(e) => setNewOrg({ ...newOrg, name: e.target.value, slug: newOrg.slugEdited ? newOrg.slug : slugOf(e.target.value) })} placeholder="Lions Clubs Australia" /></label>
          <label className="cc-field">Web code<input value={newOrg.slug} onChange={(e) => setNewOrg({ ...newOrg, slug: e.target.value.toLowerCase(), slugEdited: true })} placeholder="lions-australia" /><span className="cc-hint">Used in the link: {linkFor(newOrg.slug || "web-code")}. Lower-case letters, numbers and dashes. It cannot be changed later.</span></label>
          <label className="cc-field">Brand template (optional)<select value={newOrg.brandTemplateId} onChange={(e) => setNewOrg({ ...newOrg, brandTemplateId: e.target.value })}><option value="">Clubcraft default for now</option>{templates.map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}</select></label>
          <label className="cc-field">Districts or areas (optional, one per line)<textarea rows="4" value={newOrg.districts} onChange={(e) => setNewOrg({ ...newOrg, districts: e.target.value })} /><span className="cc-hint">The middle level clubs are grouped under. Leave blank if there is none. Level names can be changed under Organisations and branding.</span></label>
          <p className="cc-muted sm">It starts as <b>pending</b>, with no public page. Add its brand and clubs, then set it to live in the table below.</p>
          <div className="cc-row"><button className="cc-btn primary" disabled={!newOrg.name.trim() || !newOrg.slug.trim()} onClick={() => act(async () => { const r = await API.call("POST", "/ops/organisations", { name: newOrg.name, slug: newOrg.slug, brandTemplateId: newOrg.brandTemplateId || undefined, districts: newOrg.districts }); setNewOrg(null); return r; }, newOrg.name + " added as pending.")}>Add organisation</button></div>
        </div>}
        <div className="cc-table"><table>
          <thead><tr><th>Organisation</th><th>Clubs active</th><th>Lapsed</th><th>Link to send</th><th>Status</th></tr></thead>
          <tbody>{d.organisations.map((o) => <tr key={o.id}><td><b>{o.name}</b><div className="cc-muted sm">?org={o.slug}</div></td><td>{o.clubsActive} of {o.clubsListed}</td><td>{o.clubsLapsed}</td><td>{o.status === "live" ? <button className="cc-btn sm ghost" onClick={() => copyLink(o.slug)}>Copy link</button> : <span className="cc-muted sm">Live only</span>}</td>
            <td><select value={o.status} onChange={(e) => act(() => API.call("POST", "/ops/organisations/" + o.id, { status: e.target.value }), o.name + " is now " + e.target.value + ".")}>{["pending", "approved", "live"].map((x) => <option key={x}>{x}</option>)}</select></td></tr>)}</tbody>
        </table></div>
      </Card>
    </>;
  }

  const TOKEN_FIELDS = [["primary", "Primary"], ["primaryDeep", "Primary (dark)"], ["accent", "Accent"], ["bg", "Page background"], ["ink", "Text"]];
  const FONTS = ["Public Sans", "Open Sans", "Hanken Grotesk", "Inter", "Arial"];

  function BrandPreview({ tokens, logoUrl, title, sub }) {
    const t = tokens || {};
    return (
      <div className="cc-bprev" style={{ background: t.bg, color: t.ink, fontFamily: `"${t.font || "Public Sans"}", sans-serif` }}>
        <div className="cc-bprev-h" style={{ background: `linear-gradient(180deg, ${t.primary}, ${t.primaryDeep || t.primary})` }}>
          <Logo brand={{ logoUrl, tokens: t }} size={28} /><div><b>{title}</b><small>{sub}</small></div>
        </div>
        <div className="cc-bprev-b"><div className="cc-bprev-card"><span style={{ background: t.accent }} />Club home</div><button style={{ background: t.primary }}>Primary button</button></div>
      </div>
    );
  }

  // Club logos: search for a club, then upload or remove its logo. A club logo is normally the organisation's
  // logo with the club's name (for Rotary, the Masterbrand Signature plus the club name). Review checks a
  // club's website and Facebook against it first, then the org logo.
  function ClubLogos() {
    const [q, setQ] = React.useState("");
    const [rows, setRows] = React.useState(null);
    const [more, setMore] = React.useState(false);
    const [err, setErr] = React.useState(null);
    const [msg, setMsg] = React.useState(null);
    const [busy, setBusy] = React.useState(false);
    async function search(e) {
      if (e) e.preventDefault();
      setErr(null); setMsg(null);
      if (q.trim().length < 3) { setErr("Type at least 3 letters of the club's name."); return; }
      setBusy(true);
      try { const r = await API.call("GET", "/ops/clubs?q=" + encodeURIComponent(q.trim())); setRows(r.clubs); setMore(r.more); } catch (x) { setErr(x.message); }
      setBusy(false);
    }
    async function save(c, body, ok) {
      setErr(null); setMsg(null);
      try { await API.call("POST", "/ops/clubs/" + c.id + "/logo", body); setMsg(c.name + ": " + ok); const r = await API.call("GET", "/ops/clubs?q=" + encodeURIComponent(q.trim())); setRows(r.clubs); } catch (x) { setErr(x.message); }
    }
    return (
      <Card title="Club logos" aside={<span className="cc-pill quiet">Used first by Review</span>}>
        <p className="cc-muted sm" style={{ marginTop: 0 }}>The club logo is normally the organisation's logo with the club's name. Review checks a club's website and Facebook against it first, then against the org logo. It works whether or not the club's own branding switch is on.</p>
        <Err e={err} />{msg && <div className="cc-note ok">{msg}</div>}
        <form className="cc-row" style={{ marginTop: 0 }} onSubmit={search}>
          <input className="cc-input" style={{ flex: "1 1 220px" }} value={q} onChange={(e) => setQ(e.target.value)} placeholder="Club name, for example Geelong" aria-label="Search for a club" />
          <button className="cc-btn" disabled={busy}>{busy ? "Searching…" : "Find club"}</button>
        </form>
        {rows && !rows.length && <p className="cc-muted sm">No club matches that name.</p>}
        {rows && rows.length > 0 && <ul className="cc-rv-list">{rows.map((c) => (
          <li key={c.id}>
            <span className="cc-row" style={{ marginTop: 0, flexWrap: "nowrap", alignItems: "center" }}>
              {c.logoUrl ? <img src={c.logoUrl} alt="" style={{ height: 36, maxWidth: 110, objectFit: "contain" }} /> : <span className="cc-pill quiet">No logo</span>}
              <span><b>{c.name}</b><br /><small className="cc-muted">{c.org}{c.status !== "active" ? " · " + c.status.replace("_", " ") : ""}</small></span>
            </span>
            <span className="cc-row" style={{ marginTop: 0 }}>
              <label className="cc-btn sm">{c.logoUrl ? "Replace club logo" : "Upload club logo"}<input type="file" accept="image/png,image/jpeg,image/webp,image/svg+xml" hidden onChange={async (e) => { const f = e.target.files[0]; if (f) { try { save(c, { logo: await fileToDataUrl(f) }, "club logo uploaded."); } catch (x) { setErr(x.message); } } }} /></label>
              {c.logoUrl && <button className="cc-btn sm ghost" onClick={() => save(c, { removeLogo: true }, "club logo removed.")}>Remove</button>}
            </span>
          </li>))}</ul>}
        {more && <p className="cc-muted sm">More clubs match: type more of the name to narrow it down.</p>}
      </Card>
    );
  }

  /* ---------------- Extend a club's free trial (Delivio super admin) ---------------- */
  function TrialExtend() {
    const [q, setQ] = React.useState(""), [rows, setRows] = React.useState(null), [err, setErr] = React.useState(null), [msg, setMsg] = React.useState(null), [busy, setBusy] = React.useState(false);
    const [days, setDays] = React.useState({}), [reset, setReset] = React.useState({}), [note, setNote] = React.useState({});
    async function find(e) {
      if (e) e.preventDefault();
      setErr(null); setMsg(null);
      if (q.trim().length < 3) { setErr("Type at least 3 letters of the club's name."); return; }
      setBusy(true);
      try { setRows((await API.call("GET", "/ops/clubs?q=" + encodeURIComponent(q.trim()))).clubs); } catch (x) { setErr(x.message); }
      setBusy(false);
    }
    async function extend(c, n) {
      setErr(null); setMsg(null);
      try {
        const r = await API.call("POST", "/ops/clubs/" + c.id + "/trial", { days: n, resetRuns: !!reset[c.id], note: note[c.id] || "" });
        setMsg(c.name + ": trial now runs to " + fmtDate(r.endsAt) + " (" + plural(r.daysLeft, "day") + " from today)." + (reset[c.id] ? " The one-run limits are reset." : ""));
        setRows((await API.call("GET", "/ops/clubs?q=" + encodeURIComponent(q.trim()))).clubs);
      } catch (x) { setErr(x.message); }
    }
    const state = (c) => !c.plan ? "No plan or trial" : c.plan.status === "trial" ? (c.plan.endsAt < Date.now() ? "Trial ended " : "Trial ends ") + fmtDate(c.plan.endsAt) : "Paid plan";
    return (
      <Card title="Extend a free trial" aside={<span className="cc-pill quiet">On request</span>}>
        <p className="cc-muted sm" style={{ marginTop: 0 }}>Give a club more days on request. Days are added to the current end date, or to today if the trial has already ended. Tick the box to also give back the one-run limits so the club can try each app again. Every change is logged.</p>
        <Err e={err} />{msg && <div className="cc-note ok">{msg}</div>}
        <form className="cc-row" style={{ marginTop: 0 }} onSubmit={find}>
          <input className="cc-input" style={{ flex: "1 1 220px" }} value={q} onChange={(e) => setQ(e.target.value)} placeholder="Club name, for example Geelong" aria-label="Search for a club" />
          <button className="cc-btn" disabled={busy}>{busy ? "Searching…" : "Find club"}</button>
        </form>
        {rows && !rows.length && <p className="cc-muted sm">No club matches that name.</p>}
        {rows && rows.length > 0 && <ul className="cc-rv-list">{rows.map((c) => {
          const paid = c.plan && c.plan.status !== "trial";
          return <li key={c.id} style={{ display: "block" }}>
            <b>{c.name}</b> <small className="cc-muted">{c.org} · {state(c)}</small>
            {!paid && <div className="cc-row" style={{ flexWrap: "wrap", alignItems: "center" }}>
              {[14, 30, 60].map((n) => <button key={n} className="cc-btn sm" onClick={() => extend(c, n)}>+{n} days</button>)}
              <input className="cc-input" type="number" min="1" max="365" style={{ width: 90 }} placeholder="Days" aria-label="Other number of days" value={days[c.id] || ""} onChange={(e) => setDays({ ...days, [c.id]: e.target.value })} />
              <button className="cc-btn sm" disabled={!(Number(days[c.id]) >= 1)} onClick={() => extend(c, Number(days[c.id]))}>Add</button>
              <label className="cc-muted sm"><input type="checkbox" checked={!!reset[c.id]} onChange={(e) => setReset({ ...reset, [c.id]: e.target.checked })} /> Also reset the one-run limits</label>
              <input className="cc-input" style={{ flex: "1 1 200px" }} placeholder="Reason (optional, kept in the log)" aria-label="Reason" value={note[c.id] || ""} onChange={(e) => setNote({ ...note, [c.id]: e.target.value })} />
            </div>}
          </li>;
        })}</ul>}
      </Card>
    );
  }

  function OpsBranding() {
    const [gd, setGd] = React.useState(null);              // brand guide read job: { status, text, note }
    const [d, setD] = React.useState(null);
    const [sel, setSel] = React.useState(null);
    const [draft, setDraft] = React.useState(null);
    const [tplSel, setTplSel] = React.useState(null);
    const [tplDraft, setTplDraft] = React.useState(null);
    const [err, setErr] = React.useState(null);
    const [msg, setMsg] = React.useState(null);
    async function load(keep) {
      try {
        const b = await API.call("GET", "/ops/brand"); setD(b);
        const o = b.organisations.find((x) => x.id === (keep || sel)) || b.organisations.find((x) => !x.parentOrgId) || b.organisations[0];
        if (o) { setSel(o.id); setDraft({ ...o, levelLabels: { ...b.defaultLabels, ...(o.levelLabels || {}) } }); }
      } catch (e) { setErr(e.message); }
    }
    React.useEffect(() => { load(); }, []);
    // After a save, bring the saved logo, guide and draft status into the open template (leave unsaved edits alone).
    React.useEffect(() => {
      if (!d || !tplSel || tplSel === "new") return;
      const t = d.templates.find((x) => x.id === tplSel);
      if (t) setTplDraft((cur) => cur && { ...cur, logoUrl: t.logoUrl, guideUrl: t.guideUrl, guideName: t.guideName, newGuide: null, draftStatus: t.draftStatus });
    }, [d]);
    // Follow a running "read the guide" job until it finishes.
    React.useEffect(() => {
      if (!gd || gd.status !== "running" || !tplSel || tplSel === "new") return;
      const t = setInterval(async () => {
        try { const r = await API.call("GET", "/ops/brand-templates/" + tplSel + "/draft"); if (r.status !== "running") setGd(r); } catch (e) { setGd({ status: "failed", text: "", note: e.message }); }
      }, 4000);
      return () => clearInterval(t);
    }, [gd && gd.status, tplSel]);
    async function act(fn, ok) { setErr(null); setMsg(null); try { await fn(); setMsg(ok); await load(sel); } catch (e) { setErr(e.message); } }
    async function readGuide() {
      setErr(null); setMsg(null);
      try { await API.call("POST", "/ops/brand-templates/" + tplSel + "/draft-guidelines"); setGd({ status: "running", text: "", note: "" }); } catch (e) { setErr(e.message); }
    }
    // Close the draft panel and clear the stored draft too, so a used or discarded draft cannot come back as "not saved yet".
    function closeDraft() {
      setGd(null);
      if (tplSel && tplSel !== "new") API.call("POST", "/ops/brand-templates/" + tplSel + "/draft-discard").catch(() => {});
    }
    async function downloadGuide() {
      try {
        const r = await API.call("GET", "/ops/brand-templates/" + tplSel + "/guide");
        const a = document.createElement("a"); a.href = r.dataUrl; a.download = r.name; document.body.appendChild(a); a.click(); a.remove();
      } catch (e) { setErr(e.message); }
    }
    if (!d) return <><Err e={err} />{!err && <p className="cc-muted">Loading…</p>}</>;
    const byId = Object.fromEntries(d.organisations.map((o) => [o.id, o]));
    const roots = d.organisations.filter((o) => !o.parentOrgId);
    const kids = (id) => d.organisations.filter((o) => o.parentOrgId === id);
    const rootOf = (o) => (o.parentOrgId && byId[o.parentOrgId] ? rootOf(byId[o.parentOrgId]) : o);
    const labelsFor = (o) => ({ ...d.defaultLabels, ...(rootOf(o).levelLabels || {}) });
    const tplOf = (o) => d.templates.find((t) => t.id === o.brandTemplateId) || (o.parentOrgId && byId[o.parentOrgId] ? tplOf(byId[o.parentOrgId]) : null);
    const pickOrg = (o) => { setSel(o.id); setDraft({ ...o, levelLabels: { ...d.defaultLabels, ...(o.levelLabels || {}) } }); };
    const node = (o, depth) => {
      const L = labelsFor(o);
      return <div key={o.id}>
        <button className={"cc-tree-n" + (o.id === sel ? " on" : "")} style={{ paddingLeft: 12 + depth * 18 }} onClick={() => pickOrg(o)}>
          <span><b>{o.name}</b><small>{L[o.level] || o.level}{o.hidden ? " · hidden" : ""}{o.clubBrandingEnabled ? " · club branding on" : ""}</small></span>
        </button>
        {kids(o.id).map((k) => node(k, depth + 1))}
        {o.districts.length > 0 && <div className="cc-tree-leaf" style={{ paddingLeft: 30 + depth * 18 }}>{o.districts.length} {L.area}{o.districts.length === 1 ? "" : "s"}: {o.districts.map((x) => x.name.replace(/^\D+/, "")).join(", ")}</div>}
      </div>;
    };
    const o = draft;
    const tpl = o && (d.templates.find((t) => t.id === o.brandTemplateId) || (o.parentOrgId && byId[o.parentOrgId] ? tplOf(byId[o.parentOrgId]) : null));
    const previewTokens = { ...(tpl ? tpl.tokens : {}), ...((o && o.brandOverrides) || {}) };
    const tdraft = tplDraft;
    const savedTpl = tplSel && tplSel !== "new" ? d.templates.find((x) => x.id === tplSel) : null;
    // A new link or PDF must be saved before it can be read; the draft reads what is saved.
    const guideDirty = !!(tdraft && savedTpl && ((savedTpl.guideUrl || "") !== (tdraft.guideUrl || "") || tdraft.newGuide || tdraft.removeGuide));
    // Amber warning only when conflicts are listed: not when the opening says there are none.
    const gdOpen = (gd && gd.status === "done" ? gd.text || "" : "").trim().slice(0, 400);
    const gdConflict = /^CONFLICTS TO RESOLVE/i.test(gdOpen) && !/no clear conflicts between the sources/i.test(gdOpen);
    return <>
      <Err e={err} />{msg && <div className="cc-note ok">{msg}</div>}
      <div className="cc-brandgrid">
        <Card title="Levels">
          <div className="cc-tree">{roots.map((r) => node(r, 0))}</div>
          <p className="cc-muted sm">Clubs inherit the brand of the nearest level above them that has one.</p>
        </Card>
        {o && <Card title={o.name} aside={<span className="cc-pill quiet">{labelsFor(o)[o.level] || o.level}</span>}>
          {!o.parentOrgId && <div className="cc-field">Level names for this organisation
            <div className="cc-levels">{["global", "regional", "area", "club"].map((k) => <label key={k}><small>{d.defaultLabels[k]}</small><input value={o.levelLabels[k] || ""} onChange={(e) => setDraft({ ...o, levelLabels: { ...o.levelLabels, [k]: e.target.value } })} /></label>)}</div></div>}
          <label className="cc-field">Brand template<select value={o.brandTemplateId || ""} onChange={(e) => setDraft({ ...o, brandTemplateId: e.target.value || null })}><option value="">Inherit from the level above</option>{d.templates.map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}</select></label>
          <div className="cc-field">Colour overrides (optional)
            <div className="cc-colours">{TOKEN_FIELDS.slice(0, 3).map(([k, l]) => <label key={k} className="cc-colour">{l}<input type="color" value={(o.brandOverrides || {})[k] || previewTokens[k] || "#000000"} onChange={(e) => setDraft({ ...o, brandOverrides: { ...(o.brandOverrides || {}), [k]: e.target.value } })} /></label>)}
              {Object.keys(o.brandOverrides || {}).length > 0 && <button className="cc-link" onClick={() => setDraft({ ...o, brandOverrides: {} })}>Clear overrides</button>}</div></div>
          <div className="cc-switches">
            <label className="cc-switch"><input type="checkbox" checked={o.clubBrandingEnabled} onChange={(e) => setDraft({ ...o, clubBrandingEnabled: e.target.checked })} /><span><b>Enable club branding</b><small>Clubs under this level can add their own logo and accent colour. Clubs don't see the option unless this is on.</small></span></label>
            <label className="cc-switch"><input type="checkbox" checked={o.hidden} onChange={(e) => setDraft({ ...o, hidden: e.target.checked })} /><span><b>Hide this level</b><small>Keep it in the background (for example, set Rotary International's brand once and let clubs deal with their {labelsFor(o).regional}).</small></span></label>
          </div>
          <BrandPreview tokens={previewTokens} logoUrl={o.logoUrl || (tpl && tpl.logoUrl)} title="Example club" sub={`${labelsFor(o).area} 9815 · ${labelsFor(o).regional} 8`} />
          <div className="cc-row between">
            <span className="cc-row" style={{ marginTop: 0 }}>
              <label className="cc-btn sm">Upload org logo<input type="file" accept="image/png,image/jpeg,image/webp,image/svg+xml" hidden onChange={async (e) => { const f = e.target.files[0]; if (f) act(async () => API.call("POST", "/ops/organisations/" + o.id, { logo: await fileToDataUrl(f) }), "Org logo uploaded."); }} /></label>
              {o.logoUrl && <button className="cc-btn sm ghost" onClick={() => act(() => API.call("POST", "/ops/organisations/" + o.id, { removeLogo: true }), "Org logo removed.")}>Remove org logo</button>}
              {o.logoUrl ? <><img src={o.logoUrl} alt="Saved logo for this level" style={{ height: 40, maxWidth: 140, objectFit: "contain", background: "#fff", border: "1px solid var(--b-line, #ddd)", borderRadius: 6, padding: 3 }} /><span className="cc-pill ok">Logo saved</span></> : <span className="cc-pill quiet">{tpl && tpl.logoUrl ? "Using the template logo" : "No logo yet"}</span>}
              <span className="cc-hint" style={{ alignSelf: "center" }}>Clubs normally use their own club logo: set it under Club logos below.</span>
            </span>
            <button className="cc-btn primary" onClick={() => act(() => API.call("POST", "/ops/organisations/" + o.id, {
              name: o.name, brandTemplateId: o.brandTemplateId, brandOverrides: o.brandOverrides || {}, clubBrandingEnabled: o.clubBrandingEnabled, hidden: o.hidden,
              ...(o.parentOrgId ? {} : { levelLabels: o.levelLabels })
            }), o.name + " saved.")}>Save</button>
          </div>
        </Card>}
      </div>

      <Card title="Brand templates" aside={<button className="cc-btn sm" onClick={() => { setTplSel("new"); setTplDraft({ code: "", name: "", guidelines: "", tokens: { ...d.templates[0].tokens } }); }}>New template</button>}>
        <div className="cc-tpls">{d.templates.map((t) => (
          <button key={t.id} className={"cc-tpl" + (tplSel === t.id ? " on" : "")} onClick={() => {
            setTplSel(t.id); setTplDraft({ ...t, tokens: { ...t.tokens } });
            // Pick up a guide job that is still running, or one that finished within the hour.
            setGd(t.draftStatus === "running" ? { status: "running", text: "", note: "" } : null);
            if (t.draftStatus === "done") API.call("GET", "/ops/brand-templates/" + t.id + "/draft").then((r) => { if (r.status === "done" && Date.now() - r.at < 3600000) setGd(r); }).catch(() => {});
          }}>
            <span className="cc-sw">{["primary", "accent", "bg"].map((k) => <i key={k} style={{ background: t.tokens[k] }} />)}</span><b>{t.name}</b><small>{t.official ? "Official" : "Custom"} · {t.tokens.font || "default font"}</small>
          </button>))}</div>
        {tdraft && <div className="cc-tpled">
          {tplSel === "new" && <label className="cc-field">Code<input value={tdraft.code} onChange={(e) => setTplDraft({ ...tdraft, code: e.target.value.toLowerCase() })} placeholder="lions" /></label>}
          <label className="cc-field">Name<input value={tdraft.name} onChange={(e) => setTplDraft({ ...tdraft, name: e.target.value })} /></label>
          <div className="cc-colours">{TOKEN_FIELDS.map(([k, l]) => <label key={k} className="cc-colour">{l}<input type="color" value={tdraft.tokens[k] || "#000000"} onChange={(e) => setTplDraft({ ...tdraft, tokens: { ...tdraft.tokens, [k]: e.target.value } })} /></label>)}
            <label className="cc-colour">Font<select value={tdraft.tokens.font || ""} onChange={(e) => setTplDraft({ ...tdraft, tokens: { ...tdraft.tokens, font: e.target.value, display: e.target.value } })}>{FONTS.map((x) => <option key={x}>{x}</option>)}</select></label></div>
          <BrandPreview tokens={tdraft.tokens} logoUrl={tdraft.logoUrl} title={tdraft.name || "Template"} sub="Preview" />
          <label className="cc-field">Brand guidelines (used by Review to check a club's website and Facebook)<textarea rows="8" maxLength="6000" value={tdraft.guidelines || ""} onChange={(e) => setTplDraft({ ...tdraft, guidelines: e.target.value })} placeholder={"Taglines, logo rules, imagery to use and avoid, fonts, where the brand centre is. One point per line."} /><span className="cc-hint">The colours and logo above are checked too. Leave blank and Review only compares a club's channels with each other.</span></label>
          <div className="cc-field" style={{ marginTop: -6 }}>
            {tplSel !== "new" && <span className="cc-row" style={{ marginTop: 0, alignItems: "center" }}>
              <button className="cc-btn sm primary" disabled={(!tdraft.guideName && !tdraft.guideUrl) || guideDirty || gd?.status === "running"} onClick={readGuide}>{gd?.status === "running" ? "Refreshing…" : "Refresh brand guidelines"}</button>
              <span className="cc-hint">{guideDirty ? "Save the template first, so the new link or PDF is the one that gets read." : !tdraft.guideName && !tdraft.guideUrl ? "Add a link or a PDF below to enable this." : tdraft.guideName && tdraft.guideUrl ? "Reads both the link and the PDF and lists any clear conflict between them at the top of the draft." : "Reads the " + (tdraft.guideName ? "PDF" : "link") + " into a draft you can check and edit."} It takes a minute or two.</span>
            </span>}
            {gd && gd.status === "failed" && <div className="cc-err" role="alert">{gd.note || "The guide could not be read."}</div>}
            {gd && gd.status === "done" && <div className={"cc-note " + (gdConflict ? "warn" : "ok")} style={{ marginTop: 8 }}>
              <b>{gdConflict ? "The link and the PDF disagree. Read the opening lines of this draft first." : "Draft from the guide (not saved yet)"}</b>
              {gdConflict && <div className="sm">Decide which source is right, edit the guidelines to match, and delete the conflict lines before you save.</div>}
              <textarea rows="12" value={gd.text} onChange={(e) => setGd({ ...gd, text: e.target.value })} style={{ width: "100%", marginTop: 6 }} aria-label="Draft guidelines from the guide (you can edit this before using it)" />
              <div className="cc-muted sm">{gd.note} You can edit the draft here before using it.</div>
              {(() => {
                const have = (tdraft.guidelines || "").trim().length, draftLen = gd.text.trim().length;
                const tooLong = draftLen > 6000, addTooLong = have + draftLen + 2 > 6000;
                return <>
                  <div className="cc-muted sm" style={{ marginTop: 6 }}>Draft: {draftLen.toLocaleString()} characters. Existing guidelines: {have.toLocaleString()}. The box holds 6,000.</div>
                  <span className="cc-row" style={{ marginTop: 6 }}>
                    <button className="cc-btn sm primary" disabled={tooLong || !draftLen} onClick={() => { setTplDraft({ ...tdraft, guidelines: gd.text.trim() }); closeDraft(); }}>Replace existing guidelines</button>
                    <button className="cc-btn sm" disabled={!have || addTooLong || !draftLen} onClick={() => { setTplDraft({ ...tdraft, guidelines: (tdraft.guidelines.trim() + "\n\n" + gd.text.trim()) }); closeDraft(); }}>Add to existing guidelines</button>
                    <button className="cc-btn sm ghost" onClick={closeDraft}>Discard</button>
                  </span>
                  <span className="cc-hint"><b>Replace</b> swaps your current guidelines for this draft. <b>Add</b> keeps your current guidelines and puts the draft below them. {tooLong ? "The draft is over 6,000 characters: shorten it in the box above first. " : addTooLong && have ? "Together they would be over 6,000 characters, so Add is off: shorten the draft or the existing guidelines. " : ""}Nothing is saved until you press Save template.</span>
                </>;
              })()}
            </div>}
          </div>
          <div className="cc-field">Branding guide (optional)
            <span className="cc-hint">Link to the brand's guide or upload it as a PDF (4 MB at most). With both a link and a PDF, press Refresh brand guidelines above: both are read and any clear conflict between them is flagged at the top of the draft. You can check and edit what the AI took before saving, and every Review then uses that text.</span>
            <input value={tdraft.guideUrl || ""} onChange={(e) => setTplDraft({ ...tdraft, guideUrl: e.target.value })} placeholder="https://brandcenter.example.org/guide" aria-label="Link to the branding guide" />
            <span className="cc-row" style={{ marginTop: 6, alignItems: "center" }}>
              <label className="cc-btn sm">{tdraft.guideName || tdraft.newGuide ? "Replace PDF" : "Upload PDF guide"}<input type="file" accept="application/pdf" hidden onChange={async (e) => { const f = e.target.files[0]; if (!f) return; if (f.size > 4 * 1024 * 1024) { setErr("That PDF is over 4 MB. Link to it instead."); return; } setErr(null); setTplDraft({ ...tdraft, newGuide: { name: f.name, dataUrl: await fileToDataUrl(f) } }); }} /></label>
              {tdraft.newGuide && <span className="cc-pill trial">{tdraft.newGuide.name}: save to keep it</span>}
              {!tdraft.newGuide && tdraft.guideName && <><span className="cc-pill ok">{tdraft.guideName}</span>{tplSel !== "new" && <button className="cc-link" onClick={downloadGuide}>Download</button>}<button className="cc-link" onClick={() => setTplDraft({ ...tdraft, removeGuide: true, guideName: null })}>Remove</button></>}
              {tdraft.removeGuide && <span className="cc-pill warn">PDF will be removed when you save</span>}
            </span>
          </div>
          <div className="cc-row between">
            {tplSel !== "new" ? <span className="cc-row" style={{ marginTop: 0, alignItems: "center", flexWrap: "nowrap" }}><label className="cc-btn sm">{savedTpl && savedTpl.logoUrl ? "Replace org logo" : "Upload org logo"}<input type="file" accept="image/png,image/jpeg,image/webp,image/svg+xml" hidden onChange={async (e) => { const f = e.target.files[0]; if (f) act(async () => API.call("POST", "/ops/brand-templates/" + tplSel, { logo: await fileToDataUrl(f) }), "Org logo uploaded."); }} /></label>{savedTpl && savedTpl.logoUrl ? <><img src={savedTpl.logoUrl} alt="Saved org logo" style={{ height: 40, maxWidth: 140, objectFit: "contain", background: "#fff", border: "1px solid var(--b-line, #ddd)", borderRadius: 6, padding: 3 }} /><span className="cc-pill ok">Logo saved</span><button className="cc-link" onClick={() => act(() => API.call("POST", "/ops/brand-templates/" + tplSel, { removeLogo: true }), "Org logo removed.")}>Remove</button></> : <span className="cc-pill quiet">No org logo yet</span>}</span> : <span />}
            <span className="cc-row" style={{ marginTop: 0 }}><button className="cc-btn ghost" onClick={() => { setTplSel(null); setTplDraft(null); }}>Close</button>
              <button className="cc-btn primary" onClick={() => act(() => tplSel === "new"
                ? API.call("POST", "/ops/brand-templates", { code: tdraft.code, name: tdraft.name, tokens: tdraft.tokens, guidelines: tdraft.guidelines || "" })
                : API.call("POST", "/ops/brand-templates/" + tplSel, {
                  name: tdraft.name, tokens: tdraft.tokens, guidelines: tdraft.guidelines || "", guideUrl: tdraft.guideUrl || "",
                  ...(tdraft.removeGuide ? { removeGuide: true } : {}), ...(tdraft.newGuide ? { guide: tdraft.newGuide.dataUrl, guideName: tdraft.newGuide.name } : {})
                }), "Template saved.")}>Save template</button></span>
          </div>
        </div>}
      </Card>
      <ClubLogos />
      <TrialExtend />
    </>;
  }

  /* ---------------- Getting started ---------------- */
  // The landing screen. Admins see how to run the club first, then everyone sees
  // the path through the modules. Each module hands its output to the next.
  const JOURNEY = [
    ["Review", "Start here", "Run your free membership Review. It shows who is joining, who is leaving and why, and gives you a 90-day plan.", ""],
    ["Ideas", "Try out ideas", "Get fundraising and event ideas that suit your club's size and community. Pick the one you like best.", "Review → Ideas: your Review findings shape the suggestions."],
    ["Events", "Turn an idea into a plan", "Open Events, choose an Idea and turn it into a plan: timeline, budget, volunteer roles and follow-up.", "Ideas → Events: start a plan from any saved Idea."],
    ["Tasks", "Run it as a team", "Import the Event plan into Tasks and the whole team can see who is doing what, and what is overdue.", "Events → Tasks: import an Event or Comms plan as a project."],
    ["Comms", "Tell people about it", "Take the Idea or Event and create a marketing plan: who to reach, what to say and which channels to use.", "Ideas / Events → Comms: build the marketing plan from either."],
    ["Social", "Post and automate", "Take the Comms plan and create the social posts, then schedule and automate publishing.", "Comms → Social: see the Comms plan beside your posts and link them."]
  ];
  function StartPane({ clubInfo, asMember, onGo }) {
    const c = clubInfo;
    if (!c) return <div className="cc-page center"><p className="cc-muted">Loading…</p></div>;
    const isAdmin = c.me.isAdmin && !asMember;
    const trial = c.trial && !c.trial.expired ? c.trial : null;
    const can = (m) => !!c.me.access[m];
    return (
      <div className="cc-page"><div className="cc-wrap">
        <div className="cc-pagehead"><div>
          <div className="cc-label">{isAdmin ? "Club admin" : "Your club"}</div>
          <h1>{asMember ? "Welcome to " + c.club.name : "How to get started with " + c.club.name}</h1>
          <p className="cc-muted">{isAdmin ? "Set up your people first, then follow the path through the modules." : "Here is how Clubcraft works for your club, from your first Review to your social posts."}</p>
        </div></div>

        {isAdmin && <Card title="1. Set up your club" className="cc-start">
          <div className="cc-steps">
            <div><b>What an admin does</b><p>Club admins choose the plan, decide who gets which access, approve people who ask to join and keep the club's details up to date. Have more than one admin: clubs change office-bearers every year.</p></div>
            <div><b>Add another admin</b><p>In <button className="cc-link" onClick={() => onGo("admin")}>Plan, people, settings</button>, either tick <i>Admin</i> beside an existing member, or use <i>Invite someone</i> and choose <i>Club admin</i>.</p></div>
            <div><b>Add your people</b><p>Use <i>Invite someone</i> to send a link, or let members find the club and ask to join. Their requests appear under <i>Requests to join</i> for you to approve. New people start with your club defaults; set what each person can do in each app (Admin, Edit or View) on the Access page.</p></div>
            <div><b>Check what the club has</b><p><button className="cc-link" onClick={() => onGo("club")}>My club</button> shows what the club can use today and what is left of the free trial. <i>Your plan</i> in Plan, people, settings shows your bundle and band, and <i>Access</i> shows who can do what in each app.</p></div>
          </div>
        </Card>}

        <Card title={isAdmin ? "2. Work through the modules" : "Work through the modules"} className="cc-start">
          <p className="cc-muted sm cc-intro">Each module builds on the one before, so nothing is typed twice.</p>
          <ol className="cc-journey">
            {JOURNEY.map(([m, head, text, link], i) => (
              <li key={m}>
                <span className="cc-jn" aria-hidden="true">{i + 1}</span>
                <div className="cc-jb">
                  <div className="cc-jh"><ModIcon m={m} /><b>{head}</b><span className="cc-jm">{m}</span>{!can(m) && <span className="cc-pill quiet">Not in your access</span>}</div>
                  <p>{text}</p>
                  {link && <p className="cc-link-line">{link}</p>}
                  <div className="cc-row" style={{ marginTop: 6 }}>{BUILT[m] && <button className="cc-btn sm primary" disabled={!can(m)} onClick={() => onGo(m === "Social" ? "social" : "tasks")}>Open {m}</button>}<button className="cc-btn sm" onClick={() => onGo("mod:" + m)}>{DEMO && m !== "Tasks" ? "See " + m : "How to get started with " + m}</button></div>
                </div>
              </li>
            ))}
          </ol>
        </Card>

        <Card title="Also with your club" className="cc-start">
          <div className="cc-soon">{TOOLS.map((t) => <div key={t}><b>{t}</b><span className={"cc-pill " + (t === "Finances" ? "trial" : "ok")}>{TOOL_TAG[t]}</span><p>{MOD_INFO[t]}</p><button className="cc-btn sm" onClick={() => onGo("mod:" + t)}>See {t}</button></div>)}</div>
        </Card>
      </div></div>
    );
  }

  /* ---------------- Module home: example + "How to get started" for one app ---------------- */
  // Recommended steps per app. `done` reads the club's real data where the app
  // exists (Tasks today); apps not built yet show their steps with no ticks, and an
  // "Example" tab (previews.jsx) so people can see what is coming.
  const STEPS = {
    Review: ["Gather a few facts: member ages, how long people have been in, and who joined or left in the last two years", "Answer the Review form (three short steps)", "Add your website and Facebook page if you have them", "Read the report: traffic lights, pipeline and who to attract", "Pick your first actions, then print it or make a presentation for the board"],
    Ideas: ["Run your Review first (optional, but it sharpens the ideas)", "Describe your club and community", "Generate ideas", "Shortlist your top three", "Choose one and take it to Events"],
    Events: ["Open Events and choose an Idea", "Turn it into a plan", "Check the timeline and budget", "Fill the volunteer roles", "Send the plan to Tasks"],
    Tasks: [
      ["Create your first project", (b) => b.projects.length >= 1],
      ["Add at least five tasks", (b) => b.tasks.length >= 5],
      ["Give a task to someone", (b) => b.tasks.some((t) => t.members.length)],
      ["Set a due date on a task", (b) => b.tasks.some((t) => t.due)],
      ["Add a teammate to a project", (b) => b.projects.some((p) => p.memberUids.length > 1)],
      ["Finish a task", (b) => b.tasks.some((t) => t.completedAt)]
    ],
    Comms: ["Open Comms and choose an Idea or Event", "Describe who you want to reach", "Create the marketing plan", "Choose your channels", "Send the plan to Tasks, or on to Social"],
    Social: ["Open Social and choose a Comms plan", "Set your brand colours and logo", "Connect Facebook and Instagram in Socials", "Create your first posts", "Approve ready posts for auto-publish"],
    Calendar: ["Add your regular club meeting", "Check the club time zone (admins)", "Send a Comms plan's dates to the calendar", "Subscribe from your own phone or computer calendar with your personal link", "Add a personal entry and choose who can see it"],
    Members: ["Start the register (it adds everyone who has a login)", "Set your membership types and fees", "Import a spreadsheet of members who do not have a login", "Check who is lapsed or has an unpaid fee", "Choose whether members can see the directory (admins)"],
    Contacts: ["Check your members are listed (they appear by themselves)", "Add or import your sponsors, suppliers and speakers", "Add the custom fields your club needs (admins)", "Record how people agreed to a mailing list", "Download a mailing list to use in Comms or Zoho"],
    Finances: ["Start with the free Zoho Books plan (see the example for what it includes)", "Move to Standard (under US$15 a month) if you need bank feeds, recurring expenses or more reporting", "Or tell us if you already use Xero or MYOB", "Link an event's budget to your accounts", "Invite your accountant"]
  };
  const BUILT = { Tasks: true, ...(window.CCDemo && window.CCDemo.on ? {} : { Social: true }) };   // Social is live only outside the demo
  const TOOLS = ["Calendar", "Members", "Contacts", "Finances"];
  const TOOL_TAG = { Calendar: "Free", Members: "Included", Contacts: "Free", Finances: "Free to start" };

  function ModulePane({ module: m, clubId, clubInfo, onGo, onChanged }) {
    const demo = window.CCDemo && window.CCDemo.on;
    const tool = TOOLS.includes(m), built = !!BUILT[m];
    const Example = window.CCPreviews && window.CCPreviews[m];
    const RealApp = !demo && ({ Review: window.CCReview, Ideas: window.CCIdeas, Events: window.CCEvents, Comms: window.CCComms, Calendar: window.CCCalendar, Members: window.CCMembers, Contacts: window.CCContacts })[m];
    const real = !!RealApp;
    const first = () => (real ? "reports" : Example && !built && demo ? "example" : "steps");
    const [view, setView] = React.useState(first);
    const [board, setBoard] = React.useState(null);
    const [err, setErr] = React.useState(null);
    const steps = STEPS[m] || [];
    const access = tool && !((m === "Calendar" || m === "Contacts") && real) ? "edit" : clubInfo.me.access[m];
    const trial = clubInfo.trial && !clubInfo.trial.expired ? clubInfo.trial : null;
    React.useEffect(() => { store.set("cc_seen_" + clubId + "_" + m, "1"); setView(first()); }, [m, clubId]);
    React.useEffect(() => {
      setBoard(null); setErr(null);
      if (m !== "Tasks" || !access) return;
      API.call("GET", "/board", null, { club: clubId }).then((r) => {
        const projects = r.projects || [];
        setBoard({ projects, tasks: projects.reduce((a, p) => a.concat(p.tasks || []), []) });
      }).catch((e) => setErr(e.message));
    }, [m, clubId]);
    const rows = steps.map((s) => (Array.isArray(s) ? { text: s[0], done: board ? !!s[1](board) : null } : { text: s, done: null }));
    const tracked = built && !!board;
    const done = rows.filter((r) => r.done).length;
    const status = tool ? (m === "Finances" ? "Optional: free to start with Zoho Books, set up with Delivio" : m === "Members" ? "Included with your club's plan. Admins and people with Edit access manage it; everyone else sees the directory" : "Free with every plan, trial included")
      : access === "edit" ? (trial ? "You can use it during the free trial" : "You can edit it") : access === "view" ? (trial ? "You can view it during the free trial" : "You can view it") : "Not in your access";
    return (
      <div className="cc-appwrap">
      <window.CCAppMenu title={m} iconNode={<ModIcon m={m} />} active={view} groups={[{ items: [
        { key: "reports", label: m === "Review" ? "Your Reviews" : m === "Calendar" ? "The calendar" : "Your " + m, icon: window.CCMenuIcons.list, hidden: !real, onClick: () => setView("reports") },
        { key: "example", label: "See an example", icon: window.CCMenuIcons.example, hidden: !Example, onClick: () => setView("example") },
        { key: "steps", label: "How to get started", icon: window.CCMenuIcons.steps, onClick: () => setView("steps") }] }]} />
      <div className="cc-appmain"><div className="cc-page"><div className="cc-wrap wide">
        <div className="cc-pagehead"><div>
          <button className="cc-link" onClick={() => onGo("start")}>← Get started</button>
          <h1><ModIcon m={m} /> {m}</h1>
          <p className="cc-muted">{MOD_INFO[m]}</p>
          {window.CCRoomNote && <window.CCRoomNote app={m} force={view === "steps"} />}
        </div>
          {built ? <button className="cc-btn primary lg" disabled={!access} onClick={() => onGo(m === "Social" ? "social" : "tasks")}>Open {m}</button> : <span className="cc-pill trial">{real ? "Live" : demo ? "Preview" : "Coming soon"}</span>}
        </div>
        {!demo && <div className="cc-note trial">{status}.{!built && !real && ` ${m} is still being built. The example shows what it will do.`}{!access && " Ask a club admin about access."}</div>}
        <Err e={err} />
        {view === "reports" && real ? <RealApp clubId={clubId} clubInfo={clubInfo} onGo={onGo} onChanged={onChanged} /> : view === "example" && Example ? <Example onGo={onGo} /> : (
          <Card title="How to get started" aside={tracked ? <span className="cc-pill ok">{done} of {rows.length} done</span> : <span className="cc-pill quiet">{rows.length} steps</span>}>
            {tracked && <div className="cc-bar" role="img" aria-label={done + " of " + rows.length + " steps done"}><span style={{ width: Math.round(100 * done / rows.length) + "%" }} /></div>}
            <ol className="cc-steplist">
              {rows.map((r, i) => (
                <li key={i} className={r.done ? "done" : ""}>
                  <span className="cc-tick" aria-label={r.done ? "Done" : "Not done"}>{r.done ? "✓" : i + 1}</span>
                  <span>{r.text}</span>
                </li>
              ))}
            </ol>
            <p className="cc-muted sm">{built ? (access ? "Steps tick off as your club does them. Progress is for the whole club." : "") : "Progress tracking starts when " + m + " launches."}</p>
          </Card>
        )}
      </div></div></div></div>
    );
  }

  /* ---------------- Demo: banner and guided tour ---------------- */
  const TOUR = [
    ["start", "Welcome to Clubcraft", "This is a pretend club, Rotary Club of Example Bay. Everything here is example data, so click anything. We will walk through the apps in the order a club would use them."],
    ["start", "Get started", "Every new club lands here. Admins see how to set up their people, and everyone sees the path through the apps."],
    ["mod:Review", "Review", "A membership strategy audit built from what the club tells us, with traffic lights, who to attract and a 90-day plan. No membership records needed. Free with any paid plan."],
    ["mod:Ideas", "Ideas", "Fundraising, membership and community ideas that suit this club, ranked by fit, with an estimate of what each could raise."],
    ["mod:Events", "Events", "Pick an idea and turn it into a plan: timeline, budget and volunteers. Then send it on to Tasks, Comms or Calendar."],
    ["tasks", "Tasks (live)", "This one is the real task board. Drag a card, open a task, add one. Everything works in the demo and resets when you reload."],
    ["mod:Comms", "Comms", "The campaign plan, week by week, in the same layout as the Social Planner: pillars, topic and angle, and the posts planned. Tick weeks off as you go, and download it as a Word document."],
    ["mod:Social", "Social", "Posts written from the Comms plan, with AI help for captions and pictures. Each moves from Draft to Needs Edit to Ready to Post to Posted. Connect Facebook and Instagram once, and an admin approves each post before it goes out."],
    ["mod:Calendar", "Calendar", "One shared calendar, free with every plan. Add dates yourself, send them from your plans, drag items to a new day, keep personal entries only you see, and follow it from your own phone."],
    ["mod:Members", "Members", "The club's register: types and fees, who is paid up, who has lapsed, a spreadsheet import with undo, and the number that counts towards the club's price."],
    ["mod:Contacts", "Contacts", "Members appear by themselves, alongside sponsors, suppliers and speakers you add or import, with the fields your club chooses and mailing consent recorded. Free with every plan."],
    ["mod:Finances", "Finances", "Optional proper bookkeeping through Zoho Books, or a link to the system the club already uses."],
    ["club", "My club", "Every member sees what the club has, what is left of a free trial, and who to ask for more."],
    ["admin", "Admin", "Only admins see this: plans and prices, people, join requests and invitations. Try the plan chooser."],
    ["access", "Access", "Who can do what in each app. See it by app, by person, or as one grid, change a level, and set what new members start with. Club admins are Admin everywhere; everyone else is Admin, Edit, View or switched off per app."],
    ["trial", "See the free trial", "Every new club gets 14 days of everything, with clear limits and gentle reminders. Switch over to see how it looks."]
  ];
  function DemoBar() {
    const trial = window.CCDemo.trial;
    const cc = window.CCDemo.country;
    const href = (t, c) => location.pathname + "?demo=1" + (t ? "&state=trial" : "") + ((c || cc) !== "AU" ? "&country=" + (c || cc) : "") + location.hash;
    return (
      <div className="cc-demobar" role="region" aria-label="Demo">
        <span className="tag">DEMO</span>
        <span className="msg">Rotary Club of Example Bay, with example data. Changes reset when you reload.</span>
        <span className="cc-demosw" role="group" aria-label="Show the club as">
          <a className={!trial ? "on" : ""} href={href(false)}>On a paid plan</a><a className={trial ? "on" : ""} href={href(true)}>In its free trial</a>
        </span>
        <span className="cc-demosw" role="group" aria-label="Show the club in this country" title="Currency, prices, dates, time zone, tax wording and spelling follow the country">
          {window.CCCountries.COUNTRY_CODES.map((c) => <a key={c} className={cc === c ? "on" : ""} href={href(trial, c)}>{c === "GB" ? "UK" : c}</a>)}
        </span>
        <a className="cc-btn sm primary" href={location.pathname}>Start your own free trial</a>
      </div>
    );
  }
  function DemoTour({ go }) {
    const [i, setI] = React.useState(0), [open, setOpen] = React.useState(true);
    const [tab, title, text] = TOUR[i], last = i === TOUR.length - 1, trial = window.CCDemo.trial;
    const step = (n) => { const k = Math.max(0, Math.min(TOUR.length - 1, n)); setI(k); const t = TOUR[k][0]; if (t !== "trial") go(t); };
    if (!open) return <button className="cc-tourpill" onClick={() => setOpen(true)}>Guided tour</button>;
    return (
      <aside className="cc-tour" aria-label="Guided tour">
        <div className="cc-tour-h"><span>Step {i + 1} of {TOUR.length}</span><button className="cc-x" aria-label="Close the tour" onClick={() => setOpen(false)}>×</button></div>
        <div className="cc-tour-dots" aria-hidden="true">{TOUR.map((_, n) => <i key={n} className={n === i ? "on" : n < i ? "past" : ""} />)}</div>
        <h3>{title}</h3><p>{text}</p>
        <div className="cc-row between" style={{ marginTop: 10 }}>
          <button className="cc-btn sm ghost" disabled={i === 0} onClick={() => step(i - 1)}>Back</button>
          {last ? <a className="cc-btn sm primary" href={location.pathname + "?demo=1" + (trial ? "" : "&state=trial") + "#/start"}>{trial ? "Back to the paid club" : "Show the free trial"}</a>
            : <button className="cc-btn sm primary" onClick={() => step(i + 1)}>{i === 0 ? "Start the tour" : "Next"}</button>}
        </div>
      </aside>
    );
  }

  /* ---------------- Tasks tab ---------------- */
  function TasksPane({ clubId, access, allowance, isAdmin, onPlan }) {
    if (!access) return <div className="cc-page center"><Card className="narrow"><h1>Tasks isn't in your plan</h1><p className="cc-muted">Tasks is switched off for you, or is not in your club's bundle. Ask a club admin.</p></Card></div>;
    window.CC_ACTIVE_CLUB = clubId;
    const note = allowance && allowance.limit ? allow("Tasks", allowance) : null;
    return <div className="cc-boardwrap">
      {note && (allowance.state === "available" || allowance.state === "used" || allowance.state === "ended") && <div className={"cc-allowbar " + note.tone}><span><b>Free trial:</b> {plural(allowance.used, "project")} of {allowance.limit} used.{allowance.state !== "available" && !isAdmin ? " Ask your club admin about a plan." : ""}</span>{allowance.state !== "available" && isAdmin && <button className="cc-link" onClick={onPlan}>Choose a plan to add more</button>}</div>}
      <div className="cc-board">{h(window.PlannerApp, { key: clubId })}</div>
    </div>;
  }

  /* ---------------- Social tab ---------------- */
  function SocialPane({ clubId, access, allowance, isAdmin, onPlan }) {
    if (!access) return <div className="cc-page center"><Card className="narrow"><h1>Social isn't in your plan</h1><p className="cc-muted">Social is switched off for you, or is not in your club's bundle. Ask a club admin.</p></Card></div>;
    window.CC_ACTIVE_CLUB = clubId;
    const note = allowance && allowance.limit ? allow("Social", allowance) : null;
    return <div className="cc-boardwrap">
      {note && (allowance.state === "available" || allowance.state === "used" || allowance.state === "ended") && <div className={"cc-allowbar " + note.tone}><span><b>Free trial:</b> {plural(allowance.used, "campaign")} of {allowance.limit} used.{allowance.state !== "available" && !isAdmin ? " Ask your club admin about a plan." : ""}</span>{allowance.state !== "available" && isAdmin && <button className="cc-link" onClick={onPlan}>Choose a plan to add more</button>}</div>}
      <div className="cc-board cc-socialhost">{h(window.CCSocial, { key: clubId })}</div>
    </div>;
  }

  /* ---------------- root ---------------- */
  function Shell() {
    const [stage, setStage] = React.useState("loading");
    const [me, setMe] = React.useState(null);
    const [clubId, setClubId] = React.useState(store.get("cc_club"));
    const validTab = (t) => t && (/^(start|club|admin|access|tasks|social|delivio)$/.test(t) || /^mod:(Review|Ideas|Events|Tasks|Comms|Social|Calendar|Members|Contacts|Finances)$/.test(t));
    const hashTab = () => { const t = decodeURIComponent((location.hash || "").replace(/^#\/?/, "")); return validTab(t) ? t : null; };
    const [tab, setTab] = React.useState(hashTab() || (DEMO ? "start" : store.get("cc_tab")) || "start");
    const [asMember, setAsMember] = React.useState(false);
    const [planSignal, setPlanSignal] = React.useState(0);
    const [finding, setFinding] = React.useState(false);
    const [clubInfo, setClubInfo] = React.useState(undefined);
    const [note, setNote] = React.useState(null);
    const [menu, setMenu] = React.useState(false);

    async function loadMe(preferClub) {
      const m = await API.call("GET", "/me");
      setMe(m);
      const ids = m.clubs.map((x) => x.id);
      const pick = [preferClub, clubId].find((x) => x && ids.includes(x)) || ids[0] || null;
      setClubId(pick); store.set("cc_club", pick);
      return m;
    }
    React.useEffect(() => {
      (async () => {
        try {
          if (!(await API.isSignedIn())) { setStage("signed-out"); return; }
          const token = store.get("cc_invite");
          let prefer = null;
          if (token) {
            store.set("cc_invite", null);
            try { prefer = (await API.call("POST", "/invitations/accept", { token })).clubId; setNote("Invitation accepted. Welcome to the club."); }
            catch (e) { setNote("Invitation: " + e.message); }
          }
          await loadMe(prefer);
          setStage("ready");
        } catch (e) { setNote(e.message); setStage(e.status === 401 ? "signed-out" : "error"); }
      })();
    }, []);
    const refreshClub = () => API.call("GET", "/club", null, { club: clubId }).then((c) => { setClubInfo(c); applyBrand(c.brand); }).catch(() => setClubInfo(null));
    React.useEffect(() => { if (clubId) { setClubInfo(undefined); refreshClub(); } }, [clubId]);
    React.useEffect(() => {
      const onErr = (e) => { setNote(e.detail); setTimeout(() => setNote(null), 6000); };
      window.addEventListener("cc-error", onErr);
      const onChanged = () => refreshClub();      // a project or campaign was made or removed: the trial allowance changes
      window.addEventListener("cc-club-changed", onChanged);
      return () => { window.removeEventListener("cc-error", onErr); window.removeEventListener("cc-club-changed", onChanged); };
    }, []);

    if (ABOUT) return <Landing signedIn={stage === "ready"} />;
    if (stage === "loading") return <div className="cc-page center"><p className="cc-muted">Connecting…</p></div>;
    if (stage === "signed-out") return ABOUT || (!ORG && !store.get("cc_invite")) ? <Landing /> : <SignedOut />;
    if (stage === "error") return <div className="cc-page center"><Card className="narrow"><h1>Something went wrong</h1><Err e={note} /><button className="cc-btn" onClick={() => location.reload()}>Try again</button></Card></div>;

    const club = me.clubs.find((x) => x.id === clubId);
    const goPlan = () => { setPlanSignal((n) => n + 1); go("admin"); };
    const go = (t) => {
      if (t.startsWith("open:")) {   // a module name: straight into the app once seen, else its how-to page first
        const m = t.slice(5), acc = clubInfo && clubInfo.me.access[m];
        t = BUILT[m] && acc && (DEMO || store.get("cc_seen_" + clubId + "_" + m)) ? (m === "Social" ? "social" : "tasks") : "mod:" + m;
      }
      setTab(t); store.set("cc_tab", t);
      try { history.replaceState(null, "", location.pathname + location.search + "#/" + t); } catch (e) {}
    };
    const onFound = async (newClub, invite) => {
      setFinding(false);
      await loadMe(newClub);
      if (invite) setNote("Club set up. Send your second admin this link: " + location.origin + location.pathname + invite.acceptPath.replace("/join", ""));
      go("start");
    };
    const inClub = !!club && !finding;
    const opsView = me.isPlatformAdmin && tab === "delivio" && !finding;
    const brand = clubInfo && clubInfo.brand;
    const levelLine = brand ? [clubInfo.club.district, ...brand.levels.filter((l) => !l.hidden).map((l) => l.name)].filter(Boolean).join(" · ") : "";
    const topBar = () => (
      <header className="cc-top">
        <div className="cc-top-id">
          <Logo brand={inClub ? brand : null} size={30} />
          {club ? <div className="cc-clubsw">
            <button className="cc-top-club" onClick={() => setMenu(!menu)} aria-expanded={menu} aria-haspopup="menu"><b>{club.name}<span className="cc-caret" aria-hidden="true">▾</span></b><small>{levelLine || "Clubcraft"}</small></button>
            {menu && <div className="cc-menu" onMouseLeave={() => setMenu(false)}>
              {me.clubs.map((x) => <button key={x.id} className={x.id === clubId && inClub ? "on" : ""} onClick={() => { setMenu(false); setFinding(false); if (tab === "delivio") go("start"); setAsMember(false); setClubId(x.id); store.set("cc_club", x.id); }}>{x.name}{x.isAdmin ? " · admin" : ""}</button>)}
              <button onClick={() => { setMenu(false); setFinding(true); }}>Find or join another club…</button>
            </div>}
          </div> : <div className="cc-top-club"><b>Clubcraft</b></div>}
        </div>
        <nav className="cc-tabs">
          {!inClub && me.isPlatformAdmin && <button className={!opsView ? "on" : ""} onClick={() => { setFinding(false); go("club"); }}>Find a club</button>}
          {!inClub && me.isPlatformAdmin && <button className={opsView ? "on" : ""} onClick={() => { setFinding(false); go("delivio"); }}>Delivio</button>}
        </nav>
        <span className="cc-spacer" />
        <span className="cc-who">{me.user.email}</span>
        <button className="cc-btn sm ghost onbrand" onClick={API.signOut}>{DEMO ? "Exit demo" : "Sign out"}</button>
      </header>
    );
    const sidebar = () => {
      if (!inClub) return null;
      const ci = clubInfo, admin = !!(ci && ci.me.isAdmin && !asMember);
      const on = (t) => (tab === t ? " on" : "");
      return (
        <div className="cc-rail"><aside className="cc-side" aria-label="Club menu">
          <button className={"cc-nav" + on("start")} onClick={() => go("start")}><svg className="cc-micon" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 11 12 4l8 7v8a1 1 0 0 1-1 1h-4v-5H9v5H5a1 1 0 0 1-1-1Z" /></svg><span>Get started</span></button>
          <div className="cc-side-h">Apps</div>
          {MODULES.map((m) => {
            const acc = ci ? ci.me.access[m] : null, al = ci && ci.allowances ? allow(m, ci.allowances[m]) : null, here = tab === (m === "Tasks" ? "tasks" : m === "Social" ? "social" : "mod:" + m) || tab === "mod:" + m;
            return <div key={m} className={"cc-navrow" + (here ? " on" : "") + (acc ? "" : " locked") + (acc && BUILT[m] ? " hasq" : "")}>
              <button className="cc-nav" onClick={() => go("open:" + m)} title={acc ? MOD_INFO[m] : m + " is not in your access. Click to see how to get it."}>
                <ModIcon m={m} /><span>{m}</span>{!acc && <i className="cc-lock" aria-label="Not available">🔒</i>}{acc && al && al.short && <small className={"cc-chip " + al.tone}>{al.short}</small>}
              </button>
              {acc && BUILT[m] && <button className="cc-navq" onClick={() => go("mod:" + m)} title={"How to get started with " + m} aria-label={"How to get started with " + m}>?</button>}
            </div>;
          })}
          <div className="cc-side-div" />
          {TOOLS.map((m) => <div key={m} className={"cc-navrow" + (tab === "mod:" + m ? " on" : "")}>
            <button className="cc-nav" onClick={() => go("mod:" + m)} title={MOD_INFO[m]}><ModIcon m={m} /><span>{m}</span><small className={"cc-chip " + (m === "Finances" ? "warn" : "good")}>{TOOL_TAG[m]}</small></button>
          </div>)}
          <div className="cc-side-h">Club</div>
          <button className={"cc-nav" + on("club")} onClick={() => go("club")}><svg className="cc-micon" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 20h18M5 20V9l7-5 7 5v11M9 20v-6h6v6" /></svg><span>My club</span></button>
          {admin && <>
            <div className="cc-side-h">Admin</div>
            <button className={"cc-nav" + on("admin")} onClick={() => go("admin")}><svg className="cc-micon" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3 4 6v6c0 4.5 3.4 7.8 8 9 4.6-1.2 8-4.5 8-9V6l-8-3Z" /></svg><span>Plan, people, settings</span></button>
            <button className={"cc-nav" + on("access")} onClick={() => go("access")}><svg className="cc-micon" viewBox="0 0 24 24" aria-hidden="true"><path d="M14.5 9.5a4 4 0 1 1-1.2 2.9M13.3 12.4 4 21h3v-3h3v-2.5" /></svg><span>Access</span></button>
          </>}
          <span className="cc-side-sp" />
          {ci && ci.trial && <div className={"cc-sidetrial" + (ci.trial.expired ? " over" : ci.trial.daysLeft <= 3 ? " soon" : "")}>
            <b>{ci.trial.expired ? "Free trial ended" : ci.trial.unlimited ? "Free trial, unlimited" : "Free trial"}</b>
            {!ci.trial.expired && !ci.trial.unlimited && <><span>{plural(ci.trial.daysLeft, "day")} left</span><div className="cc-bar" role="img" aria-label={ci.trial.daysLeft + " of 14 days left"}><span style={{ width: Math.max(4, Math.round(100 * ci.trial.daysLeft / 14)) + "%" }} /></div></>}
            {ci.trial.unlimited ? <small>No limits for Delivio</small> : admin ? <button className="cc-link" onClick={goPlan}>Choose a plan</button> : <small>Ask your club admin about a plan</small>}
          </div>}
          {ci && ci.me.isAdmin && <button className={"cc-nav cc-asm" + (asMember ? " on" : "")} aria-pressed={asMember} onClick={() => { const next = !asMember; setAsMember(next); if (next && (tab === "admin" || tab === "access" || tab === "delivio")) go("start"); }} title="See the club the way a member sees it"><svg className="cc-micon" viewBox="0 0 24 24" aria-hidden="true"><path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12Zm10 3a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z" /></svg><span>{asMember ? "Exit member view" : "View as member"}</span></button>}
          {me.isPlatformAdmin && !asMember && <button className={"cc-nav" + on("delivio")} onClick={() => { setFinding(false); go("delivio"); }}><svg className="cc-micon" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 19V5M4 19h16M8 15v-4M12 15V8M16 15v-6" /></svg><span>Delivio operations</span></button>}
        </aside></div>
      );
    };
    const toast = note && <div className="cc-toast" role="status" onClick={() => setNote(null)}>{note}</div>;
    const body = (content) => <div className="cc-body">{sidebar()}<main className="cc-main">{content}</main></div>;
    if (opsView) return <div className="cc-shell">{topBar()}{toast}{body(<OpsPanel />)}</div>;
    if (!inClub) return <div className="cc-shell">{topBar()}{toast}{ORG ? <FindClub me={me} onDone={onFound} onCancel={club ? () => setFinding(false) : null} /> : <div className="cc-page"><div className="cc-wrap" style={{ maxWidth: 880 }}><OrgChooser /></div></div>}</div>;
    return (
      <div className="cc-shell">
        {DEMO && <DemoBar />}
        {topBar()}{toast}
        {asMember && <div className="cc-asbar" role="status"><span><b>Member view.</b> This is what an ordinary member sees. Admin tools are hidden.</span><button className="cc-btn sm" onClick={() => setAsMember(false)}>Back to admin view</button></div>}
        {body(<>
        {clubInfo && <AttentionBanner clubInfo={clubInfo} isAdmin={!!(clubInfo.me.isAdmin && !asMember)} onPlan={goPlan} />}
        {clubInfo && <WorkingFromStrip clubInfo={clubInfo} onChange={() => go("club")} />}
        {clubInfo && <TravelBanner clubInfo={clubInfo} clubId={clubId} onSaved={() => refreshClub && refreshClub()} />}
        {tab === "start" ? <StartPane clubInfo={clubInfo} asMember={asMember} onGo={go} />
          : tab.startsWith("mod:") ? (clubInfo ? <ModulePane module={tab.slice(4)} clubId={clubId} clubInfo={clubInfo} onGo={go} onChanged={refreshClub} /> : <div className="cc-page center"><p className="cc-muted">Loading…</p></div>)
          : tab === "tasks"
          ? (clubInfo === undefined ? <div className="cc-page center"><p className="cc-muted">Loading…</p></div> : <TasksPane clubId={clubId} access={clubInfo ? clubInfo.me.access.Tasks : null} allowance={clubInfo && clubInfo.allowances ? clubInfo.allowances.Tasks : null} isAdmin={!!(clubInfo && clubInfo.me.isAdmin && !asMember)} onPlan={goPlan} />)
          : tab === "social"
          ? (clubInfo === undefined ? <div className="cc-page center"><p className="cc-muted">Loading…</p></div> : <SocialPane clubId={clubId} access={clubInfo ? clubInfo.me.access.Social : null} allowance={clubInfo && clubInfo.allowances ? clubInfo.allowances.Social : null} isAdmin={!!(clubInfo && clubInfo.me.isAdmin && !asMember)} onPlan={goPlan} />)
          : tab === "access" && clubInfo && clubInfo.me.isAdmin && !asMember && window.CCAccess ? <window.CCAccess clubId={clubId} onChanged={refreshClub} onGo={go} />
          : <ClubPanel clubId={clubId} view={tab === "admin" && !asMember && clubInfo && clubInfo.me.isAdmin ? "admin" : "club"} onChanged={refreshClub} asMember={asMember} onGo={go} planSignal={planSignal} />}
        </>)}
        {DEMO && <DemoTour go={go} />}
      </div>
    );
  }

  ReactDOM.createRoot(document.getElementById("root")).render(<Shell />);
})();
