/* modals.jsx — TaskModal (permission-aware), NameDialog, ConfirmDialog, AdminsDialog */
const { LABELS: LL, PRIORITIES, uid: uid2, usersByIds: u2, members: getMembers, projectMembers: getProjectMembers, labels: getLabels, LABEL_COLORS, remindSummary } = window.PlannerData;
const Icn = window.Icons;
const Av = window.Avatar;
const MPerms = window.Auth.Perms;

function Scrim({ onClose, children, small }) {
  return (
    <div className="scrim" onMouseDown={(e) => {
      if (e.target !== e.currentTarget) return;
      // .scrim itself scrolls when the modal is taller than the viewport, so its
      // native scrollbar sits inside this element (not a child) — a click on the
      // scrollbar reports target===currentTarget just like the empty backdrop.
      // clientWidth excludes the scrollbar gutter, offsetWidth includes it, so a
      // click past clientWidth is the scrollbar, not the backdrop.
      if (e.clientX - e.currentTarget.getBoundingClientRect().left > e.currentTarget.clientWidth) return;
      onClose();
    }}>
      <div className={"modal" + (small ? " sm" : "")} onMouseDown={(e) => e.stopPropagation()}>
        <div className="modal-top" />
        {children}
      </div>
    </div>
  );
}

/* ---------- Task modal ---------- */
function TaskModal({ task, project, user, onUpdate, onMoveStage, onDelete, onClose }) {
  const [draft, setDraft] = React.useState(task);
  const [newCheck, setNewCheck] = React.useState("");
  const [remindInfo, setRemindInfo] = React.useState(false);
  // Re-seed local state only when a DIFFERENT task opens — so live writes don't
  // clobber the field you're typing in (that caused the cursor to jump).
  React.useEffect(() => { setDraft(task); }, [task.id]);

  const isAdmin = MPerms.isAdmin(user, project);
  const canEdit = MPerms.canEditTask(user, project, task);
  const ro = !canEdit;

  const checkTotal = draft.check.length;
  const checkDone = draft.check.filter((c) => c.done).length;
  // Edit locally (smooth) AND persist to the store.
  const up = (patch) => { if (!canEdit) return; setDraft((d) => ({ ...d, ...patch })); onUpdate(task.id, patch); };
  const setCheck = (arr) => up({ check: arr });

  function addCheck() {
    const v = newCheck.trim(); if (!v) return;
    setCheck([...draft.check, { id: uid2("c_"), text: v, done: false }]);
    setNewCheck("");
  }
  function toggleMember(id) {
    if (!isAdmin) return;
    up({ members: draft.members.includes(id) ? draft.members.filter((x) => x !== id) : [...draft.members, id] });
  }
  function changeStage(stageId) { setDraft((d) => ({ ...d, stageId })); onMoveStage(task.id, stageId); }

  return (
    <Scrim onClose={onClose}>
      <div className="modal-hd">
        <span className="stage-pill"><Icn.Folder s={13} /> {project.name}</span>
        {ro && <span className="ro-pill">View only</span>}
        <button className="icon-btn modal-x" onClick={onClose}><Icn.X s={18} /></button>
      </div>
      <div className="modal-body">
        <textarea
          className="modal-title" rows={1} value={draft.title} readOnly={ro}
          onChange={(e) => up({ title: e.target.value })}
          onInput={(e) => { e.target.style.height = "auto"; e.target.style.height = e.target.scrollHeight + "px"; }}
          ref={(el) => { if (el && document.activeElement !== el) { el.style.height = "auto"; el.style.height = el.scrollHeight + "px"; } }}
        />

        {ro && (
          <div className="ro-note">
            <Icn.User s={15} /> You can view this task but only its members or a project admin can make changes.
          </div>
        )}

        <div className="field">
          <span className="field-lbl">Stage</span>
          <select className="sel" value={draft.stageId} disabled={ro} onChange={(e) => changeStage(e.target.value)}>
            {project.stages.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
          </select>
        </div>

        <div className="field">
          <span className="field-lbl">Members {isAdmin ? "" : "· admins assign"}</span>
          {isAdmin ? (
            <div className="owner-row">
              {(() => {
                // Only people ON this project can be assigned. Anyone already on the
                // task but no longer a project member is still shown (greyed) so an
                // admin can clear them.
                const onProj = getProjectMembers(project);
                const onProjIds = new Set(onProj.map((m) => m.id));
                const stale = u2(draft.members).filter((m) => !onProjIds.has(m.id));
                return [...onProj, ...stale].map((m) => (
                  <button key={m.id}
                    className={"owner-opt" + (draft.members.includes(m.id) ? " sel" : "") + (onProjIds.has(m.id) ? "" : " stale")}
                    title={onProjIds.has(m.id) ? "" : m.name + " is no longer on this project"}
                    onClick={() => toggleMember(m.id)}>
                    <Av member={m} size="sm" /> {m.name}
                  </button>
                ));
              })()}
              {getProjectMembers(project).length === 0 && (
                <span className="ro-muted">No one is on this project yet — add people in People &amp; invites.</span>
              )}
            </div>
          ) : (
            <div className="owner-row">
              {draft.members.length === 0 ? <span className="ro-muted">No members assigned</span>
                : u2(draft.members).map((m) => (
                  <span key={m.id} className="owner-opt sel" style={{ cursor: "default" }}><Av member={m} size="sm" /> {m.name}</span>
                ))}
            </div>
          )}
        </div>

        <div className="fgrid">
          <div className="field">
            <span className="field-lbl">Due date</span>
            <input type="date" className="inp" value={draft.due || ""} disabled={ro} onChange={(e) => up({ due: e.target.value || null })} />
          </div>
          <div className="field remind-field">
            <span className="field-lbl">
              Remind
              <button type="button" className="info-btn" onClick={() => setRemindInfo((v) => !v)} aria-label="About reminders"><Icn.Info s={13} /></button>
            </span>
            <input type="number" step="1" min="-30" max="30" className="inp" placeholder="-2" disabled={ro || !draft.due}
              value={draft.remind == null ? -2 : draft.remind}
              onChange={(e) => { const v = Math.trunc(Number(e.target.value)); up({ remind: Number.isFinite(v) ? Math.max(-30, Math.min(30, v)) : -2 }); }} />
            {draft.due && <span className="dlg-hint remind-hint">{remindSummary(draft.remind == null ? -2 : draft.remind, draft.due)}</span>}
            {remindInfo && (
              <div className="info-pop">
                <b>Reminders are sent relative to the Due Date.</b>
                <p><b>Minus</b> = before — e.g. <code>-2</code> sends a reminder 2 days before, again the day before, and on the due date. Overdue nudges follow at 1, 2 and 5 days past due (the 5-day one is the last).</p>
                <p><b>Plus</b> = after completion — e.g. <code>+7</code> sends one follow-up 7 days after the task is marked complete.</p>
                <p>Default is <code>-2</code>. A task with no due date is never reminded.</p>
              </div>
            )}
          </div>
          <div className="field">
            <span className="field-lbl">Priority</span>
            <div className="prio-row">
              {PRIORITIES.map((p) => (
                <button key={p.id} data-p={p.id} disabled={ro} className={"prio-opt" + (draft.prio === p.id ? " sel" : "")} onClick={() => up({ prio: p.id })}>
                  {p.id !== "none" && <Icn.Flag s={13} />}{p.label}
                </button>
              ))}
            </div>
          </div>
          <div className="field">
            <span className="field-lbl">Est. budget</span>
            <input type="number" min="0" step="50" className="inp" placeholder="—" disabled={ro}
              value={draft.budget == null ? "" : draft.budget}
              onChange={(e) => up({ budget: e.target.value === "" ? null : Math.max(0, +e.target.value) })} />
          </div>
          <div className="field">
            <span className="field-lbl">Volunteers needed</span>
            <input type="number" min="0" step="1" className="inp" placeholder="—" disabled={ro}
              value={draft.vols == null ? "" : draft.vols}
              onChange={(e) => up({ vols: e.target.value === "" ? null : Math.max(0, +e.target.value) })} />
          </div>
        </div>

        <div className="field">
          <span className="field-lbl">Labels</span>
          <div className="lbl-row">
            {getLabels().map((l) => {
              const on = draft.labels.includes(l.id);
              return (
                <button key={l.id} disabled={ro} className={"lbl-opt" + (on ? " sel" : "")} style={{ color: l.fg, background: l.bg }}
                  onClick={() => up({ labels: on ? draft.labels.filter((x) => x !== l.id) : [...draft.labels, l.id] })}>
                  {l.name}
                </button>
              );
            })}
          </div>
        </div>

        <div className="field">
          <span className="field-lbl">Description / notes</span>
          <textarea className="ta" placeholder={ro ? "No notes." : "Add context, links, or details…"} value={draft.desc} readOnly={ro}
            onChange={(e) => up({ desc: e.target.value })} />
        </div>

        <div className="field">
          <div className="check-head">
            <span className="field-lbl">Checklist</span>
            {checkTotal > 0 && <span className="check-prog">{checkDone}/{checkTotal}</span>}
            {checkTotal > 0 && <span className="mini-prog" style={{ width: 70 }}><i style={{ width: (checkDone / checkTotal * 100) + "%", background: checkDone === checkTotal ? "#2faa63" : "#9aa6b8" }} /></span>}
          </div>
          <div className="check-list">
            {draft.check.map((c) => (
              <div key={c.id} className={"check-item" + (c.done ? " checked" : "")}>
                <button className={"check-box" + (c.done ? " on" : "")} disabled={ro} onClick={() => setCheck(draft.check.map((x) => x.id === c.id ? { ...x, done: !x.done } : x))}>
                  {c.done && <Icn.Check s={13} w={3} />}
                </button>
                <input className="ci" value={c.text} readOnly={ro} onChange={(e) => setCheck(draft.check.map((x) => x.id === c.id ? { ...x, text: e.target.value } : x))} />
                {!ro && <button className="icon-btn check-del" onClick={() => setCheck(draft.check.filter((x) => x.id !== c.id))}><Icn.X s={14} /></button>}
              </div>
            ))}
            {!ro && (
              <div className="check-add">
                <button className="icon-btn check-add-btn" onClick={addCheck} title="Add sub-task"><Icn.Plus s={16} /></button>
                <input value={newCheck} placeholder="Add a sub-task…" onChange={(e) => setNewCheck(e.target.value)}
                  onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addCheck(); } }} />
              </div>
            )}
          </div>
        </div>
      </div>

      <div className="modal-foot">
        {isAdmin && <button className="btn danger" onClick={() => onDelete(task.id)}><Icn.Trash s={15} /> Delete task</button>}
        <span className="sp" />
        <button className="btn primary" onClick={onClose}>Done</button>
      </div>
    </Scrim>
  );
}

