/* demo.jsx: Clubcraft demo mode (open the app with ?demo=1).
 * No sign-in and no server data. The real shell and the real Tasks board run
 * against this in-memory "club" instead of cc_api, so key people can click through
 * the whole product. Everything is example data and resets on reload.
 *   ?demo=1              a club on a paid plan (everything unlocked)
 *   ?demo=1&state=trial  the same club in its 14-day free trial (limits visible)
 * Real rules still apply where the demo can show them: plan prices come from the
 * live catalogue and the quote uses the real pricing engine (pricing-lib.js).
 */
(function () {
  const qs = new URLSearchParams(location.search);
  const on = qs.has("demo");
  const KC = window.CCCountries;
  // ?demo=1&country=US shows the same club the way a club in that country would see it (AU, NZ, US, CA or GB): currency, price list, dates,
  // time zone, tax wording and spelling. The default is Australia.
  const country = KC.isCountry(qs.get("country")) ? qs.get("country").toUpperCase() : "AU";
  window.CCDemo = { on, trial: qs.get("state") === "trial", country, chooser: qs.get("chooser") === "1" };
  if (!on) return;
  const regionOf = () => {
    const r = KC.forClub({ country });
    return { country: r.country, countryName: r.countryName, timezone: r.timezone, currency: r.currency, currencyLabel: r.currencyInfo.label, locale: r.locale, dateOrder: r.dateOrder, tax: { name: r.tax.name, fullName: r.tax.fullName, rate: r.tax.rate, included: r.tax.included }, taxIdType: r.taxIdType, taxIdLabel: r.taxId.label, taxIdExample: r.taxId.example, taxId: "", regLabel: r.regLabel, address: r.address, phone: r.phone, fiscalStart: r.fiscalStart, spelling: r.spelling, zones: r.zones };
  };
  window.CCIntl.set(regionOf());

  const API = window.ClubcraftApi;
  const real = API.call;
  const MODULES = ["Review", "Ideas", "Events", "Tasks", "Comms", "Social"];
  const DAY = 86400000;
  const iso = (n) => { const d = new Date(Date.now() + n * DAY); return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0"); };
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
  const clone = (x) => JSON.parse(JSON.stringify(x));
  let seq = 100;
  const nid = (p) => p + (++seq);

  function fallbackPlans() {
    const P = window.CCPricing;
    return {
      bands: P.BANDS.map((b) => ({ code: b.code, upTo: b.upTo, price: b.price })),
      bundles: P.BUNDLE_ORDER.map((k) => ({ code: k, name: P.BUNDLES[k].name, step: P.BUNDLES[k].step, apps: P.bundleApps(k), adds: P.BUNDLES[k].apps })),
      addons: P.ADDONS, largeFrom: P.LARGE_FROM, largeFactor: P.LARGE_FACTOR,
      assocOff: P.ASSOC_OFF, monthlyDivisor: P.MONTHLY_DIVISOR, monthlyExtra: 25, aiPacks: P.AI_PACKS, aiUnits: { included: 200, none: 0, starter: 500, plus: 1000 }, topup: P.TOPUP, graceDays: P.GRACE_DAYS,
      softLimit: P.SOFT_LIMIT, trial: P.TRIAL, defaultPeriod: "year", currency: "AUD", checkout: "test"
    };
  }
  let planCache = null;
  async function plans() {
    if (!planCache) planCache = await real("GET", "/plans", null, { anon: true }).then((c) => (c && c.bands ? c : fallbackPlans())).catch(() => fallbackPlans());
    return planCache;
  }

  /* ---------- the example club ---------- */
  const CLUB_ID = "demo_club", ME = "u_sam";
  const COLOURS = ["#0f8a8a", "#7a52c7", "#d2603a", "#2f7d4f", "#b0457a", "#3a6fb0", "#9a6a08", "#5a6b7a"];
  const PEOPLE = [
    { id: "u_sam", name: "Sam Taylor", role: "President", plan: "D", admin: true },
    { id: "u_priya", name: "Priya Nair", role: "Secretary", plan: "D", admin: true },
    { id: "u_tom", name: "Tom Walker", role: "Treasurer", plan: "D" },
    { id: "u_jess", name: "Jess Moreno", role: "Community", plan: "D" },
    { id: "u_aroha", name: "Aroha Smith", role: "Membership Director", plan: "D" },
    { id: "u_ben", name: "Ben Cho", role: "Member", plan: "D" },
    { id: "u_linda", name: "Linda Hart", role: "Member", view: ["Review", "Events", "Tasks"] },
    { id: "u_marcus", name: "Marcus Odell", role: "Member", extra: true }
  ];
  const initials = (n) => n.split(" ").map((w) => w[0]).join("").slice(0, 2).toUpperCase();
  const st = {
    sub: window.CCDemo.trial ? null : { period: "year", band: "b25", bundle: "complete", addon: null, assoc: false, aiPack: "starter", termEndAt: Date.now() + 200 * DAY, grace: {} },
    topupUnits: 0, topupExpiresAt: null,
    trialEndsAt: Date.now() + 9 * DAY,
    members: PEOPLE.map((p, i) => ({ userId: p.id, name: p.name, email: p.name.toLowerCase().replace(/[^a-z]+/g, ".") + "@example-bay.test", isAdmin: !!p.admin, isGuest: false, status: "active", role: p.role, color: COLOURS[i % COLOURS.length] })),
    requests: [
      { id: "jr1", userId: "u_morgan", name: "Morgan Reyes", email: "morgan.reyes@example-bay.test", roleInClub: "Member", message: "Hi, I joined last month and would love to help with the trivia night.", status: "pending" },
      { id: "jr2", userId: "u_dev", name: "Dev Patel", email: "dev.patel@example-bay.test", roleInClub: "Treasurer", message: null, status: "pending" }
    ],
    projects: [], brand: null
  };
  if (window.CCDemo.trial) st.members = st.members.slice(0, 4);

  const lab = { log: "l_log", spon: "l_spon", mkt: "l_mkt", vol: "l_vol", safe: "l_safe", fin: "l_fin" };
  const task = (stage, title, o) => ({ id: nid("t_"), projectId: o.p, stageId: stage, title, order: nid("") * 1024, members: o.m || [], due: o.due != null ? iso(o.due) : null, labels: o.l || [], prio: o.prio || "none", desc: o.desc || "", budget: o.budget ?? null, vols: o.vols ?? null, remind: -2, completedAt: stage === "s_done" ? Date.now() - 2 * DAY : null, check: (o.check || []).map(([text, done]) => ({ id: nid("c_"), text, done })), remLog: {} });
  function buildProjects() {
    const stages = [{ id: "s_todo", name: "To do" }, { id: "s_doing", name: "In progress" }, { id: "s_wait", name: "Waiting" }, { id: "s_done", name: "Done" }];
    const base = (id, name) => ({ id, name, stages: clone(stages), open: true, order: 0, createdBy: ME, admins: [ME], contributors: ["u_priya", "u_tom", "u_jess", "u_aroha"], memberUids: ["u_sam", "u_priya", "u_tom", "u_jess", "u_aroha", "u_ben"], markerUrl: null });
    const trivia = { ...base("p_trivia", "Trivia Night"), tasks: [
      task("s_done", "Book the hall", { p: "p_trivia", m: ["u_tom"], l: [lab.log] }),
      task("s_done", "Confirm quiz master", { p: "p_trivia", m: ["u_priya"] }),
      task("s_done", "Set up online registration and payment", { p: "p_trivia", m: ["u_sam"], l: [lab.mkt] }),
      task("s_doing", "Write 60 trivia questions", { p: "p_trivia", m: ["u_jess"], due: 5, prio: "medium", check: [["Sport and games", true], ["Local history", true], ["Music and movies", false], ["Tie-breakers", false]] }),
      task("s_doing", "Sell 12 tables (96 seats)", { p: "p_trivia", m: ["u_sam", "u_aroha"], due: 12, prio: "high", l: [lab.mkt], budget: 2880, desc: "Tables of 8 at $30 a seat. 7 sold so far." }),
      task("s_doing", "Collect raffle prizes from local businesses", { p: "p_trivia", m: ["u_priya"], due: 10, l: [lab.spon], check: [["Cafe voucher", true], ["Hardware hamper", false], ["Restaurant dinner", false]] }),
      task("s_wait", "Arrange licence and RSA-trained bar volunteers", { p: "p_trivia", m: ["u_tom"], due: 9, prio: "high", l: [lab.safe, lab.log] }),
      task("s_todo", "Print posters and social pack", { p: "p_trivia", m: ["u_aroha"], due: 7, l: [lab.mkt], budget: 180 }),
      task("s_todo", "Recruit 8 volunteers for the night", { p: "p_trivia", m: ["u_aroha"], due: 14, l: [lab.vol], vols: 8 }),
      task("s_todo", "Buy supplies: answer sheets, pens, table decorations", { p: "p_trivia", m: ["u_tom"], due: 16, l: [lab.log, lab.fin], budget: 250 }),
      task("s_todo", "Write the run sheet for the night", { p: "p_trivia", m: ["u_sam"], due: 18 }),
      task("s_todo", "Thank-you notes and results post", { p: "p_trivia", m: ["u_jess"], due: 24, l: [lab.mkt] })
    ] };
    const sizzle = { ...base("p_sizzle", "Hardware-store Sausage Sizzle"), order: 1, tasks: [
      task("s_done", "Book the Saturday slot with the store", { p: "p_sizzle", m: ["u_tom"] }),
      task("s_doing", "Roster 8 volunteers in two shifts", { p: "p_sizzle", m: ["u_aroha"], due: 6, l: [lab.vol], vols: 8 }),
      task("s_todo", "Order sausages, bread and onions", { p: "p_sizzle", m: ["u_tom"], due: 8, budget: 220, l: [lab.fin] }),
      task("s_todo", "Borrow BBQ and gas bottle", { p: "p_sizzle", m: ["u_ben"], due: 8, l: [lab.log] }),
      task("s_todo", "Food safety checklist and hand-wash station", { p: "p_sizzle", m: ["u_priya"], due: 9, l: [lab.safe] })
    ] };
    return window.CCDemo.trial ? [trivia] : [trivia, sizzle];
  }
  st.projects = buildProjects();

  /* ---------- responses ---------- */
  const bundleKey = () => (st.sub ? st.sub.bundle : "complete");
  const bundleApps = () => window.CCPricing.planApps(bundleKey(), st.sub && st.sub.addon);
  const bandOf = () => window.CCPricing.bandByCode(st.sub ? st.sub.band : window.CCPricing.TRIAL.band);
  // Apps the example club dropped that are still readable ({app: until}).
  const graceNow = () => { const g = {}; Object.entries((st.sub && st.sub.grace) || {}).forEach(([a, t]) => { if (t > Date.now() && !bundleApps().includes(a)) g[a] = t; }); return g; };
  // What the example member can do in each app: club admins are Admin; others follow what the Access page shows; apps outside the plan are off
  // (or view-only for 60 days after the club dropped them).
  function levelOf(member, m) {
    const ro = !bundleApps().includes(m);
    if (ro && !graceNow()[m]) return null;
    const set = (st.access[member.userId] || {})[m], lvl = member.isAdmin ? "admin" : set || st.defaults[m] || BUILT_IN[m] || "view";
    return lvl === "none" ? null : ro ? "view" : lvl;
  }
  function access(member) {
    return Object.fromEntries(MODULES.map((m) => { const l = levelOf(member, m); return [m, l === "admin" ? "edit" : l]; }));
  }
  function allowances() {
    const out = {}, apps = bundleApps();
    const UNIT = { Review: "run", Ideas: "run", Events: "run", Comms: "run", Tasks: "project", Social: "campaign" };
    MODULES.forEach((m) => {
      if (st.sub) { const g = graceNow()[m]; out[m] = g ? { unit: UNIT[m], state: "readonly", until: g } : { unit: UNIT[m], state: apps.includes(m) ? "unlimited" : "locked" }; return; }
      const used = m === "Tasks" ? st.projects.length : 0;
      out[m] = { unit: UNIT[m], limit: 1, used, state: used >= 1 ? "used" : "available" };
    });
    return out;
  }
  function brandResp() { return st.brand || { template: "Rotary (Official)", tokens: { primary: "#17458F", primaryDeep: "#0F2F63", accent: "#F7A81B", wash: "#E8EEF8", bg: "#F4F6FA", surface: "#FFFFFF", ink: "#1B2433", muted: "#5B667A", line: "#DCE2EC", font: "Public Sans", display: "Public Sans", mark: "rotary-wheel" }, logoUrl: null, labels: { global: "Rotary International", regional: "Zone", area: "District", club: "Club" }, clubBrandingEnabled: false, levels: [{ id: "o1", name: "Zone 99", level: "regional", hidden: false }, { id: "o2", name: "District 9999", level: "area", hidden: false }] }; }
  async function loadBrand() {
    try { const o = await real("GET", "/orgs/rotary", null, { anon: true }); if (o && o.brand && o.brand.tokens) st.brand = { ...brandResp(), ...o.brand, levels: brandResp().levels, clubBrandingEnabled: false }; } catch (e) { /* the built-in Rotary look is fine */ }
  }
  const me = () => ({ user: { id: ME, email: "sam.taylor@example-bay.test", name: "Sam Taylor", initials: "ST", colour: COLOURS[0] }, isPlatformAdmin: false, pendingRequests: [], clubs: [{ id: CLUB_ID, name: "Rotary Club of Example Bay", status: "active", isAdmin: true }] });
  function clubResp() {
    const active = st.members.filter((m) => m.status === "active");
    const meM = active.find((m) => m.userId === ME);
    const trial = !st.sub;
    const apps = bundleApps(), band = bandOf(), bk = bundleKey();
    return {
      brand: brandResp(), canEditBranding: false,
      trial: trial ? { endsAt: st.trialEndsAt, expired: false, daysLeft: Math.max(0, Math.ceil((st.trialEndsAt - Date.now()) / DAY)), limits: { Review: 1, Ideas: 1, Events: 1, Comms: 1, Tasks: 1, Social: 1 }, bundle: "complete", bundleName: "Complete", band: band.code, upTo: band.upTo } : null,
      club: { id: CLUB_ID, name: "Rotary Club of Example Bay", status: "active", freeReviewUsed: false, district: "District 9999 (example)", brandAccent: null, region: regionOf() },
      me: { id: ME, isAdmin: true, access: access(meM), levels: Object.fromEntries(APPS.map((m) => [m, levelOf(meM, m)])) },
      aiPercentUsed: trial ? 0 : 34, allowances: allowances(),
      plan: { bundle: bk, bundleName: window.CCPricing.BUNDLES[bk].name, addon: (st.sub && window.CCPricing.addonOf(st.sub)) || null, apps, readOnly: graceNow(), band: band.code, assoc: false, upTo: band.upTo, live: !trial, none: false },
      aiTopups: trial ? undefined : { units: st.topupUnits, expiresAt: st.topupExpiresAt, price: window.CCPricing.topupPrice(false, window.CCIntl.currency()), size: window.CCPricing.TOPUP.units, months: window.CCPricing.TOPUP.months },
      members: clone(active.map((m) => ({ userId: m.userId, name: m.name, email: m.email, isAdmin: m.isAdmin, isGuest: m.isGuest, status: m.status }))),
      register: { started: true, total: 11, counting: 8, band: { upTo: 25, price: 19 }, next: { upTo: 100, price: 39 }, spare: 17, over: 0, nearTop: false, contactUs: false },     // the example Members register (previews.jsx)
      licences: { subscription: st.sub ? { status: "live", addon: st.sub.addon, aiPack: st.sub.aiPack, termEndAt: st.sub.termEndAt, billingPeriod: st.sub.period, bundle: st.sub.bundle, band: st.sub.band, assoc: st.sub.assoc } : { status: "trial", aiPack: "none", termEndAt: st.trialEndsAt, billingPeriod: null, bundle: "complete", band: band.code, assoc: false } }
    };
  }
  function boardResp() {
    const active = st.members.filter((m) => m.status === "active");
    const editsTasks = true;
    return {
      user: { id: ME, email: "sam.taylor@example-bay.test", name: "Sam Taylor", clubRole: "super-admin", clubAccess: "all", tasksAccess: editsTasks ? "edit" : "view" },
      members: active.map((m) => ({ id: m.userId, email: m.email, name: m.name, initials: initials(m.name), color: m.color, role: m.isAdmin ? "super-admin" : "member", status: "active", guest: false, tasksAccess: access(m).Tasks })),
      club: { id: CLUB_ID, name: "Rotary Club of Example Bay", labels: null, superAdmins: active.filter((m) => m.isAdmin).map((m) => m.userId) },
      projects: clone(st.projects), serverNow: Date.now()
    };
  }
  const findTask = (id) => { for (const p of st.projects) { const t = p.tasks.find((x) => x.id === id); if (t) return [p, t]; } return [null, null]; };
  const fail = (status, error, extra) => { throw new API.ApiError(status, { error, ...(extra || {}) }); };

  async function quote(body) {
    const cat = await plans(), P = window.CCPricing;
    const band = P.bandByCode(String(body.band || "")), bundle = String(body.bundle || "");
    if (!band) fail(400, "Choose a band");
    if (!P.BUNDLES[bundle]) fail(400, "Choose a bundle");
    const assoc = !!body.assoc;
    const aiPack = P.AI_PACKS[body.aiPack] !== undefined ? body.aiPack : "none";
    const period = body.billingPeriod === "month" ? "month" : "year";
    const currency = window.CCIntl.currency();
    const next = { period, band: band.code, bundle, addon: P.addonOf({ bundle, addon: body.addon }), assoc, aiPack, currency };
    const current = st.sub ? { period: st.sub.period, band: st.sub.band, bundle: st.sub.bundle, addon: st.sub.addon, assoc: st.sub.assoc, aiPack: st.sub.aiPack, currency, termEndAt: st.sub.termEndAt } : null;
    const q = P.quote(current, next);
    const problems = [];
    if (8 > band.upTo) problems.push("8 members count towards your price, which needs a bigger band.");
    if (assoc && String(body.assocNumber || "").trim().length < 3) problems.push("Enter your association or club number to claim the 20% discount.");
    const losing = bundleApps().filter((a) => !P.planApps(next.bundle, next.addon).includes(a));
    return { q: { ...q, bundleInstead: P.bundleInstead(next), losing, graceDays: P.GRACE_DAYS }, problems, next };
  }

  /* ---------- routes ---------- */
  /* ---------- Access (the same rules as routes/access.js, in memory) ---------- */
  const APPS = ["Review", "Ideas", "Events", "Tasks", "Comms", "Social", "Calendar", "Members", "Contacts", "Finances"];
  const BUILT_IN = { Tasks: "edit", Calendar: "edit", Contacts: "edit" };
  st.access = { u_ben: { Social: "edit", Ideas: "none" }, u_linda: { Tasks: "view", Events: "edit" }, u_tom: { Finances: "admin" }, u_aroha: { Members: "admin" } };
  st.defaults = {};
  function accessList() {
    const active = st.members.filter((m) => m.status === "active");
    const people = active.map((m) => {
      const mine = st.access[m.userId] || {}, access = {};
      APPS.forEach((mod) => {
        const set = mine[mod] || null;
        let level = levelOf(m, mod);
        if (level && m.isGuest && !m.isAdmin) level = "view";
        const outside = !bundleApps().includes(mod), readOnlyUntil = outside ? graceNow()[mod] || null : null;
        access[mod] = { level, outside, readOnlyUntil, source: readOnlyUntil ? "read-only after a plan change" : outside ? "not in your bundle" : m.isAdmin ? "club admin" : set ? "set" : st.defaults[mod] ? "club default" : "built-in default", set };
      });
      return { userId: m.userId, name: m.name, email: m.email, isAdmin: !!m.isAdmin, isGuest: !!m.isGuest, lastSeenAt: Date.now() - (m.userId === ME ? 0 : (2 + m.userId.length) * DAY), access };
    }).sort((a, b) => (b.isAdmin - a.isAdmin) || a.name.localeCompare(b.name));
    const counts = {};
    APPS.forEach((mod) => { counts[mod] = { admin: 0, edit: 0, view: 0, none: 0 }; people.forEach((p) => { counts[mod][p.access[mod].level || "none"]++; }); });
    return { apps: APPS, levels: ["view", "edit", "admin"], defaults: clone(st.defaults), builtIn: BUILT_IN, trialExpired: false, people, counts };
  }
  function setAccess(uid, mod, level) {
    const m = st.members.find((x) => x.userId === uid && x.status === "active"); if (!m) fail(404, "That person is not an active member of the club");
    if (!APPS.includes(mod)) fail(400, "Unknown app");
    if (!["view", "edit", "admin", "none", "default"].includes(level)) fail(400, "Level must be admin, edit, view, none or default");
    if (m.isAdmin) fail(409, "A club admin is Admin in every app. Remove their club admin role first");
    if (m.isGuest && (level === "edit" || level === "admin")) fail(409, "Guests are view-only");
    st.access[uid] = st.access[uid] || {};
    if (level === "default") delete st.access[uid][mod]; else st.access[uid][mod] = level;
  }
  async function route(method, path, body, opts) {
    const [pth] = path.split("?"), p = pth.split("/").filter(Boolean);
    const is = (m, ...segs) => method === m && p.length === segs.length && segs.every((s, i) => s === "*" || s === p[i]);
    if (is("GET", "plans")) return plans();
    if (is("GET", "me")) return me();
    if (is("GET", "club")) return clubResp();
    if (is("GET", "board")) return boardResp();
    if (is("GET", "club", "access")) return accessList();
    if (is("PUT", "club", "access", "user", "*")) { Object.entries((body || {}).levels || {}).forEach(([mod, lvl]) => setAccess(p[3], mod, lvl)); return { changed: 1, ...accessList() }; }
    if (is("PUT", "club", "access", "app", "*")) { Object.entries((body || {}).levels || {}).forEach(([uid, lvl]) => setAccess(uid, p[3], lvl)); return { changed: 1, ...accessList() }; }
    if (is("PUT", "club", "access", "defaults")) {
      Object.entries((body || {}).levels || {}).forEach(([mod, lvl]) => { if (!APPS.includes(mod)) fail(400, "Unknown app"); if (lvl === "default") delete st.defaults[mod]; else if (["view", "edit", "none"].includes(lvl)) st.defaults[mod] = lvl; else fail(400, "A default can be view, edit, none or default (never admin)"); });
      return accessList();
    }
    if (is("GET", "club", "join-requests")) return { requests: clone(st.requests) };
    if (is("POST", "club", "quote")) { const { q, problems } = await quote(body || {}); return { ...q, problems }; }
    if (is("POST", "club", "checkout")) {
      const { q, problems, next } = await quote(body || {});
      if (problems.length) fail(409, problems[0]);
      const P = window.CCPricing;
      const grace = P.graceAfterChange(bundleApps(), P.planApps(next.bundle, next.addon), graceNow(), Date.now());
      st.sub = { period: next.period, band: next.band, bundle: next.bundle, addon: next.addon, assoc: next.assoc, aiPack: next.aiPack, termEndAt: q.renewsAt, grace };
      const monthly = next.period === "year" ? Math.round(q.recurring / 12 * 100) / 100 : q.recurring;
      return { ok: true, test: true, appliedNowInTest: false, ...q, band: next.band, bundle: next.bundle, addon: next.addon, assoc: next.assoc, aiPack: next.aiPack, billingPeriod: next.period, monthly, charge: q.dueToday, readOnly: grace };
    }
    if (is("POST", "club", "topup")) {
      if (!st.sub) fail(409, "Choose a plan before buying an AI top-up.");
      const P = window.CCPricing;
      st.topupUnits += P.TOPUP.units;
      const expiresAt = P.addMonths(Date.now(), P.TOPUP.months);
      st.topupExpiresAt = st.topupExpiresAt || expiresAt;
      return { ok: true, test: true, units: P.TOPUP.units, price: P.topupPrice(false, window.CCIntl.currency()), currency: window.CCIntl.currency(), expiresAt };
    }
    if (method === "PATCH" && p[0] === "club" && p[1] === "members" && p[2]) {
      const m = st.members.find((x) => x.userId === p[2]); if (!m) fail(404, "Member not found");
      if ("isAdmin" in body) m.isAdmin = !!body.isAdmin;
      if (body.status === "removed") m.status = "removed";
      return { ok: true };
    }
    if (is("POST", "club", "invitations")) return { acceptPath: "/join?invite=DEMO-INVITE", demo: true };
    if (p[0] === "club" && p[1] === "join-requests" && p[3] === "decide") {
      const r = st.requests.find((x) => x.id === p[2]); st.requests = st.requests.filter((x) => x.id !== p[2]);
      if (r && body.decision !== "decline") st.members.push({ userId: r.userId, name: r.name, email: r.email, isAdmin: false, isGuest: false, status: "active", color: COLOURS[st.members.length % COLOURS.length] });
      return { ok: true };
    }
    if (is("PUT", "club", "labels")) return { ok: true };
    /* Tasks board */
    if (is("POST", "projects")) {
      if (!st.sub && st.projects.length >= 1) fail(409, "The free trial includes one Tasks project. Choose a plan to add more.", { trialLimit: "Tasks" });
      const id = nid("p_");
      st.projects.push({ id, name: body.name, stages: body.stages, open: true, order: st.projects.length, createdBy: ME, admins: [ME], contributors: [], memberUids: [ME], markerUrl: null,
        tasks: (body.tasks || []).map((t, i) => ({ ...t, id: nid("t_"), projectId: id, order: t.order || (i + 1) * 1024 })) });
      return { id };
    }
    if (is("PATCH", "projects", "*")) { const pr = st.projects.find((x) => x.id === p[1]); if (pr) Object.assign(pr, body); return { ok: true }; }
    if (is("DELETE", "projects", "*")) { st.projects = st.projects.filter((x) => x.id !== p[1]); return { ok: true }; }
    if (is("POST", "projects", "*", "tasks")) {
      const pr = st.projects.find((x) => x.id === p[1]); if (!pr) fail(404, "Project not found");
      const t = { ...body.task, id: nid("t_"), projectId: pr.id, remLog: {} }; pr.tasks.push(t); return { id: t.id };
    }
    if (is("POST", "projects", "*", "delete-stage")) { const pr = st.projects.find((x) => x.id === p[1]); if (pr) { pr.stages = pr.stages.filter((s) => s.id !== body.stageId); pr.tasks = pr.tasks.filter((t) => t.stageId !== body.stageId); } return { ok: true }; }
    if (is("PATCH", "tasks", "*")) { const [, t] = findTask(p[1]); if (t) Object.assign(t, body.patch); return { ok: true }; }
    if (is("DELETE", "tasks", "*")) { const [pr] = findTask(p[1]); if (pr) pr.tasks = pr.tasks.filter((t) => t.id !== p[1]); return { ok: true }; }
    if (method !== "GET") return { ok: true, demo: true };
    return real(method, path, body, opts);
  }

  API.call = async function (method, path, body, opts) {
    await window.CCDemo.ready;
    await sleep(60);
    return clone(await route(method, path, body ? clone(body) : body, opts));
  };
  API.isSignedIn = async () => true;
  API.signIn = API.signUp = () => window.location.assign(location.pathname);
  API.signOut = async () => window.location.assign(location.pathname);
  window.CCDemo.ready = loadBrand();
})();
