/* members.jsx: the real Members module (docs/members-module.md). Version 1.3, 2026-11-04 15:00 (types, import, Start and settings need Admin access to Members; Edit manages members and fees).
 * The club's register of members: who belongs, which type, whether they are paid up, and how many count towards the club's price band.
 * Club admins and membership officers see and change everything; every other login sees a directory (name, email, phone, type) unless
 * the club turns it off. All rules are enforced by cc_api (routes/members.js); this file only draws what it is given.
 * Exposes window.CCMembers; shell.jsx mounts it on the Members page when not in demo mode.
 */
(function () {
  const API = window.ClubcraftApi;
  const call = (clubId, method, path, body) => API.call(method, path, body, { club: clubId });
  const fmtDate = (iso) => (iso ? new Date(iso + "T12:00:00").toLocaleDateString(CCIntl.locale(), { day: "numeric", month: "short", year: "numeric" }) : "");
  const fmtWhen = (ms) => new Date(ms).toLocaleDateString(CCIntl.locale(), { day: "numeric", month: "short", year: "numeric" });
  const money = (n) => CCIntl.money2(n);
  const initials = (n) => (n || "?").split(/\s+/).filter(Boolean).slice(0, 2).map((w) => w[0].toUpperCase()).join("");
  const Avatar = ({ name, size }) => <span aria-hidden="true" style={{ width: size, height: size, borderRadius: "50%", background: "var(--b-wash)", color: "var(--b-primary)", display: "inline-grid", placeItems: "center", fontWeight: 700, fontSize: size * 0.38, flex: "none" }}>{initials(name)}</span>;
  const SHOWN = { active: ["Active", "ok"], grace: ["Grace", "trial"], lapsed: ["Lapsed", "bad"], life: ["Life", "ok"], honorary: ["Honorary", "ok"], prospect: ["Prospect", "quiet"], resigned: ["Resigned", "quiet"], archived: ["Archived", "quiet"] };
  const StatusPill = ({ s }) => { const [l, t] = SHOWN[s] || [s, "quiet"]; return <span className={"cc-pill " + t}>{l}</span>; };
  const COUNTING = ["active", "grace", "life", "honorary"];
  const FILTERS = [["counting", "Counting", (m) => COUNTING.includes(m.shown)], ["lapsed", "Lapsed", (m) => m.shown === "lapsed"], ["prospect", "Prospects", (m) => m.shown === "prospect"], ["past", "Past", (m) => m.shown === "resigned" || m.shown === "archived"], ["all", "All", () => true]];
  const PERIOD_LABEL = { fixed: "On a set date each year", annual: "A year after they join or renew", lifetime: "Never (life member)", free: "Never (no fee)" };
  const PLAN_LABEL = { full: "All at once", half: "Two halves (the second half is due 31 December)", monthly: "Monthly" };
  const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  const fmtBirthday = (md) => (md ? new Date("2000-" + md + "T12:00:00").toLocaleDateString(CCIntl.locale(), { day: "numeric", month: "long" }) : "");
  const TYPE_LABEL = { text: "Text", date: "Date", year: "Year", pick: "Pick-list", yesno: "Yes or no" };

  function Modal({ title, onClose, children, foot, label }) {
    return (
      <div className="cc-modal-bg" role="dialog" aria-modal="true" aria-label={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" onClick={onClose} aria-label="Close">✕</button></div>
          <div className="cc-modal-b">{children}</div>
          <div className="cc-modal-f">{foot}</div>
        </div>
      </div>
    );
  }
  const Foot = ({ onClose, onSave, busy, label, disabled }) => <><span /><div className="cc-row"><button className="cc-btn ghost" onClick={onClose}>Cancel</button><button className="cc-btn primary" disabled={busy || disabled} onClick={onSave}>{busy ? "Saving…" : label || "Save"}</button></div></>;

  /* ---------- add / edit one member ---------- */
  function MemberForm({ clubId, m, data, onClose, onSaved }) {
    const isNew = !m.id, live = data.types.filter((t) => t.active), linked = !!m.userId;
    const orig = { firstName: m.firstName || "", lastName: m.lastName || "", email: m.email || "", phone: m.phone || "", hidePhone: isNew ? true : m.hidePhone !== false, address: m.address || "", hideAddress: isNew ? true : m.hideAddress !== false,
      dob: m.dob || "", hideDob: isNew ? true : m.hideDob !== false, memberNo: m.memberNo || "", notes: m.notes || "", typeId: m.typeId || (live[0] ? live[0].id : ""), status: m.status || "active", joinedAt: m.joinedAt || "",
      householdId: m.householdId || "", leftReason: m.leftReason || "", payPlan: m.payPlan || "full", feeAmount: m.feeAmount != null ? String(m.feeAmount) : "", custom: m.custom || {} };
    const [f, setF] = React.useState(orig), [busy, setBusy] = React.useState(false), [err, setErr] = React.useState(null);
    const set = (k, v) => setF((x) => ({ ...x, [k]: v }));
    const selType = live.find((t) => t.id === f.typeId);
    const renews = !!selType && (selType.period === "annual" || selType.period === "fixed");
    async function save() {
      setBusy(true); setErr(null);
      const body = {};
      const always = ["hidePhone", "hideDob", "hideAddress", "payPlan"];
      Object.keys(f).forEach((k) => { if (isNew ? (k === "custom" ? Object.keys(f.custom).length : always.includes(k) || f[k] !== "") : JSON.stringify(f[k]) !== JSON.stringify(orig[k])) body[k] = f[k]; });
      if (body.feeAmount !== undefined && body.feeAmount !== "") body.feeAmount = Number(body.feeAmount);
      if (!renews) { delete body.payPlan; delete body.feeAmount; }
      if (linked) { delete body.firstName; delete body.lastName; delete body.email; }
      if (!isNew && !Object.keys(body).length) { onClose(); return; }
      try { const r = await call(clubId, isNew ? "POST" : "PATCH", "/club/register" + (isNew ? "" : "/" + m.id), body); onSaved(r.member.id); }
      catch (e) { setErr(e.message); setBusy(false); }
    }
    const input = (k, label, extra) => <label className="cc-field">{label}<input value={f[k]} onChange={(e) => set(k, e.target.value)} {...extra} /></label>;
    // A field with its own Hide tick: hidden fields stay out of the directory other members see.
    const withHide = (k, hideKey, label, extra) => (
      <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 10, alignItems: "end" }}>
        {input(k, label, extra)}
        <label style={{ display: "flex", flexDirection: "column", fontSize: 13, paddingBottom: 8, maxWidth: 170 }}>
          <span><input type="checkbox" checked={f[hideKey]} onChange={(e) => set(hideKey, e.target.checked)} aria-label={"Hide " + label.toLowerCase()} /> Hide</span>
          <small className="cc-muted">Only visible to Admins and the member</small>
        </label>
      </div>);
    const fields = data.settings.fields || [];
    return (
      <Modal title={isNew ? "Add a member" : "Edit " + (m.name || "member")} onClose={onClose} foot={<Foot onClose={onClose} onSave={save} busy={busy} disabled={!live.length || (!linked && !f.firstName.trim())} />}>
        {!live.length && <div className="cc-note">Add a membership type first (Types and fees, in the toolbar).</div>}
        {linked && <div className="cc-note trial">Name and email come from this member's Clubcraft login, so they are changed there.</div>}
        {!linked && <div className="cc-grid2">{input("firstName", "First name", { autoFocus: true })}{input("lastName", "Last name")}</div>}
        {!linked && input("email", "Email (optional)", { type: "email" })}
        {withHide("phone", "hidePhone", "Phone (optional)", { type: "tel" })}
        {withHide("dob", "hideDob", "Date of birth (optional)", { type: "date" })}
        {withHide("address", "hideAddress", "Address (optional)")}
        <div className="cc-grid2">
          <label className="cc-field">Membership type<select value={f.typeId} onChange={(e) => set("typeId", e.target.value)}>{live.map((t) => <option key={t.id} value={t.id}>{t.name}{t.fee ? " (" + money(t.fee) + ")" : ""}</option>)}</select></label>
          <label className="cc-field">Status<select value={f.status === "archived" ? "resigned" : f.status} onChange={(e) => set("status", e.target.value)}><option value="active">Active</option><option value="prospect">Prospect</option><option value="resigned">Resigned</option></select></label>
        </div>
        {renews && <div className="cc-grid2">
          <label className="cc-field">How they pay<select value={f.payPlan} onChange={(e) => set("payPlan", e.target.value)}>{Object.entries(PLAN_LABEL).map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select></label>
          <label className="cc-field">Fee for this member ($ a year)<input type="number" min="0" step="0.01" value={f.feeAmount} placeholder={String(selType.fee)} onChange={(e) => set("feeAmount", e.target.value)} /><small className="cc-muted">Leave blank to use the type's default of {money(selType.fee)}.</small></label>
        </div>}
        {f.status === "resigned" && input("leftReason", "Reason for leaving (optional)")}
        <div className="cc-grid2">
          {input("joinedAt", "Joined", { type: "date" })}
          {input("memberNo", "Member number (optional)", { placeholder: "Next: " + data.settings.nextNo })}
        </div>
        <label className="cc-field">Household (optional)<select value={f.householdId} onChange={(e) => set("householdId", e.target.value)}><option value="">None</option>{data.households.map((h) => <option key={h.id} value={h.id}>{h.name}</option>)}</select></label>
        {fields.map((d) => (
          <label key={d.id} className="cc-field">{d.label}
            {d.type === "pick" ? <select value={f.custom[d.id] || ""} onChange={(e) => set("custom", { ...f.custom, [d.id]: e.target.value })}><option value="">Not set</option>{d.options.map((o) => <option key={o}>{o}</option>)}</select>
              : d.type === "yesno" ? <select value={f.custom[d.id] === true ? "yes" : f.custom[d.id] === false ? "no" : ""} onChange={(e) => set("custom", { ...f.custom, [d.id]: e.target.value === "" ? "" : e.target.value === "yes" })}><option value="">Not set</option><option value="yes">Yes</option><option value="no">No</option></select>
                : <input type={d.type === "date" ? "date" : "text"} inputMode={d.type === "year" ? "numeric" : undefined} maxLength={d.type === "year" ? 4 : 500} value={f.custom[d.id] || ""} onChange={(e) => set("custom", { ...f.custom, [d.id]: e.target.value })} />}
          </label>))}
        <label className="cc-field">Notes (optional, only admins and membership officers see these)<textarea rows={3} maxLength={10000} value={f.notes} onChange={(e) => set("notes", e.target.value)} /></label>
        {err && <div className="cc-err" role="alert">{err}</div>}
      </Modal>
    );
  }

  /* ---------- record a payment ---------- */
  function PayModal({ clubId, m, fee, onClose, onDone }) {
    const [f, setF] = React.useState({ method: "bank", paidAt: "", reference: "" }), [busy, setBusy] = React.useState(false), [err, setErr] = React.useState(null);
    async function save() {
      setBusy(true); setErr(null);
      try { await call(clubId, "POST", "/club/register/" + m.id + "/fees/" + fee.id, { action: "paid", method: f.method, paidAt: f.paidAt || undefined, reference: f.reference }); onDone(); }
      catch (e) { setErr(e.message); setBusy(false); }
    }
    return (
      <Modal title={"Record payment from " + m.name} onClose={onClose} foot={<Foot onClose={onClose} onSave={save} busy={busy} label="Mark as paid" />}>
        <p className="cc-muted sm">{fee.label}: {money(fee.amount)}. If your club uses Zoho Books for invoices and payments, record it there instead. This ledger is for clubs that keep their own records.</p>
        <div className="cc-grid2">
          <label className="cc-field">How it was paid<select value={f.method} onChange={(e) => setF({ ...f, method: e.target.value })}><option value="bank">Bank transfer</option><option value="cash">Cash</option><option value="card">Card</option><option value="other">Other</option></select></label>
          <label className="cc-field">Date paid (today if blank)<input type="date" value={f.paidAt} onChange={(e) => setF({ ...f, paidAt: e.target.value })} /></label>
        </div>
        <label className="cc-field">Reference (optional)<input value={f.reference} maxLength={80} onChange={(e) => setF({ ...f, reference: e.target.value })} /></label>
        {err && <div className="cc-err" role="alert">{err}</div>}
      </Modal>
    );
  }

  /* ---------- renew ---------- */
  function RenewModal({ clubId, m, type, onClose, onDone }) {
    const [how, setHow] = React.useState("paid"), [f, setF] = React.useState({ method: "bank", paidAt: "", reference: "", amount: "" });
    const [busy, setBusy] = React.useState(false), [err, setErr] = React.useState(null);
    async function save() {
      setBusy(true); setErr(null);
      const body = {};
      if (f.amount !== "") body.amount = Number(f.amount);
      if (how === "paid") Object.assign(body, { method: f.method, paidAt: f.paidAt || undefined, reference: f.reference });
      if (how === "waive") body.waive = true;
      try { await call(clubId, "POST", "/club/register/" + m.id + "/renew", body); onDone(); }
      catch (e) { setErr(e.message); setBusy(false); }
    }
    return (
      <Modal title={"Renew " + m.name} onClose={onClose} foot={<Foot onClose={onClose} onSave={save} busy={busy} label="Renew" />}>
        <p className="cc-muted sm">Moves {m.name} on to the next period{m.renewDue ? " (now due " + fmtDate(m.renewDue) + ")" : ""} and records that period's fee of {money(m.feeAmount != null ? m.feeAmount : type ? type.fee : 0)}.{m.payPlan !== "full" && " Their payment option is: " + PLAN_LABEL[m.payPlan].toLowerCase() + ". A payment you record here is the first one; the rest stay due."}</p>
        <div role="radiogroup" aria-label="Payment">
          {[["paid", m.payPlan === "full" ? "They have paid" : "They have paid the first payment"], ["due", "Not paid yet (leave the fee due)"], ["waive", "Waive the fee"]].map(([k, l]) => <label key={k} style={{ display: "block", margin: "4px 0" }}><input type="radio" name="how" checked={how === k} onChange={() => setHow(k)} /> {l}</label>)}
        </div>
        <label className="cc-field">Different amount (optional)<input type="number" min="0" step="0.01" value={f.amount} onChange={(e) => setF({ ...f, amount: e.target.value })} placeholder={type ? String(type.fee) : ""} /></label>
        {how === "paid" && <div className="cc-grid2">
          <label className="cc-field">How it was paid<select value={f.method} onChange={(e) => setF({ ...f, method: e.target.value })}><option value="bank">Bank transfer</option><option value="cash">Cash</option><option value="card">Card</option><option value="other">Other</option></select></label>
          <label className="cc-field">Date paid (today if blank)<input type="date" value={f.paidAt} onChange={(e) => setF({ ...f, paidAt: e.target.value })} /></label>
          <label className="cc-field">Reference (optional)<input value={f.reference} maxLength={80} onChange={(e) => setF({ ...f, reference: e.target.value })} /></label>
        </div>}
        {err && <div className="cc-err" role="alert">{err}</div>}
      </Modal>
    );
  }

  /* ---------- membership types ---------- */
  function TypesModal({ clubId, types, onClose, onSaved }) {
    const [ts, setTs] = React.useState(() => types.filter((t) => t.active).map((t) => ({ ...t })));
    const [busy, setBusy] = React.useState(false), [err, setErr] = React.useState(null);
    const upd = (i, k, v) => setTs(ts.map((t, j) => (j === i ? { ...t, [k]: v } : t)));
    const setPeriod = (i, v) => setTs(ts.map((t, j) => (j === i ? { ...t, period: v, ...(v === "fixed" && !t.renewMonth ? { renewMonth: 6, renewDay: 30 } : {}) } : t)));
    async function save() {
      setBusy(true); setErr(null);
      try {
        await call(clubId, "PUT", "/club/register/types", { types: ts.map((t) => ({ id: t.id, name: t.name, fee: Number(t.fee || 0), period: t.period, renewMonth: t.period === "fixed" ? t.renewMonth : undefined, renewDay: t.period === "fixed" ? t.renewDay : undefined, graceDays: t.graceDays, household: t.household || "single" })) });
        onSaved();
      } catch (e) { setErr(e.message); setBusy(false); }
    }
    return (
      <Modal title="Membership types" onClose={onClose} foot={<Foot onClose={onClose} onSave={save} busy={busy} />}>
        <p className="cc-muted sm">Each type has a default fee and a renewal date. 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. A type with members in it that you remove is hidden rather than deleted. Up to 20.</p>
        {ts.map((t, i) => (
          <fieldset key={t.id || i} style={{ border: "1px solid var(--b-line)", borderRadius: 8, margin: "0 0 10px", padding: "8px 10px" }}>
            <div className="cc-row" style={{ gap: 6, flexWrap: "wrap" }}>
              <input aria-label="Type name" placeholder="Name, for example Senior" value={t.name} onChange={(e) => upd(i, "name", e.target.value)} style={{ flex: "1 1 160px" }} />
              <label className="cc-muted sm">Default fee $<input aria-label="Default fee" type="number" min="0" step="0.01" value={t.period === "free" ? 0 : t.fee} disabled={t.period === "free"} onChange={(e) => upd(i, "fee", e.target.value)} style={{ width: 90, marginLeft: 4 }} /></label>
              <button type="button" className="cc-btn sm ghost" aria-label={"Remove " + (t.name || "type")} onClick={() => setTs(ts.filter((_, j) => j !== i))}>✕</button>
            </div>
            <div className="cc-row" style={{ gap: 6, flexWrap: "wrap", marginTop: 6 }}>
              <select aria-label="Renews" value={t.period} onChange={(e) => setPeriod(i, e.target.value)}>{Object.entries(PERIOD_LABEL).map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select>
              {t.period === "fixed" && <><span className="cc-muted sm">Due on</span><input aria-label="Due day" type="number" min="1" max="31" value={t.renewDay || ""} onChange={(e) => upd(i, "renewDay", Number(e.target.value))} style={{ width: 64 }} />
                <select aria-label="Due month" value={t.renewMonth || ""} onChange={(e) => upd(i, "renewMonth", Number(e.target.value))}><option value="">Month</option>{MONTHS.map((n, k) => <option key={n} value={k + 1}>{n}</option>)}</select></>}
              {(t.period === "annual" || t.period === "fixed") && <label className="cc-muted sm">Grace days <input aria-label="Grace days" type="number" min="0" max="365" value={t.graceDays} onChange={(e) => upd(i, "graceDays", Number(e.target.value))} style={{ width: 64 }} /></label>}
              <label className="cc-muted sm">Household <select aria-label="Household" value={t.household || "single"} onChange={(e) => upd(i, "household", e.target.value)}><option value="single">Single</option><option value="couple">Couple</option><option value="family">Family</option></select></label>
            </div>
          </fieldset>))}
        {ts.length < 20 && <button type="button" className="cc-btn sm" onClick={() => setTs(ts.concat({ name: "", fee: 0, period: "fixed", renewMonth: 6, renewDay: 30, graceDays: 30, household: "single", active: true }))}>Add a type</button>}
        {err && <div className="cc-err" role="alert">{err}</div>}
      </Modal>
    );
  }

  /* ---------- club settings: directory and custom fields (admins) ---------- */
  function SettingsModal({ clubId, settings, onClose, onSaved }) {
    const [dir, setDir] = React.useState(settings.directoryVisible);
    const [fs, setFs] = React.useState(() => (settings.fields || []).map((f) => ({ ...f, options: (f.options || []).join(", ") })));
    const [busy, setBusy] = React.useState(false), [err, setErr] = React.useState(null);
    const upd = (i, k, v) => setFs(fs.map((f, j) => (j === i ? { ...f, [k]: v } : f)));
    async function save() {
      setBusy(true); setErr(null);
      try { await call(clubId, "PUT", "/club/register/settings", { directoryVisible: dir, fields: fs.map((f) => ({ id: f.id, label: f.label, type: f.type, options: f.type === "pick" ? f.options.split(",").map((o) => o.trim()).filter(Boolean) : undefined })) }); onSaved(); }
      catch (e) { setErr(e.message); setBusy(false); }
    }
    return (
      <Modal title="Register settings" onClose={onClose} foot={<Foot onClose={onClose} onSave={save} busy={busy} />}>
        <label style={{ display: "block", marginBottom: 12 }}><input type="checkbox" checked={dir} onChange={(e) => setDir(e.target.checked)} /> Members can see the directory (name, email, phone and type of current members). Turn this off for clubs with young members or privacy concerns.</label>
        <h3 style={{ margin: "0 0 6px" }}>Your own fields</h3>
        <p className="cc-muted sm">Extra things you keep about members, such as emergency contact, skills or locker number. Up to 20.</p>
        {fs.map((f, i) => <div key={f.id || i} className="cc-row" style={{ gap: 6, marginBottom: 8, flexWrap: "wrap" }}>
          <input aria-label="Field name" placeholder="Field name" value={f.label} onChange={(e) => upd(i, "label", e.target.value)} style={{ flex: "1 1 150px" }} />
          <select aria-label="Field type" value={f.type} onChange={(e) => upd(i, "type", e.target.value)}>{Object.entries(TYPE_LABEL).map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select>
          {f.type === "pick" && <input aria-label="Choices" placeholder="Choices, separated by commas" value={f.options} onChange={(e) => upd(i, "options", e.target.value)} style={{ flex: "1 1 200px" }} />}
          <button type="button" className="cc-btn sm ghost" aria-label={"Remove " + (f.label || "field")} onClick={() => setFs(fs.filter((_, j) => j !== i))}>✕</button>
        </div>)}
        {fs.length < 20 && <button type="button" className="cc-btn sm" onClick={() => setFs(fs.concat({ label: "", type: "text", options: "" }))}>Add a field</button>}
        {err && <div className="cc-err" role="alert">{err}</div>}
      </Modal>
    );
  }

  /* ---------- import a spreadsheet (CSV) ---------- */
  const IMPORT_FIELDS = [["name", "Full name", /^(full )?name$/i], ["firstName", "First name", /first/i], ["lastName", "Last name", /last|surname|family/i], ["email", "Email", /e-?mail/i], ["phone", "Phone", /phone|mobile|cell/i], ["address", "Address", /address|street/i],
    ["dob", "Date of birth", /birth|dob/i], ["memberNo", "Member number", /member.*(no|number)|^no\.?$|^number$/i], ["type", "Membership type", /type|category|class/i], ["status", "Status", /status/i], ["joinedAt", "Joined", /join|since|start/i], ["renewDue", "Renewal due", /renew|expir|due/i], ["notes", "Notes", /notes?|comment/i]];
  function ImportModal({ clubId, data, onClose, onDone }) {
    const parseCsv = window.CCParseCsv;
    const [table, setTable] = React.useState(null), [map, setMap] = React.useState({}), [typeId, setTypeId] = React.useState((data.types.find((t) => t.active) || {}).id || "");
    const [busy, setBusy] = React.useState(false), [err, setErr] = React.useState(null), [result, setResult] = React.useState(null);
    const [order, setOrder] = React.useState(CCIntl.dateOrder() || "");      // the club's usual date order; Canada has none, so the person chooses
    function pick(file) {
      if (!file) return;
      const rd = new FileReader();
      rd.onload = () => {
        const rows = parseCsv(String(rd.result).replace(/^﻿/, ""));
        if (rows.length < 2) { setErr("That file has no rows. Save your spreadsheet as CSV (comma separated) with a heading row."); return; }
        setErr(null); setTable(rows);
        const m = {}; IMPORT_FIELDS.forEach(([k, , re]) => { const i = rows[0].findIndex((h) => re.test(h.trim())); if (i >= 0 && !Object.values(m).includes(i)) m[k] = i; });
        setMap(m);
      };
      rd.readAsText(file);
    }
    const body = table ? table.slice(1).map((r) => Object.fromEntries(IMPORT_FIELDS.map(([k]) => [k, map[k] != null ? (r[map[k]] || "").trim() : ""]))) : [];
    /* Dates such as 4/5/2026 are day-first in Australia, New Zealand and the UK, month-first in the USA: reading them the wrong way would silently
       change every date, so the file is checked. A date with a part over 12 settles the order; if nothing does, the person says. */
    const slashDates = body.flatMap((r) => ["dob", "joinedAt", "renewDue"].map((k) => r[k])).map((v) => (v || "").match(/^(\d{1,2})[\/.-](\d{1,2})[\/.-](\d{4})$/)).filter(Boolean).map((m) => [Number(m[1]), Number(m[2])]);
    const seenDay = slashDates.some(([a]) => a > 12), seenMonth = slashDates.some(([, b]) => b > 12);
    const clash = seenDay && seenMonth;
    const settled = clash ? "" : seenDay ? "dmy" : seenMonth ? "mdy" : "";
    const unclear = slashDates.some(([a, b]) => a !== b && a <= 12 && b <= 12);
    const effOrder = settled || order;
    const needOrder = !clash && !settled && unclear && !effOrder;
    const readDate = (v) => { const m = (v || "").match(/^(\d{1,2})[\/.-](\d{1,2})[\/.-](\d{4})$/); if (!m) return v || ""; const [a, b] = [Number(m[1]), Number(m[2])]; const [d, mo] = effOrder === "mdy" ? [b, a] : [a, b]; return d >= 1 && d <= 31 && mo >= 1 && mo <= 12 ? CCIntl.date(m[3] + "-" + String(mo).padStart(2, "0") + "-" + String(d).padStart(2, "0")) : v + " (not a date)"; };
    async function run() {
      setBusy(true); setErr(null);
      let added = 0, skipped = 0; const notes = [], batches = [];
      try {
        for (let i = 0; i < body.length; i += 500) {
          const r = await call(clubId, "POST", "/club/register/import", { rows: body.slice(i, i + 500), typeId: typeId || undefined, dateOrder: effOrder || undefined });
          added += r.added; skipped += r.skippedCount; if (r.batch) batches.push(r.batch);
          r.skipped.forEach((s) => notes.push("Row " + (i + s.line + 1) + ": " + s.reason));
        }
        setResult({ added, skipped, notes: notes.slice(0, 20), batches });
      } catch (e) { setErr(e.message); }
      setBusy(false);
    }
    async function undo() {
      setBusy(true); setErr(null);
      try { for (const b of result.batches) await call(clubId, "POST", "/club/register/import/" + b + "/undo", {}); onDone(); }
      catch (e) { setErr(e.message); setBusy(false); }
    }
    const nameOk = map.name != null || map.firstName != null || map.email != null;
    return (
      <Modal title="Import members" onClose={result ? onDone : onClose} foot={result
        ? <><span>{result.batches.length > 0 && <button className="cc-btn ghost" disabled={busy} onClick={undo}>Undo this import</button>}</span><button className="cc-btn primary" onClick={onDone}>Done</button></>
        : <><span /><div className="cc-row"><button className="cc-btn ghost" onClick={onClose}>Cancel</button><button className="cc-btn primary" disabled={busy || !table || !nameOk || needOrder || clash || (map.type == null && !typeId)} onClick={run}>{busy ? "Importing…" : "Import " + body.length + " rows"}</button></div></>}>
        {result ? <div>
          <div className="cc-note trial" role="status">Added {result.added} members.{result.skipped ? " Skipped " + result.skipped + "." : ""}</div>
          {result.notes.length > 0 && <ul className="cc-muted sm">{result.notes.map((n, i) => <li key={i}>{n}</li>)}</ul>}
          <p className="cc-muted sm">Nobody imported is on a mailing list, and no fees were raised. You can undo this import for 72 hours; people you have edited since are kept.</p>
        </div> : <div>
          <p className="cc-muted sm">Choose a CSV file (in Excel or Google Sheets: Save as, CSV). The first row must be headings. Dates can be 2026-03-05 or written with slashes ({CCIntl.dateOrder() === "mdy" ? "month first, so 5/3/2026 is 3 May" : CCIntl.dateOrder() === "dmy" ? "day first, so 5/3/2026 is 5 March" : "we ask which way round"}). People already in the register (same email, or same name and birth date) are skipped.</p>
          <input type="file" accept=".csv,text/csv" aria-label="CSV file" onChange={(e) => pick(e.target.files[0])} />
          {table && <div style={{ marginTop: 10 }}>
            <label className="cc-field">Membership type for everyone without one in the file<select value={typeId} onChange={(e) => setTypeId(e.target.value)}><option value="">None (my file has a type column)</option>{data.types.filter((t) => t.active).map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}</select></label>
            <div className="cc-grid2">{IMPORT_FIELDS.map(([k, label]) => <label key={k} className="cc-field">{label}<select value={map[k] != null ? map[k] : ""} onChange={(e) => setMap({ ...map, [k]: e.target.value === "" ? undefined : Number(e.target.value) })}><option value="">Not in my file</option>{table[0].map((h, i) => <option key={i} value={i}>{h || "Column " + (i + 1)}</option>)}</select></label>)}</div>
            {clash && <div className="cc-err" role="alert">This file mixes day-first and month-first dates (some have a day over 12 in the first place, others in the second). Fix the dates in your spreadsheet, or use the format 2026-03-05, then choose the file again.</div>}
            {slashDates.length > 0 && !clash && !settled && <label className="cc-field">How are the dates in this file written?
              <select value={order} onChange={(e) => setOrder(e.target.value)} aria-label="Date order"><option value="">Choose…</option><option value="dmy">{CCIntl.dateOrderText("dmy")}</option><option value="mdy">{CCIntl.dateOrderText("mdy")}</option></select>
              <span className="cc-hint">Dates like 4/5/2026 could be 4 May or 5 April, so we ask rather than guess. The preview below shows how they will be read.</span></label>}
            {settled && <p className="cc-muted sm">Dates in this file are {CCIntl.dateOrderText(settled).split(" (")[0]} (the file shows it).</p>}
            <p className="cc-muted sm">{body.length} rows. First rows as they will be imported:</p>
            <ul className="cc-muted sm">{body.slice(0, 4).map((r, i) => <li key={i}>{[r.name || (r.firstName + " " + r.lastName).trim(), r.email, r.type, r.joinedAt && "joined " + readDate(r.joinedAt), r.renewDue && "renews " + readDate(r.renewDue), r.dob && "born " + readDate(r.dob)].filter(Boolean).join(", ") || "(empty)"}</li>)}</ul>
          </div>}
        </div>}
        {err && <div className="cc-err" role="alert">{err}</div>}
      </Modal>
    );
  }

  /* ---------- mailing consent on one member ---------- */
  function Mailing({ clubId, m, lists, onChanged }) {
    const [how, setHow] = React.useState({}), [busy, setBusy] = React.useState(false), [err, setErr] = React.useState(null), [ask, setAsk] = React.useState(false);
    async function patch(body) {
      setBusy(true); setErr(null);
      try { await call(clubId, "PATCH", "/club/register/" + m.id, body); setAsk(false); await onChanged(); } catch (e) { setErr(e.message); }
      setBusy(false);
    }
    if (!lists.length) return null;
    return (
      <div className="lists" style={{ marginTop: 12 }}>
        <b>Mailing lists</b>
        {m.unsubAt && <div className="cc-note trial">Unsubscribed {fmtWhen(m.unsubAt)}. They stay off every list until you clear this. <button className="cc-link" disabled={busy} onClick={() => patch({ unsubscribed: false })}>Clear</button></div>}
        {lists.map((l) => {
          const x = m.mailing[l];
          return <div key={l} style={{ margin: "6px 0" }}>
            {x ? <div><span className="cc-ex-list">{l}</span> <span className="cc-muted sm">agreed {fmtWhen(x.at)}: {x.how}</span> <button className="cc-link" disabled={busy} onClick={() => patch({ mailing: { [l]: { on: false } } })}>Remove</button></div>
              : !m.unsubAt && <div className="cc-row" style={{ gap: 6, flexWrap: "wrap" }}><span className="cc-muted sm">{l}:</span>
                <input aria-label={"How they agreed to " + l} placeholder="How they agreed (for example, ticked the box on the join form)" value={how[l] || ""} onChange={(e) => setHow({ ...how, [l]: e.target.value })} style={{ flex: "1 1 200px" }} />
                <button className="cc-btn sm" disabled={busy || !(how[l] || "").trim()} onClick={() => patch({ mailing: { [l]: { on: true, how: how[l] } } })}>Add</button></div>}
          </div>;
        })}
        {!m.unsubAt && (ask ? <span className="cc-muted sm">Mark {m.name} as unsubscribed from every list? <button className="cc-link" disabled={busy} onClick={() => patch({ unsubscribed: true })}>Yes, unsubscribe</button> <button className="cc-link" onClick={() => setAsk(false)}>No</button></span>
          : <button className="cc-link" onClick={() => setAsk(true)}>They asked to unsubscribe</button>)}
        {err && <div className="cc-err" role="alert">{err}</div>}
      </div>
    );
  }

  /* ---------- one member: details, fees, history ---------- */
  function Drawer({ clubId, m, data, reload, rev, onClose, openModal }) {
    const [d, setD] = React.useState(null), [err, setErr] = React.useState(null), [busy, setBusy] = React.useState(false), [ask, setAsk] = React.useState(false), [link, setLink] = React.useState("");
    const load = React.useCallback(() => call(clubId, "GET", "/club/register/" + m.id).then((r) => { setD(r); setErr(null); }).catch((e) => setErr(e.message)), [clubId, m.id]);
    React.useEffect(() => { setAsk(false); load(); }, [load, rev]);
    React.useEffect(() => { setD(null); }, [m.id]);
    const after = async () => { await load(); await reload(); };
    const act = async (fn) => { setBusy(true); setErr(null); try { await fn(); await after(); } catch (e) { setErr(e.message); } setBusy(false); };
    const type = data.types.find((t) => t.id === m.typeId);
    const household = data.households.find((h) => h.id === m.householdId);
    const fieldDefs = data.settings.fields || [];
    const canRenew = m.status === "active" && type && (type.period === "annual" || type.period === "fixed");
    return (
      <aside className="cc-ex-drawer" aria-label={"Details for " + m.name}>
        <button className="cc-x" aria-label="Close" onClick={onClose}>×</button>
        <div className="who big"><Avatar name={m.name} size={48} /><div><h3>{m.name}</h3><StatusPill s={m.shown} /> <span className="cc-muted sm">{m.typeName}</span></div></div>
        <dl>
          {m.memberNo && <div><dt>Member number</dt><dd>{m.memberNo}</dd></div>}
          <div><dt>Email</dt><dd>{m.email ? <a href={"mailto:" + m.email}>{m.email}</a> : <span className="cc-muted">Not set</span>}</dd></div>
          <div><dt>Phone</dt><dd>{m.phone || <span className="cc-muted">Not set</span>}{m.phone && m.hidePhone && <span className="cc-pill quiet" style={{ marginLeft: 6 }}>Hidden</span>}</dd></div>
          {m.address && <div><dt>Address</dt><dd>{m.address}{m.hideAddress && <span className="cc-pill quiet" style={{ marginLeft: 6 }}>Hidden</span>}</dd></div>}
          {m.dob && <div><dt>Date of birth</dt><dd>{fmtDate(m.dob)}{m.hideDob && <span className="cc-pill quiet" style={{ marginLeft: 6 }}>Hidden</span>}</dd></div>}
          <div><dt>Joined</dt><dd>{fmtDate(m.joinedAt) || <span className="cc-muted">Not set</span>}</dd></div>
          {m.renewDue && <div><dt>Renewal due</dt><dd>{fmtDate(m.renewDue)}</dd></div>}
          {type && (type.period === "annual" || type.period === "fixed") && <div><dt>Pays</dt><dd>{PLAN_LABEL[m.payPlan]}: {money(m.feeAmount != null ? m.feeAmount : type.fee)} a year{m.feeAmount != null && " (their own amount)"}</dd></div>}
          {m.paidThrough && <div><dt>Paid through</dt><dd>{fmtDate(m.paidThrough)}</dd></div>}
          {m.leftAt && <div><dt>Left</dt><dd>{fmtDate(m.leftAt)}{m.leftReason ? ": " + m.leftReason : ""}</dd></div>}
          {household && <div><dt>Household</dt><dd>{household.name}</dd></div>}
          {fieldDefs.map((f) => { const v = (m.custom || {})[f.id]; return <div key={f.id} className="custom"><dt>{f.label}</dt><dd>{v === true ? "Yes" : v === false ? "No" : f.type === "date" && v ? fmtDate(v) : v || <span className="cc-muted">Not set</span>}</dd></div>; })}
          {m.notes && <div><dt>Notes</dt><dd style={{ whiteSpace: "pre-wrap" }}>{m.notes}</dd></div>}
        </dl>
        <div className="cc-row" style={{ gap: 8, margin: "8px 0", flexWrap: "wrap" }}>
          <button className="cc-btn sm primary" onClick={() => openModal({ kind: "form", m })}>Edit</button>
          {canRenew && <button className="cc-btn sm" onClick={() => openModal({ kind: "renew", m, type })}>Renew</button>}
        </div>
        {err && <div className="cc-err" role="alert">{err}</div>}
        <h4 style={{ margin: "14px 0 4px" }}>Fees</h4>
        {!d ? <p className="cc-muted sm">Loading…</p> : d.fees.length === 0 ? <p className="cc-muted sm">No fees yet.</p> : (
          <table className="cc-ex-table"><tbody>{d.fees.map((f) => (
            <tr key={f.id}><td>{f.label}<br /><span className="cc-muted sm">{f.status === "paid" ? "Paid " + fmtDate(f.paidAt) + (f.method ? " by " + f.method : "") + (f.reference ? ", " + f.reference : "") : "Due " + fmtDate(f.dueDate)}</span></td>
              <td>{money(f.amount)}<br /><span className={"cc-pill " + (f.status === "paid" ? "ok" : f.status === "due" ? "warn" : "quiet")}>{f.status}</span></td>
              <td>{f.status === "due" && <><button className="cc-link" disabled={busy} onClick={() => openModal({ kind: "pay", m, fee: f })}>Paid</button> <button className="cc-link" disabled={busy} onClick={() => act(() => call(clubId, "POST", "/club/register/" + m.id + "/fees/" + f.id, { action: "waived" }))}>Waive</button></>}
                {f.status === "paid" && <button className="cc-link" disabled={busy} onClick={() => act(() => call(clubId, "POST", "/club/register/" + m.id + "/fees/" + f.id, { action: "refunded" }))}>Refund</button>}</td></tr>))}</tbody></table>)}
        <Mailing clubId={clubId} m={m} lists={data.settings.lists || []} onChanged={after} />
        {!m.userId && <div style={{ marginTop: 12 }}><b>Link to a login</b>
          <div className="cc-row" style={{ gap: 6, flexWrap: "wrap" }}><input aria-label="Login email" type="email" placeholder="Their Clubcraft login email" value={link} onChange={(e) => setLink(e.target.value)} style={{ flex: "1 1 200px" }} />
            <button className="cc-btn sm" disabled={busy || !link.trim()} onClick={() => act(async () => { await call(clubId, "POST", "/club/register/" + m.id + "/link-login", { email: link.trim() }); setLink(""); })}>Link</button></div></div>}
        <h4 style={{ margin: "14px 0 4px" }}>History</h4>
        {d && (d.history.length ? <ul className="cc-muted sm" style={{ paddingLeft: 18 }}>{d.history.map((h, i) => <li key={i}>{fmtWhen(h.at)}: {h.summary}{h.by ? " (" + h.by + ")" : ""}</li>)}</ul> : <p className="cc-muted sm">Nothing yet.</p>)}
        <div style={{ marginTop: 12 }}>
          {m.status === "archived" ? null : ask ? <span className="cc-muted sm">{m.status === "prospect" ? "Delete this prospect?" : "Archive " + m.name + "? They leave the register but their history and payments are kept."} <button className="cc-link" disabled={busy} onClick={() => act(async () => { await call(clubId, "DELETE", "/club/register/" + m.id); onClose(); })}>Yes</button> <button className="cc-link" onClick={() => setAsk(false)}>No</button></span>
            : <button className="cc-link" onClick={() => setAsk(true)}>{m.status === "prospect" ? "Delete prospect" : "Archive member"}</button>}
        </div>
      </aside>
    );
  }

  /* ---------- reports ---------- */
  function Bars({ rows, label }) {
    const max = Math.max(1, ...rows.map((r) => r.count));
    return <div className="cc-ex-bars" role="img" aria-label={label}>{rows.map((r) => <div className="row" key={r.month} style={{ gridTemplateColumns: "70px 1fr 28px" }}><span>{r.month.slice(2).replace("-", "/")}</span><span className="t"><i style={{ width: (100 * r.count / max) + "%" }} /></span><b>{r.count}</b></div>)}</div>;
  }
  function Reports({ clubId }) {
    const [r, setR] = React.useState(null), [err, setErr] = React.useState(null);
    React.useEffect(() => { call(clubId, "GET", "/club/register/report").then(setR).catch((e) => setErr(e.message)); }, [clubId]);
    if (!r) return err ? <div className="cc-err" role="alert">{err}</div> : <p className="cc-muted">Loading…</p>;
    return (
      <div>
        <div className="cc-ex-stats">
          <div className="cc-ex-stat"><span>Counting towards your price</span><b>{r.band}</b></div>
          <div className="cc-ex-stat warn"><span>Lapsed now</span><b>{r.lapsedNow}</b></div>
          <div className="cc-ex-stat"><span>Renewing in 30 days</span><b>{r.renewingSoon}</b></div>
          <div className="cc-ex-stat warn"><span>Unpaid fees</span><b>{money(r.unpaid.amount)}</b><small>{r.unpaid.count} fees</small></div>
        </div>
        <div className="cc-ex-cols" style={{ marginTop: 16 }}>
          <section className="cc-card"><h3>Members by type</h3><table className="cc-ex-table"><thead><tr><th>Type</th><th>Counting</th><th>Lapsed</th><th>Total</th></tr></thead>
            <tbody>{r.byType.map((t) => <tr key={t.typeId}><td>{t.name}</td><td>{t.counted}</td><td>{t.lapsed}</td><td>{t.total}</td></tr>)}{!r.byType.length && <tr><td colSpan="4" className="cc-muted">No types yet.</td></tr>}</tbody></table></section>
          <section className="cc-card"><h3>Unpaid fees by age</h3><table className="cc-ex-table"><thead><tr><th>Late by</th><th>Fees</th><th>Amount</th></tr></thead>
            <tbody>{r.unpaid.ageing.map((b) => <tr key={b.label}><td>{b.label}</td><td>{b.count}</td><td>{money(b.amount)}</td></tr>)}</tbody></table></section>
        </div>
        <div className="cc-ex-cols" style={{ marginTop: 16 }}>
          <section className="cc-card"><h3>Joined, last 12 months</h3><Bars rows={r.joins} label="Members who joined each month" /></section>
          <section className="cc-card"><h3>Left, last 12 months</h3><Bars rows={r.leaves} label="Members who left each month" /></section>
        </div>
        {r.unpaid.oldest.length > 0 && <section className="cc-card" style={{ marginTop: 16 }}><h3>Longest unpaid</h3><table className="cc-ex-table"><tbody>{r.unpaid.oldest.map((o, i) => <tr key={i}><td>{o.name}</td><td>{o.label}</td><td>{money(o.amount)}</td><td className="cc-muted">{o.daysLate ? o.daysLate + " days late" : "Not yet late"}</td></tr>)}</tbody></table></section>}
      </div>
    );
  }

  /* ---------- first visit: start the register ---------- */
  function StartPanel({ clubId, again, onDone }) {
    const [name, setName] = React.useState("Member"), [busy, setBusy] = React.useState(false), [err, setErr] = React.useState(null), [res, setRes] = React.useState(null);
    async function run() {
      setBusy(true); setErr(null);
      try { setRes(await call(clubId, "POST", "/club/register/start", again ? {} : { typeName: name })); onDone(); } catch (e) { setErr(e.message); }
      setBusy(false);
    }
    if (again) return <div className="cc-note">{res ? "Added " + res.added + " people from your logins." : <>Someone joined the club after the register was started? <button className="cc-link" disabled={busy} onClick={run}>Add people who are missing from the register</button></>}{err && <span className="cc-err"> {err}</span>}</div>;
    return (
      <section className="cc-card" style={{ marginBottom: 16 }}>
        <h3>Start your register</h3>
        <p>This makes a member for everyone who has a login, and moves the phone numbers, notes and mailing consent you already keep in Contacts across, so you never keep them twice. You can add types and fees, and import a spreadsheet of members who do not have a login, afterwards. Nobody is charged and nobody is emailed.</p>
        <label className="cc-field" style={{ maxWidth: 360 }}>Name for your first membership type (no fee until you set one)<input value={name} onChange={(e) => setName(e.target.value)} maxLength={60} /></label>
        {err && <div className="cc-err" role="alert">{err}</div>}
        <button className="cc-btn primary" disabled={busy || !name.trim()} onClick={run}>{busy ? "Starting…" : "Start the register"}</button>
      </section>
    );
  }

  const csvCell = (v) => { const s = String(v == null ? "" : v); return /[",\r\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; };
  function exportCsv(list) {
    const rows = [["Member number", "Name", "Email", "Phone", "Type", "Status", "Joined", "Renewal due"]].concat(list.map((m) => [m.memberNo, m.name, m.email, m.phone, m.typeName, (SHOWN[m.shown] || [m.shown])[0], m.joinedAt, m.renewDue]));
    const a = document.createElement("a"); a.href = URL.createObjectURL(new Blob([rows.map((r) => r.map(csvCell).join(",")).join("\r\n") + "\r\n"], { type: "text/csv" })); a.download = "members.csv"; a.click();
  }

  /* ---------- a member's own details, with what they share ---------- */
  function YourDetails({ clubId, mine, onChanged }) {
    const [busy, setBusy] = React.useState(false), [err, setErr] = React.useState(null);
    async function share(key, on) {
      setBusy(true); setErr(null);
      try { await call(clubId, "PATCH", "/club/register/me", { [key]: !on }); await onChanged(); } catch (e) { setErr(e.message); }
      setBusy(false);
    }
    const row = (label, value, key) => (
      <div key={label} style={{ display: "flex", gap: 10, margin: "4px 0", alignItems: "baseline", flexWrap: "wrap" }}>
        <b style={{ minWidth: 110 }}>{label}</b><span>{value || "Not set"}</span>
        {key && value && <label className="cc-muted sm"><input type="checkbox" disabled={busy} checked={!mine[key]} onChange={(e) => share(key, e.target.checked)} aria-label={"Share my " + label.toLowerCase() + " with other members"} /> Share with other members</label>}
      </div>);
    return (
      <section className="cc-card" style={{ marginBottom: 12 }}>
        <h3 style={{ marginTop: 0 }}>Your details</h3>
        <p className="cc-muted sm">Your phone, address and date of birth are hidden from other members until you choose to share them. Club admins and membership officers can always see them. To change anything else, ask them.</p>
        {row("Name", mine.name)}{row("Type", mine.typeName)}
        {row("Phone", mine.phone, "hidePhone")}{row("Address", mine.address, "hideAddress")}{row("Date of birth", mine.dob ? fmtDate(mine.dob) : "", "hideDob")}
        {mine.renewDue && row("Renewal due", fmtDate(mine.renewDue))}
        {err && <div className="cc-err" role="alert">{err}</div>}
      </section>
    );
  }

  /* ---------- the page ---------- */
  function MembersApp({ clubId, onGo }) {
    const [data, setData] = React.useState(null), [err, setErr] = React.useState(null);
    const [q, setQ] = React.useState(""), [filter, setFilter] = React.useState("counting"), [typeF, setTypeF] = React.useState(""), [sel, setSel] = React.useState(null), [view, setView] = React.useState("register"), [modal, setModal] = React.useState(null), [rev, setRev] = React.useState(0);
    const load = React.useCallback(() => call(clubId, "GET", "/club/register").then((r) => { setData(r); setErr(null); }).catch((e) => setErr(e.message)), [clubId]);
    React.useEffect(() => { load(); }, [load]);
    if (!data) return err ? <div className="cc-err" role="alert">{err}</div> : <p className="cc-muted">Loading…</p>;
    if (data.access === "none") return <div><div className="cc-note">The club has turned the member directory off. Ask a club admin or membership officer if you need someone's details.</div>{data.mine && <YourDetails clubId={clubId} mine={data.mine} onChanged={load} />}</div>;
    const match = (m) => !q || ((m.name || "") + " " + (m.email || "") + " " + (m.phone || "") + " " + (m.typeName || "")).toLowerCase().includes(q.toLowerCase());

    if (data.access === "directory") {
      const list = data.members.filter(match);
      return (
        <div>
          <div className="cc-note">The club's current members. You can see name, email and membership type, and the phone, address and birthday members have chosen to share (everyone starts with these hidden).</div>
          {data.mine && <YourDetails clubId={clubId} mine={data.mine} onChanged={load} />}
          <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 members" /></label></div>
          <div className="cc-table"><table className="cc-ex-table"><thead><tr><th>Name</th><th>Type</th><th>Phone</th>{list.some((x) => x.address) && <th>Address</th>}{list.some((x) => x.birthday) && <th>Birthday</th>}</tr></thead>
            <tbody>{list.map((m) => <tr key={m.id}><td><div className="who"><Avatar name={m.name} size={30} /><div><b>{m.name}</b><span>{m.email}</span></div></div></td><td>{m.typeName}</td><td className="cc-muted">{m.phone}</td>{list.some((x) => x.address) && <td className="cc-muted">{m.address}</td>}{list.some((x) => x.birthday) && <td className="cc-muted">{fmtBirthday(m.birthday)}</td>}</tr>)}{!list.length && <tr><td colSpan="5" className="cc-muted">No members match.</td></tr>}</tbody></table></div>
        </div>
      );
    }

    const all = data.members;
    const f = FILTERS.find((x) => x[0] === filter);
    const list = all.filter((m) => f[2](m) && (!typeF || m.typeId === typeF) && match(m));
    const m = sel && all.find((x) => x.id === sel);
    const by = data.summary.byShown || {};
    const started = data.settings.started;
    const done = async (id) => { setModal(null); await load(); if (id) setSel(id); };
    return (
      <div>
        {err && <div className="cc-err" role="alert">{err}</div>}
        {!started && data.isAdmin && <StartPanel clubId={clubId} onDone={load} />}
        {!started && !data.isAdmin && <div className="cc-note">The register has not been started yet. A Members admin starts it.</div>}
        <div className="cc-ex-stats" style={{ marginBottom: 12 }}>
          <div className="cc-ex-stat good"><span>Counting towards your price</span><b>{data.summary.band}</b></div>
          <div className="cc-ex-stat"><span>Active</span><b>{(by.active || 0) + (by.life || 0) + (by.honorary || 0)}</b></div>
          <div className="cc-ex-stat warn"><span>In grace</span><b>{by.grace || 0}</b></div>
          <div className="cc-ex-stat warn"><span>Lapsed</span><b>{by.lapsed || 0}</b></div>
          <div className="cc-ex-stat"><span>Prospects</span><b>{by.prospect || 0}</b></div>
        </div>
        <div className="cc-ex-tools">
          <span className="cc-seg" role="group" aria-label="View">{[["register", "Register"], ["reports", "Reports"]].map(([k, l]) => <button key={k} className={view === k ? "on" : ""} onClick={() => setView(k)}>{l}</button>)}</span>
          {view === "register" && <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 members" /></label>}
          <button className="cc-btn primary" onClick={() => setModal({ kind: "form", m: {} })}>Add a member</button>
          {data.isAdmin && <button className="cc-btn" onClick={() => setModal({ kind: "import" })}>Import a spreadsheet</button>}
          {data.isAdmin && <button className="cc-btn" onClick={() => setModal({ kind: "types" })}>Types and fees</button>}
          {data.isAdmin && <button className="cc-btn" onClick={() => setModal({ kind: "settings" })}>Settings</button>}
          <button className="cc-btn" onClick={() => exportCsv(list)}>Download list</button>
        </div>
        {view === "reports" ? <Reports clubId={clubId} /> : <>
          <div className="cc-ex-tools" style={{ marginTop: 0 }}>
            <div className="cc-ex-chips tight">{FILTERS.map(([k, l, fn]) => <button key={k} className={filter === k ? "on" : ""} onClick={() => setFilter(k)}>{l}<small>{all.filter(fn).length}</small></button>)}</div>
            {data.types.length > 1 && <select aria-label="Membership type" value={typeF} onChange={(e) => setTypeF(e.target.value)}><option value="">All types</option>{data.types.filter((t) => t.active).map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}</select>}
          </div>
          <div className={"cc-ex-contacts" + (m ? " withdrawer" : "")}>
            <div className="cc-table"><table className="cc-ex-table clickable">
              <thead><tr><th>Name</th><th>Type</th><th>Status</th><th>Renewal due</th><th>Phone</th></tr></thead>
              <tbody>{list.map((x) => <tr key={x.id} className={sel === x.id ? "sel" : ""} onClick={() => setSel(sel === x.id ? null : x.id)} tabIndex="0" onKeyDown={(e) => { if (e.key === "Enter") setSel(x.id); }}>
                <td><div className="who"><Avatar name={x.name} size={30} /><div><b>{x.name}</b><span>{x.memberNo ? "#" + x.memberNo + " " : ""}{x.email}</span></div></div></td>
                <td>{x.typeName}</td><td><StatusPill s={x.shown} /></td><td className="cc-muted">{fmtDate(x.renewDue)}</td><td className="cc-muted">{x.phone}</td></tr>)}
                {!list.length && <tr><td colSpan="5" className="cc-muted">{all.length ? "No members match." : "Nobody here yet. Start the register, add a member, or import a spreadsheet."}</td></tr>}</tbody>
            </table></div>
            {m && <Drawer clubId={clubId} m={m} data={data} reload={load} rev={rev} onClose={() => setSel(null)} openModal={setModal} />}
          </div>
          {data.isAdmin && data.imports.length > 0 && data.imports[0].canUndo && <div className="cc-note" style={{ marginTop: 12 }}>Last import: {data.imports[0].rowsAdded} people on {fmtWhen(data.imports[0].at)}. <button className="cc-link" onClick={async () => { try { await call(clubId, "POST", "/club/register/import/" + data.imports[0].batch + "/undo", {}); await load(); } catch (e) { setErr(e.message); } }}>Undo this import</button> (people you have edited since are kept).</div>}
          {started && data.isAdmin && <div style={{ marginTop: 12 }}><StartPanel clubId={clubId} again onDone={load} /></div>}
        </>}
        {modal && modal.kind === "form" && <MemberForm clubId={clubId} m={modal.m} data={data} onClose={() => setModal(null)} onSaved={done} />}
        {modal && modal.kind === "pay" && <PayModal clubId={clubId} m={modal.m} fee={modal.fee} onClose={() => setModal(null)} onDone={async () => { setModal(null); await load(); setRev((r) => r + 1); }} />}
        {modal && modal.kind === "renew" && <RenewModal clubId={clubId} m={modal.m} type={modal.type} onClose={() => setModal(null)} onDone={async () => { setModal(null); await load(); setRev((r) => r + 1); }} />}
        {modal && modal.kind === "types" && <TypesModal clubId={clubId} types={data.types} onClose={() => setModal(null)} onSaved={() => done()} />}
        {modal && modal.kind === "settings" && <SettingsModal clubId={clubId} settings={data.settings} onClose={() => setModal(null)} onSaved={() => done()} />}
        {modal && modal.kind === "import" && <ImportModal clubId={clubId} data={data} onClose={() => setModal(null)} onDone={() => done()} />}
      </div>
    );
  }

  window.CCMembers = MembersApp;
})();
