/* previews.jsx: "see an example" screens for the apps that are not built yet
 * (Review, Ideas, Events, Comms, Social) and for the club tools (Calendar,
 * Contacts, Finances). Canned data for a pretend club, "Rotary Club of Example
 * Bay". Used in two places: the demo (?demo=1) and the "Example" tab of each
 * app's page in the real app, so a club on its free trial can see what is coming.
 * Nothing here talks to the server.
 */
(function () {
  const h = React.createElement;
  const DAY = 86400000;
  const D = (n) => new Date(new Date().setHours(12, 0, 0, 0) + n * DAY);
  const nextSat = (min) => { let d = D(min); while (d.getDay() !== 6) d = new Date(d.getTime() + DAY); return d; };
  const fmt = (d) => d.toLocaleDateString(CCIntl.locale(), { weekday: "short", day: "numeric", month: "short" });
  const fmtShort = (d) => d.toLocaleDateString(CCIntl.locale(), { day: "numeric", month: "short" });
  const money = (n) => CCIntl.money(Math.round(n));
  const key = (d) => d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate();
  const COL = ["#0f8a8a", "#7a52c7", "#d2603a", "#2f7d4f", "#b0457a", "#3a6fb0", "#9a6a08", "#5a6b7a"];
  const ini = (n) => n.split(" ").map((w) => w[0]).join("").slice(0, 2).toUpperCase();
  const colOf = (n) => COL[Math.abs([...n].reduce((a, c) => a + c.charCodeAt(0), 0)) % COL.length];

  function Av({ name, size = 28 }) { return <span className="cc-ex-av" style={{ background: colOf(name), width: size, height: size, fontSize: size * 0.4 }} title={name}>{ini(name)}</span>; }
  function Tag({ tone, children }) { return <span className={"cc-pill " + (tone || "quiet")}>{children}</span>; }

  /* The frame every example sits in. */
  function Ex({ title, sub, actions, children }) {
    return (
      <div className="cc-ex">
        <div className="cc-ex-head">
          <div><h2>{title}</h2>{sub && <p>{sub}</p>}</div>
          <div className="cc-ex-actions"><span className="cc-ex-tag">Example data</span>{actions}</div>
        </div>
        {children}
      </div>
    );
  }
  const Panel = ({ title, aside, children, className }) => (
    <section className={"cc-ex-panel " + (className || "")}>{(title || aside) && <div className="cc-ex-ph">{title && <h3>{title}</h3>}{aside}</div>}{children}</section>
  );
  const Stat = ({ label, value, note, tone }) => <div className={"cc-ex-stat " + (tone || "")}><span>{label}</span><b>{value}</b>{note && <small>{note}</small>}</div>;
  const NextBtn = ({ onGo, to, children, primary }) => <button className={"cc-btn sm" + (primary ? " primary" : "")} onClick={() => onGo && onGo(to)}>{children}</button>;

  /* ---------------- Review: Membership Strategy Audit ---------------- */
  // Mirrors the Rotary AI audit (Rotary AI folder, "ServiceClub Response V2"): a traffic-light
  // dashboard, membership health from what the club told us, the four-stage pipeline, who to
  // attract and a 90-day plan. Clubcraft does not keep membership numbers; every figure here is
  // one the club typed into the Review form.
  const RAG = { g: ["Strength", "✓"], a: ["Needs attention", "!"], r: ["Critical gap", "✕"] };
  function Rag({ s, l }) { return <span className={"cc-rag " + s}><i aria-hidden="true">{RAG[s][1]}</i>{l || RAG[s][0]}</span>; }
  function Segments({ data, label }) {
    const total = data.reduce((a, d) => a + d.v, 0);
    return (
      <div className="cc-ex-seg" role="img" aria-label={label}>
        <div className="bar">{data.map((d) => <span key={d.l} style={{ flex: d.v, background: d.c }} title={d.l + ": " + d.v} />)}</div>
        <div className="key">{data.map((d) => <span key={d.l}><i style={{ background: d.c }} /><b>{d.l}</b> {d.v} <small>({Math.round(100 * d.v / total)}%)</small></span>)}</div>
      </div>
    );
  }
  function Review({ onGo }) {
    const dash = [["Website effectiveness", "a"], ["Facebook presence", "a"], ["Brand alignment", "g"], ["Membership appeal", "a"], ["Member retention", "r"], ["Meeting accessibility", "a"], ["Growth readiness", "r"]];
    const pipe = [["Awareness", "r", "Few people in Example Bay know the club exists outside its own circle.", "Your Facebook page posts about twice a month, mostly meeting reminders."],
      ["Interest", "a", "People who find the website cannot see when or where you meet.", "Add the meeting day, time and a contact to the home page."],
      ["Engagement", "a", "There is no easy way to try the club before joining.", "Open one project day a quarter to guests."],
      ["Conversion", "g", "Members say joining was friendly and low-pressure.", "Keep the personal welcome. Write it down so it survives a change of officers."]];
    const who = [["The busy professional", "30 to 45", "Wants useful contacts and a project, not a long dinner.", "Short project-based membership, evening or online."],
      ["The recent retiree", "60 to 70", "Wants purpose and company after work.", "Weekday daytime activity and a role that uses their skills."],
      ["The community leader", "40 to 60", "Teachers, health workers, small business owners who already volunteer.", "Introduced by a member they know."]];
    const plan = [["1 to 2", "Ring each member who missed three meetings in a row", "Membership Director", "Find out who is at risk before they leave"],
      ["2 to 3", "Add meeting day, time and contact to the website home page", "Secretary", "Interested people can find you"],
      ["3 to 4", "Name a buddy for every member of under three years", "President", "New members feel looked after"],
      ["5 to 6", "Trial one shorter, no-meal meeting a month", "Secretary", "Test whether time is the barrier"],
      ["7 to 8", "Hold a Bring-a-Friend night, with the Rotaract club invited", "Membership Director", "3 to 6 guests, 1 to 2 who join"],
      ["10 to 12", "Report back to the board and set next year's target", "President", "Agreed membership goal"]];
    return (
      <Ex title="Membership Strategy Audit" sub="Rotary Club of Example Bay. Built from what your club told us, in about ten minutes.">
        <div className="cc-ex-hero">
          <div><span>Prepared for</span><b>Sam Taylor, President</b></div>
          <div><span>Date</span><b>{fmt(D(0))}</b></div>
          <div><span>Based on</span><b>Your answers, website and Facebook page</b></div>
          <div className="act"><button className="cc-btn sm" type="button">Print</button><button className="cc-btn sm primary" type="button">Download Word</button></div>
        </div>
        <div className="cc-ex-note"><b>No membership records needed.</b> Clubcraft does not hold your member numbers, so every figure below is one your club typed in. If we connect to Rotary later, trends over the years could fill in by themselves.</div>

        <Panel title="1. Executive summary" aside={<small className="cc-muted">Traffic lights: strength, needs attention, critical gap</small>}>
          <p className="cc-ex-lead">Example Bay is a friendly club with a strong welcome and a loyal core, but more than half of members are over 65 and more people left than joined in the last two years. The main risk is time, not cost: members told us the meetings are the hardest part to fit in.</p>
          <div className="cc-ex-rag">{dash.map(([n, s]) => <div key={n}><span>{n}</span><Rag s={s} /></div>)}</div>
          <div className="cc-ex-callout"><b>Your most important action in the next 30 days</b><p>Ring every member who has missed three meetings in a row. Ask what would make it easier to come, and write down the answers.</p></div>
        </Panel>

        <Panel title="2. Membership health" aside={<small className="cc-muted">All figures are from your Review form</small>}>
          <div className="cc-ex-cols">
            <div>
              <h4 className="cc-ex-h4">Age profile (38 active members)</h4>
              <Segments label="Age profile: 65 plus 22, 40 to 65 14, under 40 2" data={[{ l: "65 and over", v: 22, c: "var(--b-primary-deep)" }, { l: "40 to 65", v: 14, c: "var(--b-primary)" }, { l: "Under 40", v: 2, c: "var(--b-accent)" }]} />
              <h4 className="cc-ex-h4">How long they have been members</h4>
              <Segments label="Tenure: under 3 years 6, 3 to 10 years 15, over 10 years 17" data={[{ l: "Under 3 years", v: 6, c: "var(--b-accent)" }, { l: "3 to 10 years", v: 15, c: "var(--b-primary)" }, { l: "Over 10 years", v: 17, c: "var(--b-primary-deep)" }]} />
            </div>
            <div>
              <h4 className="cc-ex-h4">The last two years, as you told us</h4>
              <div className="cc-ex-stats tight"><Stat label="Joined" value="5" tone="good" /><Stat label="Left" value="11" tone="warn" /><Stat label="Net" value="-6" tone="warn" note="Not sustainable" /></div>
              <h4 className="cc-ex-h4">Why members left</h4>
              <div className="cc-ex-tags">{["Not enough time", "Moved away", "Meetings not for me", "Cost", "Health"].map((t, i) => <span key={t}><b>{i + 1}</b>{t}</span>)}</div>
              <h4 className="cc-ex-h4">Why members joined</h4>
              <div className="cc-ex-tags alt">{["A friend invited me", "Wanted to give back", "Local projects", "Meeting people"].map((t, i) => <span key={t}><b>{i + 1}</b>{t}</span>)}</div>
            </div>
          </div>
          <div className="cc-ex-finds">
            <div><b>New members leave early</b><p>Most who left had been in the club under three years.</p></div>
            <div><b>Time is the main barrier</b><p>Your meeting is a weekday evening dinner. That suits retirees and works against anyone under 60.</p></div>
            <div><b>Friends bring friends</b><p>Every new member was invited by someone already in the club.</p></div>
          </div>
        </Panel>

        <Panel title="3. Membership pipeline">
          <div className="cc-ex-pipe">{pipe.map(([s, r, a, b]) => <div key={s}><div className="h"><b>{s}</b><Rag s={r} /></div><p>{a}</p><p className="cc-muted">{b}</p></div>)}</div>
        </Panel>

        <Panel title="4. Who to attract" aside={<small className="cc-muted">Only 2 members are under 40: the first step is a Rotaract link</small>}>
          <div className="cc-ex-cols three">{who.map(([n, age, m, j]) => <div key={n} className="cc-ex-persona"><b>{n}</b><span>{age}</span><p>{m}</p><small>What would help them join</small><p>{j}</p></div>)}</div>
          <p className="cc-muted sm">Under 30? Point them to the nearest Rotaract club first. It is the better peer fit and leads naturally to Rotary at 30.</p>
        </Panel>

        <Panel title="5. Your 90-day action plan" aside={<NextBtn onGo={onGo} to="tasks" primary>Send to Tasks</NextBtn>}>
          <table className="cc-ex-table"><thead><tr><th>Week</th><th>Action</th><th>Owner</th><th>Expected outcome</th></tr></thead>
            <tbody>{plan.map((r) => <tr key={r[1]}><td className="when">{r[0]}</td><td><b>{r[1]}</b></td><td>{r[2]}</td><td className="cc-muted">{r[3]}</td></tr>)}</tbody></table>
        </Panel>
        <p className="cc-ex-foot">Prepared by Clubcraft Review. This report is written by AI from your answers. Please check it with your club leadership before you share it. Example only.</p>
      </Ex>
    );
  }

  /* ---------------- Ideas (Rotary Event Ideas) ---------------- */
  // Each idea carries what the Rotary Event Ideas agent returns: name with the full club name,
  // audience, cost range, Area of Focus, cultural fit and timing.
  const IDEAS = [
    { t: "Trivia night", n: "Rotary Club of Example Bay Trivia Night", c: "Raise funds", a: "Supporting education", d: "Teams of eight compete over three rounds, with a raffle. A good mix for families, workplaces and sports clubs.", who: "Families, workplaces, sports clubs", cost: "$800 to $1,500", r: "$2,500 to $4,000", e: 2, p: 12, w: "Autumn or winter Saturday", f: 92, local: "Offer alcohol-free drinks and vegetarian, halal and gluten-free food. Check local licence rules.", why: "Your Audit says time is the barrier. One evening a year, with a team format, brings guests under 60." },
    { t: "Hardware-store sausage sizzle", n: "Rotary Club of Example Bay Community Sizzle", c: "Raise funds", a: "Growing local economies", d: "A weekend morning at a local hardware store. Light on money and effort.", who: "Shoppers, tradespeople, neighbours", cost: "$200 to $300", r: "$900 to $1,500", e: 1, p: 8, w: "Any Saturday morning", f: 88, local: "Offer a vegetarian option and a clean, labelled hot plate. Check council food-safety rules.", why: "Low effort for an older membership, and it puts the club's name on a busy street." },
    { t: "Bring-a-Friend dinner", n: "Rotary Club of Example Bay Open Night", c: "Find members", a: "Membership", d: "A relaxed meeting where every member brings one guest, with a short project story and an easy next step.", who: "Friends, neighbours, local Rotaract members", cost: "$300 to $600", r: "3 to 6 guests who may join", e: 1, p: 10, w: "Within eight weeks", f: 85, local: "Keep it informal and welcoming. Offer a choice of meals and a quiet start time.", why: "Every new member came through a friend. This turns that habit into an event." },
    { t: "Community garage sale", n: "Rotary Club of Example Bay Garage Sale Weekend", c: "Raise funds", a: "Protecting the environment", d: "Members and neighbours donate goods, and a reuse message goes with every sale.", who: "Neighbours, bargain hunters, families", cost: "$100", r: "$1,200 to $2,000", e: 2, p: 15, w: "Spring", f: 81, local: "Check weather and noise rules, and have a plan for unsold goods.", why: "Members have plenty to give, and the sale draws a younger crowd." },
    { t: "Clean-up day with the Scouts", n: "Rotary Club of Example Bay Clean-up Day", c: "Serve the community", a: "Protecting the environment", d: "A morning of litter pick-up on the foreshore with Scouts and families, followed by a barbecue.", who: "Young families, schools, local press", cost: "$150", r: "Goodwill and local news", e: 2, p: 20, w: "Any weekend", f: 79, local: "Provide gloves and a first aid kit, and respect any local rules on wildlife areas.", why: "Gets young families and the local paper to know your name." },
    { t: "Charity fun run or walk", n: "Rotary Club of Example Bay Fun Run", c: "Raise funds", a: "Fighting disease", d: "A 5 km run and 2 km family walk with sponsors, a coffee van and a warm-up.", who: "Runners, schools, families", cost: "$3,000 to $5,000", r: "$6,000 to $12,000", e: 3, p: 30, w: "Autumn", f: 74, local: "Needs council permits and first aid. Best as a second project once the team is bigger.", why: "A big return, but it needs 30 people and permits." }
  ];
  function Ideas({ onGo }) {
    const [f, setF] = React.useState("All");
    const [star, setStar] = React.useState({});
    const nStar = Object.values(star).filter(Boolean).length;
    const cats = ["All", "Raise funds", "Find members", "Serve the community", ...(nStar ? ["Shortlisted"] : [])];
    const list = IDEAS.filter((i) => (f === "All" || (f === "Shortlisted" ? star[i.t] : i.c === f)));
    return (
      <Ex title="Event ideas for Rotary Club of Example Bay" sub="Six ideas, ranked by how well they fit your club and community. Informed by your Membership Strategy Audit.">
        <div className="cc-ex-note"><b>From your audit:</b> most members are over 65 and few are under 40, so these favour low-effort events that also bring in younger guests. Event names include the full club name, as Rotary's brand guidance asks.</div>
        <div className="cc-ex-chips" role="tablist" aria-label="Filter ideas">{cats.map((c) => <button key={c} role="tab" aria-selected={f === c} className={f === c ? "on" : ""} onClick={() => setF(c)}>{c}{c === "Shortlisted" && <small>{nStar}</small>}</button>)}</div>
        <div className="cc-row" style={{ gap: 8, flexWrap: "wrap" }}><button className="cc-btn sm" type="button">Download Word</button>{nStar > 0 && <button className="cc-btn sm" type="button">Word: shortlist ({nStar})</button>}<button className="cc-btn sm" type="button">Print</button><button className="cc-btn sm ghost" type="button">Run again with changes</button></div>
        <div className="cc-ex-cards">
          {list.map((i) => (
            <article key={i.t} className="cc-ex-idea">
              <div className="top"><span className="tags"><Tag>{i.c}</Tag><Tag tone="trial">{i.a}</Tag></span><span className="fit" title="How well this fits your club"><b>{i.f}</b>fit</span></div>
              <h3>{i.n}</h3>
              <p className="why">{CCIntl.sample(i.d)}</p>
              <dl>
                <div><dt>Who comes</dt><dd>{i.who}</dd></div>
                <div><dt>Costs about</dt><dd>{CCIntl.sample(i.cost)}</dd></div>
                <div><dt>Could raise</dt><dd>{CCIntl.sample(i.r)}</dd></div>
                <div><dt>Effort</dt><dd><span className="dots" aria-label={["Low", "Medium", "High"][i.e - 1] + " effort"}>{[1, 2, 3].map((n) => <i key={n} className={n <= i.e ? "on" : ""} />)}</span> {["Low", "Medium", "High"][i.e - 1]}, {i.p} people</dd></div>
                <div><dt>Best time</dt><dd>{i.w}</dd></div>
              </dl>
              <p className="cc-ex-fit"><b>Why it suits you:</b> {CCIntl.sample(i.why)}</p>
              <p className="cc-ex-local"><b>Check locally:</b> {CCIntl.sample(i.local)}</p>
              <div className="cc-row" style={{ marginTop: 10 }}>
                <NextBtn onGo={onGo} to="mod:Events" primary>Plan this in Events</NextBtn>
                <button className={"cc-btn sm " + (star[i.t] ? "" : "ghost")} type="button" aria-pressed={!!star[i.t]} onClick={() => setStar({ ...star, [i.t]: !star[i.t] })}>{star[i.t] ? "★ Shortlisted" : "☆ Shortlist"}</button>
              </div>
            </article>
          ))}
        </div>
      </Ex>
    );
  }

  /* ---------------- Events (Rotary Event Planner) ---------------- */
  function Events({ onGo }) {
    const date = nextSat(16);
    const miles = [["8 weeks out", "Choose the date and book the hall", true], ["6 weeks out", "Quiz master confirmed, sponsors approached", true], ["5 weeks out", "Online registration and payment page live", true], ["4 weeks out", "Promotion starts, raffle prizes requested", false], ["2 weeks out", "Volunteer roster full, licence arranged", false], ["1 week out", "Final numbers, run sheet, supplies bought", false], ["Event day", "Doors 6:00pm, first question 7:00pm", false], ["1 week after", "Thank-yous, results post, money banked", false]];
    const inc = [["Tables: 96 seats at $30", 2880], ["Raffle and silent auction", 1100], ["Sponsors: 4 at $250", 1000]];
    const exp = [["Hall hire", 300], ["Catering platters", 900], ["Prizes and supplies", 350], ["Printing and promotion", 180], ["Insurance and permits", 120]];
    const ti = inc.reduce((a, x) => a + x[1], 0), te = exp.reduce((a, x) => a + x[1], 0);
    const roles = [["Registration desk", 3, 3, ["Priya Nair", "Aroha Smith", "Ben Cho"]], ["Bar (RSA trained)", 4, 4, ["Tom Walker", "Linda Hart", "Marcus Odell", "Ben Cho"]], ["Raffle sellers", 3, 2, ["Jess Moreno", "Priya Nair"]], ["Set-up and pack-down", 8, 6, ["Sam Taylor", "Tom Walker", "Ben Cho", "Marcus Odell", "Linda Hart", "Aroha Smith"]], ["Photographer", 1, 1, ["Jess Moreno"]]];
    const check = [["g", "Four-Way Test", "Prizes are donated openly, prices are fair, and the marketing is truthful."], ["g", "Rotary brand", "Event name carries the full club name and the Rotary signature is from the Brand Center."], ["a", "Insurance and liability", "Confirm the club's cover includes an event with alcohol. Ask the District if unsure."], ["a", "Permits", "Liquor licence for the hall and the raffle permit are still to be lodged."], ["g", "Access and inclusion", "Step-free entry, a quiet corner, and alcohol-free, vegetarian and halal food."]];
    const [doneM, setDoneM] = React.useState(() => Object.fromEntries(miles.map(([w, , d]) => [w, d])));
    const [covered, setCovered] = React.useState(() => Object.fromEntries(check.map(([s, t]) => [t, s === "g"])));
    const risks = [["Fewer than 8 tables sold by week 3", "Ask each member to bring one table, and send the sponsor note again"], ["Quiz master unwell", "Name a back-up host and keep a printed question set"], ["Volunteers fall short", "Invite the Rotaract club and the school's service group"]];
    return (
      <Ex title="Rotary Club of Example Bay Trivia Night" sub={fmt(date) + ", 6:00pm, Example Bay Community Hall. 96 guests."}
        actions={<><button className="cc-btn sm" type="button">Download Word</button><button className="cc-btn sm" type="button">Print</button><button className="cc-btn sm ghost" type="button">Plan again with changes</button><Tag tone="ok">Planned from the Trivia night idea</Tag></>}>
        <div className="cc-ex-stats">
          <Stat label="Expected income" value={money(ti)} />
          <Stat label="Expected costs" value={money(te)} />
          <Stat label="Expected profit" value={money(ti - te)} tone="good" note="63% of income" />
          <Stat label="Volunteers" value="16 of 19" tone="warn" note="3 roles still open" />
        </div>
        <Panel title="Purpose and success">
          <div className="cc-ex-purpose">
            <div><span>The cause</span><b>Local reading project, Supporting education</b></div>
            <div><span>Budget limit</span><b>{money(2000)} to spend, approved by the board</b></div>
            <div><span>Success looks like</span><b>12 tables sold, {money(3000)} profit, 3 guests who ask about membership</b></div>
          </div>
        </Panel>
        <div className="cc-ex-cols">
          <Panel title="Timeline">
            <ol className="cc-ex-time">{miles.map(([w, t]) => <li key={w} className={doneM[w] ? "done" : ""} onClick={() => setDoneM({ ...doneM, [w]: !doneM[w] })} style={{ cursor: "pointer" }} title="Click to tick this step off"><span className="dot" aria-hidden="true">{doneM[w] ? "✓" : ""}</span><div><b>{w}</b><span>{t}</span></div></li>)}</ol>
            <p className="cc-muted sm">Tick steps off as you go. Progress is saved for the whole club.</p>
          </Panel>
          <Panel title="Budget">
            <table className="cc-ex-table"><tbody>
              <tr className="sec"><td colSpan="2">Money in</td></tr>{inc.map(([a, b]) => <tr key={a}><td>{a}</td><td className="n">{money(b)}</td></tr>)}
              <tr className="sec"><td colSpan="2">Money out</td></tr>{exp.map(([a, b]) => <tr key={a}><td>{a}</td><td className="n">{money(b)}</td></tr>)}
              <tr className="tot"><td>Expected profit</td><td className="n">{money(ti - te)}</td></tr>
            </tbody></table>
          </Panel>
        </div>
        <div className="cc-ex-cols">
          <Panel title="Check before you commit" aside={<small className="cc-muted">Rotary compliance</small>}>
            <ul className="cc-ex-check">{check.map(([s, t, d]) => <li key={t}><Rag s={covered[t] ? "g" : "a"} l={covered[t] ? "Covered" : "To check"} /><div><b>{t}</b><span>{d}</span>{!covered[t] && <button className="cc-link" type="button" onClick={() => setCovered({ ...covered, [t]: true })}>Mark covered</button>}</div></li>)}</ul>
          </Panel>
          <Panel title="If things go wrong">
            <table className="cc-ex-table"><tbody>{risks.map(([a, b]) => <tr key={a}><td><b>{a}</b><div className="cc-muted sm">{b}</div></td></tr>)}</tbody></table>
          </Panel>
        </div>
        <Panel title="Volunteer roles">
          <div className="cc-ex-roles">{roles.map(([r, need, have, who]) => (
            <div key={r}><div><b>{r}</b><span className="cc-muted sm">{have} of {need}</span></div>
              <div className="faces">{who.map((n) => <Av key={n} name={n} size={26} />)}{Array.from({ length: need - have }).map((_, i) => <span key={i} className="cc-ex-open" title="Still needed">+</span>)}</div></div>))}</div>
        </Panel>
        <Panel title="After the night">
          <ul className="cc-ex-after"><li>Thank every sponsor and prize donor within three days, with the total raised.</li><li>Post the results and photos, and publish the amount raised for the project.</li><li>Give every guest a way in that is not money: a project day, or a first meeting as a guest.</li><li>Record what worked, so next year's plan starts from this one.</li></ul>
        </Panel>
        <Panel title="Take the plan further">
          <div className="cc-ex-next">
            <div><b>Tasks</b><p>Turn the timeline into 12 tasks with owners and due dates.</p><NextBtn onGo={onGo} to="tasks" primary>Send to Tasks</NextBtn></div>
            <div><b>Comms</b><p>Build the marketing plan from this event.</p><NextBtn onGo={onGo} to="mod:Comms">Build the marketing plan</NextBtn></div>
            <div><b>Calendar</b><p>Put the date and milestones where every member can see them.</p><NextBtn onGo={onGo} to="mod:Calendar">Add to Calendar</NextBtn></div>
          </div>
        </Panel>
      </Ex>
    );
  }

  /* ---------------- Comms and Social: one campaign, in the Social Planner's style ---------------- */
  // Comms is the plan (the Social Planner's Week Planner). Social is the posts (its Post Brief and
  // Ready to Post). Same pillars, same four statuses, same colours as plansocial.
  const PILLARS = {
    event: { label: "About the Event", color: "#17458F", bg: "#E7EEF8" },
    impact: { label: "Community Impact", color: "#0E7490", bg: "#DEF1F4" },
    involved: { label: "How to Get Involved", color: "#6D28D9", bg: "#EDE7FB" },
    story: { label: "Stories", color: "#C2410C", bg: "#FAE7DB" }
  };
  const STATUS = {
    draft: { label: "Draft", color: "#5A6473", bg: "#EDF1F7", dot: "#94A3B8", next: "needs" },
    needs: { label: "Needs Edit", color: "#B45309", bg: "#FCEEDA", dot: "#F59E0B", next: "ready" },
    ready: { label: "Ready to Post", color: "#15803D", bg: "#E3F5E9", dot: "#22C55E", next: "needs" },
    posted: { label: "Posted", color: "#17458F", bg: "#E6EDF7", dot: "#17458F", next: null }
  };
  const ORDER = ["draft", "needs", "ready", "posted"];
  const eventDay = () => nextSat(16);
  const weekStart = (i) => new Date(eventDay().getTime() + (-26 + 7 * i) * DAY);
  const range = (i) => fmtShort(weekStart(i)) + " to " + fmtShort(new Date(weekStart(i).getTime() + 6 * DAY));
  const WEEKS = [
    { p: "event", topic: "Save the date. Introduce the night, the hall, the quiz master and what the money is for.", ref: "club website: events page" },
    { p: "involved", topic: "Book a table, give a prize, volunteer. Make saying yes easy, with one link per ask.", ref: "registration page" },
    { p: "impact", topic: "Where the money goes: the local reading project. Thank early sponsors by name.", ref: "reading project one-pager" },
    { p: "story", topic: "Meet the teams and the people behind the night. Countdown, then doors open.", ref: "photos from last year" }
  ];
  const POSTS0 = [
    [0, "Trivia Night is on", "Grab seven friends and book a table at the Community Hall. Every dollar goes to the local reading project.", "Photo of the hall set for a quiz night", "posted", -25],
    [0, "Meet your quiz master", "Meet Alex, who has written 60 questions and promises at least one about the 1990s.", "Alex at the microphone, laughing", "posted", -23],
    [0, "Tables are open", "Tables of eight are $30 a seat. Book yours before the weekend.", "Graphic: price and the booking link", "posted", -21],
    [1, "Book your table", "Seven tables are booked. Five left. Workplaces and sports clubs, this one is for you.", "Photo of a table set with answer sheets", "posted", -17],
    [1, "Prizes wanted", "Do you run a business in Example Bay? We would love a prize for the raffle, and we will thank you on the night.", "Graphic: raffle prizes so far", "ready", -15],
    [1, "Volunteers needed", "We need eight friendly people on the night, from the door to the bar. Tell us if you can help.", "Photo of last year's volunteers", "needs", -13],
    [2, "Where the money goes", "Your night out pays for reading books and tutors at Example Bay Primary School.", "Photo of children reading", "needs", -11],
    [2, "Thank you, sponsors", "Four local businesses are backing Trivia Night. We are grateful to every one.", "Graphic: sponsor logos", "draft", -9],
    [2, "Tables going fast", "Only three tables left. Bring your team before they are gone.", "Graphic: 3 tables left", "draft", -7],
    [3, "Meet the teams", "Footballers, teachers and one very confident hairdresser. Meet the teams so far.", "Collage of team photos", "draft", -4],
    [3, "One week to go", "One week until Trivia Night. A few seats left. Link in bio.", "Countdown graphic", "draft", -2],
    [3, "Doors open tonight", "Doors open at 6pm. Bring a pen, and your best general knowledge.", "Photo of the hall tonight", "draft", 0]
  ].map(([w, angle, cap, brief, status, off], i) => ({ id: "p" + i, w, n: (i % 3) + 1, angle, cap, brief, status, date: new Date(eventDay().getTime() + off * DAY), time: ["7:30am", "12:30pm", "6:00pm"][i % 3] }));

  function StatusCells({ posts }) {
    return <span className="cc-sp-cells">{ORDER.map((k) => { const n = posts.filter((p) => p.status === k).length; return n ? <span key={k} style={{ color: STATUS[k].color, background: STATUS[k].bg }}><i style={{ background: STATUS[k].dot }} />{n} {STATUS[k].label}</span> : null; })}</span>;
  }
  const PillarChip = ({ p }) => <span className="cc-sp-pillar" style={{ color: PILLARS[p].color, background: PILLARS[p].bg }}>{PILLARS[p].label}</span>;

  function Comms({ onGo }) {
    const [view, setView] = React.useState("table");
    const [wdone, setWdone] = React.useState({ 0: true });
    const tick = (i) => <label className="cc-switch inline"><input type="checkbox" checked={!!wdone[i]} onChange={() => setWdone({ ...wdone, [i]: !wdone[i] })} aria-label={"Week " + (i + 1) + " done"} /><span>Done</span></label>;
    const nPosts = (i) => POSTS0.filter((p) => p.w === i).length + " posts";
    return (
      <Ex title="Campaign plan: Trivia Night" sub={"Rotary Club of Example Bay, event on " + fmt(eventDay()) + ". Built from your Event plan."} actions={<><button className="cc-btn sm" type="button">Download Word</button><button className="cc-btn sm" type="button">Print</button><button className="cc-btn sm ghost" type="button">Plan again with changes</button><Tag tone="ok">From the Events plan</Tag></>}>
        <div className="cc-ex-purpose">
          <div><span>The goal</span><b>Sell all 12 tables three days before the night, and name 4 sponsors on the posters</b></div>
          <div><span>Who we want to reach</span><b>Members and families, local businesses, schools and sports clubs</b></div>
          <div><span>Channels</span><b>Facebook, Instagram, member emails, the local paper, posters in shops</b></div>
          <div><span>Voice</span><b>People of Action: warm, clear, and about what the club does</b></div>
        </div>
        <Panel title="Content pillars" aside={<small className="cc-muted">Each week leads with one pillar</small>}>
          <div className="cc-sp-pillars">{Object.entries(PILLARS).map(([k, p]) => <span key={k} className="cc-sp-pillar big" style={{ color: p.color, background: p.bg }}>{p.label}</span>)}</div>
        </Panel>
        <div className="cc-sp">
          <div className="cc-sp-bar">
            <div><h3>Week Planner</h3><p>{WEEKS.length} weeks &nbsp;·&nbsp; {POSTS0.length} posts &nbsp;·&nbsp; kicks off {fmtShort(weekStart(0))}</p></div>
            <div className="cc-sp-seg"><button className={view === "table" ? "on" : ""} onClick={() => setView("table")}>Table</button><button className={view === "board" ? "on" : ""} onClick={() => setView("board")}>Board</button></div>
          </div>
          {view === "table" ? (
            <div className="cc-sp-table" role="table" aria-label="Week planner">
              <div className="head" role="row">{["Week", "Dates", "Pillar", "Topic and angle", "Reference", "Posts", "Done"].map((h) => <div key={h}>{h}</div>)}</div>
              {WEEKS.map((w, i) => (
                <div className="row" role="row" key={i}>
                  <div><b>Week {i + 1}</b></div><div className="muted">{range(i)}</div><div><PillarChip p={w.p} /></div>
                  <div>{w.topic}</div><div className="ref">{w.ref}</div>
                  <div>{nPosts(i)}</div>
                  <div>{tick(i)}</div>
                </div>
              ))}
            </div>
          ) : (
            <div className="cc-sp-board">
              {WEEKS.map((w, i) => (
                <div className="card" key={i}>
                  <div className="h"><div><b>Week {i + 1}</b><small>{range(i)}</small></div><PillarChip p={w.p} /></div>
                  <div className="b"><span className="lab">Topic and angle</span><p>{w.topic}</p><span className="lab">Reference</span><p className="ref">{w.ref}</p><p className="cc-muted sm">{nPosts(i)} planned</p></div>
                  <div className="f">{tick(i)}</div>
                </div>
              ))}
            </div>
          )}
        </div>
        <Panel title="Take the plan further">
          <div className="cc-ex-next">
            <div><b>Social</b><p>Write and schedule the 12 posts from this plan.</p><NextBtn onGo={onGo} to="mod:Social" primary>Create the posts in Social</NextBtn></div>
            <div><b>Tasks</b><p>Add the printing, emailing and posting jobs to the board.</p><NextBtn onGo={onGo} to="tasks">Send to Tasks</NextBtn></div>
            <div><b>Calendar</b><p>Show the campaign dates to the whole club.</p><NextBtn onGo={onGo} to="mod:Calendar">Add to Calendar</NextBtn></div>
          </div>
        </Panel>
      </Ex>
    );
  }

  function Social({ onGo }) {
    const [tab, setTab] = React.useState("brief");
    const [approved, setApproved] = React.useState({});
    const [posts, setPosts] = React.useState(POSTS0);
    const [open, setOpen] = React.useState({ p4: true });
    const [shut, setShut] = React.useState({});
    const [preview, setPreview] = React.useState(null);
    const advance = (e, id) => { e.stopPropagation(); setPosts(posts.map((p) => (p.id === id && STATUS[p.status].next ? { ...p, status: STATUS[p.status].next } : p))); };
    const setCap = (id, cap) => setPosts(posts.map((p) => (p.id === id ? { ...p, cap } : p)));
    const mark = (id, status) => setPosts(posts.map((p) => (p.id === id ? { ...p, status } : p)));
    const ready = posts.filter((p) => p.status === "ready");
    const tabBtn = (id, label, n) => <button key={id} className={tab === id ? "on" : ""} onClick={() => setTab(id)}>{label}<small>{n}</small></button>;
    return (
      <Ex title="Social: Rotary Club of Example Bay Trivia Night" sub="Posts written from your Comms plan. You check them, then they are published for you."
        actions={<Tag tone="ok">Facebook and Instagram connected</Tag>}>
        <div className="cc-ex-linkbar">Linked to <button className="cc-link" onClick={() => onGo && onGo("mod:Comms")}>Campaign plan: Trivia Night</button> and <button className="cc-link" onClick={() => onGo && onGo("mod:Events")}>Event: Trivia Night</button>. Posts move from Draft to Needs Edit to Ready to Post to Posted, and an admin approves each post before it can go out. Facebook and Instagram connect once from Socials: log in, pick your Page, and there are no IDs to paste.</div>
        <div className="cc-sp">
          <div className="cc-sp-tabs" role="tablist">{tabBtn("brief", "Post Brief", posts.length)}{tabBtn("ready", "Ready to Post", ready.length)}</div>
          {tab === "brief" ? WEEKS.map((w, i) => {
            const wp = posts.filter((p) => p.w === i), isOpen = !shut[i];
            return (
              <div className="cc-sp-week" key={i}>
                <button className="wh" onClick={() => setShut({ ...shut, [i]: isOpen })} aria-expanded={isOpen}><span className="chev" style={{ transform: isOpen ? "rotate(90deg)" : "none" }}>›</span><b>Week {i + 1}</b><span className="muted">{range(i)}</span><PillarChip p={w.p} /><span className="grow" /><StatusCells posts={wp} /></button>
                {isOpen && wp.map((p) => { const st = STATUS[p.status], ex = !!open[p.id]; return (
                  <div key={p.id} className="post">
                    <div className="line" onClick={() => setOpen({ ...open, [p.id]: !ex })}>
                      <b>Post {p.n}</b><span className="muted">{fmt(p.date)}</span>
                      <div className="txt"><b>{p.angle}</b><span>{p.cap}</span></div>
                      <PillarChip p={w.p} />
                      <button className="cc-sp-status" style={{ color: st.color, background: st.bg, cursor: st.next ? "pointer" : "default" }} onClick={(e) => advance(e, p.id)} title={st.next ? "Move to " + STATUS[st.next].label : "Posted"}><i style={{ background: st.dot }} />{st.label}</button>
                      <span className="chev" style={{ transform: ex ? "rotate(90deg)" : "none" }}>›</span>
                    </div>
                    {ex && <div className="detail">
                      <div><span className="lab">Draft caption</span><textarea rows="3" value={p.cap} onChange={(e) => setCap(p.id, e.target.value)} aria-label="Caption" />
                        <div className="meta"><span className="lab">Post date</span><b>{fmt(p.date)}</b><span className="lab">Time</span><b>{p.time}</b><span className="muted">Campaign default</span></div></div>
                      <div><span className="lab">Media brief</span><p>{p.brief}</p><span className="lab">Image style</span><div className="cc-ex-chips tight"><button className="on" type="button">Photo</button><button type="button">Graphic</button><button type="button">None</button></div>
                        <div className="cc-row" style={{ gap: 6, flexWrap: "wrap" }}><button className="cc-btn sm" type="button">Generate caption</button><button className="cc-btn sm" type="button">Image Library</button><button className="cc-btn sm" type="button" onClick={() => setPreview(p)}>Preview on Facebook and Instagram</button></div></div>
                    </div>}
                  </div>); })}
              </div>
            );
          }) : (
            <div className="cc-sp-ready">
              {ready.length === 0 && <div className="cc-ex-note">Nothing is ready yet. In Post Brief, move a post to <b>Ready to Post</b> and it appears here.</div>}
              {ready.map((p) => (
                <article key={p.id} className="cc-ex-panel"><div className="cc-ex-ph"><h3>{p.angle}</h3><span className="cc-sp-pillar" style={{ color: PILLARS[WEEKS[p.w].p].color, background: PILLARS[WEEKS[p.w].p].bg }}>{PILLARS[WEEKS[p.w].p].label}</span></div>
                  <p>{p.cap}</p><p className="cc-muted sm">{approved[p.id] ? "Approved for auto-publish: it goes out by itself" : "Not yet approved"}: {fmt(p.date)}, {p.time}. Facebook and Instagram.</p>
                  <div className="cc-row" style={{ gap: 6, flexWrap: "wrap" }}><button className="cc-btn sm primary" type="button" disabled={!!approved[p.id]} onClick={() => setApproved({ ...approved, [p.id]: true })}>{approved[p.id] ? "Approved" : "Approve for Auto-Publish"}</button><button className="cc-btn sm" type="button" onClick={() => mark(p.id, "posted")}>Mark Posted</button><button className="cc-btn sm" type="button">Copy caption</button><button className="cc-btn sm ghost" type="button" onClick={() => { setApproved({ ...approved, [p.id]: false }); mark(p.id, "needs"); }}>Send back for edit</button></div></article>
              ))}
            </div>
          )}
        </div>
        {preview && <div className="cc-modal-bg" onClick={(e) => { if (e.target === e.currentTarget) setPreview(null); }}><div className="cc-modal" role="dialog" aria-modal="true" aria-label="Post preview"><div className="cc-modal-h"><h2>Preview</h2><button className="cc-x" aria-label="Close" onClick={() => setPreview(null)}>×</button></div>
          <div className="cc-modal-b"><div className="cc-ex-fb"><div className="who"><span className="cc-ex-av" style={{ background: "#17458F", width: 36, height: 36, fontSize: 14 }}>RC</span><div><b>Rotary Club of Example Bay</b><small>{fmt(preview.date)} · Public</small></div></div><p>{preview.cap}</p><div className="pic">{preview.brief}</div></div></div></div></div>}
      </Ex>
    );
  }

  /* ---------------- Calendar ---------------- */
  // Mirrors the real Calendar (app/calendar.jsx): colour-coded types including Personal, drag to move (hand-added, Tasks and Social items;
  // Events and repeating items are locked), Tasks and Social items shown only to people who can open that project or campaign, Personal
  // entries private to their owner unless shared, club reminders, and a personal link plus a club link. Email-in is not built yet.
  const TYPES = { Meeting: "#17458F", Event: "#d2603a", Task: "#2f7d4f", Post: "#7a52c7", Club: "#9a6a08", Personal: "#0e7490" };
  const TYPE_NAME = { Meeting: "Meetings", Event: "Events", Task: "Tasks", Post: "Posts", Club: "Club", Personal: "Personal" };
  const VIEWERS = { admin: "Sam Taylor", member: "Jess Moreno" };
  function Calendar({ onGo }) {
    const [off, setOff] = React.useState(0), [f, setF] = React.useState("All"), [as, setAs] = React.useState("admin");
    const [drag, setDrag] = React.useState(null), [over, setOver] = React.useState(null), [note, setNote] = React.useState("");
    const today = new Date();
    const [items, setItems] = React.useState(() => [
      { id: "e1", d: nextSat(16), t: "Trivia Night", k: "Event", src: "Events" },
      { id: "e2", d: nextSat(7), t: "Sausage sizzle", k: "Event", src: "Events" },
      { id: "t1", d: D(7), t: "Posters printed", k: "Task", src: "Tasks", proj: "Trivia Night" },
      { id: "t2", d: D(9), t: "Bar licence arranged", k: "Task", src: "Tasks", proj: "Trivia Night" },
      { id: "t3", d: D(10), t: "Raffle prizes in", k: "Task", src: "Tasks", proj: "Trivia Night" },
      { id: "t4", d: D(12), t: "12 tables sold", k: "Task", src: "Tasks", proj: "Trivia Night" },
      { id: "t5", d: D(6), t: "Approve the club budget", k: "Task", src: "Tasks", proj: "Committee budget", closed: true },
      { id: "s1", d: D(2), t: "Post: Meet the quiz master", k: "Post", src: "Social" }, { id: "s2", d: D(5), t: "Post: Tables going fast", k: "Post", src: "Social" },
      { id: "s3", d: D(9), t: "Post: Thank our sponsors", k: "Post", src: "Social" }, { id: "s4", d: D(13), t: "Post: One week to go", k: "Post", src: "Social" },
      { id: "s0", d: D(-3), t: "Posted: Trivia Night is on", k: "Post", src: "Social", done: true },
      { id: "c1", d: D(4), t: "School assembly talk", k: "Club" },
      { id: "m1", d: D(3), t: "Dentist", k: "Personal", owner: "Sam Taylor", share: "me", time: "9:00am" },
      { id: "m2", d: D(8), t: "Family barbecue", k: "Personal", owner: "Sam Taylor", share: "Bea Chan, Tom Walker" },
      { id: "m3", d: D(11), t: "Alex: rowing training", k: "Personal", owner: "Alex Kim", share: "club", time: "6:00pm" },
      { id: "m4", d: D(5), t: "Swim club", k: "Personal", owner: "Jess Moreno", share: "me", time: "5:30pm" }
    ]);
    const me = VIEWERS[as], isAdmin = as === "admin";
    const sees = (i) => (i.k === "Personal" ? i.owner === me || i.share === "club" || i.share.split(", ").includes(me) : !i.closed || isAdmin);   // Personal: owner or shared with; a project's tasks: only people who can open the project
    const movable = (i) => (i.k === "Personal" ? i.owner === me : isAdmin && i.src !== "Events");
    const first = new Date(today.getFullYear(), today.getMonth() + off, 1);
    const days = new Date(first.getFullYear(), first.getMonth() + 1, 0).getDate();
    const evs = {};
    const add = (d, e) => { (evs[key(d)] = evs[key(d)] || []).push(e); };
    items.filter(sees).forEach((i) => add(i.d, i));
    for (let n = 1; n <= days; n++) {
      const d = new Date(first.getFullYear(), first.getMonth(), n, 12);
      if (d.getDay() === 2) add(d, { id: "mt" + n, t: "Club meeting", k: "Meeting", time: "6:30pm", repeat: true });
      if (d.getDay() === 4 && n <= 7) add(d, { id: "bd" + n, t: "Board meeting", k: "Meeting", time: "7:00pm", repeat: true });
    }
    const lead = (first.getDay() + 6) % 7;   // Monday first
    const cells = Array.from({ length: Math.ceil((lead + days) / 7) * 7 }, (_, i) => (i < lead || i >= lead + days ? null : new Date(first.getFullYear(), first.getMonth(), i - lead + 1, 12)));
    const upcoming = items.filter((i) => sees(i) && i.d >= D(0)).sort((a, b) => a.d - b.d).slice(0, 6);
    const shown = (e) => f === "All" || e.k === f;
    const tip = (e) => e.t + (e.time ? ", " + e.time : "") + (e.repeat ? ". Open a repeating item to change it." : e.src === "Events" ? ". Change it in Events." : movable(e) ? ". Drag to another day to move it." : e.k === "Personal" ? ". Shared with you by " + e.owner + "." : isAdmin ? "" : ". Only a club admin or Paid Seat member changes club items.");
    const moveTo = (d) => {
      const it = items.find((x) => x.id === drag); setDrag(null); setOver(null);
      if (!it || key(d) === key(it.d)) return;
      setItems(items.map((x) => (x.id === it.id ? { ...x, d } : x)));
      setNote("Moved " + it.t + " to " + fmt(d) + "." + (it.src === "Tasks" ? " The due date in Tasks changed too." : it.src === "Social" ? " The post's week and day in Social changed too." : ""));
    };
    const shareText = (i) => (i.share === "me" ? "Only you" : i.share === "club" ? "The whole club" : i.share);
    return (
      <Ex title="Club calendar" sub="Everything the club is doing, in one place every member can see."
        actions={<><span className="cc-ex-chips tight" role="group" aria-label="View as">{[["admin", "Club admin"], ["member", "Member"]].map(([k, l]) => <button key={k} className={as === k ? "on" : ""} onClick={() => { setAs(k); setNote(""); }}>View as: {l}</button>)}</span><Tag tone="ok">Free with every plan</Tag></>}>
        {note && <div className="cc-ex-note" role="status">{note}</div>}
        {!isAdmin && <div className="cc-ex-note">You can view the club calendar and keep your own personal entries. A club admin or a member with Edit access to Calendar can add and change club items.</div>}
        <div className="cc-ex-cal">
          <div>
            <div className="cc-ex-calbar">
              <div className="nav"><button className="cc-btn sm" onClick={() => setOff(off - 1)} aria-label="Previous month">‹</button><b>{first.toLocaleDateString(CCIntl.locale(), { month: "long", year: "numeric" })}</b><button className="cc-btn sm" onClick={() => setOff(off + 1)} aria-label="Next month">›</button>{off !== 0 && <button className="cc-link" onClick={() => setOff(0)}>Today</button>}</div>
              <div className="cc-ex-chips tight">{["All", ...Object.keys(TYPES)].map((k) => <button key={k} className={f === k ? "on" : ""} onClick={() => setF(k)}>{k !== "All" && <i style={{ background: TYPES[k] }} />}{k === "All" ? "All" : TYPE_NAME[k]}</button>)}</div>
            </div>
            <div className="cc-ex-grid" role="grid" aria-label="Month">
              {["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => <div key={d} className="dow">{d}</div>)}
              {cells.map((d, i) => d ? (
                <div key={i} className={"day" + (key(d) === key(today) ? " today" : "") + (drag && over === key(d) ? " drop" : "")}
                  onDragOver={drag ? (e) => { e.preventDefault(); if (over !== key(d)) setOver(key(d)); } : undefined} onDrop={drag ? (e) => { e.preventDefault(); moveTo(d); } : undefined}><span className="n">{d.getDate()}</span>
                  {(evs[key(d)] || []).filter(shown).slice(0, 3).map((e, j) => <span key={e.id + j} className="ev" draggable={!e.repeat && movable(e)} style={{ "--c": TYPES[e.k], cursor: !e.repeat && movable(e) ? "grab" : "default" }} title={tip(e)}
                    onDragStart={(ev) => { ev.dataTransfer.effectAllowed = "move"; ev.dataTransfer.setData("text/plain", e.id); setDrag(e.id); }} onDragEnd={() => { setDrag(null); setOver(null); }}>{(e.time ? e.time.replace(":00", "").replace("am", "a").replace("pm", "p") + " " : "") + e.t}</span>)}
                  {(evs[key(d)] || []).filter(shown).length > 3 && <span className="more">+{(evs[key(d)] || []).filter(shown).length - 3} more</span>}</div>
              ) : <div key={i} className="day off" />)}
            </div>
            <div className="cc-ex-legend">{Object.entries(TYPES).map(([k, c]) => <span key={k}><i style={{ background: c }} />{{ Meeting: "Meetings", Event: "From Events", Task: "From Tasks", Post: "From Social", Club: "Club activities", Personal: "Personal" }[k]}</span>)}</div>
            <p className="cc-muted sm">Try it: drag a task, a post or one of your personal entries to another day. A task changes its due date in Tasks and a post changes its day in Social. Events and repeating meetings are changed where they come from. Switch to Member to see how Personal entries and Tasks follow who can see them.</p>
          </div>
          <aside className="cc-ex-side">
            <Panel title="Add to the calendar">
              <button className="cc-btn primary" type="button" onClick={() => setNote("In the app this opens a short form: what is on, type, date and time, repeat and reminders. Choose Personal to keep it private, or share it with the club or people you pick.")}>{isAdmin ? "Add an item" : "Add a personal entry"}</button>
              <ul className="cc-ex-ways">
                <li><b>Personal entries</b><span>Choose the Personal type for something only you see, or share it with the club or with people you pick.</span></li>
                {isAdmin && <li><b>From your plans</b><span>Use Add to Calendar on an Events or Comms plan, or add a Tasks project or Social campaign below. Tasks and posts show only to people who can open that project or campaign.</span></li>}
                <li><b>Email it in <Tag>Coming soon</Tag></b><span>Forward an invitation to a club calendar address and it will appear here.</span></li>
              </ul>
            </Panel>
            {isAdmin && <Panel title="Task due dates">
              <p className="cc-muted sm">Show a project's open tasks on the calendar. They refresh each night, or press Refresh to update now.</p>
              <ul className="cc-ex-ways">{[["Trivia Night", "4 open with a due date"], ["Committee budget", "1 open with a due date"]].map(([p, n]) => <li key={p}><b>{p}</b><span>{n}</span><button className="cc-btn sm" type="button" onClick={() => setNote("The " + p + " due dates are refreshed on the calendar.")}>Refresh</button></li>)}</ul>
            </Panel>}
            {isAdmin && <Panel title="Social posts">
              <p className="cc-muted sm">Show a campaign's planned and posted posts on the calendar. They refresh each night.</p>
              <ul className="cc-ex-ways"><li><b>Trivia Night</b><button className="cc-btn sm" type="button" onClick={() => setNote("The Trivia Night posts are refreshed on the calendar.")}>Refresh now</button></li></ul>
            </Panel>}
            <Panel title="Reminders">
              <p className="cc-muted sm">Every item gets these unless it has its own: <b>30 minutes before</b>.</p>
              {isAdmin && <button className="cc-btn sm" type="button" onClick={() => setNote("Admins choose up to five club reminders, such as 10 minutes, 1 hour or 1 day before. Any item can have its own.")}>Change the club's reminders</button>}
              <p className="cc-muted sm">Reminders come from your calendar app once you subscribe below. Apple and Outlook calendars show them. Google Calendar ignores reminders on subscribed calendars, so set those in Google.</p>
            </Panel>
            <Panel title="See it on your phone">
              <p className="cc-muted sm">Subscribe once from Google, Outlook, Apple or Zoho Calendar and it stays up to date. No Clubcraft login needed.</p>
              <b className="sm">Your link</b>
              <p className="cc-muted sm" style={{ margin: "2px 0 4px" }}>Everything you can see, including your personal entries and the tasks and posts you can open.</p>
              <div className="cc-ex-copy"><code>https://clubcraft.example/cal/example-bay/u-4f2a9c.ics</code><button className="cc-btn sm" type="button">Copy link</button></div>
              <p className="cc-muted sm">Keep this one to yourself. <button className="cc-link" type="button">Make a new link</button></p>
              <b className="sm">Club link</b>
              <p className="cc-muted sm" style={{ margin: "2px 0 4px" }}>Club items only: no personal entries, no tasks or posts (unless a personal entry is shared with the whole club).</p>
              <div className="cc-ex-copy"><code>https://clubcraft.example/cal/example-bay/b81d70.ics</code><button className="cc-btn sm" type="button">Copy link</button></div>
            </Panel>
            <Panel title="Coming up">
              <ul className="cc-ex-up">{upcoming.map((i) => <li key={i.id}><i style={{ background: TYPES[i.k] }} /><div><b>{i.t}</b><span>{fmt(i.d)}{i.k === "Personal" ? " · " + (i.owner === me ? shareText(i) : "Shared by " + i.owner) : ""}</span></div></li>)}</ul>
            </Panel>
          </aside>
        </div>
      </Ex>
    );
  }

  /* ---------------- Contacts ---------------- */
  // Mirrors the real Contacts (app/contacts.jsx): members appear by themselves (same record as a club member, name and email from their
  // profile); a club admin or a member with Edit access sees everyone, other members see the members and the contacts they added themselves;
  // mailing consent is recorded person by person (nobody starts on a list); custom fields, CSV import and a mailing export.
  const HOW = { Newsletter: "Ticked the box on the join form", Volunteers: "Put their name down at a meeting", Fundraisers: "Said yes by email" };
  const CONTACTS = [
    ["Sam Taylor", "Member", ["Newsletter", "Volunteers"], 2, { Birthday: "14 Mar", "Joined club": "2016", Skills: "Event management", Dietary: "None" }],
    ["Priya Nair", "Member", ["Newsletter", "Volunteers"], 1, { Birthday: "2 Aug", "Joined club": "2019", Skills: "Accounting", Dietary: "Vegetarian" }],
    ["Tom Walker", "Member", ["Newsletter", "Fundraisers"], 4, { Birthday: "27 Nov", "Joined club": "2012", Skills: "Bar and catering", Dietary: "None" }],
    ["Jess Moreno", "Member", ["Newsletter", "Volunteers"], 3, { Birthday: "9 Jun", "Joined club": "2022", Skills: "Photography, social media", Dietary: "Gluten free" }],
    ["Aroha Smith", "Member", ["Newsletter", "Volunteers"], 1, { Birthday: "21 Jan", "Joined club": "2021", Skills: "Recruiting", Dietary: "None" }],
    ["Ben Cho", "Member", ["Newsletter"], 6, { Birthday: "30 Sep", "Joined club": "2023", Skills: "Carpentry", Dietary: "None" }],
    ["Morgan Reyes", "Member", [], 0, { "Joined club": "This month", Skills: "Spreadsheets", Dietary: "Vegan" }],
    ["Margaret Ellis", "Past member", ["Newsletter"], 40, { "Joined club": "1998", Notes: "Moved to be near family. Happy to hear about big events." }],
    ["Colin Park", "Past member", [], 120, { "Joined club": "2009", Notes: "Left for work reasons. Might return after retiring." }, true],
    ["Bayside Hardware", "Sponsor", ["Fundraisers"], 9, { "Sponsor level": "Gold", Contact: "Dana Cruz", "Gave last year": "$1,000 plus sausage sizzle site" }],
    ["Harbour Cafe", "Sponsor", ["Fundraisers"], 14, { "Sponsor level": "Silver", Contact: "Luis Ortega", "Gave last year": "Raffle vouchers" }],
    ["Coastal Printing", "Supplier", [], 20, { Contact: "Hannah Lee", Notes: "Prints posters at cost for the club." }],
    ["Alex Bennett", "Speaker", ["Newsletter"], 11, { Topic: "Local history", "Quiz master": "Yes", Contact: "alex.bennett@example-bay.test" }],
    ["Example Bay Primary School", "Community partner", ["Newsletter"], 5, { Contact: "Principal's office", Notes: "Assembly talk next week. Schools Reading project." }],
    ["Reliable Plumbing", "Supplier", [], 8, { Notes: "Fixed the hall tap. Fair prices." }, false, "Jess Moreno"]
  ].map(([name, rel, lists, last, f, unsub, by]) => ({ name, rel, lists, last, f, unsub: !!unsub, by: by || "", member: rel === "Member", email: name.toLowerCase().replace(/[^a-z]+/g, ".").replace(/\.$/, "") + "@example-bay.test", phone: "04" + String(10 + (name.length * 7) % 90) + " 555 " + String(100 + (name.length * 13) % 900) }));
  function Contacts() {
    const [q, setQ] = React.useState(""), [rel, setRel] = React.useState("All"), [sel, setSel] = React.useState(null), [as, setAs] = React.useState("admin"), [note, setNote] = React.useState(""), [fields, setFields] = React.useState(false);
    const isAdmin = as === "admin", me = "Jess Moreno";
    const visible = CONTACTS.filter((c) => isAdmin || c.member || c.by === me);   // other members: the members and contacts they added themselves
    const rels = ["All", ...Array.from(new Set(visible.map((c) => c.rel)))];
    const list = visible.filter((c) => (rel === "All" || c.rel === rel) && (!q || (c.name + c.email + c.rel + c.phone).toLowerCase().includes(q.toLowerCase())));
    const c = sel && visible.find((x) => x.name === sel);
    const ago = (n) => (n === 0 ? "Today" : n === 1 ? "Yesterday" : n < 60 ? n + " days ago" : Math.round(n / 30) + " months ago");
    const when = (n) => fmtShort(new Date(D(0).getTime() - n * DAY));
    const mine = (x) => x.by === me;
    return (
      <Ex title="Contacts" sub="Everyone connected to the club, with the details you need and fields you choose."
        actions={<><span className="cc-ex-chips tight" role="group" aria-label="View as">{[["admin", "Club admin"], ["member", "Member"]].map(([k, l]) => <button key={k} className={as === k ? "on" : ""} onClick={() => { setAs(k); setSel(null); setRel("All"); setNote(""); }}>View as: {l}</button>)}</span><Tag tone="ok">Free with every plan</Tag></>}>
        {isAdmin ? <div className="cc-ex-note"><b>Members appear by themselves.</b> Each member's name and email come from their Clubcraft profile, so you never keep them up to date twice. Add sponsors, suppliers, speakers and others yourself, or import a spreadsheet.</div>
          : <div className="cc-ex-note">You can see the club's members and the contacts you add yourself. Contacts you add are seen only by you and the club's admins and people with Edit access to Contacts.</div>}
        {note && <div className="cc-ex-note" role="status">{note}</div>}
        <div className="cc-ex-tools">
          <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 value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search name, email or phone" aria-label="Search contacts" /></label>
          <div className="cc-ex-chips tight">{rels.map((r) => <button key={r} className={rel === r ? "on" : ""} onClick={() => setRel(r)}>{r}<small>{r === "All" ? visible.length : visible.filter((x) => x.rel === r).length}</small></button>)}</div>
          <button className="cc-btn primary" type="button" onClick={() => setNote("In the app this opens a short form: name, email, phone, address, how they are connected and notes." + (isAdmin ? "" : " Only you and the club's admins will see the contact."))}>Add a contact</button>
          {isAdmin && <button className="cc-btn" type="button" onClick={() => setNote("Choose a CSV file from Excel or Google Sheets. Clubcraft matches the column headings, skips people already in your contacts (same email) and never puts anyone on a mailing list.")}>Import a spreadsheet</button>}
          {isAdmin && <button className="cc-btn" type="button" onClick={() => setFields(!fields)}>Fields and lists</button>}
        </div>
        <div className={"cc-ex-contacts" + (c ? " withdrawer" : "")}>
          <div className="cc-table"><table className="cc-ex-table clickable">
            <thead><tr><th>Name</th><th>Relationship</th><th>Phone</th>{isAdmin && <th>Lists</th>}</tr></thead>
            <tbody>{list.map((x) => <tr key={x.name} className={sel === x.name ? "sel" : ""} onClick={() => setSel(sel === x.name ? null : x.name)} tabIndex="0" onKeyDown={(e) => { if (e.key === "Enter") setSel(x.name); }}>
              <td><div className="who"><Av name={x.name} size={30} /><div><b>{x.name}</b><span>{x.email}</span></div></div></td>
              <td><Tag tone={x.rel === "Member" ? "ok" : x.rel === "Sponsor" ? "trial" : "quiet"}>{x.rel}</Tag>{!isAdmin && mine(x) && <Tag> Added by you</Tag>}{isAdmin && x.by && <Tag> Added by {x.by.split(" ")[0]}</Tag>}</td>
              <td className="cc-muted">{x.phone}</td>
              {isAdmin && <td>{x.lists.length && !x.unsub ? x.lists.map((l) => <span key={l} className="cc-ex-list">{l}</span>) : <span className="cc-muted sm">{x.unsub ? "Unsubscribed" : "None"}</span>}</td>}</tr>)}
              {!list.length && <tr><td colSpan={isAdmin ? 4 : 3} className="cc-muted">No contacts match.</td></tr>}</tbody>
          </table></div>
          {c && <aside className="cc-ex-drawer" aria-label={"Details for " + c.name}>
            <button className="cc-x" aria-label="Close" onClick={() => setSel(null)}>×</button>
            <div className="who big"><Av name={c.name} size={48} /><div><h3>{c.name}</h3><Tag tone={c.rel === "Member" ? "ok" : "quiet"}>{c.rel}</Tag></div></div>
            <dl><div><dt>Email</dt><dd>{c.email}</dd></div><div><dt>Phone</dt><dd>{c.phone}</dd></div>
              {(isAdmin || mine(c)) && <div><dt>Last contact</dt><dd>{ago(c.last)}</dd></div>}
              {(isAdmin || mine(c)) && Object.entries(c.f).map(([k, v]) => <div key={k} className={isAdmin && k !== "Notes" && k !== "Contact" ? "custom" : ""}><dt>{k}</dt><dd>{v}</dd></div>)}</dl>
            {c.member && <div className="cc-muted sm">A club member. Their name and email come from their Clubcraft profile.</div>}
            {isAdmin && <div className="lists"><b>Mailing lists</b>
              {c.unsub && <div className="cc-ex-note">Unsubscribed {when(c.last)}. They stay off every list until you clear this.</div>}
              {!c.unsub && c.lists.length === 0 && <div className="cc-muted sm">Not on any list. Add them once you know how they agreed.</div>}
              {!c.unsub && c.lists.map((l) => <div key={l} style={{ margin: "4px 0" }}><span className="cc-ex-list">{l}</span> <span className="cc-muted sm">agreed {when(c.last + 3)}: {HOW[l]}</span></div>)}
              <div className="cc-muted sm" style={{ marginTop: 6 }}>Nobody is on a list until someone records how they agreed.</div></div>}
            <div className="cc-row" style={{ gap: 8, marginTop: 12 }}>{(isAdmin || mine(c)) && <button className="cc-btn sm primary" type="button" onClick={() => setNote("In the app this opens the contact's details to change.")}>Edit</button>}{(isAdmin || mine(c)) && !c.member && c.rel !== "Past member" && <button className="cc-btn sm ghost" type="button">Delete</button>}</div>
          </aside>}
        </div>
        {isAdmin && <Panel title="Mailing list exports" aside={<small className="cc-muted">For Comms or Zoho</small>}>
          <p className="cc-muted sm">People who agreed to a list and have not unsubscribed, as a spreadsheet. Sending stays in Comms or Zoho.</p>
          <div className="cc-row" style={{ gap: 8 }}>{["Newsletter", "Volunteers", "Fundraisers"].map((l) => <button key={l} className="cc-btn sm" type="button" onClick={() => setNote("Downloads the " + l + " list: " + CONTACTS.filter((x) => !x.unsub && x.lists.includes(l)).length + " people, with when and how each agreed.")}>{l}</button>)}</div>
        </Panel>}
        {isAdmin && fields && <Panel title="Your custom fields" aside={<small className="cc-muted">Club admins set these</small>}>
          <div className="cc-ex-fields">{[["Birthday", "Date"], ["Joined club", "Year"], ["Skills", "Text"], ["Dietary", "Pick-list"], ["Sponsor level", "Pick-list"], ["Quiz master", "Yes or no"]].map(([n, t]) => <span key={n}><b>{n}</b>{t}</span>)}</div>
          <p className="cc-muted sm" style={{ marginTop: 8 }}>Add up to 20 fields: text, date, year, a pick-list or yes/no. Mailing lists: Newsletter, Volunteers, Fundraisers.</p>
        </Panel>}
      </Ex>
    );
  }

  /* ---------------- Members ---------------- */
  // Mirrors the real Members register (app/members.jsx): types with fees and renewal rules, status worked out from the renewal date
  // (Active, Grace, Lapsed, plus Life and Honorary), the count that sets the club's price, fees and Renew, a spreadsheet import with
  // 72-hour undo, and a directory for ordinary members. Online joining, reminder emails and the Zoho Books link are marked Coming soon.
  const MTYPES = [["Senior", 180, "Due 30 June each year", "Single"], ["Couple", 300, "Due 30 June each year", "Couple"], ["Family", 360, "Due 30 June each year", "Family"], ["Student", 60, "A year after they join", "Single"], ["Life", 0, "Never falls due", "Single"], ["Honorary", 0, "No fee", "Single"]];
  const MEMBERS = [
    ["Sam Taylor", "Senior", "active", 210, "Paid"], ["Priya Nair", "Senior", "active", 95, "Paid"], ["Tom Walker", "Life", "life", 0, ""], ["Jess Moreno", "Family", "active", 140, "Paid"],
    ["Ben Moreno", "Family", "active", 140, "Paid"], ["Aroha Smith", "Senior", "grace", -12, "Fee due"], ["Colin Park", "Senior", "lapsed", -75, "Fee due"], ["Morgan Reyes", "Student", "prospect", 0, ""],
    ["Margaret Ellis", "Honorary", "honorary", 0, ""], ["Ana Costa", "Student", "active", 260, "Paid"], ["Dev Patel", "Senior", "resigned", 0, ""]
  ].map(([name, type, st, due, fee]) => ({ name, type, st, due, fee, email: name.toLowerCase().replace(/[^a-z]+/g, ".") + "@example-bay.test", phone: "04" + String(10 + (name.length * 7) % 90) + " 555 " + String(100 + (name.length * 13) % 900) }));
  const MSTATUS = { active: ["Active", "ok"], grace: ["Grace", "trial"], lapsed: ["Lapsed", "bad"], life: ["Life", "ok"], honorary: ["Honorary", "ok"], prospect: ["Prospect", "quiet"], resigned: ["Resigned", "quiet"] };
  function Members() {
    const [as, setAs] = React.useState("officer"), [sel, setSel] = React.useState(null), [f, setF] = React.useState("counting"), [q, setQ] = React.useState(""), [note, setNote] = React.useState(""), [panel, setPanel] = React.useState("");
    const officer = as === "officer";
    const counting = (m) => ["active", "grace", "life", "honorary"].includes(m.st);
    const FIL = [["counting", "Counting", counting], ["lapsed", "Lapsed", (m) => m.st === "lapsed"], ["prospect", "Prospects", (m) => m.st === "prospect"], ["past", "Past", (m) => m.st === "resigned"], ["all", "All", () => true]];
    const shown = officer ? MEMBERS : MEMBERS.filter(counting);
    const list = shown.filter((m) => (!officer || FIL.find((x) => x[0] === f)[2](m)) && (!q || (m.name + m.email + m.type).toLowerCase().includes(q.toLowerCase())));
    const m = officer && sel && MEMBERS.find((x) => x.name === sel);
    const band = MEMBERS.filter(counting).length;
    const noDue = ["life", "honorary", "prospect", "resigned"];
    const dueText = (n) => (n === 0 ? "" : fmtShort(D(n)));
    const price = (x) => MTYPES.find((t) => t[0] === x.type)[1];
    return (
      <Ex title="Members" sub="The club's register: who belongs, which type, who is paid up, and the count that sets your price."
        actions={<><span className="cc-ex-chips tight" role="group" aria-label="View as">{[["officer", "Admin or membership officer"], ["member", "Member"]].map(([k, l]) => <button key={k} className={as === k ? "on" : ""} onClick={() => { setAs(k); setSel(null); setNote(""); setPanel(""); }}>View as: {l}</button>)}</span><Tag tone="ok">Included</Tag></>}>
        {officer ? <div className="cc-ex-note"><b>One register, kept once.</b> Start the register and everyone who has a login becomes a member, with their phone, notes and mailing consent moved across from Contacts. Import a spreadsheet for members who do not have a login.</div>
          : <div className="cc-ex-note">You can see the club's current members: name, email, type, and the phone, address and birthday members have chosen to share. Phone, address and date of birth start hidden: each member chooses what to share, and a hidden one is only visible to admins and that member. Your club can turn this directory off.</div>}
        {note && <div className="cc-ex-note" role="status">{note}</div>}
        {officer && <div className="cc-ex-stats"><Stat label="Counting towards your price" value={band} tone="good" note="Active, grace, life and honorary" /><Stat label="In grace" value={MEMBERS.filter((x) => x.st === "grace").length} tone="warn" /><Stat label="Lapsed" value={MEMBERS.filter((x) => x.st === "lapsed").length} tone="warn" /><Stat label="Unpaid fees" value="$360" note="2 fees" /></div>}
        <div className="cc-ex-tools">
          <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 value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search name, email or type" aria-label="Search members" /></label>
          {officer && <div className="cc-ex-chips tight">{FIL.map(([k, l, fn]) => <button key={k} className={f === k ? "on" : ""} onClick={() => setF(k)}>{l}<small>{MEMBERS.filter(fn).length}</small></button>)}</div>}
          {officer && <button className="cc-btn primary" type="button" onClick={() => setNote("In the app this opens a short form: name, email, phone, date of birth, address, type, how they pay (all at once, two halves or monthly), their own fee if it differs, joined date and your own fields. Each of phone, date of birth and address has a Hide tick, ticked by default: only admins and the member see a hidden one, and each member can choose to share theirs. An active member with a fee gets those fees raised as due.")}>Add a member</button>}
          {officer && <button className="cc-btn" type="button" onClick={() => setNote("Choose a CSV file. Clubcraft matches the headings, accepts dates like 5/3/2026, skips people already in the register, never puts anyone on a mailing list and raises no fees. You can undo the import for 72 hours; people you have edited since are kept.")}>Import a spreadsheet</button>}
          {officer && <button className="cc-btn" type="button" onClick={() => setPanel(panel === "types" ? "" : "types")}>Types and fees</button>}
          {officer && <button className="cc-btn" type="button" onClick={() => setPanel(panel === "reports" ? "" : "reports")}>Reports</button>}
        </div>
        <div className={"cc-ex-contacts" + (m ? " withdrawer" : "")}>
          <div className="cc-table"><table className={"cc-ex-table" + (officer ? " clickable" : "")}>
            <thead><tr><th>Name</th><th>Type</th>{officer && <th>Status</th>}{officer && <th>Renewal due</th>}<th>Phone</th></tr></thead>
            <tbody>{list.map((x) => <tr key={x.name} className={sel === x.name ? "sel" : ""} onClick={() => officer && setSel(sel === x.name ? null : x.name)} tabIndex={officer ? "0" : undefined} onKeyDown={(e) => { if (officer && e.key === "Enter") setSel(x.name); }}>
              <td><div className="who"><Av name={x.name} size={30} /><div><b>{x.name}</b><span>{x.email}</span></div></div></td><td>{x.type}</td>
              {officer && <td><Tag tone={MSTATUS[x.st][1]}>{MSTATUS[x.st][0]}</Tag></td>}{officer && <td className="cc-muted">{noDue.includes(x.st) ? "" : dueText(x.due)}</td>}
              <td className="cc-muted">{x.phone}</td></tr>)}
              {!list.length && <tr><td colSpan={officer ? 5 : 3} className="cc-muted">No members match.</td></tr>}</tbody>
          </table></div>
          {m && <aside className="cc-ex-drawer" aria-label={"Details for " + m.name}>
            <button className="cc-x" aria-label="Close" onClick={() => setSel(null)}>×</button>
            <div className="who big"><Av name={m.name} size={48} /><div><h3>{m.name}</h3><Tag tone={MSTATUS[m.st][1]}>{MSTATUS[m.st][0]}</Tag> <span className="cc-muted sm">{m.type}</span></div></div>
            <dl><div><dt>Email</dt><dd>{m.email}</dd></div><div><dt>Phone</dt><dd>{m.phone}</dd></div><div><dt>Joined</dt><dd>{fmtShort(D(-900))}</dd></div>
              {!noDue.includes(m.st) && <div><dt>Renewal due</dt><dd>{dueText(m.due)}</dd></div>}</dl>
            {price(m) > 0 && m.fee && <><h4 style={{ margin: "12px 0 4px" }}>Fees</h4>
              <div className="cc-muted sm">{m.type} to next renewal: ${price(m)}.00 <Tag tone={m.fee === "Paid" ? "ok" : "warn"}>{m.fee === "Paid" ? "paid" : "due"}</Tag></div>
              <div className="cc-muted sm" style={{ marginTop: 4 }}>Pays: {m.name.length % 3 === 0 ? "monthly" : m.name.length % 3 === 1 ? "all at once" : "in two halves (second half 31 December)"}. The amount and the option can be set for each member.</div>
              <div className="cc-muted sm" style={{ marginTop: 6 }}>If your club uses Zoho Books, invoices and payments are managed there. This ledger is for clubs that keep their own records. <Tag tone="trial">Books link coming soon</Tag></div></>}
            <div className="lists"><b>Mailing lists</b><div className="cc-muted sm">Recorded here, with how and when each person agreed. Contacts shows the same consent.</div></div>
            <div className="cc-row" style={{ gap: 8, marginTop: 12 }}><button className="cc-btn sm primary" type="button" onClick={() => setNote("In the app this opens the member's details to change.")}>Edit</button>
              {["active", "grace", "lapsed"].includes(m.st) && price(m) > 0 && <button className="cc-btn sm" type="button" onClick={() => setNote("Renew moves " + m.name + " on to the next period and records that period's fee: paid now, left due, or waived.")}>Renew</button>}</div>
          </aside>}
        </div>
        {officer && panel === "types" && <Panel title="Membership types" aside={<small className="cc-muted">Admins and membership officers set these</small>}>
          <table className="cc-ex-table"><thead><tr><th>Type</th><th>Default fee</th><th>Renews</th><th>Household</th></tr></thead><tbody>{MTYPES.map(([n, fee, r, h]) => <tr key={n}><td>{n}</td><td>{fee ? CCIntl.money(fee) : "No fee"}</td><td className="cc-muted">{r}</td><td className="cc-muted">{h}</td></tr>)}</tbody></table>
          <p className="cc-muted sm" style={{ marginTop: 8 }}>Each type has a default fee, a renewal date (30 June is common) and grace days (30 by default). A person is Grace until the grace days run out, then Lapsed. On each member you can change their amount and choose how they pay: all at once, in two halves (the second half is due 31 December) or monthly.</p></Panel>}
        {officer && panel === "reports" && <Panel title="Reports" aside={<small className="cc-muted">Updated as you work</small>}>
          <div className="cc-ex-bars">{[["Senior", 4], ["Family", 2], ["Student", 2], ["Life", 1], ["Honorary", 1]].map(([n, v]) => <div className="row" key={n}><span>{n}</span><span className="t"><i style={{ width: (v * 25) + "%" }} /></span><b>{v}</b></div>)}</div>
          <p className="cc-muted sm" style={{ marginTop: 8 }}>Members by type, joins and leaves by month, renewals coming up, and unpaid fees by how late they are. Online joining, reminder emails and the Zoho Books link are coming soon.</p></Panel>}
      </Ex>
    );
  }

  /* ---------------- Finances ---------------- */
  // Feature lists follow the Zoho Books Australia pricing page (checked 2026-10-22); recheck before launch.
  const BOOKS_FREE = [
    ["Who it suits", ["For businesses with revenue under A$50,000 a year, which covers most clubs", "1 user plus 1 accountant"]],
    ["Invoices and payments", ["Up to 1,000 invoices a year", "Clients, credit notes and recurring invoices", "Customer portal, automated payment reminders, online and offline payments", "Three payment gateways: Stripe, PayPal and GoCardless", "Invoice customisation and multilingual invoicing"]],
    ["Bank and expenses", ["Several bank and credit card accounts", "Import bank and card statements (no live bank feed)", "Bank rules and reconciliation", "Expense and mileage tracking, receipt scanning (50 a month)"]],
    ["Tax and reports", ["GST tracking and BAS", "Chart of accounts and manual journals", "Standard reports, with up to 5 scheduled reports"]],
    ["Connects to", ["Zoho CRM, Analytics, Mail, Desk, Expense, Inventory and Cliq", "Google Workspace, Microsoft 365, Slack, Zapier, Dropbox and OneDrive"]],
    ["Support", ["Email support"]]
  ];
  const BOOKS_STD = [
    ["Everything in Free, plus", ["3 users (instead of 1 plus your accountant)", "Up to 5,000 invoices a year"]],
    ["Closes the gaps", ["Bank and credit card feeds, so transactions arrive by themselves", "Recurring expenses", "Eight payment gateways, including Square and Authorize.Net", "More reporting: custom reports, reporting tags and up to 50 scheduled reports"]],
    ["Control and tidiness", ["Predefined user roles (treasurer, president)", "Transaction locking at year end", "Custom fields, bulk updates and journal templates", "Progress invoicing and retention payments"]],
    ["More help", ["Receipt scanning, 200 a month", "Email, voice and chat support"]]
  ];
  function PlanModal({ title, sub, groups, onClose }) {
    return (
      <div className="cc-modal-bg" role="dialog" aria-modal="true" aria-label={title} onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
        <div className="cc-modal">
          <div className="cc-modal-h"><h2>{title}</h2><button className="cc-btn sm" type="button" onClick={onClose} aria-label="Close">✕</button></div>
          <div className="cc-modal-b">
            <p className="cc-muted sm">{sub}</p>
            <div className="cc-ex-feat">{groups.map(([t, items]) => <div key={t}><b>{t}</b><ul>{items.map((i) => <li key={i}>{i}</li>)}</ul></div>)}</div>
          </div>
          <div className="cc-modal-f"><span /><button className="cc-btn primary" type="button" onClick={onClose}>Close</button></div>
        </div>
      </div>
    );
  }
  function Finances() {
    const [pop, setPop] = React.useState(null);
    return (
      <Ex title="Finances" sub="Book-keeping for your club, free to start." actions={<Tag tone="ok">Free to start</Tag>}>
        {CCIntl.country() !== "AU" && <div className="cc-note">This page describes Zoho Books in Australia. Zoho Books plans, limits and prices differ by country, so we confirm them for {CCIntl.get().countryName} before Finances opens here. {CCIntl.tax().name === "sales tax" ? "Sales tax" : CCIntl.tax().name} tracking follows your country's rules.</div>}
        {pop === "free" && <PlanModal title="Zoho Books Free: what your club gets" sub="Free for organisations with revenue under A$50,000 a year." groups={BOOKS_FREE} onClose={() => setPop(null)} />}
        {pop === "std" && <PlanModal title="Zoho Books Standard: what your club gets" sub="Everything in Free, plus the items below. Under US$15 a month, billed annually." groups={BOOKS_STD} onClose={() => setPop(null)} />}
        <div className="cc-ex-fin">
          <Panel title="Start free with Zoho Books" className="lead">
            <p>Clubcraft keeps the money side of your <b>events</b> (the budget and the profit). For the books of the club itself, a typical club can use the <b>Zoho Books Free plan at no cost</b>. Invoices, expenses, bank statement import, reconciliation and GST/BAS are all there.</p>
            <div className="cc-ex-price"><b>Free</b><span>For clubs with revenue under A$50,000 a year. Priced and supported by Zoho, with help from Delivio and your own accountant.</span></div>
            <p className="cc-muted sm"><b>The main gaps:</b> no live bank feed (you import statements), no recurring expenses, only three payment gateways and limited reporting.</p>
            <div className="cc-row"><button className="cc-btn primary" type="button" onClick={() => setPop("free")}>See what Free includes</button></div>
          </Panel>
          <Panel title="Want the gaps covered? Step up to Standard">
            <p>The Standard plan adds bank feeds, recurring expenses, more payment gateways, fuller reporting and three users.</p>
            <div className="cc-ex-price"><b>Under US$15 a month</b><span>Zoho Books Standard, billed annually. You can move up at any time and keep your books.</span></div>
            <div className="cc-row"><button className="cc-btn" type="button" onClick={() => setPop("std")}>See what Standard adds</button><button className="cc-btn primary" type="button">Ask about Finances</button></div>
            <p className="cc-muted sm" style={{ marginTop: 10 }}>Clubcraft will connect to Zoho Books where it helps, for example an event's profit flowing into the books. Already on Xero or MYOB? Tell us what you use.</p>
          </Panel>
        </div>
        <Panel title="How it looks when connected" aside={<small className="cc-muted">Example figures</small>}>
          <div className="cc-ex-stats">
            <Stat label="In the bank" value="$12,480" />
            <Stat label="Money in this month" value={CCIntl.sample("$4,980")} tone="good" note="Trivia Night tickets and raffle" />
            <Stat label="Money out this month" value="$1,850" />
            <Stat label="Next BAS due" value="28 Oct" tone="warn" />
          </div>
        </Panel>
      </Ex>
    );
  }

  window.CCPreviews = { Review, Ideas, Events, Comms, Social, Calendar, Members, Contacts, Finances };
})();
