/* app.jsx — root App: store-backed (Firebase or demo), header, toolbar, projects, roles, tweaks */
const PD = window.PlannerData;
const { labelById: lById, usersByIds: uByIds } = PD;
const Icon = window.Icons;
const RotaryWheel = window.RotaryWheel;
const AvA = window.Avatar;
const { Board, TaskModal, NameDialog, ConfirmDialog, AdminsDialog, ClubSettingsDialog, ActivityDialog, MembersConsoleDialog, ClubApprovalsDialog } = window;
const { Perms } = window.Auth;
const usePlannerStore = window.usePlannerStore;
const { useTweaks, TweaksPanel, TweakSection, TweakColor, TweakRadio, TweakToggle } = window;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "brand": "#17458F",
  "density": "roomy",
  "showAvatars": true
}/*EDITMODE-END*/;

const BRAND_OPTS = ["#17458F", "#1b6fb0", "#1f7a44", "#7a4fb0", "#384a63"];

/* Organisation identity — comes from firebase-config.js bootstrapClub, so a
 * different club only edits that one file. The live club doc overrides at runtime. */
const BOOT_CLUB = (window.FIREBASE && window.FIREBASE.bootstrapClub) || {};
const ORG_NAME_DEFAULT = BOOT_CLUB.name || "Project Planner";
const ORG_DOMAINS = BOOT_CLUB.autoJoinDomains || [];
// Sign-in screen can't read the club doc (pre-auth), so use the last name a
// signed-in session cached in this browser, falling back to the config default.
function cachedOrgName() {
  try { return window.localStorage.getItem("rotary_org_name") || ORG_NAME_DEFAULT; } catch (e) { return ORG_NAME_DEFAULT; }
}
const ORG_NAME = cachedOrgName();
function orgName(club) { return (club && club.name) || ORG_NAME; }

