/* access.jsx: the Access page (docs/access-and-permissions.md). Version 1.0, 2026-11-04 17:00.
 * One place to see and change who can do what in every app. Every member has Admin, Edit or View (or no access) in each app; club admins are Admin
 * everywhere. Styled on the Zoho One Directory: a list, and a side drawer for the app or person you click. Four views: By app, By user, Everyone
 * (a grid of every person and every app) and Defaults (what new members start with). The rules are enforced by cc_api (routes/access.js).
 * Exposes window.CCAccess; shell.jsx mounts it on the Access tab for club admins.
 */
(function () {
  const API = window.ClubcraftApi;
  const call = (clubId, method, path, body) => API.call(method, path, body, { club: clubId });
  const LEVEL = { admin: ["Admin", "ok"], edit: ["Edit", "ok"], view: ["View", "quiet"], none: ["No access", "bad"] };
  const lv = (l) => LEVEL[l || "none"];
  const Pill = ({ level }) => <span className={"cc-pill " + lv(level)[1]}>{lv(level)[0]}</span>;
  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 seen = (ms) => (ms ? new Date(ms).toLocaleDateString(CCIntl.locale(), { day: "numeric", month: "short", year: "numeric" }) : "Not yet");
  // What each level means in each app (the table in docs/access-and-permissions.md).
  const MEANS = {
    Tasks: ["See the projects they can open", "Create and change tasks in their projects", "Create, delete and share projects, and manage who is in them"],
    Social: ["See campaigns and posts", "Write posts, and approve them where their campaign role allows", "Create campaigns, connect Facebook and Instagram, set the brand kit, approve campaigns"],
    Calendar: ["See the calendar and keep personal entries", "Add and move the club's entries", "Set the club time zone, reminder defaults and calendar links"],
    Contacts: ["See members' name, email and phone and their own added contacts", "See and manage everyone's contacts and mailing consent", "Set the custom fields and mailing lists, and import"],
    Members: ["See the directory (name, email and what members share)", "Add and edit members, fees and renewals, and see reports", "Types and fees, import, start the register, and the register settings"],
    Review: ["Read the club's Reviews", "Run and edit a Review (uses the AI allowance)", "As Edit, and decide who else can run Reviews"],
    Ideas: ["Read the club's Ideas", "Generate and shortlist ideas (uses the AI allowance)", "As Edit, and decide who else can run Ideas"],
    Events: ["Read event plans", "Run and edit event plans (uses the AI allowance)", "As Edit, and decide who else can plan events"],
    Comms: ["Read marketing plans", "Run and edit marketing plans (uses the AI allowance)", "As Edit, and decide who else can run Comms"],
    Finances: ["Read the club's finances", "Enter and change finances", "Link Zoho Books and set up the accounts"]
  };
  const means = (mod, level) => (MEANS[mod] || [])[["view", "edit", "admin"].indexOf(level)] || "";
  const defaultOf = (data, mod) => data.defaults[mod] || data.builtIn[mod] || "view";

  /* ---------- one level picker: used in the drawers and the grid ---------- */
  function Picker({ person, mod, data, onChange, busy, compact }) {
    const cur = person.access[mod], locked = person.isAdmin || !!cur.outside;
    const label = person.name + " in " + mod;
    return (
      <select aria-label={label} title={cur.level ? lv(cur.level)[0] + " (" + cur.source + ")" : "No access (" + cur.source + ")"} disabled={locked || busy} value={locked ? "admin" : cur.set || "default"} onChange={(e) => onChange(e.target.value)} style={compact ? { maxWidth: 108, fontSize: 13 } : undefined}>
        {locked ? <option value="admin">{cur.readOnlyUntil ? "Read-only (plan change)" : cur.outside ? "Not in your bundle" : "Admin (club admin)"}</option> : <>
          <option value="default">Default ({lv(defaultOf(data, mod))[0]})</option>
          <option value="view">View</option>
          <option value="edit" disabled={person.isGuest}>Edit</option>
          <option value="admin" disabled={person.isGuest}>Admin</option>
          <option value="none">No access</option></>}
      </select>
    );
  }

  /* ---------- By app ---------- */
  function ByApp({ data, busy, setApp, q }) {
    const [sel, setSel] = React.useState(null), [flt, setFlt] = React.useState("all"), [ticked, setTicked] = React.useState({}), [bulk, setBulk] = React.useState("view");
    const rows = data.apps.filter((m) => !q || m.toLowerCase().includes(q.toLowerCase()));
    const people = sel ? data.people.filter((p) => flt === "all" || (p.access[sel].level || "none") === flt) : [];
    const chosen = Object.keys(ticked).filter((k) => ticked[k] && data.people.find((p) => p.userId === k && !p.isAdmin));
    return (
      <div className={"cc-ex-contacts" + (sel ? " withdrawer" : "")}>
        <div className="cc-table"><table className="cc-ex-table clickable">
          <thead><tr><th>App</th><th>Admin</th><th>Edit</th><th>View</th><th>No access</th></tr></thead>
          <tbody>{rows.map((m) => { const c = data.counts[m]; return (
            <tr key={m} className={sel === m ? "sel" : ""} onClick={() => { setSel(sel === m ? null : m); setTicked({}); setFlt("all"); }} tabIndex="0" onKeyDown={(e) => { if (e.key === "Enter") setSel(m); }}>
              <td><b>{m}</b></td><td>{c.admin}</td><td>{c.edit}</td><td>{c.view}</td><td className={c.none ? "" : "cc-muted"}>{c.none}</td></tr>); })}
            {!rows.length && <tr><td colSpan="5" className="cc-muted">No apps match.</td></tr>}</tbody>
        </table></div>
        {sel && <aside className="cc-ex-drawer" aria-label={"Who has access to " + sel}>
          <button className="cc-x" aria-label="Close" onClick={() => setSel(null)}>×</button>
          <h3 style={{ margin: "0 0 4px" }}>{sel}</h3>
          <p className="cc-muted sm" style={{ margin: "0 0 8px" }}><b>View:</b> {means(sel, "view")}. <b>Edit:</b> {means(sel, "edit")}. <b>Admin:</b> {means(sel, "admin")}.</p>
          <div className="cc-ex-chips tight" role="group" aria-label="Show">{[["all", "All"], ["admin", "Admin"], ["edit", "Edit"], ["view", "View"], ["none", "No access"]].map(([k, l]) => <button key={k} className={flt === k ? "on" : ""} onClick={() => setFlt(k)}>{l}<small>{k === "all" ? data.people.length : data.counts[sel][k]}</small></button>)}</div>
          {chosen.length > 0 && <div className="cc-row" style={{ gap: 6, margin: "8px 0", flexWrap: "wrap" }}>
            <span className="cc-muted sm">{chosen.length} selected:</span>
            <select aria-label="Set selected people to" value={bulk} onChange={(e) => setBulk(e.target.value)}><option value="view">View</option><option value="edit">Edit</option><option value="admin">Admin</option><option value="none">No access</option><option value="default">The default</option></select>
            <button className="cc-btn sm primary" disabled={busy} onClick={async () => { await setApp(sel, Object.fromEntries(chosen.map((k) => [k, bulk]))); setTicked({}); }}>Apply</button></div>}
          <div style={{ marginTop: 8 }}>{people.map((p) => (
            <div key={p.userId} className="cc-row" style={{ gap: 8, alignItems: "center", padding: "6px 0", borderTop: "1px solid var(--b-line)", flexWrap: "wrap" }}>
              <input type="checkbox" disabled={p.isAdmin} checked={!!ticked[p.userId]} onChange={(e) => setTicked({ ...ticked, [p.userId]: e.target.checked })} aria-label={"Select " + p.name} />
              <Avatar name={p.name} size={30} />
              <div style={{ flex: "1 1 120px", minWidth: 0 }}><b>{p.name}</b>{p.isGuest && <span className="cc-pill quiet" style={{ marginLeft: 6 }}>Guest</span>}<br /><span className="cc-muted sm">{p.email}</span></div>
              <Pill level={p.access[sel].level} />
              <Picker person={p} mod={sel} data={data} busy={busy} onChange={(l) => setApp(sel, { [p.userId]: l })} />
            </div>))}
            {!people.length && <p className="cc-muted sm">Nobody here.</p>}</div>
        </aside>}
      </div>
    );
  }

  /* ---------- By user ---------- */
  function ByUser({ data, busy, setUser, q }) {
    const [sel, setSel] = React.useState(null);
    const list = data.people.filter((p) => !q || (p.name + " " + p.email).toLowerCase().includes(q.toLowerCase()));
    const p = sel && data.people.find((x) => x.userId === sel);
    const count = (x) => data.apps.filter((m) => x.access[m].level).length;
    return (
      <div className={"cc-ex-contacts" + (p ? " withdrawer" : "")}>
        <div className="cc-table"><table className="cc-ex-table clickable">
          <thead><tr><th>Name / email</th><th>Apps</th><th>Role</th><th>Last seen</th></tr></thead>
          <tbody>{list.map((x) => (
            <tr key={x.userId} className={sel === x.userId ? "sel" : ""} onClick={() => setSel(sel === x.userId ? null : x.userId)} tabIndex="0" onKeyDown={(e) => { if (e.key === "Enter") setSel(x.userId); }}>
              <td><div className="who"><Avatar name={x.name} size={30} /><div><b>{x.name}</b><span>{x.email}</span></div></div></td>
              <td>{count(x)} of {data.apps.length}</td><td>{x.isAdmin ? <span className="cc-pill ok">Club admin</span> : x.isGuest ? <span className="cc-pill quiet">Guest</span> : <span className="cc-muted">Member</span>}</td>
              <td className="cc-muted">{seen(x.lastSeenAt)}</td></tr>))}
            {!list.length && <tr><td colSpan="4" className="cc-muted">Nobody matches.</td></tr>}</tbody>
        </table></div>
        {p && <aside className="cc-ex-drawer" aria-label={"Access for " + p.name}>
          <button className="cc-x" aria-label="Close" onClick={() => setSel(null)}>×</button>
          <div className="who big"><Avatar name={p.name} size={48} /><div><h3>{p.name}</h3><span className="cc-muted sm">{p.email}</span><br />{p.isAdmin && <span className="cc-pill ok">Club admin</span>}{p.isGuest && <span className="cc-pill quiet">Guest: view only</span>}</div></div>
          {p.isAdmin && <p className="cc-muted sm">A club admin is Admin in every app. To change that, remove their club admin role under Plan, people and settings.</p>}
          {p.isGuest && <p className="cc-muted sm">Guests can only view.</p>}
          <h4 style={{ margin: "12px 0 6px" }}>Apps</h4>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(190px, 1fr))", gap: 8 }}>
            {data.apps.map((m) => { const c = p.access[m]; return (
              <div key={m} className="cc-card" style={{ padding: 10, opacity: c.level ? 1 : 0.7 }}>
                <b>{m}</b> <Pill level={c.level} /><br />
                <span className="cc-muted sm">{c.readOnlyUntil ? m + " is no longer in your plan: read-only until " + new Date(c.readOnlyUntil).toLocaleDateString(CCIntl.locale(), { day: "numeric", month: "short", year: "numeric" }) : c.outside ? m + " is not in your club's bundle" : c.level ? means(m, c.level) : "Cannot open " + m}{c.source === "set" || c.outside ? "" : ". " + (c.source === "club admin" ? "Club admin" : "Default")}</span>
                <div style={{ marginTop: 6 }}><Picker person={p} mod={m} data={data} busy={busy} onChange={(l) => setUser(p.userId, m, l)} /></div>
              </div>); })}
          </div>
        </aside>}
      </div>
    );
  }

  /* ---------- Everyone: the grid ---------- */
  function Grid({ data, busy, setUser, q }) {
    const list = data.people.filter((p) => !q || (p.name + " " + p.email).toLowerCase().includes(q.toLowerCase()));
    return (
      <div className="cc-table" style={{ overflowX: "auto" }}>
        <table className="cc-ex-table">
          <thead><tr><th style={{ minWidth: 150 }}>Person</th>{data.apps.map((m) => <th key={m} style={{ whiteSpace: "nowrap" }}>{m}</th>)}</tr></thead>
          <tbody>{list.map((p) => (
            <tr key={p.userId}><td><b>{p.name}</b>{p.isAdmin && <span className="cc-pill ok" style={{ marginLeft: 6 }}>Admin</span>}{p.isGuest && <span className="cc-pill quiet" style={{ marginLeft: 6 }}>Guest</span>}</td>
              {data.apps.map((m) => <td key={m}><Picker compact person={p} mod={m} data={data} busy={busy} onChange={(l) => setUser(p.userId, m, l)} /></td>)}</tr>))}
            {!list.length && <tr><td colSpan={data.apps.length + 1} className="cc-muted">Nobody matches.</td></tr>}</tbody>
        </table>
      </div>
    );
  }

  /* ---------- Defaults ---------- */
  function Defaults({ data, busy, setDefault }) {
    return (
      <div>
        <p className="cc-muted">What a member gets in each app until you set something for them. Their own setting always wins, club admins are Admin everywhere, and guests are view only. A default is never Admin.</p>
        <div className="cc-table"><table className="cc-ex-table">
          <thead><tr><th>App</th><th>Built in</th><th>Your default</th><th>What a new member can do</th></tr></thead>
          <tbody>{data.apps.map((m) => { const eff = defaultOf(data, m); return (
            <tr key={m}><td><b>{m}</b></td><td className="cc-muted">{lv(data.builtIn[m] || "view")[0]}</td>
              <td><select aria-label={"Default for " + m} disabled={busy} value={data.defaults[m] || "builtin"} onChange={(e) => setDefault(m, e.target.value === "builtin" ? "default" : e.target.value)}>
                <option value="builtin">Built in ({lv(data.builtIn[m] || "view")[0]})</option><option value="view">View</option><option value="edit">Edit</option><option value="none">No access</option></select></td>
              <td className="cc-muted">{eff === "none" ? "Cannot open it" : means(m, eff)}</td></tr>); })}</tbody>
        </table></div>
        <p className="cc-muted sm" style={{ marginTop: 8 }}>Contacts at Edit means every member sees everyone's contacts and mailing consent. Set Contacts to View if you would rather keep that to the people you choose.</p>
      </div>
    );
  }

  /* ---------- the page ---------- */
  function AccessPage({ clubId, onChanged, onGo }) {
    const [data, setData] = React.useState(null), [err, setErr] = React.useState(null), [busy, setBusy] = React.useState(false);
    const [view, setView] = React.useState("app"), [q, setQ] = React.useState("");
    React.useEffect(() => { call(clubId, "GET", "/club/access").then((r) => { setData(r); setErr(null); }).catch((e) => setErr(e.message)); }, [clubId]);
    if (!data) return <div className="cc-page"><div className="cc-wrap">{err ? <div className="cc-err" role="alert">{err}</div> : <p className="cc-muted">Loading…</p>}</div></div>;
    const apply = async (fn) => { setBusy(true); setErr(null); try { setData(await fn()); if (onChanged) onChanged(); } catch (e) { setErr(e.message); } setBusy(false); };
    const setUser = (uid, mod, level) => apply(() => call(clubId, "PUT", "/club/access/user/" + uid, { levels: { [mod]: level } }));
    const setApp = (mod, levels) => apply(() => call(clubId, "PUT", "/club/access/app/" + mod, { levels }));
    const setDefault = (mod, level) => apply(() => call(clubId, "PUT", "/club/access/defaults", { levels: { [mod]: level } }));
    const VIEWS = [["app", "By app"], ["user", "By user"], ["grid", "Everyone"], ["defaults", "Defaults"]];
    return (
      <div className="cc-page"><div className="cc-wrap wide">
        <div className="cc-pagehead"><div><div className="cc-label">Club admin</div><h1>Access</h1>
          <p className="cc-muted">Who can do what in each app. Everyone has Admin, Edit or View in every app, and you can switch an app off for someone. Club admins are Admin everywhere.</p></div></div>
        {err && <div className="cc-err" role="alert">{err}</div>}
        {data.trialExpired && <div className="cc-note trial">The free trial has ended, so everyone is view only until a plan is chosen.</div>}
        <div className="cc-ex-tools">
          <span className="cc-seg" role="group" aria-label="View">{VIEWS.map(([k, l]) => <button key={k} className={view === k ? "on" : ""} onClick={() => setView(k)}>{l}</button>)}</span>
          {view !== "defaults" && <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={view === "app" ? "Search apps" : "Search people"} aria-label="Search" /></label>}
          {onGo && <button className="cc-btn" onClick={() => onGo("admin")}>Plan, people and settings</button>}
        </div>
        {view === "app" && <ByApp data={data} busy={busy} setApp={setApp} q={q} />}
        {view === "user" && <ByUser data={data} busy={busy} setUser={setUser} q={q} />}
        {view === "grid" && <Grid data={data} busy={busy} setUser={setUser} q={q} />}
        {view === "defaults" && <Defaults data={data} busy={busy} setDefault={setDefault} />}
      </div></div>
    );
  }

  window.CCAccess = AccessPage;
})();
