/* social-store.jsx: Clubcraft Social store. Same interface as Plan Social's useFirebaseSocialStore ({ state, actions, ... }), so
 * social-app.jsx runs as ported. Data comes from cc_api (routes/social.js):
 *  - GET /club/social lists the campaigns I can see, then GET /club/social/:id loads each document.
 *  - Every edit is applied to the screen straight away, then sent as ops (one at a time per campaign, so they stay in order).
 *    The reply carries the new item revisions; a refusal or conflict reloads that campaign.
 *  - Live refresh: polls the open campaign's public Stratus marker every 5 s while the tab is visible.
 * Sign-in, club choice and invitations live in shell.jsx.
 */
(function () {
  const API = window.ClubcraftApi;
  const SD = window.SocialData;
  const POLL_MS = 5000;
  const ROLE_UP = { read: "Read", write: "Write", action: "Action", admin: "Admin" };
  const ROLE_DOWN = { Read: "read", Write: "write", Action: "action", Admin: "admin" };
  const COLOURS = ["#1E6E8C", "#DE7A3B", "#2F7A4F", "#4A3F8C", "#9A5A12", "#A23B2C", "#16536B", "#726A60"];
  const rnd = () => Math.random().toString(36).slice(2, 5);
  const note = (detail) => window.dispatchEvent(new CustomEvent("cc-error", { detail }));
  const colourFor = (id) => COLOURS[Number(String(id).slice(-3)) % COLOURS.length];
  const initialsOf = (name) => String(name || "?").trim().split(/\s+/).map((w) => w[0]).join("").toUpperCase().slice(0, 2) || "?";

  /* ---------- building campaigns (same shapes as Plan Social) ---------- */

  function newPost(weekId, postNo, dayOffset, platforms) {
    return {
      id: weekId + "p" + postNo + "_" + rnd(), weekId, postNo, dayOffset, status: "draft", draftCaption: "", mediaBrief: "", mediaFileLink: "",
      reviewerNotes: "", updatedBy: "", imageStyle: "", generatedImageUrl: "", platforms: platforms || { facebook: true, instagram: false }
    };
  }

  // The starting scaffold: four fixed pillars, `numWeeks` weeks, one post per preferred day.
  function blankCampaign(name, numWeeks, days, perDay) {
    const pillars = SD.defaultPillars();
    const ppd = Math.max(1, Math.min(3, parseInt(perDay) || 1));
    const prefDays = Array.isArray(days) && days.length ? [...new Set(days.map(Number).filter((d) => d >= 0 && d <= 6))].sort((a, b) => a - b) : [1, 4];
    const weeks = [], posts = [];
    for (let i = 0; i < (numWeeks || 4); i++) {
      const wid = "w" + i + "_" + rnd();
      weeks.push({ id: wid, idx: i, pillarId: pillars[i % pillars.length].id, topicAndAngle: "", referenceUrl: "" });
      let no = 0;
      for (let k = 0; k < prefDays.length; k++) for (let j = 0; j < ppd; j++) posts.push(newPost(wid, ++no, prefDays[k], { facebook: false, instagram: false }));
    }
    // Posts need dates to appear on the calendar: start on the next Monday until Setup says otherwise.
    const d = new Date(); d.setDate(d.getDate() + ((8 - d.getDay()) % 7 || 7));
    const start = d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
    return {
      config: {
        eventName: name, campaignStart: start, facebookPage: "", facebookPageId: "", instagramAccountId: "", preferredDays: prefDays, postsPerDay: ppd,
        beneficiaries: [], sponsors: [], referenceDocs: [], pillars, branding: SD.blankBranding()
      },
      weeks, posts
    };
  }

  /* From a finished Comms plan: its weeks become the campaign weeks (topic and pillar kept), with the planned number of posts
   * spread across each week. `eventDate` (YYYY-MM-DD) anchors the first week; without it the start date is left for Setup. */
  const PILLAR_MAP = { event: "p_event", impact: "p_support", involved: "p_tips", story: "p_story" };
  const dayFor = (n, k) => Math.min(6, Math.floor(((k + 0.5) * 7) / Math.max(1, n)));
  function fromCommsPlan(plan, eventDate, name) {
    const base = blankCampaign(name || (plan.campaign && plan.campaign.name) || "Campaign", 1);
    const pillars = base.config.pillars.map((p) => {
      const key = Object.keys(PILLAR_MAP).find((k) => PILLAR_MAP[k] === p.id);
      const given = (plan.pillars || []).find((x) => x.key === key);
      return { ...p, description: given ? given.focus || "" : "" };
    });
    const sorted = (plan.weeks || []).slice().sort((a, b) => b.weeks_out - a.weeks_out);
    const weeks = [], posts = [];
    sorted.forEach((w, i) => {
      const wid = "w" + i + "_" + rnd(), n = Math.max(1, Math.min(7, w.posts || 2));
      weeks.push({ id: wid, idx: i, pillarId: PILLAR_MAP[w.pillar] || pillars[i % 4].id, topicAndAngle: w.topic || "", referenceUrl: "", commsReference: w.reference || "" });
      for (let k = 0; k < n; k++) posts.push(newPost(wid, k + 1, dayFor(n, k), { facebook: false, instagram: false }));
    });
    let start = "";
    if (/^\d{4}-\d{2}-\d{2}$/.test(eventDate || "") && sorted.length) {
      const d = new Date(eventDate + "T00:00:00");
      d.setDate(d.getDate() - 7 * sorted[0].weeks_out);
      start = d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
    }
    const lines = [];
    if (plan.goal) lines.push("Goal: " + plan.goal);
    if (plan.voice) lines.push("Voice: " + plan.voice);
    (plan.audiences || []).forEach((a) => lines.push("Audience: " + a.who + (a.message ? ": " + a.message : "")));
    (plan.key_messages || []).forEach((m) => lines.push("Key message: " + m));
    return { config: { ...base.config, pillars, campaignStart: start, moreInfo: lines.join("\n") }, weeks, posts };
  }
  window.CCSocialSeed = { fromCommsPlan, blankCampaign, newPost };

  /* An Events plan's promotion step says when in words ("6 weeks before", "day of", "2 days after"). Returns days before the
   * event (negative = after), or null when it cannot be read. */
  function whenToDays(when) {
    const t = String(when || "").toLowerCase();
    const after = /after|following|follow-up|follow up|post-event|post event|thank/.test(t);
    let m, days = null;
    if ((m = t.match(/(\d+)\s*(?:-\s*\d+\s*)?weeks?/))) days = Number(m[1]) * 7;
    else if ((m = t.match(/(\d+)\s*(?:-\s*\d+\s*)?days?/))) days = Number(m[1]);
    else if (/day before|\bthe eve\b|\beve of\b/.test(t)) days = 1;
    else if (/week before|week prior|last week/.test(t)) days = 7;
    else if (/day of|event day|on the day|on the night|during|at the event|launch day/.test(t)) days = 0;
    else if (after) days = 3;
    if (days == null) return null;
    return after && days > 0 ? -days : after ? -3 : days;
  }
  window.CCSocialSeed.whenToDays = whenToDays;

  // Setup's "Save & rebuild": works out the new weeks and posts from the draft (the same rules as Plan Social).
  function rebuild(c, draft) {
    const prefDays = draft.preferredDays && draft.preferredDays.length ? draft.preferredDays : [1, 4];
    const N = Math.max(1, Math.min(16, parseInt(draft.numWeeks) || 1));
    const PPD = Math.max(1, Math.min(3, parseInt(draft.postsPerDay) || 1));
    const slots = prefDays.flatMap((d) => Array(PPD).fill(d));          // one slot per post in a week, in day order
    const PPW = slots.length;
    const pillars = draft.pillars.length ? draft.pillars : c.config.pillars;
    let weeks = [...c.weeks], posts = [...c.posts];
    if (N < weeks.length) {
      const keep = weeks.slice(0, N), ids = new Set(keep.map((w) => w.id));
      weeks = keep; posts = posts.filter((p) => ids.has(p.weekId));
    } else {
      for (let i = weeks.length; i < N; i++) weeks.push({ id: "w" + i + "_" + rnd(), idx: i, pillarId: "", topicAndAngle: "", referenceUrl: "" });
    }
    weeks = weeks.map((w, i) => ({ ...w, pillarId: (pillars[i % pillars.length] || {}).id || w.pillarId }));
    const defaultPlatforms = { facebook: !!draft.facebookPageId, instagram: !!draft.instagramAccountId };
    weeks.forEach((w) => {
      const defaults = posts.filter((p) => p.weekId === w.id && !p.extra).sort((a, b) => (a.postNo || 0) - (b.postNo || 0));
      const maxNo = posts.filter((p) => p.weekId === w.id).reduce((m, p) => Math.max(m, p.postNo || 0), 0);
      for (let k = defaults.length; k < PPW; k++) posts.push(newPost(w.id, maxNo + 1 + (k - defaults.length), slots[k] !== undefined ? slots[k] : Math.min(6, k * 2 + 1), defaultPlatforms));
      const keepDefault = new Set(defaults.slice(0, PPW).map((p) => p.id));
      const surplus = new Set(defaults.slice(PPW).map((p) => p.id));
      posts = posts.map((p) => {
        if (p.weekId !== w.id) return p;
        if (surplus.has(p.id)) return { ...p, extra: true };
        if (!keepDefault.has(p.id)) return p;
        const idx = defaults.findIndex((x) => x.id === p.id);
        if (p.dateLocked) return p;
        return slots[idx] !== undefined ? { ...p, dayOffset: slots[idx] } : p;
      });
    });
    return {
      config: {
        ...c.config,
        eventName: draft.eventName, eventWebsite: draft.eventWebsite || "", facebookPage: draft.facebookPage,
        facebookPageId: draft.facebookPageId || "", facebookPageUrl: draft.facebookPageUrl || "", facebookPushUrl: draft.facebookPushUrl || "",
        instagramAccountId: draft.instagramAccountId || "", campaignStart: draft.campaignStart, webhookUrl: draft.webhookUrl,
        preferredDays: prefDays, postsPerDay: PPD, beneficiaries: draft.beneficiaries, sponsors: draft.sponsors, referenceDocs: draft.referenceDocs || [], pillars,
        exclusions: draft.exclusions || [], moreInfo: draft.moreInfo || "", moreInfoDocs: draft.moreInfoDocs || [],
        signOffMessage: draft.signOffMessage || "", defaultPostTime: draft.defaultPostTime || c.config.defaultPostTime || "",
        timeZone: draft.timeZone || c.config.timeZone || CCIntl.timezone(), branding: draft.branding || {}
      },
      memberRoles: draft.memberRoles || c.memberRoles, weeks, posts
    };
  }

  /* ---------- server <-> screen shapes ---------- */

  const strip = (it) => { const { rev, generating, ...rest } = it; return rest; };          // what is stored: no revision, no busy flag
  const same = (a, b) => JSON.stringify(strip(a)) === JSON.stringify(strip(b));
  // Only the keys that changed (removed keys become null, which clears them); an unchanged status must not be re-sent.
  function diff(a, b) {
    const x = strip(a), y = strip(b), out = {};
    Object.keys(y).forEach((k) => { if (JSON.stringify(x[k]) !== JSON.stringify(y[k])) out[k] = y[k]; });
    Object.keys(x).forEach((k) => { if (!(k in y)) out[k] = null; });
    delete out.id;
    return out;
  }

  function toCampaign(doc, me) {
    const c = doc.campaign;
    const memberRoles = {};
    (doc.roles || []).forEach((r) => { memberRoles[r.userId] = ROLE_UP[r.role] || "Read"; });
    memberRoles[me] = ROLE_UP[c.role] || "Read";
    return {
      id: c.id, status: c.status, version: c.version, markerUrl: c.markerUrl, requestedBy: c.createdBy, commsReportId: c.commsReportId,
      memberRoles, config: { eventName: c.name, ...(doc.config || {}) }, weeks: doc.weeks || [], posts: doc.posts || []
    };
  }

  function useCatalystSocialStore() {
    const club = window.CC_ACTIVE_CLUB;
    const [stage, setStage] = React.useState("loading");
    const [authError, setAuthError] = React.useState(null);
    const [state, setState] = React.useState({
      clubName: "", clubBrandKit: {}, clubImageStorage: {}, members: [], campaigns: [], currentCampaignId: null, currentUserId: null,
      socialSuperAdmins: [], isSocialSuperAdmin: false, canCreate: false, trial: false, platformAdmin: false, campaignIndex: [], pendingApprovals: [], myPendingRequests: [], declinedForMe: [],
      tab: "planner", plannerView: "card", filterWeek: "all", filterStatus: "all", filterPillar: "all", expanded: {}, collapsed: {}
    });
    const ref = React.useRef(state); ref.current = state;
    const all = React.useRef([]);          // every campaign I can see, whatever its status
    const markers = React.useRef({});
    const busy = React.useRef(0);
    const chains = React.useRef({});       // campaign id -> promise: edits to one campaign are sent in order
    const gen = React.useRef({ weeks: {}, posts: {} });   // local "generating" flags, never sent

    const api = async (method, path, body) => { busy.current++; try { return await API.call(method, path, body, { club }); } finally { busy.current--; } };

    // Folds the visible campaigns into the lists the screens use.
    function publish(list, extra) {
      all.current = list;
      setState((s) => {
        const me = (extra && extra.currentUserId) || s.currentUserId, admin = (extra && extra.isSocialSuperAdmin !== undefined) ? extra.isSocialSuperAdmin : s.isSocialSuperAdmin;
        const active = list.filter((c) => c.status === "active");
        const mine = list.filter((c) => c.requestedBy === me);
        const withGen = active.map((c) => ({
          ...c, weeks: c.weeks.map((w) => ({ ...w, generating: !!gen.current.weeks[w.id] })), posts: c.posts.map((p) => ({ ...p, generating: !!gen.current.posts[p.id] }))
        }));
        const cur = s.currentCampaignId === "all" || list.some((c) => c.id === s.currentCampaignId) ? s.currentCampaignId : (active[0] ? active[0].id : null);
        return {
          ...s, ...(extra || {}), campaigns: withGen, currentCampaignId: cur,
          campaignIndex: active.map((c) => ({ id: c.id, name: c.config.eventName, status: "active" })),
          pendingApprovals: admin ? list.filter((c) => c.status === "pending") : [],
          myPendingRequests: mine.filter((c) => c.status === "pending"), declinedForMe: mine.filter((c) => c.status === "declined")
        };
      });
    }

    async function loadCampaign(id, me) {
      const doc = await api("GET", "/club/social/" + id);
      if (doc.campaign.markerUrl) markers.current[doc.campaign.markerUrl] = Math.max(markers.current[doc.campaign.markerUrl] || 0, Date.now() - 2000);
      return toCampaign(doc, me);
    }

    async function loadAll() {
      const l = await api("GET", "/club/social");
      const members = l.members.map((m) => ({ id: m.id, name: m.name, email: m.email, initials: m.initials || initialsOf(m.name), avatarColor: m.color || colourFor(m.id), uid: m.id }));
      const docs = await Promise.all(l.campaigns.map((c) => loadCampaign(c.id, l.me).catch((e) => { console.error("[cc] campaign load failed:", e.message); return null; })));
      publish(docs.filter(Boolean), {
        clubName: l.clubName, clubBrandKit: l.brandKit || {}, members, currentUserId: l.me, canCreate: l.canCreate, trial: !!l.trial, platformAdmin: !!l.platformAdmin,
        isSocialSuperAdmin: !!(l.clubAdmin && l.access === "edit")
      });
    }

    async function refreshOne(id) {
      try {
        const c = await loadCampaign(id, ref.current.currentUserId);
        publish(all.current.some((x) => x.id === id) ? all.current.map((x) => (x.id === id ? c : x)) : [...all.current, c]);
      } catch (e) {
        if (e.status === 404) publish(all.current.filter((x) => x.id !== id)); else console.error("[cc] refresh failed:", e.message);
      }
    }

    React.useEffect(() => {
      let alive = true;
      loadAll().then(() => { if (alive) setStage("signed-in"); }).catch((e) => {
        if (!alive) return;
        setAuthError(e.message);
        setStage(e.status === 401 ? "signed-out" : "no-access");
      });
      return () => { alive = false; };
    }, []);

    // Live refresh: the open campaign's marker (all of them while "All Campaigns" is open).
    const watch = state.currentCampaignId === "all" ? state.campaigns : state.campaigns.filter((c) => c.id === state.currentCampaignId);
    const watchKey = watch.map((c) => c.id + "|" + c.markerUrl).join(",");
    React.useEffect(() => {
      if (stage !== "signed-in" || !watch.length) return;
      let stopped = false;
      const tick = async () => {
        if (stopped || document.visibilityState === "hidden" || busy.current > 0) return;
        for (const c of watch) {
          if (!c.markerUrl) continue;
          try {
            const r = await fetch(c.markerUrl, { cache: "no-store" });
            if (!r.ok) continue;
            const { changedAt } = await r.json();
            const seen = markers.current[c.markerUrl];
            markers.current[c.markerUrl] = changedAt;
            if (seen && changedAt > seen) refreshOne(c.id);
          } 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); };
    }, [stage, watchKey]);

    /* ---------- sending edits ---------- */

    const campaignOf = (id) => all.current.find((c) => c.id === id);
    const itemRev = (c, op) => {
      const list = op.op === "updateWeek" ? c.weeks : c.posts, it = list.find((x) => x.id === op.id);
      return it ? it.rev : undefined;
    };

    // Applies `fn` to one campaign's weeks/posts/config on screen, now.
    function local(id, fn) {
      publish(all.current.map((c) => (c.id === id ? fn(c) : c)));
    }

    function send(id, ops, after) {
      const run = async () => {
        const c = campaignOf(id);
        if (!c) return;
        const body = ops.map((o) => ((o.op === "updatePost" || o.op === "updateWeek") && itemRev(c, o) != null ? { ...o, baseRev: itemRev(c, o) } : o));
        try {
          const r = await api("POST", "/club/social/" + id + "/ops", { ops: body });
          const byId = (list) => new Map(list.map((x) => [x.id, x]));
          const w = byId(r.changed.weeks), p = byId(r.changed.posts);
          if (!r.reordered) {                            // keep what is on screen, take the new revisions
            local(id, (cc) => ({
              ...cc, version: r.version,
              weeks: cc.weeks.map((x) => (w.has(x.id) ? { ...x, rev: w.get(x.id).rev } : x)),
              posts: cc.posts.map((x) => (p.has(x.id) ? { ...x, rev: p.get(x.id).rev } : x))
            }));
          } else await refreshOne(id);
          if (after) after(r);
        } catch (e) {
          note(e.status === 409 && e.data && e.data.conflict ? "Someone else changed that just now. Their version is shown, so please make your change again." : e.message);
          await refreshOne(id);
        }
      };
      chains.current[id] = (chains.current[id] || Promise.resolve()).then(run, run);
      return chains.current[id];
    }

    const sendSettled = (path, method, body) => api(method, path, body).catch((e) => { note(e.message); throw e; });

    /* ---------- actions ---------- */

    const curId = () => ref.current.currentCampaignId;
    const persist = (patch) => {                           // a patch without the local-only busy flag
      const { generating, ...rest } = patch;
      return Object.keys(rest).length ? rest : null;
    };
    const setGen = (kind, id, on) => { if (on) gen.current[kind][id] = true; else delete gen.current[kind][id]; };

    const actions = {
      patch: (p) => setState((s) => ({ ...s, ...(typeof p === "function" ? p(s) : p) })),

      updateWeek: (weekId, patch) => {
        const id = curId();
        if ("generating" in patch) { setGen("weeks", weekId, patch.generating); }
        const rest = persist(patch);
        local(id, (c) => ({ ...c, weeks: c.weeks.map((w) => (w.id === weekId ? { ...w, ...(rest || {}) } : w)) }));
        if (rest) return send(id, [{ op: "updateWeek", id: weekId, patch: rest }]);
      },

      reorderWeeks: (orderedIds) => {
        const id = curId(), c = campaignOf(id);
        if (!c) return;
        const byId = new Map(c.weeks.map((w) => [w.id, w]));
        const weeks = orderedIds.map((wid, i) => (byId.has(wid) ? { ...byId.get(wid), idx: i } : null)).filter(Boolean);
        local(id, (cc) => ({ ...cc, weeks }));
        return send(id, [{ op: "reorderWeeks", ids: orderedIds }, ...weeks.map((w, i) => ({ op: "updateWeek", id: w.id, patch: { idx: i } }))]);
      },

      updatePost: (postId, patch) => {
        const id = curId();
        if ("generating" in patch) { setGen("posts", postId, patch.generating); }
        const rest = persist(patch);
        if (rest) rest.updatedAt = Date.now();
        local(id, (c) => ({ ...c, posts: c.posts.map((p) => (p.id === postId ? { ...p, ...(rest || {}) } : p)) }));
        if (rest) return send(id, [{ op: "updatePost", id: postId, patch: rest }]);
      },

      addPost: (weekId, dayOffset) => {
        const id = curId(), c = campaignOf(id);
        if (!c) return;
        const maxNo = c.posts.filter((p) => p.weekId === weekId).reduce((m, p) => Math.max(m, p.postNo || 0), 0);
        const plat = { facebook: !!c.config.facebookPageId, instagram: !!c.config.instagramAccountId };
        const post = { ...newPost(weekId, maxNo + 1, dayOffset, plat), extra: true, topic: "" };
        local(id, (cc) => ({ ...cc, posts: [...cc.posts, post] }));
        return send(id, [{ op: "addPost", post }]);
      },

      removePost: (postId) => {
        const id = curId(), c = campaignOf(id);
        if (!c || !c.posts.some((p) => p.id === postId && p.extra)) return;
        local(id, (cc) => ({ ...cc, posts: cc.posts.filter((p) => p.id !== postId) }));
        return send(id, [{ op: "deletePost", id: postId }]);
      },

      movePost: (campaignId, postId, weekId, dayOffset) => {
        const patch = { weekId, dayOffset, dateLocked: true };
        local(campaignId, (c) => ({ ...c, posts: c.posts.map((p) => (p.id === postId ? { ...p, ...patch } : p)) }));
        return send(campaignId, [{ op: "updatePost", id: postId, patch }]);
      },

      // Posts pulled in from an Events plan's promotion steps. Each lands in the week the step's timing points to (counted back
      // from the event date when the campaign has a start date, otherwise back from the last week), as an extra draft post with the step's
      // message as its topic. A step already pulled in is skipped, so pulling in twice is safe.
      importEventsPosts: (reportId, eventDate, items) => {
        const id = curId(), c = campaignOf(id);
        if (!c || !c.weeks.length) return { added: 0, skipped: 0 };
        const weeks = [...c.weeks].sort((a, b) => a.idx - b.idx), N = weeks.length;
        const ok = (d) => /^\d{4}-\d{2}-\d{2}$/.test(d || "");
        const dated = ok(c.config.campaignStart) && ok(eventDate);
        const have = new Set(c.posts.map((p) => p.fromEvents).filter(Boolean));
        const added = [], next = {};
        let skipped = 0;
        items.forEach((it) => {
          const key = "events:" + reportId + ":" + it.i;
          if (have.has(key)) { skipped++; return; }
          const days = whenToDays(it.when);
          let idx, day;
          if (dated && days != null) {
            const t = new Date(eventDate + "T00:00:00"); t.setDate(t.getDate() - days);
            let off = Math.round((t - new Date(c.config.campaignStart + "T00:00:00")) / 864e5);
            off = Math.max(0, Math.min(N * 7 - 1, off));
            idx = Math.floor(off / 7); day = off % 7;
          } else {
            idx = days == null ? 0 : Math.max(0, Math.min(N - 1, N - 1 - Math.ceil(Math.max(days, 0) / 7)));
            day = days != null && days <= 0 ? 0 : 1;
          }
          const w = weeks[idx];
          const base = c.posts.filter((p) => p.weekId === w.id).reduce((m, p) => Math.max(m, p.postNo || 0), 0);
          next[w.id] = (next[w.id] || 0) + 1;
          const ch = String(it.channel || "").toLowerCase();
          const plat = { facebook: /facebook|social/.test(ch) || !!c.config.facebookPageId, instagram: /instagram|social/.test(ch) || !!c.config.instagramAccountId };
          added.push({ ...newPost(w.id, base + next[w.id], day, plat), extra: true, topic: String(it.message || "").slice(0, 400), fromEvents: key, eventsChannel: String(it.channel || "").slice(0, 60), eventsWhen: String(it.when || "").slice(0, 40) });
        });
        if (added.length) {
          local(id, (cc) => ({ ...cc, posts: [...cc.posts, ...added] }));
          send(id, added.map((post) => ({ op: "addPost", post })));
        }
        return { added: added.length, skipped };
      },

      // AI drafting (week topics, captions, media briefs, draft text): Clubcraft charges credits and asks n8n; resolves to the drafted result.
      ai: (campaignId, body) => api("POST", "/club/social/" + campaignId + "/ai", body).then((r) => r.result),

      // Replaces this campaign's weeks and posts with the given ones (ids kept), e.g. from a Plan Social export.
      replaceContent: (weeks, posts) => {
        const id = curId(), c = campaignOf(id);
        if (!c) return;
        const clean = (it) => { const { generating, rev, ...rest } = it; return rest; };
        const ws = weeks.map(clean), ps = posts.map(clean);
        local(id, (cc) => ({ ...cc, weeks: ws, posts: ps }));
        return send(id, [
          ...c.posts.map((p) => ({ op: "deletePost", id: p.id })), ...c.weeks.map((w) => ({ op: "deleteWeek", id: w.id })),
          ...ws.map((week) => ({ op: "addWeek", week })), ...ps.map((post) => ({ op: "addPost", post })),
          { op: "reorderWeeks", ids: ws.slice().sort((a, b) => a.idx - b.idx).map((w) => w.id) }
        ]);
      },

      addExclusion: (campaignId, excl) => {
        const c = campaignOf(campaignId);
        if (!c) return;
        const exclusions = [...(c.config.exclusions || []), excl];
        local(campaignId, (cc) => ({ ...cc, config: { ...cc.config, exclusions } }));
        return send(campaignId, [{ op: "setConfig", patch: { exclusions } }]);
      },

      // Setup's Save & rebuild: the new campaign is worked out here, then sent as the smallest set of changes.
      saveSetup: async (draft) => {
        const id = curId(), c = campaignOf(id);
        if (!c) return;
        const next = rebuild(c, draft);
        const ops = [{ op: "setConfig", patch: next.config }];
        const haveW = new Map(c.weeks.map((w) => [w.id, w])), haveP = new Map(c.posts.map((p) => [p.id, p]));
        const wantW = new Set(next.weeks.map((w) => w.id)), wantP = new Set(next.posts.map((p) => p.id));
        c.posts.forEach((p) => { if (!wantP.has(p.id)) ops.push({ op: "deletePost", id: p.id }); });
        c.weeks.forEach((w) => { if (!wantW.has(w.id)) ops.push({ op: "deleteWeek", id: w.id }); });
        next.weeks.forEach((w) => {
          if (!haveW.has(w.id)) ops.push({ op: "addWeek", week: strip(w) });
          else if (!same(haveW.get(w.id), w)) ops.push({ op: "updateWeek", id: w.id, patch: diff(haveW.get(w.id), w) });
        });
        next.posts.forEach((p) => {
          if (!haveP.has(p.id)) ops.push({ op: "addPost", post: strip(p) });
          else if (!same(haveP.get(p.id), p)) ops.push({ op: "updatePost", id: p.id, patch: diff(haveP.get(p.id), p) });
        });
        ops.push({ op: "reorderWeeks", ids: next.weeks.map((w) => w.id) });
        local(id, (cc) => ({ ...cc, config: next.config, weeks: next.weeks, posts: next.posts }));
        await send(id, ops);
        if (c.memberRoles && JSON.stringify(c.memberRoles) !== JSON.stringify(next.memberRoles)) await actions.setRoles(id, next.memberRoles);
      },

      saveBrandKit: (brandKit) => {
        setState((s) => ({ ...s, clubBrandKit: brandKit }));
        return sendSettled("/club/social/settings", "PUT", { brandKit }).catch(() => loadAll());
      },
      saveImageStorage: () => {},
      // Reload one campaign now (after the server changed it, e.g. a publish).
      refresh: (campaignId) => refreshOne(campaignId),

      // Everyone on the club's Social licence can be given a role; this sends the whole list.
      setRoles: async (campaignId, memberRoles) => {
        const roles = Object.keys(memberRoles).map((u) => ({ userId: u, role: ROLE_DOWN[memberRoles[u]] || "read" }));
        try { await api("PUT", "/club/social/" + campaignId + "/roles", { roles }); } catch (e) { note(e.message); }
        await refreshOne(campaignId);
      },
      setMemberRole: (memberId, role) => {
        const id = curId(), c = campaignOf(id);
        if (!c) return;
        return actions.setRoles(id, { ...c.memberRoles, [memberId]: role });
      },

      // A new campaign starts from the scaffold. A club admin's is live at once; anyone else's waits for approval.
      requestCampaign: async (name, seed, opts) => {
        if (!name || !name.trim()) return;
        const o = opts || {};
        const base = seed || blankCampaign(name.trim(), Math.max(1, Math.min(16, parseInt(o.numWeeks) || 4)), o.prefDays, o.postsPerDay);
        try {
          const r = await api("POST", "/club/social", { name: name.trim(), config: { ...base.config, eventName: name.trim() }, weeks: base.weeks, posts: base.posts });
          await loadAll();
          window.dispatchEvent(new Event("cc-club-changed"));
          if (r.status === "active") setState((s) => ({ ...s, currentCampaignId: r.id, tab: "planner" }));
          return r;
        } catch (e) { note(e.message); }
      },
      deleteCampaign: async (campaignId) => {
        try { await api("DELETE", "/club/social/" + campaignId); } catch (e) { note(e.message); return; }
        await loadAll();
        window.dispatchEvent(new Event("cc-club-changed"));
      },
      approveCampaignRequest: async (campaignId) => {
        try { await api("POST", "/club/social/" + campaignId + "/decide", { decision: "approve" }); } catch (e) { note(e.message); }
        await loadAll();
      },
      declineCampaignRequest: async (campaignId, reason) => {
        try {
          await api("POST", "/club/social/" + campaignId + "/decide", { decision: "decline" });
          if (reason) await api("POST", "/club/social/" + campaignId + "/ops", { ops: [{ op: "setConfig", patch: { declineReason: reason } }] });
        } catch (e) { note(e.message); }
        await loadAll();
      },
      // People are added to the club in the Club tab; there is nothing to invite here.
      inviteToCampaign: () => {},
      setSocialSuperAdmins: () => {}
    };

    return {
      mode: "catalyst", ready: stage !== "loading", authStage: stage, authError, user: null, authLoading: false,
      state, actions, signIn: null, sendEmailLink: null, signOut: null
    };
  }

  window.useSocialStore = useCatalystSocialStore;
})();
