/* catalyst-store.jsx: Clubcraft Tasks store. Same interface as Project Planner's
 * useFirebaseStore, so app.jsx / board.jsx / modals.jsx run unchanged.
 *  - Data: GET /board from cc_api for the club the shell chose (window.CC_ACTIVE_CLUB).
 *    Each action is applied optimistically, sent, then the board is re-fetched
 *    (which also rolls back anything the server refused).
 *  - Live refresh: polls the current project's public Stratus marker every 5 s
 *    while the tab is visible.
 *  - Sign-in, club choice, invitations and club admin live in shell.jsx.
 */
(function () {
  const PDc = window.PlannerData;
  const API = window.ClubcraftApi;
  const POLL_MS = 5000;
  const GAP = 1024;
  const changed = () => window.dispatchEvent(new Event("cc-club-changed"));   // the shell re-reads the trial allowance (projects used)

  /* View-only users (a Tasks view-only place, or the $1 extra view-only) see
   * the board but get no edit controls. The server enforces the same rules. */
  const P = window.Auth.Perms, orig = { ...P };
  const edits = (u) => !u || u.tasksAccess === "edit";
  P.isAdmin = (u, p) => edits(u) && orig.isAdmin(u, p);
  P.isContributor = (u, p) => edits(u) && orig.isContributor(u, p);
  P.canCreateTask = (u, p) => edits(u) && orig.canCreateTask(u, p);
  P.canEditTask = (u, p, t) => edits(u) && orig.canEditTask(u, p, t);
  P.canManageProject = (u, p) => edits(u) && orig.canManageProject(u, p);
  P.canCreateProjects = (u) => edits(u) && (!u || u.clubRole === "super-admin" || u.clubAccess !== "projects");
  P.isSuper = () => false;   // Planner's club dialogs are replaced by the shell's Club tab

  function orderBetween(a, b) {
    if (a == null && b == null) return GAP;
    if (a == null) return b - GAP;
    if (b == null) return a + GAP;
    return (a + b) / 2;
  }
  const byOrder = (a, b) => (a.order ?? 0) - (b.order ?? 0);
  const STUB = { ok: false, msg: "Use the Club tab to invite people." };

  function useCatalystStore() {
    const club = window.CC_ACTIVE_CLUB;
    const curKey = "cc_current_" + club;
    const [authStage, setAuthStage] = React.useState("loading");
    const [authError, setAuthError] = React.useState(null);
    const [user, setUser] = React.useState(null);
    const [board, setBoard] = React.useState(null);
    const [currentId, setCurrentIdState] = React.useState(() => { try { return localStorage.getItem(curKey) || null; } catch (e) { return null; } });
    const markerSeen = React.useRef({});
    const inflight = React.useRef(0);

    async function api(method, path, body) {
      inflight.current++;
      try { return await API.call(method, path, body, { club }); }
      finally { inflight.current--; }
    }

    async function load() {
      const b = await api("GET", "/board");
      const decorate = (m) => ({ ...m, initials: m.initials || PDc.initialsFrom(m.name, m.email), color: m.color || PDc.colorFor(m.id) });
      const members = b.members.map(decorate);
      PDc.setMembers(members);
      setUser(decorate({ ...b.user, ...(members.find((m) => m.id === b.user.id) || {}), ...b.user }));
      setBoard({ members, club: b.club, projects: b.projects });
      b.projects.forEach((p) => {
        if (p.markerUrl) markerSeen.current[p.markerUrl] = Math.max(markerSeen.current[p.markerUrl] || 0, b.serverNow || 0);
      });
      return b;
    }
    const refresh = () => load().catch((e) => console.error("refresh failed:", e.message));

    React.useEffect(() => {
      let alive = true;
      load().then(() => { if (alive) setAuthStage("signed-in"); }).catch((e) => {
        if (!alive) return;
        setAuthError(e.message);
        setAuthStage(e.status === 401 ? "signed-out" : "no-access");
      });
      return () => { alive = false; };
    }, []);

    const projects = board ? board.projects : [];
    const resolvedCurrent = projects.find((p) => p.id === currentId) ? currentId : (projects[0] && projects[0].id) || null;
    const markerUrl = (projects.find((p) => p.id === resolvedCurrent) || {}).markerUrl;
    React.useEffect(() => {
      if (authStage !== "signed-in" || !markerUrl) return;
      let stopped = false;
      const tick = async () => {
        if (stopped || document.visibilityState === "hidden" || inflight.current > 0) return;
        try {
          const r = await fetch(markerUrl, { cache: "no-store" });
          if (!r.ok) return;
          const { changedAt } = await r.json();
          const seen = markerSeen.current[markerUrl];
          markerSeen.current[markerUrl] = changedAt;
          if (seen && changedAt > seen) refresh();
        } catch (e) { /* offline: next tick */ }
      };
      tick();
      const iv = setInterval(tick, POLL_MS);
      const onVis = () => { if (document.visibilityState === "visible") tick(); };
      document.addEventListener("visibilitychange", onVis);
      return () => { stopped = true; clearInterval(iv); document.removeEventListener("visibilitychange", onVis); };
    }, [authStage, markerUrl]);

    const proj = (pid) => projects.find((p) => p.id === pid);
    const patchLocal = (pid, fn) => setBoard((b) => b && ({ ...b, projects: b.projects.map((p) => p.id === pid ? fn(p) : p) }));
    const tasksIn = (pid, sid) => ((proj(pid) || {}).tasks || []).filter((t) => t.stageId === sid).sort(byOrder);
    const send = (method, path, body) => api(method, path, body)
      .catch((e) => { console.error("[cc]", method, path, "failed:", e.message); window.dispatchEvent(new CustomEvent("cc-error", { detail: e.message })); })
      .finally(refresh);
    const patchProject = (pid, upd) => { patchLocal(pid, (p) => ({ ...p, ...upd })); return send("PATCH", "/projects/" + pid, upd); };
    const patchTask = (pid, id, patch) => {
      patchLocal(pid, (p) => ({ ...p, tasks: p.tasks.map((t) => t.id === id ? { ...t, ...patch } : t) }));
      return send("PATCH", "/tasks/" + id, { patch });
    };
    const blankTask = (stageId, title) => ({ stageId, title, members: [], due: null, labels: [], prio: "none", desc: "", budget: null, vols: null, remind: -2, completedAt: null, check: [] });

    const actions = {
      updateTask: (pid, id, patch) => patchTask(pid, id, "due" in patch ? { ...patch, remLog: {} } : patch),
      addTask: (pid, stageId, title) => {
        const items = tasksIn(pid, stageId);
        const task = { ...blankTask(stageId, title), order: orderBetween(items.length ? items[items.length - 1].order : null, null) };
        patchLocal(pid, (p) => ({ ...p, tasks: [...p.tasks, { ...task, id: "tmp_" + Date.now() }] }));
        return send("POST", "/projects/" + pid + "/tasks", { task });
      },
      moveTask: (pid, id, toStageId, index) => {
        const p = proj(pid); if (!p) return;
        const items = tasksIn(pid, toStageId).filter((t) => t.id !== id);
        const before = items[index - 1], after = items[index];
        const patch = { stageId: toStageId, order: orderBetween(before ? before.order : null, after ? after.order : null) };
        const lastId = p.stages.length ? p.stages[p.stages.length - 1].id : null;
        const tk = p.tasks.find((t) => t.id === id);
        if (lastId && tk) {
          if (toStageId === lastId && !tk.completedAt) patch.completedAt = Date.now();
          else if (toStageId !== lastId && tk.completedAt) patch.completedAt = null;
        }
        return patchTask(pid, id, patch);
      },
      deleteTask: (pid, id) => {
        patchLocal(pid, (p) => ({ ...p, tasks: p.tasks.filter((t) => t.id !== id) }));
        return send("DELETE", "/tasks/" + id);
      },
      reAddTask: (pid, task) => { const { id, projectId, ...rest } = task; return send("POST", "/projects/" + pid + "/tasks", { task: rest }); },
      renameStage: (pid, sid, name) => { const p = proj(pid); if (p) return patchProject(pid, { stages: p.stages.map((s) => s.id === sid ? { ...s, name } : s) }); },
      addStage: (pid) => { const p = proj(pid); if (p) return patchProject(pid, { stages: [...p.stages, { id: PDc.uid("s_"), name: "New Stage" }] }); },
      reorderStage: (pid, sid, index) => {
        const p = proj(pid); if (!p) return;
        const moved = p.stages.find((s) => s.id === sid); if (!moved) return;
        const stages = p.stages.filter((s) => s.id !== sid);
        stages.splice(Math.max(0, Math.min(index, stages.length)), 0, moved);
        return patchProject(pid, { stages });
      },
      deleteStage: (pid, sid) => {
        patchLocal(pid, (p) => ({ ...p, stages: p.stages.filter((s) => s.id !== sid), tasks: p.tasks.filter((t) => t.stageId !== sid) }));
        return send("POST", "/projects/" + pid + "/delete-stage", { stageId: sid });
      },
      toggleAdmin: (pid, mid) => {
        const p = proj(pid); if (!p) return; const a = p.admins || []; const c = p.contributors || [];
        if (a.includes(mid)) { if (a.length <= 1) return; return patchProject(pid, { admins: a.filter((x) => x !== mid) }); }
        if (a.length >= 2) return;
        return patchProject(pid, { admins: [...a, mid], contributors: c.filter((x) => x !== mid) });
      },
      toggleContributor: (pid, mid) => {
        const p = proj(pid); if (!p) return; const a = p.admins || []; const c = p.contributors || [];
        if (c.includes(mid)) return patchProject(pid, { contributors: c.filter((x) => x !== mid) });
        return patchProject(pid, { contributors: [...c, mid], ...(a.includes(mid) && a.length > 1 ? { admins: a.filter((x) => x !== mid) } : {}) });
      },
      newProject: async (name) => {
        const r = await api("POST", "/projects", { name, stages: PDc.defaultStages() });
        setCurrentId(r.id); await refresh(); changed(); return r.id;
      },
      renameProject: (pid, name) => patchProject(pid, { name }),
      duplicateProject: async (pid) => {
        const src = proj(pid); if (!src) return;
        const tmpl = PDc.duplicateProjectTemplate(src);
        const r = await api("POST", "/projects", { name: tmpl.name, stages: tmpl.stages, tasks: tmpl.tasks.map(({ id, projectId, ...t }, i) => ({ ...t, order: (i + 1) * GAP })) });
        setCurrentId(r.id); await refresh(); changed(); return r.id;
      },
      deleteProject: (pid) => {
        setBoard((b) => b && ({ ...b, projects: b.projects.filter((p) => p.id !== pid) }));
        return send("DELETE", "/projects/" + pid).then(changed);
      },
      addMemberToProject: (pid, uid) => { const p = proj(pid); if (p) return patchProject(pid, { memberUids: Array.from(new Set([...(p.memberUids || []), uid])) }); },
      removeMemberFromProject: (pid, uid) => { const p = proj(pid); if (p) return patchProject(pid, { memberUids: (p.memberUids || []).filter((x) => x !== uid) }); },
      reassignMemberTasks: async (pid, fromUid, toUid) => {
        const p = proj(pid); if (!p) return;
        for (const tk of p.tasks.filter((t) => (t.members || []).includes(fromUid))) {
          const m = tk.members.filter((x) => x !== fromUid);
          if (toUid && !m.includes(toUid)) m.push(toUid);
          await api("PATCH", "/tasks/" + tk.id, { patch: { members: m } });
        }
        return refresh();
      },
      setClubLabels: (labels) => { PDc.setLabels(labels); return send("PUT", "/club/labels", { labels }); },

      /* handled by the shell's Club tab */
      inviteToProject: async () => STUB, inviteGuestToProjects: async () => STUB, setInviteProjects: async () => {},
      approveInvite: async () => {}, declineInvite: async () => {}, resendInvite: async () => STUB,
      requestContributorAccess: async () => {}, approveContributorRequest: async () => {}, declineContributorRequest: async () => {},
      renameClub: () => {}, setSuperAdmins: () => {}, setMemberAccess: () => {}, setMemberStatus: () => {}, removeMember: async () => {},
      loadActivity: async () => [],
      restore: null, snapshot: () => null,
    };

    function setCurrentId(id) { try { localStorage.setItem(curKey, id); } catch (e) {} setCurrentIdState(id); }

    return {
      mode: "catalyst",
      ready: authStage !== "signed-in" || !!board,
      authStage, user, authError,
      members: board ? board.members : [], club: board ? board.club : null,
      invites: [], pendingApprovals: [], presentUids: user ? [user.id] : [],
      signIn: async () => API.signIn(),
      sendEmailLink: async () => { throw new Error("Use the sign-in button."); },
      signOut: async () => API.signOut(),
      data: { projects, currentId: resolvedCurrent }, setCurrentId, actions,
    };
  }

  window.usePlannerStore = useCatalystStore;
})();