/* ---------- Sign-in screen (Firebase mode, signed out) ---------- */
function SignIn({ onSignIn, error, store }) {
  const [busy, setBusy] = React.useState(false);
  const [email, setEmail] = React.useState("");
  const [linkSent, setLinkSent] = React.useState(false);
  const [linkBusy, setLinkBusy] = React.useState(false);
  const [linkErr, setLinkErr] = React.useState(null);
  const go = () => {
    if (busy) return;
    setBusy(true);
    Promise.resolve(onSignIn()).finally(() => setTimeout(() => setBusy(false), 4000));
  };
  async function sendLink() {
    if (linkBusy || !email.trim()) return;
    setLinkBusy(true); setLinkErr(null);
    try { await store.sendEmailLink(email.trim()); setLinkSent(true); }
    catch (e) { setLinkErr(e && e.message ? e.message : "Could not send the link."); }
    finally { setLinkBusy(false); }
  }
  return (
    <div className="signin">
      <div className="signin-card">
        <img className="signin-mark" src="plan-mark.svg?v=5" alt="" width="64" height="64" />
        <div className="signin-club">{ORG_NAME}</div>
        <h1>Project Planner</h1>
        <p>Sign in with your account to view and manage projects.</p>
        <button className="google-btn" onClick={go} disabled={busy}>
          <svg width="18" height="18" viewBox="0 0 48 48" aria-hidden="true"><path fill="#FFC107" d="M43.6 20.5h-1.9V20H24v8h11.3c-1.6 4.7-6.1 8-11.3 8-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.9 1.2 8 3.1l5.7-5.7C34.5 6.5 29.5 4.5 24 4.5 13.2 4.5 4.5 13.2 4.5 24S13.2 43.5 24 43.5 43.5 34.8 43.5 24c0-1.2-.1-2.3-.3-3.5z"/><path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 15.1 19 12 24 12c3.1 0 5.9 1.2 8 3.1l5.7-5.7C34.5 6.5 29.5 4.5 24 4.5c-7.6 0-14.2 4.3-17.7 10.2z"/><path fill="#4CAF50" d="M24 43.5c5.4 0 10.3-2 14-5.3l-6.5-5.5C29.6 34.4 26.9 35.5 24 35.5c-5.2 0-9.6-3.3-11.3-7.9l-6.5 5C9.7 39.1 16.3 43.5 24 43.5z"/><path fill="#1976D2" d="M43.6 20.5H24v8h11.3c-.8 2.2-2.2 4.2-4.1 5.6l6.5 5.5c-.5.4 7-5.1 7-15.6 0-1.2-.1-2.3-.3-3.5z"/></svg>
          {busy ? "Opening Google…" : "Club Members Sign In Here"}
        </button>
        {ORG_DOMAINS.length > 0 && <div className="signin-subtext">(use your @{ORG_DOMAINS[0]} email)</div>}

        <div className="signin-or"><span>or use your email</span></div>

        {linkSent ? (
          <div className="signin-sent">
            <b>Check your inbox</b>
            <span>We've emailed a sign-in link to <b>{email}</b>. Open it on this device to finish signing in.</span>
          </div>
        ) : (
          <div className="signin-email">
            <input className="inp" type="email" placeholder="you@example.com" value={email}
              onChange={(e) => setEmail(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") sendLink(); }} />
            <button className="btn" disabled={linkBusy || !email.trim()} onClick={sendLink}>{linkBusy ? "Sending…" : "Email me a sign-in link"}</button>
          </div>
        )}
        {linkErr && <div className="signin-err">{linkErr}</div>}
        {error && <div className="signin-err">{error}</div>}
        <div className="signin-foot">{ORG_DOMAINS.length > 0 ? <>Club members sign in with <b>@{ORG_DOMAINS[0]}</b>; guests by invitation.</> : <>Sign in with an invited account.</>}</div>
      </div>
    </div>
  );
}

function Splash({ label }) {
  return <div className="splash"><RotaryWheel size={46} color="#17458F" spin /><div className="splash-label">{label || "Loading…"}</div></div>;
}

/* ---------- Gated screens for external guests ---------- */
function GateScreen({ user, store, title, body, tone }) {
  return (
    <div className="signin">
      <div className="signin-card">
        <img className="signin-mark" src="plan-mark.svg?v=5" alt="" width="56" height="56" />
        <div className="signin-club">{ORG_NAME}</div>
        <h1 style={{ marginBottom: 8 }}>{title}</h1>
        <p>{body}</p>
        <div className={"gate-chip " + (tone || "")}>{user.email}</div>
        <button className="btn ghost" style={{ marginTop: 18 }} onClick={store.signOut}>Sign out</button>
      </div>
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const store = usePlannerStore();
  const { mode, authStage, user, members, data, setCurrentId, actions } = store;
  const activeUids = React.useMemo(() => new Set(store.presentUids || []), [store.presentUids]);
  const [club, setClub] = React.useState(null);

  // load the club doc (for verifiedDomains + superAdmins) once signed in
  React.useEffect(() => {
    if (mode !== "firebase" || authStage !== "signed-in") return;
    try {
      const db = firebase.firestore();
      const unsub = db.collection("clubs").doc(window.FIREBASE.bootstrapClub.id).onSnapshot((d) => {
        const c = d.exists ? { id: d.id, ...d.data() } : null;
        setClub(c);
        if (c && c.name) { try { window.localStorage.setItem("rotary_org_name", c.name); } catch (e) {} }
        PD.setLabels(c && c.labels && c.labels.length ? c.labels : PD.DEFAULT_LABELS);
      }, () => {});
      return unsub;
    } catch (e) {}
  }, [mode, authStage]);
  // SPIKE 2: stores other than Firebase hand the club over directly (the only
  // change to app.jsx; the Firebase read above should move into its store too).
  React.useEffect(() => {
    if (!store.club) return;
    setClub(store.club);
    PD.setLabels(store.club.labels && store.club.labels.length ? store.club.labels : PD.DEFAULT_LABELS);
  }, [store.club]);

  const [openTaskId, setOpenTaskId] = React.useState(null);
  const [dialog, setDialog] = React.useState(null);
  const [projMenu, setProjMenu] = React.useState(false);
  const [switchOpen, setSwitchOpen] = React.useState(false);
  const [idMenu, setIdMenu] = React.useState(false);
  const [search, setSearch] = React.useState("");
  const [ownerFilter, setOwnerFilter] = React.useState(() => new Set());
  const [myOnly, setMyOnly] = React.useState(false);
  const [toast, setToast] = React.useState(null);
  const toastTimer = React.useRef(null);
  const [reqBusy, setReqBusy] = React.useState(false);

  function showToast(msg, undo) { clearTimeout(toastTimer.current); setToast({ msg, undo }); toastTimer.current = setTimeout(() => setToast(null), 5000); }

  /* ---- gates: auth + loading ---- */
  if (authStage === "loading") return <Splash label="Connecting…" />;
  if (authStage === "signed-out") return <SignIn onSignIn={store.signIn} error={store.authError} store={store} />;
  if (authStage === "pending") return <GateScreen user={user} store={store} tone="wait"
    title="Awaiting approval" body="You've signed in, but a project admin needs to approve your access. You'll get an email once you're approved — then just sign in again." />;
  if (authStage === "no-access") return <GateScreen user={user} store={store} tone="err"
    title="No access yet" body="This account isn't a member of the club and hasn't been invited to a project. Ask a project admin to invite this email address, then sign in again." />;
  if (!store.ready || !data.projects) return <Splash label="Loading your board…" />;

  const project = data.projects.find((p) => p.id === data.currentId) || data.projects[0];

  /* empty-state: no projects yet */
  if (!project) {
    return (
      <div className="app" style={{ "--brand": t.brand }} data-density={t.density}>
        <Header store={store} project={null} isAdmin={false} club={club} onNewProject={() => setDialog({ type: "newproj" })}
          switchOpen={switchOpen} setSwitchOpen={setSwitchOpen} idMenu={idMenu} setIdMenu={setIdMenu}
          projMenu={projMenu} setProjMenu={setProjMenu} setCurrentId={setCurrentId} setDialog={setDialog} duplicateProject={() => {}} />
        <div className="app-main"><div className="empty-board">
          <h3>No projects yet</h3>
          <p style={{ margin: 0, color: "var(--muted)" }}>Create your first project to start planning.</p>
          <button className="btn primary" onClick={() => setDialog({ type: "newproj" })}><Icon.Plus s={16} /> New project</button>
        </div>
        {dialog?.type === "newproj" && <NameDialog title="New project" label="Project name" initial="" confirmLabel="Create project" hint="Starts with the five default stages — and you as its admin." onConfirm={(name) => { actions.newProject(name); setDialog(null); }} onClose={() => setDialog(null)} />}
        </div>
        <TweaksPanelUI t={t} setTweak={setTweak} />
      </div>
    );
  }

  const pid = project.id;
  const isAdmin = Perms.isAdmin(user, project);
  const isContributor = Perms.isContributor(user, project);
  const hasRequested = (project.contributorRequests || []).includes(user.id);
  async function requestAccess() {
    if (reqBusy || hasRequested) return;
    setReqBusy(true);
    try { await actions.requestContributorAccess(pid); showToast("Contributor access requested — the project admin has been notified."); }
    catch (e) { showToast("Could not send request: " + (e && e.message ? e.message : e)); }
    finally { setReqBusy(false); }
  }

  /* ---- task ops ---- */
  function deleteTask(id) {
    const task = project.tasks.find((x) => x.id === id);
    setOpenTaskId(null);
    actions.deleteTask(pid, id);
    showToast("Task deleted", task ? () => actions.reAddTask(pid, task) : null);
  }
  function deleteStage(stageId) {
    const count = project.tasks.filter((tk) => tk.stageId === stageId).length;
    if (count === 0) actions.deleteStage(pid, stageId);
    else setDialog({ type: "confirm", title: "Delete stage?", body: `This stage has ${count} task${count > 1 ? "s" : ""}. Deleting it will remove ${count > 1 ? "them" : "it"} too.`, confirmLabel: "Delete stage", danger: true, onConfirm: () => { actions.deleteStage(pid, stageId); setDialog(null); } });
  }
  function duplicateProject() { actions.duplicateProject(pid); setProjMenu(false); showToast("Duplicated as a fresh template — members & dates cleared"); }
  function deleteProject() { setDialog({ type: "confirm", title: "Delete project?", body: `“${project.name}” and all its tasks will be removed.`, confirmLabel: "Delete project", danger: true, onConfirm: () => { actions.deleteProject(pid); setDialog(null); setProjMenu(false); } }); }

  /* ---- filtering ---- */
  const filtering = search.trim() || ownerFilter.size > 0 || myOnly;
  function matches(tk) {
    if (myOnly && !(tk.members || []).includes(user.id)) return false;
    if (ownerFilter.size > 0) {
      const ms = tk.members || [];
      if (!(ms.some((m) => ownerFilter.has(m)) || (ms.length === 0 && ownerFilter.has("none")))) return false;
    }
    if (search.trim()) {
      const q = search.toLowerCase();
      const names = uByIds(tk.members).map((m) => m.name).join(" ");
      const hay = (tk.title + " " + tk.desc + " " + tk.labels.map((id) => lById(id)?.name || "").join(" ") + " " + names).toLowerCase();
      if (!hay.includes(q)) return false;
    }
    return true;
  }
  const viewProject = filtering ? { ...project, tasks: project.tasks.filter(matches) } : project;

  /* ---- progress ---- */
  const lastStage = project.stages[project.stages.length - 1];
  const total = project.tasks.length;
  const done = lastStage ? project.tasks.filter((tk) => tk.stageId === lastStage.id).length : 0;
  const pct = total ? Math.round(done / total * 100) : 0;
  const myCount = project.tasks.filter((tk) => (tk.members || []).includes(user.id)).length;
  const openTask = openTaskId ? project.tasks.find((tk) => tk.id === openTaskId) : null;
  function toggleOwner(key) { setOwnerFilter((s) => { const n = new Set(s); n.has(key) ? n.delete(key) : n.add(key); return n; }); }

  // Owner filter shows only people on this project — same rule as the task Members picker.
  const filterPeople = PD.projectMembers(project);

  return (
    <div className="app" style={{ "--brand": t.brand }} data-density={t.density}>
      <Header store={store} project={project} isAdmin={isAdmin} club={club} duplicateProject={duplicateProject}
        switchOpen={switchOpen} setSwitchOpen={setSwitchOpen} idMenu={idMenu} setIdMenu={setIdMenu}
        projMenu={projMenu} setProjMenu={setProjMenu} setCurrentId={setCurrentId} setDialog={setDialog}
        pendingCount={(store.pendingApprovals || []).length + (project.contributorRequests || []).length} onPeople={() => setDialog({ type: "people" })}
        onNewProject={() => setDialog({ type: "newproj" })} onDeleteProject={deleteProject} />
      <div className="app-main">

      {window.CCRoomNote && <window.CCRoomNote app="Tasks" style={{ margin: "12px 16px 0", maxWidth: "none" }} />}

      {/* Toolbar */}
      <div className="toolbar">
        <div className="search">
          <Icon.Search s={16} />
          <input placeholder="Search tasks…" value={search} onChange={(e) => setSearch(e.target.value)} />
        </div>
        <button className={"chip-toggle" + (myOnly ? " on" : "")} onClick={() => setMyOnly((v) => !v)}>
          <Icon.User s={15} /> My tasks <span className="ct-count">{myCount}</span>
        </button>
        <div className="filt-grp">
          <span className="filt-lbl">Owner</span>
          {filterPeople.map((m) => (
            <button key={m.id} className={"av-toggle" + (ownerFilter.has(m.id) ? " on" : "") + (activeUids.has(m.id) ? " active" : "")}
              onClick={() => toggleOwner(m.id)} title={activeUids.has(m.id) ? m.name + " · active now" : m.name}>
              <AvA member={m} size="sm" active={activeUids.has(m.id)} />
            </button>
          ))}
          <button className={"av-toggle" + (ownerFilter.has("none") ? " on" : "")} onClick={() => toggleOwner("none")} title="Unassigned">
            <AvA member={null} size="sm" />
          </button>
          {(ownerFilter.size > 0 || myOnly) && <button className="btn ghost" style={{ padding: "5px 9px", fontSize: 12.5 }} onClick={() => { setOwnerFilter(new Set()); setMyOnly(false); }}>Clear</button>}
        </div>
        <div className="tb-right">
          {!isAdmin && !isContributor && (
            <button className="btn ghost" disabled={hasRequested || reqBusy} onClick={requestAccess}>
              {hasRequested ? "Access requested" : (reqBusy ? "Requesting…" : "Request contributor access")}
            </button>
          )}
          <div className="progress-wrap">
            <span>{done} of {total} complete</span>
            <span className="progress-bar"><i style={{ width: pct + "%" }} /></span>
          </div>
        </div>
      </div>

      {/* Board */}
      <Board
        project={viewProject} user={user} showAvatars={t.showAvatars}
        onOpenTask={setOpenTaskId}
        onAddTask={(stageId, title) => actions.addTask(pid, stageId, title)}
        onMoveTask={(id, stageId, index) => actions.moveTask(pid, id, stageId, index)}
        onRenameStage={(sid, name) => actions.renameStage(pid, sid, name)}
        onReorderStage={(sid, index) => actions.reorderStage(pid, sid, index)}
        onDeleteStage={deleteStage} onAddStage={() => actions.addStage(pid)}
      />

      {/* Modals */}
      {openTask && (
        <TaskModal task={openTask} project={project} user={user}
          onUpdate={(id, patch) => actions.updateTask(pid, id, patch)}
          onMoveStage={(id, stageId) => actions.moveTask(pid, id, stageId, 1e9)}
          onDelete={deleteTask} onClose={() => setOpenTaskId(null)} />
      )}
      {dialog?.type === "newproj" && (
        <NameDialog title="New project" label="Project name" initial="" confirmLabel="Create project"
          hint="Starts with the five default stages, no tasks — and you as its admin." onConfirm={(name) => { actions.newProject(name); setDialog(null); }} onClose={() => setDialog(null)} />
      )}
      {dialog?.type === "renameproj" && (
        <NameDialog title="Rename project" label="Project name" initial={project.name} confirmLabel="Save" onConfirm={(name) => { actions.renameProject(pid, name); setDialog(null); }} onClose={() => setDialog(null)} />
      )}
      {dialog?.type === "admins" && (
        <AdminsDialog project={project} onToggle={(mid) => actions.toggleAdmin(pid, mid)} onClose={() => setDialog(null)} />
      )}
      {dialog?.type === "people" && (
        <MembersDialog project={project} club={club} store={store} onOpenActivity={() => setDialog({ type: "activity", scope: project })} onClose={() => setDialog(null)} />
      )}
      {dialog?.type === "renameclub" && (
        <NameDialog title="Rename organisation" label="Organisation name" initial={orgName(club)} confirmLabel="Save"
          hint="Shown in the header and on the sign-in screen for everyone in the club." onConfirm={(name) => { actions.renameClub(name); setDialog(null); }} onClose={() => setDialog(null)} />
      )}
      {dialog?.type === "clubsettings" && (
        <ClubSettingsDialog club={club} store={store} onOpenActivity={() => setDialog({ type: "activity", scope: null })} onOpenMembers={() => setDialog({ type: "membersconsole" })} onOpenApprovals={() => setDialog({ type: "clubapprovals" })} onClose={() => setDialog(null)} />
      )}
      {dialog?.type === "membersconsole" && (
        <MembersConsoleDialog club={club} store={store} onClose={() => setDialog(null)} />
      )}
      {dialog?.type === "clubapprovals" && (
        <ClubApprovalsDialog store={store} projects={data.projects} onClose={() => setDialog(null)} />
      )}
      {dialog?.type === "activity" && (
        <ActivityDialog store={store} scopeProject={dialog.scope} onClose={() => setDialog(null)} />
      )}
      {dialog?.type === "confirm" && (
        <ConfirmDialog title={dialog.title} body={dialog.body} confirmLabel={dialog.confirmLabel} danger={dialog.danger} onConfirm={dialog.onConfirm} onClose={() => setDialog(null)} />
      )}

      {/* Toast */}
      {toast && (
        <div className="toast">
          <span>{toast.msg}</span>
          {toast.undo && <button className="undo" onClick={() => { toast.undo(); setToast(null); }}>Undo</button>}
        </div>
      )}

      </div>
      <TweaksPanelUI t={t} setTweak={setTweak} />
    </div>
  );
}

/* ---------- Header (shared) ---------- */
function Header({ store, project, isAdmin, club, duplicateProject, switchOpen, setSwitchOpen, idMenu, setIdMenu, projMenu, setProjMenu, setCurrentId, setDialog, onNewProject, onDeleteProject, onPeople, pendingCount = 0 }) {
  // Clubcraft's standard app menu (appmenu.jsx): the project switcher on top, the project's actions as menu items.
  const { user, data } = store;
  const projects = data.projects;
  const M = window.CCAppMenu, I = window.CCMenuIcons;
  const top = (
    <div>
      <button onClick={() => setSwitchOpen((v) => !v)} aria-expanded={!!switchOpen}
        style={{ width: "100%", display: "flex", alignItems: "center", gap: 8, border: "1px solid var(--line)", borderRadius: 8, padding: "8px 10px", background: "#fff", color: "var(--ink)", cursor: "pointer", textAlign: "left" }}>
        <span style={{ flex: 1, minWidth: 0 }}>
          <span style={{ display: "block", font: "700 10px var(--font, 'Public Sans')", color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".06em" }}>Project</span>
          <span style={{ display: "block", fontWeight: 700, fontSize: 13.5, color: "var(--ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{project ? project.name : "No project"}</span>
        </span>
        <span style={{ color: "var(--muted)", display: "grid" }}><Icon.Chevron s={14} /></span>
      </button>
      {project && project.source && <div style={{ marginTop: 6, display: "inline-block", font: "700 11px var(--font, sans-serif)", padding: "2px 8px", borderRadius: 999, background: "var(--b-wash, #EAF0F1)", color: "var(--b-primary-deep, #16536B)" }} title={"This project was made from an " + project.source.type + " plan. Open " + project.source.type + " to see the plan."}>From the {project.source.type} plan</div>}
      {switchOpen && (
        <div style={{ marginTop: 4, border: "1px solid var(--line)", borderRadius: 8, padding: 4, background: "#fff" }}>
          {projects.map((p) => (
            <button key={p.id} className={"menu-item" + (project && p.id === project.id ? " active" : "")} onClick={() => { setCurrentId(p.id); setSwitchOpen(false); }}>
              <span className="ic"><Icon.Folder s={16} /></span>
              <span className="mi-name">{p.name}{Perms.isAdmin(user, p) && <span className="mi-badge">Admin</span>}</span>
              <small>{p.tasks.length}</small>
            </button>
          ))}
        </div>
      )}
    </div>
  );
  const only = projects.length <= 1;
  const groups = [
    { label: "Project", items: [
      { key: "board", label: "Board", icon: I.board, onClick: () => setSwitchOpen(false), hidden: !project },
      { key: "people", label: "People and invites", icon: I.team, onClick: onPeople, hidden: !project, badge: pendingCount || null },
      { key: "rename", label: "Rename project", icon: I.edit, onClick: () => setDialog({ type: "renameproj" }), hidden: !isAdmin },
      { key: "admins", label: "Manage admins", icon: I.shield, onClick: () => setDialog({ type: "admins" }), hidden: !isAdmin },
      { key: "duplicate", label: "Duplicate as template", icon: I.copy, onClick: duplicateProject, hidden: !isAdmin, title: "Duplicate this project as a fresh template" },
      { key: "delete", label: "Delete project", icon: I.trash, onClick: onDeleteProject, hidden: !isAdmin, disabled: only, title: only ? "A club needs at least one project" : undefined } ] },
    { label: "Club", items: [
      { key: "new", label: "New project", icon: I.add, onClick: onNewProject },
      { key: "settings", label: "Club settings", icon: I.setup, onClick: () => setDialog({ type: "clubsettings" }), hidden: !(Perms.isSuper && Perms.isSuper(user)) } ] }
  ];
  return <M title="Tasks" icon={I.board} top={top} groups={groups} active={project ? "board" : null} />;
}

/* ---------- Tweaks ---------- */
function TweaksPanelUI({ t, setTweak }) {
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Brand" />
      <TweakColor label="Accent color" value={t.brand} options={BRAND_OPTS} onChange={(v) => setTweak("brand", v)} />
      <TweakSection label="Board" />
      <TweakRadio label="Card density" value={t.density} options={["compact", "roomy"]} onChange={(v) => setTweak("density", v)} />
      <TweakToggle label="Show owner avatars" value={t.showAvatars} onChange={(v) => setTweak("showAvatars", v)} />
      <div className="tweak-tip">Tip: double-click a column title to rename a stage (admins only).</div>
    </TweaksPanel>
  );
}

// Clubcraft: the shell (shell.jsx) renders App once a club with Tasks is chosen.
window.PlannerApp = App;
