/* contacts.jsx: the real Contacts module (free with every plan).
 * The club's address book. Every active club member appears automatically (name and email come from their Clubcraft profile); club admins
 * and people with Edit access also add sponsors, suppliers, speakers and the like, record mailing consent, import a spreadsheet and define custom
 * fields. Any other member sees the members (name, email, phone) and the contacts they added themselves, and can add their own.
 * All rules are enforced by cc_api (routes/contacts.js); this file only draws what it is given.
 * Exposes window.CCContacts; shell.jsx mounts it on the Contacts page when not in demo mode.
 */
(function () {
  const API = window.ClubcraftApi;
  const TYPE_LABEL = { text: "Text", date: "Date", year: "Year", pick: "Pick-list", yesno: "Yes or no" };
  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 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>;

  /* ---------- a small CSV reader (quotes, commas and line breaks inside quotes) ---------- */
  function parseCsv(text) {
    const rows = []; let row = [], cell = "", q = false;
    for (let i = 0; i < text.length; i++) {
      const ch = text[i];
      if (q) { if (ch === '"') { if (text[i + 1] === '"') { cell += '"'; i++; } else q = false; } else cell += ch; }
      else if (ch === '"') q = true;
      else if (ch === ",") { row.push(cell); cell = ""; }
      else if (ch === "\n" || ch === "\r") { if (ch === "\r" && text[i + 1] === "\n") i++; row.push(cell); rows.push(row); row = []; cell = ""; }
      else cell += ch;
    }
    if (cell || row.length) { row.push(cell); rows.push(row); }
    return rows.filter((r) => r.some((c) => c.trim()));
  }
  window.CCParseCsv = parseCsv;           // the Members import reads CSV the same way
  const IMPORT_FIELDS = [["name", "Name", /name/i], ["email", "Email", /e-?mail/i], ["phone", "Phone", /phone|mobile|cell/i], ["address", "Address", /address|street/i], ["relationship", "Relationship", /relationship|type|category/i], ["notes", "Notes", /notes?|comment/i]];

  /* ---------- add / edit one contact ---------- */
  function ContactForm({ clubId, c, editor, fields, rels: allRels, onClose, onSaved }) {
    const [f, setF] = React.useState(() => ({ name: c.name || "", email: c.email || "", phone: c.phone || "", address: c.address || "", relationship: c.relationship || "Other", notes: c.notes || "", lastContact: c.lastContact || "", custom: { ...(c.custom || {}) } }));
    const [busy, setBusy] = React.useState(false), [err, setErr] = React.useState(null);
    const set = (k, v) => setF((x) => ({ ...x, [k]: v }));
    const isNew = !c.id, linked = !!c.linked;
    const rels = allRels.filter((r) => r !== "Past member" || c.memberState === "past");
    async function save() {
      setBusy(true); setErr(null);
      const body = { phone: f.phone, address: f.address, relationship: f.relationship, notes: f.notes, lastContact: f.lastContact };
      if (!linked) { body.name = f.name; body.email = f.email; }
      if (editor) body.custom = f.custom;
      try { const r = await API.call(isNew ? "POST" : "PATCH", "/club/contacts" + (isNew ? "" : "/" + c.id), body, { club: clubId }); onSaved(r.contact.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>;
    return (
      <div className="cc-modal-bg" role="dialog" aria-modal="true" aria-label={isNew ? "Add a contact" : "Edit contact"} onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
        <div className="cc-modal">
          <div className="cc-modal-h"><h2>{isNew ? "Add a contact" : "Edit " + (c.name || "contact")}</h2><button className="cc-btn sm" onClick={onClose} aria-label="Close">✕</button></div>
          <div className="cc-modal-b">
            {isNew && !editor && <div className="cc-note">Only you and the club's admins and people with Edit access to Contacts will see this contact.</div>}
            {linked && <div className="cc-note trial">Name and email come from this member's Clubcraft profile, so they are changed there.</div>}
            {!linked && input("name", "Name", { autoFocus: true })}
            <div className="cc-grid2">
              {!linked && input("email", "Email (optional)", { type: "email" })}
              {input("phone", "Phone (optional)", { type: "tel" })}
            </div>
            {input("address", "Address (optional)")}
            <div className="cc-grid2">
              <label className="cc-field">How they are connected<select value={f.relationship} onChange={(e) => set("relationship", e.target.value)}>{rels.map((r) => <option key={r}>{r}</option>)}</select></label>
              <label className="cc-field">Last contact (optional)<input type="date" value={f.lastContact} onChange={(e) => set("lastContact", e.target.value)} /></label>
            </div>
            {editor && 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)<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>}
          </div>
          <div className="cc-modal-f"><span /><div className="cc-row"><button className="cc-btn ghost" onClick={onClose}>Cancel</button><button className="cc-btn primary" disabled={busy || (!linked && !f.name.trim())} onClick={save}>{busy ? "Saving…" : "Save"}</button></div></div>
        </div>
      </div>
    );
  }

  /* ---------- import a spreadsheet (CSV) ---------- */
  function ImportModal({ clubId, onClose, onDone }) {
    const [table, setTable] = React.useState(null);       // rows of cells, first row = headers
    const [map, setMap] = React.useState({});             // target field -> column index
    const [busy, setBusy] = React.useState(false), [err, setErr] = React.useState(null), [result, setResult] = React.useState(null);
    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)); if (i >= 0) 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() : ""]))) : [];
    async function run() {
      setBusy(true); setErr(null);
      let added = 0, skipped = 0; const notes = [];
      try {
        for (let i = 0; i < body.length; i += 500) {
          const r = await API.call("POST", "/club/contacts/import", { rows: body.slice(i, i + 500) }, { club: clubId });
          added += r.added; skipped += r.skippedCount; r.skipped.forEach((s) => notes.push("Row " + (i + s.line) + ": " + s.reason));
        }
        setResult({ added, skipped, notes: notes.slice(0, 20) });
      } catch (e) { setErr(e.message); }
      setBusy(false);
    }
    return (
      <div className="cc-modal-bg" role="dialog" aria-modal="true" aria-label="Import contacts" onMouseDown={(e) => { if (e.target === e.currentTarget) (result ? onDone : onClose)(); }}>
        <div className="cc-modal">
          <div className="cc-modal-h"><h2>Import contacts</h2><button className="cc-btn sm" onClick={result ? onDone : onClose} aria-label="Close">✕</button></div>
          <div className="cc-modal-b">
            {result ? <div>
              <div className="cc-note trial" role="status">Added {result.added} contacts.{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. Record how each person agreed from their details.</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. People already in your contacts (same email) 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 }}>
                <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>
                <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.email, r.phone, r.relationship].filter(Boolean).join(", ") || "(empty)"}</li>)}</ul>
              </div>}
            </div>}
            {err && <div className="cc-err" role="alert">{err}</div>}
          </div>
          <div className="cc-modal-f"><span /><div className="cc-row">
            {result ? <button className="cc-btn primary" onClick={onDone}>Done</button> : <><button className="cc-btn ghost" onClick={onClose}>Cancel</button><button className="cc-btn primary" disabled={busy || !table || (map.name == null && map.email == null)} onClick={run}>{busy ? "Importing…" : "Import " + body.length + " rows"}</button></>}
          </div></div>
        </div>
      </div>
    );
  }

  /* ---------- the club's custom fields and mailing lists (admins) ---------- */
  function SettingsModal({ clubId, fields, lists, onClose, onSaved }) {
    const [fs, setFs] = React.useState(() => fields.map((f) => ({ ...f, options: (f.options || []).join(", ") })));
    const [ls, setLs] = React.useState(lists.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 API.call("PUT", "/club/contacts/settings", { 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 })), lists: ls.split(",").map((l) => l.trim()).filter(Boolean) }, { club: clubId });
        onSaved();
      } catch (e) { setErr(e.message); setBusy(false); }
    }
    return (
      <div className="cc-modal-bg" role="dialog" aria-modal="true" aria-label="Contact fields and lists" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
        <div className="cc-modal">
          <div className="cc-modal-h"><h2>Fields and mailing lists</h2><button className="cc-btn sm" onClick={onClose} aria-label="Close">✕</button></div>
          <div className="cc-modal-b">
            <h3 style={{ margin: "0 0 6px" }}>Your own fields</h3>
            <p className="cc-muted sm">Extra things you want to keep about people, such as birthday, skills, dietary needs or sponsor level. 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>}
            <h3 style={{ margin: "16px 0 6px" }}>Mailing lists</h3>
            <p className="cc-muted sm">Names of the lists you keep, separated by commas. Nobody is on a list until you record how they agreed.</p>
            <input aria-label="Mailing lists" value={ls} onChange={(e) => setLs(e.target.value)} style={{ width: "100%" }} />
            {err && <div className="cc-err" role="alert">{err}</div>}
          </div>
          <div className="cc-modal-f"><span /><div className="cc-row"><button className="cc-btn ghost" onClick={onClose}>Cancel</button><button className="cc-btn primary" disabled={busy} onClick={save}>{busy ? "Saving…" : "Save"}</button></div></div>
        </div>
      </div>
    );
  }

  /* ---------- mailing consent on one contact (editors) ---------- */
  function Mailing({ clubId, c, lists, onChanged }) {
    const [how, setHow] = React.useState({}), [busy, setBusy] = React.useState(false), [err, setErr] = React.useState(null);
    async function patch(body) {
      setBusy(true); setErr(null);
      try { await API.call("PATCH", "/club/contacts/" + c.id, body, { club: clubId }); onChanged(); } catch (e) { setErr(e.message); }
      setBusy(false);
    }
    if (!lists.length) return null;
    return (
      <div className="lists" style={{ marginTop: 12 }}>
        <b>Mailing lists</b>
        {c.unsubAt && <div className="cc-note trial">Unsubscribed {fmtWhen(c.unsubAt)}. They stay off every list until you clear this.
          <button className="cc-link" disabled={busy} onClick={() => patch({ unsubscribed: false })} style={{ marginLeft: 6 }}>Clear</button></div>}
        {lists.map((l) => {
          const m = c.mailing[l];
          return <div key={l} style={{ margin: "6px 0" }}>
            {m ? <div><span className="cc-ex-list">{l}</span> <span className="cc-muted sm">agreed {fmtWhen(m.at)}: {m.how}</span> <button className="cc-link" disabled={busy} onClick={() => patch({ mailing: { [l]: { on: false } } })}>Remove</button></div>
              : !c.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>;
        })}
        {!c.unsubAt && <button className="cc-link" disabled={busy} onClick={() => { if (window.confirm("Mark " + c.name + " as unsubscribed from every list?")) patch({ unsubscribed: true }); }}>They asked to unsubscribe</button>}
        {err && <div className="cc-err" role="alert">{err}</div>}
      </div>
    );
  }

  /* ---------- the page ---------- */
  function ContactsApp({ clubId, onGo }) {
    const [data, setData] = React.useState(null), [err, setErr] = React.useState(null);
    const [q, setQ] = React.useState(""), [rel, setRel] = React.useState("All"), [sel, setSel] = React.useState(null);
    const [modal, setModal] = React.useState(null);
    const load = React.useCallback(() => API.call("GET", "/club/contacts", null, { club: clubId }).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>;
    const editor = data.canEdit;
    const all = data.contacts;
    const rels = ["All", ...Array.from(new Set(all.map((c) => c.relationship)))];
    const list = all.filter((c) => (rel === "All" || c.relationship === rel) && (!q || (c.name + " " + c.email + " " + c.relationship + " " + (c.phone || "")).toLowerCase().includes(q.toLowerCase())));
    const c = sel && all.find((x) => x.id === sel);
    const canChange = (x) => (editor || x.mine) && !x.register;     // members of the Members register are changed in Members
    const exportList = async (l) => {
      try {
        const r = await API.call("GET", "/club/contacts/mailing?list=" + encodeURIComponent(l), null, { club: clubId });
        const a = document.createElement("a"); a.href = URL.createObjectURL(new Blob([r.csv], { type: "text/csv" })); a.download = "mailing-list-" + l.replace(/[^A-Za-z0-9]+/g, "-") + ".csv"; a.click();
      } catch (e) { setErr(e.message); }
    };
    const del = async (x) => {
      if (!window.confirm("Delete " + x.name + " from your contacts?")) return;
      try { await API.call("DELETE", "/club/contacts/" + x.id, null, { club: clubId }); setSel(null); await load(); } catch (e) { setErr(e.message); }
    };
    return (
      <div>
        {err && <div className="cc-err" role="alert">{err}</div>}
        {!editor && <div className="cc-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>}
        <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" ? all.length : all.filter((x) => x.relationship === r).length}</small></button>)}</div>
          <button className="cc-btn primary" onClick={() => setModal({ kind: "form", c: {} })}>Add a contact</button>
          {editor && <button className="cc-btn" onClick={() => setModal({ kind: "import" })}>Import a spreadsheet</button>}
          {data.isAdmin && <button className="cc-btn" onClick={() => setModal({ kind: "settings" })}>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>{editor && <th>Lists</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.email}</span></div></div></td>
              <td><span className={"cc-pill " + (x.relationship === "Member" ? "ok" : "quiet")}>{x.relationship}</span>{x.mine && !editor && <span className="cc-pill quiet" style={{ marginLeft: 4 }}>Added by you</span>}</td>
              <td className="cc-muted">{x.phone}</td>
              {editor && <td>{Object.keys(x.mailing || {}).length ? Object.keys(x.mailing).map((l) => <span key={l} className="cc-ex-list">{l}</span>) : <span className="cc-muted sm">None</span>}</td>}</tr>)}
              {!list.length && <tr><td colSpan={editor ? 4 : 3} className="cc-muted">{all.length ? "No contacts match." : "Nobody here yet. Add a contact, or import a spreadsheet."}</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"><Avatar name={c.name} size={48} /><div><h3>{c.name}</h3><span className={"cc-pill " + (c.relationship === "Member" ? "ok" : "quiet")}>{c.relationship}</span></div></div>
            <dl>
              <div><dt>Email</dt><dd>{c.email ? <a href={"mailto:" + c.email}>{c.email}</a> : <span className="cc-muted">Not set</span>}</dd></div>
              <div><dt>Phone</dt><dd>{c.phone || <span className="cc-muted">Not set</span>}</dd></div>
              {c.address !== undefined && <div><dt>Address</dt><dd>{c.address || <span className="cc-muted">Not set</span>}</dd></div>}
              {c.lastContact !== undefined && <div><dt>Last contact</dt><dd>{c.lastContact ? fmtDate(c.lastContact) : <span className="cc-muted">Not set</span>}</dd></div>}
              {editor && data.fields.map((d) => { const v = c.custom[d.id]; return <div key={d.id} className="custom"><dt>{d.label}</dt><dd>{v === true ? "Yes" : v === false ? "No" : d.type === "date" && v ? fmtDate(v) : v || <span className="cc-muted">Not set</span>}</dd></div>; })}
              {c.notes !== undefined && c.notes && <div><dt>Notes</dt><dd style={{ whiteSpace: "pre-wrap" }}>{c.notes}</dd></div>}
            </dl>
            {c.register ? <p className="cc-muted sm">A member in the Members register, so their details are kept and changed there. {onGo && <button className="cc-link" onClick={() => onGo("mod:Members")}>Open in Members</button>}</p>
              : c.linked && <p className="cc-muted sm">A club member. Their name and email come from their Clubcraft profile.</p>}
            {editor && !c.register && <Mailing clubId={clubId} c={c} lists={data.lists} onChanged={load} />}
            {editor && c.register && <p className="cc-muted sm">Mailing lists: {Object.keys(c.mailing || {}).length ? Object.keys(c.mailing).join(", ") : "none"}. Consent for members is recorded in Members.</p>}
            <div className="cc-row" style={{ gap: 8, marginTop: 12 }}>
              {canChange(c) && <button className="cc-btn sm primary" onClick={() => setModal({ kind: "form", c })}>Edit</button>}
              {canChange(c) && !c.linked && <button className="cc-btn sm ghost" onClick={() => del(c)}>Delete</button>}
            </div>
          </aside>}
        </div>
        {editor && data.lists.length > 0 && <div className="cc-note" style={{ marginTop: 12 }}>
          <b>Mailing list exports.</b> People who agreed to a list and have not unsubscribed, as a spreadsheet you can use in Comms or Zoho: {data.lists.map((l) => <button key={l} className="cc-btn sm" style={{ marginLeft: 6 }} onClick={() => exportList(l)}>{l}</button>)}
        </div>}
        {modal && modal.kind === "form" && <ContactForm clubId={clubId} c={modal.c} editor={editor} fields={data.fields} rels={data.relationships} onClose={() => setModal(null)} onSaved={async (id) => { setModal(null); await load(); setSel(id); }} />}
        {modal && modal.kind === "import" && <ImportModal clubId={clubId} onClose={() => setModal(null)} onDone={() => { setModal(null); load(); }} />}
        {modal && modal.kind === "settings" && <SettingsModal clubId={clubId} fields={data.fields} lists={data.lists} onClose={() => setModal(null)} onSaved={() => { setModal(null); load(); }} />}
      </div>
    );
  }

  window.CCContacts = ContactsApp;
})();