/* ---------- Name dialog ---------- */
function NameDialog({ title, label, initial, confirmLabel, onConfirm, onClose, hint }) {
  const [v, setV] = React.useState(initial || "");
  const ref = React.useRef(null);
  React.useEffect(() => { if (ref.current) { ref.current.focus(); ref.current.select(); } }, []);
  function go() { const t = v.trim(); if (t) onConfirm(t); }
  return (
    <Scrim onClose={onClose} small>
      <div className="modal-hd"><h3 className="dlg-title">{title}</h3>
        <button className="icon-btn modal-x" onClick={onClose}><Icn.X s={18} /></button></div>
      <div className="modal-body">
        <div className="field">
          <span className="field-lbl">{label}</span>
          <input ref={ref} className="inp" value={v} onChange={(e) => setV(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") go(); }} />
          {hint && <span className="dlg-hint">{hint}</span>}
        </div>
      </div>
      <div className="modal-foot">
        <span className="sp" />
        <button className="btn ghost" onClick={onClose}>Cancel</button>
        <button className="btn primary" onClick={go}>{confirmLabel || "Save"}</button>
      </div>
    </Scrim>
  );
}

/* ---------- Confirm dialog ---------- */
function ConfirmDialog({ title, body, confirmLabel, danger, onConfirm, onClose }) {
  return (
    <Scrim onClose={onClose} small>
      <div className="modal-hd"><h3 className="dlg-title">{title}</h3>
        <button className="icon-btn modal-x" onClick={onClose}><Icn.X s={18} /></button></div>
      <div className="modal-body"><p className="dlg-body">{body}</p></div>
      <div className="modal-foot">
        <span className="sp" />
        <button className="btn ghost" onClick={onClose}>Cancel</button>
        <button className={"btn " + (danger ? "danger" : "primary")} onClick={onConfirm}>{confirmLabel || "Confirm"}</button>
      </div>
    </Scrim>
  );
}

/* ---------- Remove-member dialog: confirm + (if they hold tasks) reassign ---------- */
function RemoveMemberDialog({ member, project, others, onConfirm, onClose }) {
  const theirTasks = (project.tasks || []).filter((t) => (t.members || []).includes(member.id));
  const [toUid, setToUid] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const first = (member.name || "").split(" ")[0] || member.name;
  async function go() {
    if (busy) return;
    setBusy(true);
    try { await onConfirm(theirTasks.length ? (toUid || null) : null); }
    finally { setBusy(false); }
  }
  return (
    <Scrim onClose={onClose} small>
      <div className="modal-hd"><h3 className="dlg-title">Remove from project?</h3>
        <button className="icon-btn modal-x" onClick={onClose}><Icn.X s={18} /></button></div>
      <div className="modal-body">
        <p className="dlg-body">
          Remove <strong>{member.name}</strong> from {project.name}? They stay in the club and can be added back at any time.
        </p>
        {theirTasks.length > 0 && (
          <div className="field" style={{ marginTop: 12 }}>
            <span className="field-lbl">
              {first} is assigned to {theirTasks.length} task{theirTasks.length !== 1 ? "s" : ""} here — move {theirTasks.length !== 1 ? "them" : "it"} to
            </span>
            <select className="sel" value={toUid} onChange={(e) => setToUid(e.target.value)}>
              <option value="">Leave unassigned</option>
              {others.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}
            </select>
          </div>
        )}
      </div>
      <div className="modal-foot">
        <span className="sp" />
        <button className="btn ghost" onClick={onClose}>Cancel</button>
        <button className="btn danger" disabled={busy} onClick={go}>{busy ? "…" : "Remove"}</button>
      </div>
    </Scrim>
  );
}

/* ---------- Admins dialog (allocate 1–2 admins per project) ---------- */
function AdminsDialog({ project, onToggle, onClose }) {
  const admins = project.admins || [];
  const atMax = admins.length >= 2;
  return (
    <Scrim onClose={onClose} small>
      <div className="modal-hd"><h3 className="dlg-title">Project admins</h3>
        <button className="icon-btn modal-x" onClick={onClose}><Icn.X s={18} /></button></div>
      <div className="modal-body">
        <p className="dlg-body" style={{ marginBottom: 4 }}>
          Admins manage stages, create &amp; assign tasks, and can rename, duplicate or delete <strong>{project.name}</strong>. Pick one or two.
        </p>
        <div className="admin-list">
          {getMembers().filter((m) => m.role !== "guest" || admins.includes(m.id)).map((m) => {
            const on = admins.includes(m.id);
            const disabled = !on && atMax;
            return (
              <button key={m.id} className={"admin-row" + (on ? " on" : "")} disabled={disabled}
                onClick={() => onToggle(m.id)} title={disabled ? "Remove an admin first (max 2)" : ""}>
                <Av member={m} size="" />
                <span className="admin-meta"><b>{m.name}</b><small>{m.email}</small></span>
                <span className={"admin-tick" + (on ? " on" : "")}>{on ? <Icn.Check s={15} w={3} /> : null}</span>
              </button>
            );
          })}
        </div>
        {atMax && <span className="dlg-hint">Maximum of two admins — remove one to add another.</span>}
      </div>
      <div className="modal-foot">
        <span className="sp" />
        <button className="btn primary" onClick={onClose}>Done</button>
      </div>
    </Scrim>
  );
}

Object.assign(window, { TaskModal, NameDialog, ConfirmDialog, AdminsDialog, MembersDialog });

/* ---------- Members & Invites dialog (Stage 1) ----------
 * Tabbed: project members (add/remove existing club members + invite by email)
 * and the pending-approvals queue for external guests.
 */
function MembersDialog({ project, club, store, onOpenActivity, onClose }) {
  const me = store.user;
  const isSuper = (club && (club.superAdmins || []).includes(me.id)) || me.clubRole === "super-admin";
  const [tab, setTab] = React.useState("members");
  const [email, setEmail] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [note, setNote] = React.useState(null);

  const all = getMembers();
  const memberUids = project.memberUids || project.admins || [];
  const onProject = all.filter((m) => memberUids.includes(m.id) || (project.admins || []).includes(m.id));
  // Candidates an admin can add to this project = domain club members not already
  // on it. External guests are deliberately excluded — a guest's access is scoped
  // to the exact project(s) their invitation was approved for and must not be
  // borrowable into other projects from here.
  const offProject = all.filter((m) => !memberUids.includes(m.id) && !(project.admins || []).includes(m.id) && m.role !== "guest");
  const pending = (store.pendingApprovals || []).filter((i) => (i.projectIds || []).includes(project.id) || !i.projectIds);
  const allPending = store.pendingApprovals || [];
  // people invited to THIS project who haven't signed in yet (no member doc)
  const joinedEmails = new Set(all.map((m) => (m.email || "").toLowerCase()));
  const invitedHere = (store.invites || []).filter((i) =>
    (i.projectIds || []).includes(project.id) && i.status !== "accepted" && i.status !== "revoked" && !joinedEmails.has((i.email || "").toLowerCase()));
  const [resendingId, setResendingId] = React.useState(null);
  const [confirmRemove, setConfirmRemove] = React.useState(null);

  async function resendInvite(inv) {
    if (resendingId) return; setResendingId(inv.id); setNote(null);
    const res = await store.actions.resendInvite(inv.id);
    setResendingId(null);
    setNote({ ok: !!(res && res.ok), msg: (res && res.msg) || "Could not resend." });
  }

  async function sendInvite() {
    if (busy) return; setBusy(true); setNote(null);
    const res = await store.actions.inviteToProject(project.id, email);
    setBusy(false);
    if (res && res.ok) { setEmail(""); setNote({ ok: true, msg: res.msg }); }
    else setNote({ ok: false, msg: (res && res.msg) || "Could not invite." });
  }
  async function addPerson(m) {
    setNote(null);
    try {
      await store.actions.addMemberToProject(project.id, m.id);
      setNote({ ok: true, msg: m.name + " added to this project." });
    } catch (e) {
      setNote({ ok: false, msg: "Couldn't add " + m.name + ": " + (e && e.message ? e.message : e) });
    }
  }
  async function removePerson(m) {
    setNote(null);
    try { await store.actions.removeMemberFromProject(project.id, m.id); }
    catch (e) { setNote({ ok: false, msg: "Couldn't remove " + m.name + ": " + (e && e.message ? e.message : e) }); }
  }

  return (
    <Scrim onClose={onClose}>
      <div className="modal-hd">
        <h3 className="dlg-title">People · {project.name}</h3>
        <button className="icon-btn modal-x" onClick={onClose}><Icn.X s={18} /></button>
      </div>

      <div className="tabs">
        <button className={"tab" + (tab === "members" ? " on" : "")} onClick={() => setTab("members")}>Members</button>
        <button className={"tab" + (tab === "approvals" ? " on" : "")} onClick={() => setTab("approvals")}>
          Approvals {allPending.length > 0 && <span className="tab-badge">{allPending.length}</span>}
        </button>
      </div>

      <div className="modal-body">
        {tab === "members" && (
          <>
            <div className="field">
              <span className="field-lbl">Invite by email</span>
              <div className="invite-row">
                <input className="inp" type="email" placeholder="name@example.com" value={email}
                  onChange={(e) => setEmail(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") sendInvite(); }} />
                <button className="btn primary" disabled={busy || !email.trim()} onClick={sendInvite}>{busy ? "…" : "Invite"}</button>
              </div>
              {note && <span className={"invite-note" + (note.ok ? " ok" : " err")}>{note.msg}</span>}
              <span className="dlg-hint">Club-domain emails ({(club && club.verifiedDomains || []).join(", ") || "your domain"}) join automatically on sign-in. Outside emails become a pending request you approve under <b>Approvals</b>.</span>
            </div>

            <div className="field">
              <span className="field-lbl">On this project ({onProject.length})</span>
              <div className="people-list">
                {onProject.map((m) => {
                  const admins = project.admins || [];
                  const contributors = project.contributors || [];
                  const isAdminHere = admins.includes(m.id);
                  const isContribHere = !isAdminHere && contributors.includes(m.id);
                  const lastAdmin = isAdminHere && admins.length <= 1;
                  const canPromote = !isAdminHere && admins.length < 2;
                  return (
                    <div key={m.id} className="person-row">
                      <Av member={m} size="" />
                      <span className="person-meta"><b>{m.name}{m.id === me.id ? " (you)" : ""}</b><small>{m.email || ""}</small></span>
                      {m.role === "guest" && <span className="role-tag guest">Guest</span>}
                      {isAdminHere && <span className="role-tag admin">Admin</span>}
                      {isContribHere && <span className="role-tag contrib">Contributor</span>}
                      {isAdminHere ? (
                        <button className="btn ghost sm" disabled={lastAdmin}
                          title={lastAdmin ? "A project needs at least one admin" : "Remove admin role"}
                          onClick={() => store.actions.toggleAdmin(project.id, m.id)}>Remove admin</button>
                      ) : (
                        <>
                          {canPromote && <button className="btn ghost sm" title="Make a project admin" onClick={() => store.actions.toggleAdmin(project.id, m.id)}>Make admin</button>}
                          <button className="btn ghost sm" title={isContribHere ? "Remove contributor role" : "Make a contributor"}
                            onClick={() => store.actions.toggleContributor(project.id, m.id)}>
                            {isContribHere ? "Remove contributor" : "Contributor"}
                          </button>
                          <button className="btn ghost sm" onClick={() => setConfirmRemove(m)} title="Remove from project"><Icn.X s={15} /></button>
                        </>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>

            {(project.contributorRequests || []).length > 0 && (
              <div className="field">
                <span className="field-lbl">Contributor requests ({(project.contributorRequests || []).length})</span>
                <div className="people-list">
                  {(project.contributorRequests || []).map((uid) => {
                    const m = all.find((x) => x.id === uid);
                    if (!m) return null;
                    return (
                      <div key={uid} className="person-row">
                        <Av member={m} size="" />
                        <span className="person-meta"><b>{m.name}</b><small>{m.email || ""}</small></span>
                        <button className="btn ghost sm danger" onClick={() => store.actions.declineContributorRequest(project.id, uid)}>Decline</button>
                        <button className="btn primary sm" onClick={() => store.actions.approveContributorRequest(project.id, uid)}>Approve</button>
                      </div>
                    );
                  })}
                </div>
                <span className="dlg-hint">Approving makes this person a contributor — they can create and edit tasks.</span>
              </div>
            )}

            {invitedHere.length > 0 && (
              <div className="field">
                <span className="field-lbl">Invited · awaiting first sign-in ({invitedHere.length})</span>
                <div className="people-list">
                  {invitedHere.map((inv) => (
                    <div key={inv.id} className="person-row">
                      <div className="avatar" style={{ background: "#c3cdda", color: "#46566c" }}>{(inv.email || "?").slice(0, 2).toUpperCase()}</div>
                      <span className="person-meta"><b>{inv.email}</b><small>{inv.isExternal ? "External guest" : "Club member"} · {inv.status === "pending" ? "awaiting approval" : "approved — not signed in yet"}</small></span>
                      {inv.status === "pending" && <span className="role-tag" style={{ background: "#fdf2e2", color: "#9a6a08" }}>Pending</span>}
                      {inv.status === "approved" && <span className="role-tag" style={{ background: "#e3f3e9", color: "#1f7a44" }}>Approved</span>}
                      {inv.status === "approved" && (
                        <span className="reminder-ticks" title={
                          "24h reminder: " + (inv.reminder1SentAt ? "sent " + new Date(inv.reminder1SentAt).toLocaleDateString(CCIntl.locale(), { day: "numeric", month: "short" }) : "not yet due") +
                          "  ·  48h reminder: " + (inv.reminder2SentAt ? "sent " + new Date(inv.reminder2SentAt).toLocaleDateString(CCIntl.locale(), { day: "numeric", month: "short" }) : "not yet due")
                        }>
                          <span className={"tick" + (inv.reminder1SentAt ? " sent" : "")}>{inv.reminder1SentAt ? <Icn.Check s={11} /> : "24h"}</span>
                          <span className={"tick" + (inv.reminder2SentAt ? " sent" : "")}>{inv.reminder2SentAt ? <Icn.Check s={11} /> : "48h"}</span>
                        </span>
                      )}
                      {inv.status === "approved" && (
                        <button className="btn ghost sm" disabled={resendingId === inv.id} onClick={() => resendInvite(inv)} title="Resend the invite email">
                          {resendingId === inv.id ? "…" : "Resend"}
                        </button>
                      )}
                      <button className="btn ghost sm danger" onClick={() => store.actions.declineInvite(inv.id)} title="Cancel invitation"><Icn.X s={15} /></button>
                    </div>
                  ))}
                </div>
                <span className="dlg-hint">They'll appear as members once they sign in — then you can assign them to tasks.</span>
              </div>
            )}

            {offProject.length > 0 && (
              <div className="field">
                <span className="field-lbl">Other club members</span>
                <div className="people-list">
                  {offProject.map((m) => (
                    <div key={m.id} className="person-row">
                      <Av member={m} size="" />
                      <span className="person-meta"><b>{m.name}</b><small>{m.email || ""}</small></span>
                      <button className="btn sm" onClick={() => addPerson(m)}><Icn.Plus s={15} /> Add</button>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </>
        )}

        {tab === "approvals" && (
          <div className="field">
            <span className="field-lbl">Pending external requests</span>
            {allPending.length === 0 ? (
              <div className="approvals-empty"><Icn.Check s={18} /> Nothing waiting. External invites you create appear here for approval.</div>
            ) : (
              <div className="people-list">
                {allPending.map((inv) => (
                  <div key={inv.id} className="person-row">
                    <div className="avatar" style={{ background: "#8a97a8" }}>{(inv.email || "?").slice(0, 2).toUpperCase()}</div>
                    <span className="person-meta"><b>{inv.email}</b><small>External guest · {(inv.projectIds || []).length} project{(inv.projectIds || []).length !== 1 ? "s" : ""}</small></span>
                    <button className="btn ghost sm danger" onClick={() => store.actions.declineInvite(inv.id)}>Decline</button>
                    <button className="btn primary sm" onClick={() => store.actions.approveInvite(inv.id)}>Approve</button>
                  </div>
                ))}
              </div>
            )}
            <span className="dlg-hint">Approving sends the person a confirmation email and grants access once they sign in.</span>
          </div>
        )}
      </div>

      <div className="modal-foot">
        {onOpenActivity && <button className="btn" onClick={onOpenActivity}><Icn.ListChk s={15} /> Activity log</button>}
        {project.createdBy && (() => {
          const creator = all.find((m) => m.id === project.createdBy);
          const when = project.createdAt ? new Date(project.createdAt).toLocaleDateString(CCIntl.locale(), { day: "numeric", month: "short", year: "numeric" }) : null;
          return <span className="created-by">Created by <b>{creator ? creator.name : "—"}</b>{when ? " · " + when : ""}</span>;
        })()}
        <span className="sp" />
        <button className="btn primary" onClick={onClose}>Done</button>
      </div>

      {confirmRemove && (
        <RemoveMemberDialog member={confirmRemove} project={project}
          others={onProject.filter((x) => x.id !== confirmRemove.id)}
          onConfirm={async (toUid) => {
            await store.actions.reassignMemberTasks(project.id, confirmRemove.id, toUid);
            await removePerson(confirmRemove);
            setConfirmRemove(null);
          }}
          onClose={() => setConfirmRemove(null)} />
      )}
    </Scrim>
  );
}

Object.assign(window, { MembersDialog, ClubSettingsDialog });

/* ---------- Activity log viewer (super-admins: whole club · project admins: their project) ---------- */
const ACT_ICON = {
  "task.create": "＋", "task.delete": "🗑", "project.create": "📁", "project.rename": "✏️",
  "project.duplicate": "⧉", "project.delete": "🗑", "admin.add": "★", "admin.remove": "☆",
  "guest.resend": "✉️",
  "contributor.add": "▲", "contributor.remove": "▽",
  "member.add": "👤", "member.remove": "✖", "task.reassign": "⇄", "guest.approve": "✓", "guest.decline": "✕",
  "club.rename": "✏️", "club.superadmins": "★", "label.change": "🏷",
};
function ActivityDialog({ store, scopeProject, onClose }) {
  const [rows, setRows] = React.useState(null);
  const [err, setErr] = React.useState(null);
  React.useEffect(() => {
    let live = true;
    store.actions.loadActivity(scopeProject ? scopeProject.id : null)
      .then((r) => { if (live) setRows(r); })
      .catch((e) => { if (live) setErr(e && e.message ? e.message : String(e)); });
    return () => { live = false; };
  }, [scopeProject && scopeProject.id]);

  function when(ms) {
    const d = new Date(ms);
    const today = new Date(); const sameDay = d.toDateString() === today.toDateString();
    const time = d.toLocaleTimeString(CCIntl.locale(), { hour: "numeric", minute: "2-digit" });
    return sameDay ? "Today " + time : d.toLocaleDateString(CCIntl.locale(), { day: "numeric", month: "short" }) + " " + time;
  }

  return (
    <Scrim onClose={onClose}>
      <div className="modal-hd">
        <h3 className="dlg-title">Activity log{scopeProject ? " · " + scopeProject.name : ""}</h3>
        <button className="icon-btn modal-x" onClick={onClose}><Icn.X s={18} /></button>
      </div>
      <div className="modal-body">
        {err && <div className="invite-note err">Couldn't load activity: {err}</div>}
        {rows === null && !err && <div className="approvals-empty">Loading…</div>}
        {rows && rows.length === 0 && <div className="approvals-empty"><Icn.ListChk s={18} /> No activity recorded yet.</div>}
        {rows && rows.length > 0 && (
          <div className="act-list">
            {rows.map((r) => (
              <div key={r.id} className="act-row">
                <span className="act-ico">{ACT_ICON[r.verb] || "•"}</span>
                <div className="act-body">
                  <div className="act-summary">{r.summary}</div>
                  <div className="act-meta">{r.byName}{!scopeProject && r.projectName ? " · " + r.projectName : ""} · {when(r.at)}</div>
                </div>
              </div>
            ))}
          </div>
        )}
        <span className="dlg-hint">Showing the {rows ? Math.min(rows.length, 200) : "most recent"} latest events. The log is append-only and cannot be edited.</span>
      </div>
      <div className="modal-foot">
        <span className="sp" />
        <button className="btn primary" onClick={onClose}>Done</button>
      </div>
    </Scrim>
  );
}

Object.assign(window, { ActivityDialog });

/* ---------- Club members console (super-admin: roles · access · status) ---------- */
function MembersConsoleDialog({ club, store, onClose }) {
  const me = store.user;
  const supers = (club && club.superAdmins) || [];
  const all = getMembers();
  const [confirm, setConfirm] = React.useState(null);

  const order = { "super-admin": 0, "member": 1, "guest": 2 };
  const sorted = [...all].sort((a, b) => (order[a.role] ?? 1) - (order[b.role] ?? 1) || (a.name || "").localeCompare(b.name || ""));

  function roleLabel(m) {
    if (supers.includes(m.id)) return { txt: "Super-admin", cls: "admin" };
    if (m.role === "guest") return { txt: "Guest", cls: "guest" };
    return { txt: "Member", cls: "" };
  }

  return (
    <Scrim onClose={onClose}>
      <div className="modal-hd">
        <h3 className="dlg-title">Club members ({all.length})</h3>
        <button className="icon-btn modal-x" onClick={onClose}><Icn.X s={18} /></button>
      </div>
      <div className="modal-body">
        <span className="dlg-hint" style={{ marginTop: -2 }}>Manage everyone in the club: access scope, suspension, and removal. Super-admins are promoted under <b>Super-admins</b> in Club settings.</span>
        <div className="people-list">
          {sorted.map((m) => {
            const rl = roleLabel(m);
            const isSuper = supers.includes(m.id);
            const suspended = m.status === "suspended";
            const access = m.clubAccess || "all";
            const isMe = m.id === me.id;
            return (
              <div key={m.id} className={"mc-row" + (suspended ? " suspended" : "")}>
                <Av member={m} size="" />
                <div className="mc-meta">
                  <b>{m.name}{isMe ? " (you)" : ""} <span className={"role-tag " + rl.cls}>{rl.txt}</span>{suspended && <span className="role-tag susp">Suspended</span>}</b>
                  <small>{m.email || ""} · {access === "all" ? "all projects" : "assigned projects"}{m.joinedVia ? " · joined via " + m.joinedVia : ""}</small>
                </div>
                <div className="mc-actions">
                  {!isSuper && (
                    <button className="btn ghost sm" title="Toggle project access"
                      onClick={() => store.actions.setMemberAccess(m.id, access === "all" ? "projects" : "all")}>
                      {access === "all" ? "Limit to assigned" : "Grant all projects"}
                    </button>
                  )}
                  {!isSuper && !isMe && (
                    suspended
                      ? <button className="btn ghost sm" onClick={() => store.actions.setMemberStatus(m.id, "active")}>Reactivate</button>
                      : <button className="btn ghost sm" onClick={() => store.actions.setMemberStatus(m.id, "suspended")}>Suspend</button>
                  )}
                  {!isSuper && !isMe && (
                    <button className="icon-btn" title="Remove from club" onClick={() => setConfirm(m)}><Icn.Trash s={15} /></button>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
      <div className="modal-foot">
        <span className="sp" />
        <button className="btn primary" onClick={onClose}>Done</button>
      </div>

      {confirm && (
        <ConfirmDialog title="Remove from club?" danger confirmLabel="Remove"
          body={`“${confirm.name}” will lose all access and be removed from every project. Their tasks stay, but unassigned. They can re-join only by domain sign-in or a fresh invitation.`}
          onConfirm={() => { store.actions.removeMember(confirm.id); setConfirm(null); }} onClose={() => setConfirm(null)} />
      )}
    </Scrim>
  );
}

Object.assign(window, { MembersConsoleDialog });

/* ---------- Club-level approvals + invite with project picker (super-admin) ---------- */
function ClubApprovalsDialog({ store, projects, onClose }) {
  const [email, setEmail] = React.useState("");
  const [pick, setPick] = React.useState(() => new Set());
  const [busy, setBusy] = React.useState(false);
  const [note, setNote] = React.useState(null);
  const pending = store.pendingApprovals || [];

  function togglePick(pid, set, setter) { const n = new Set(set); n.has(pid) ? n.delete(pid) : n.add(pid); setter(n); }

  async function sendInvite() {
    if (busy || !email.trim()) return;
    if (pick.size === 0) { setNote({ ok: false, msg: "Pick at least one project to grant." }); return; }
    setBusy(true); setNote(null);
    const res = await store.actions.inviteGuestToProjects(email, [...pick]);
    setBusy(false);
    if (res && res.ok) { setEmail(""); setPick(new Set()); setNote({ ok: true, msg: res.msg }); }
    else setNote({ ok: false, msg: (res && res.msg) || "Could not invite." });
  }

  return (
    <Scrim onClose={onClose}>
      <div className="modal-hd">
        <h3 className="dlg-title">Approvals &amp; invites</h3>
        <button className="icon-btn modal-x" onClick={onClose}><Icn.X s={18} /></button>
      </div>
      <div className="modal-body">
        <div className="field">
          <span className="field-lbl">Invite someone by email</span>
          <div className="invite-row">
            <input className="inp" type="email" placeholder="name@example.com" value={email}
              onChange={(e) => setEmail(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") sendInvite(); }} />
            <button className="btn primary" disabled={busy || !email.trim()} onClick={sendInvite}>{busy ? "…" : "Invite"}</button>
          </div>
          <span className="field-lbl" style={{ marginTop: 4 }}>Grant access to</span>
          <div className="proj-pick">
            {projects.map((p) => (
              <button key={p.id} className={"proj-chip" + (pick.has(p.id) ? " on" : "")} onClick={() => togglePick(p.id, pick, setPick)}>
                {pick.has(p.id) && <Icn.Check s={13} w={3} />}{p.name}
              </button>
            ))}
          </div>
          {note && <span className={"invite-note" + (note.ok ? " ok" : " err")}>{note.msg}</span>}
          <span className="dlg-hint">Club-domain emails join automatically on sign-in. Outside emails appear below as pending until you approve.</span>
        </div>

        <div className="field">
          <span className="field-lbl">Pending external requests ({pending.length})</span>
          {pending.length === 0 ? (
            <div className="approvals-empty"><Icn.Check s={18} /> Nothing waiting.</div>
          ) : (
            <div className="people-list">
              {pending.map((inv) => <PendingRow key={inv.id} inv={inv} projects={projects} store={store} />)}
            </div>
          )}
        </div>
      </div>
      <div className="modal-foot">
        <span className="sp" />
        <button className="btn primary" onClick={onClose}>Done</button>
      </div>
    </Scrim>
  );
}

function PendingRow({ inv, projects, store }) {
  const [sel, setSel] = React.useState(() => new Set(inv.projectIds || []));
  function toggle(pid) { const n = new Set(sel); n.has(pid) ? n.delete(pid) : n.add(pid); setSel(n); }
  return (
    <div className="pending-card">
      <div className="person-row" style={{ border: 0, padding: 0 }}>
        <div className="avatar" style={{ background: "#8a97a8" }}>{(inv.email || "?").slice(0, 2).toUpperCase()}</div>
        <span className="person-meta"><b>{inv.email}</b><small>External guest</small></span>
        <button className="btn ghost sm danger" onClick={() => store.actions.declineInvite(inv.id)}>Decline</button>
        <button className="btn primary sm" disabled={sel.size === 0} onClick={() => store.actions.approveInvite(inv.id, [...sel])}>Approve</button>
      </div>
      <div className="proj-pick" style={{ marginTop: 8 }}>
        {projects.map((p) => (
          <button key={p.id} className={"proj-chip" + (sel.has(p.id) ? " on" : "")} onClick={() => toggle(p.id)}>
            {sel.has(p.id) && <Icn.Check s={13} w={3} />}{p.name}
          </button>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ClubApprovalsDialog });

/* ---------- Club settings dialog (super-admin): org name + super-admins ---------- */
function ClubSettingsDialog({ club, store, onOpenActivity, onOpenMembers, onOpenApprovals, onClose }) {
  const [name, setName] = React.useState((club && club.name) || "");
  const supers = (club && club.superAdmins) || [];
  const all = getMembers();
  const activeMembers = all.filter((m) => m.status !== "suspended");
  const serverLabels = (club && club.labels && club.labels.length) ? club.labels : getLabels();
  const [labelDraft, setLabelDraft] = React.useState(serverLabels);
  const idSig = serverLabels.map((l) => l.id).join(",");
  // re-seed local draft only when labels are added/removed (id set changes), not on every keystroke
  React.useEffect(() => { setLabelDraft(serverLabels); }, [idSig]);
  const [newLabel, setNewLabel] = React.useState("");

  function persist(arr) { store.actions.setClubLabels(arr); }
  function addLabel() {
    const v = newLabel.trim(); if (!v) return;
    const color = LABEL_COLORS[labelDraft.length % LABEL_COLORS.length];
    const arr = [...labelDraft, { id: uid2("l_"), name: v, fg: color.fg, bg: color.bg }];
    setLabelDraft(arr); persist(arr); setNewLabel("");
  }
  function editLabelName(id, name) { setLabelDraft((d) => d.map((l) => l.id === id ? { ...l, name } : l)); }
  function commitLabelNames() { persist(labelDraft); }
  function recolorLabel(id, c) { const arr = labelDraft.map((l) => l.id === id ? { ...l, fg: c.fg, bg: c.bg } : l); setLabelDraft(arr); persist(arr); }
  function deleteLabel(id) { const arr = labelDraft.filter((l) => l.id !== id); setLabelDraft(arr); persist(arr); }

  function saveName() {
    const v = name.trim();
    if (v && v !== (club && club.name)) store.actions.renameClub(v);
  }
  function toggleSuper(uid) {
    const isSuper = supers.includes(uid);
    if (isSuper) { if (supers.length <= 1) return; store.actions.setSuperAdmins(supers.filter((x) => x !== uid)); }
    else store.actions.setSuperAdmins([...supers, uid]);
  }

  return (
    <Scrim onClose={onClose}>
      <div className="modal-hd">
        <h3 className="dlg-title">Club settings</h3>
        <button className="icon-btn modal-x" onClick={onClose}><Icn.X s={18} /></button>
      </div>
      <div className="modal-body">
        <div className="field">
          <span className="field-lbl">Organisation name</span>
          <div className="invite-row">
            <input className="inp" value={name} onChange={(e) => setName(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") saveName(); }} />
            <button className="btn primary" onClick={saveName}>Save</button>
          </div>
          <span className="dlg-hint">Shown in the header and on the sign-in screen for everyone in the club.</span>
        </div>

        <div className="field">
          <span className="field-lbl">Super-admins ({supers.length})</span>
          <span className="dlg-hint" style={{ marginTop: -2 }}>Super-admins manage the whole club and reach every project. A person must have signed in at least once to appear here. At least one is always required.</span>
          <div className="people-list" style={{ marginTop: 4 }}>
            {activeMembers.map((m) => {
              const on = supers.includes(m.id);
              const lastOne = on && supers.length <= 1;
              return (
                <div key={m.id} className="person-row">
                  <Av member={m} size="" />
                  <span className="person-meta"><b>{m.name}{m.id === store.user.id ? " (you)" : ""}</b><small>{m.email || ""}</small></span>
                  {m.role === "guest" && <span className="role-tag guest">Guest</span>}
                  <button className={"btn sm" + (on ? "" : " ")} disabled={lastOne}
                    style={on ? { background: "var(--brand)", color: "#fff", borderColor: "transparent" } : null}
                    title={lastOne ? "A club needs at least one super-admin" : ""}
                    onClick={() => toggleSuper(m.id)}>
                    {on ? "Super-admin ✓" : "Make super-admin"}
                  </button>
                </div>
              );
            })}
          </div>
        </div>

        <div className="field">
          <span className="field-lbl">Labels / tags ({labelDraft.length})</span>
          <span className="dlg-hint" style={{ marginTop: -2 }}>Used to categorise tasks across every project. Rename, recolour, or remove — changes apply everywhere.</span>
          <div className="label-mgr">
            {labelDraft.map((l) => (
              <div key={l.id} className="label-row">
                <span className="lbl" style={{ color: l.fg, background: l.bg }}>{l.name || "—"}</span>
                <input className="label-name" value={l.name} onChange={(e) => editLabelName(l.id, e.target.value)} onBlur={commitLabelNames}
                  onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); commitLabelNames(); e.target.blur(); } }} />
                <div className="label-swatches">
                  {LABEL_COLORS.map((c, i) => (
                    <button key={i} className={"swatch" + (c.bg === l.bg ? " on" : "")} style={{ background: c.bg, borderColor: c.fg }}
                      title="Recolour" onClick={() => recolorLabel(l.id, c)} />
                  ))}
                </div>
                <button className="icon-btn label-del" title="Delete label" onClick={() => deleteLabel(l.id)}><Icn.Trash s={15} /></button>
              </div>
            ))}
          </div>
          <div className="invite-row" style={{ marginTop: 8 }}>
            <input className="inp" placeholder="New label name…" value={newLabel}
              onChange={(e) => setNewLabel(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") addLabel(); }} />
            <button className="btn primary" disabled={!newLabel.trim()} onClick={addLabel}><Icn.Plus s={15} /> Add</button>
          </div>
        </div>
      </div>
      <div className="modal-foot">
        <button className="btn" onClick={onOpenApprovals}><Icn.User s={15} /> Approvals &amp; invites</button>
        <button className="btn" onClick={onOpenMembers}><Icn.Users s={15} /> Members</button>
        <button className="btn" onClick={onOpenActivity}><Icn.ListChk s={15} /> Activity</button>
        <span className="sp" />
        <button className="btn primary" onClick={onClose}>Done</button>
      </div>
    </Scrim>
  );
}

Object.assign(window, { ClubSettingsDialog });
