/* seed.jsx — data model, seed content, persistence + helpers */

const uid = (p = "") => p + Math.random().toString(36).slice(2, 9);

/* ---- club users (signed-in members). In Firebase these map to Google accounts by email. ---- */
const MEMBERS = [
  { id: "u_phil",  name: "Phil L.",  initials: "PL", color: "#0f8a8a", email: "phil@rotarypeninsula.org" },
  { id: "u_dylan", name: "Dylan T.", initials: "DT", color: "#7a52c7", email: "dylan@rotarypeninsula.org" },
  { id: "u_diana", name: "Diana O.", initials: "DO", color: "#d2603a", email: "diana@rotarypeninsula.org" },
];

const LABELS = [
  { id: "l_log",  name: "Logistics",   fg: "#1f5fae", bg: "#e4eefb" },
  { id: "l_spon", name: "Sponsorship", fg: "#1f7a44", bg: "#e3f3e9" },
  { id: "l_mkt",  name: "Marketing",   fg: "#8a3fb0", bg: "#f3e8fa" },
  { id: "l_vol",  name: "Volunteers",  fg: "#3a4bb0", bg: "#e8eafb" },
  { id: "l_safe", name: "Safety",      fg: "#c0392b", bg: "#fbe6e3" },
  { id: "l_fin",  name: "Finance",     fg: "#9a6a08", bg: "#fbeed5" },
];

const PRIORITIES = [
  { id: "none",   label: "None" },
  { id: "low",    label: "Low" },
  { id: "medium", label: "Medium" },
  { id: "high",   label: "High" },
];

const STAGE_DOTS = ["#9aa6b8", "#4a90d9", "#f7a81b", "#a06bd0", "#2faa63", "#0f8a8a", "#d2603a"];

function defaultStages() {
  return ["Ideas", "Planning", "In Progress", "Review", "Complete"].map((name) => ({ id: uid("s_"), name }));
}

function mk(stageIdx, t) { return { _stage: stageIdx, ...t }; }

function bake(stages, raw, extra) {
  const S = stages.map((s) => s.id);
  return {
    id: uid("p_"), stages,
    tasks: raw.map((t) => ({
      id: uid("t_"),
      stageId: S[t._stage],
      title: t.title,
      members: t.members || [],
      due: t.due || null,
      labels: t.labels || [],
      prio: t.prio || "none",
      desc: t.desc || "",
      budget: t.budget != null ? t.budget : null,
      vols: t.vols != null ? t.vols : null,
      remind: t.remind != null ? t.remind : -2,
      completedAt: null,
      check: (t.check || []).map(([text, done]) => ({ id: uid("c_"), text, done })),
    })),
    ...extra,
  };
}

function buildFunRun() {
  const stages = defaultStages();
  const raw = [
    mk(0, { title: "Add a kids' 2 km fun-run category", labels: ["l_mkt"], desc: "Shorter loop for under-12s with a separate start so families can join. Could pair with the school." }),
    mk(0, { title: "Partner with a local gym for the warm-up", labels: ["l_spon"] }),
    mk(0, { title: "Glow-in-the-dark evening edition?", labels: [] }),

    mk(1, { title: "Secure council permit for road closure", members: ["u_phil"], due: "2026-08-14", labels: ["l_log", "l_safe"], prio: "high",
      desc: "Submit the traffic-management plan to council. Allow 6 weeks for approval.",
      check: [["TMP drafted", true], ["Submitted to council", false], ["Approval received", false]] }),
    mk(1, { title: "Line up event sponsors", members: ["u_dylan"], due: "2026-08-30", labels: ["l_spon", "l_fin"], prio: "medium", budget: 8000,
      desc: "Target 3 gold ($2.5k) + 5 bronze ($500) sponsors. Update the prospectus first.",
      check: [["Refresh prospectus", true], ["Contact last year's sponsors", false], ["New leads list", false]] }),
    mk(1, { title: "Order finisher medals & t-shirts", members: ["u_diana"], due: "2026-09-12", labels: ["l_log"], prio: "medium", budget: 3200,
      check: [["Confirm sizes & qty", false], ["Get 2 quotes", false]] }),

    mk(2, { title: "Build the online registration page", members: ["u_dylan", "u_phil"], due: "2026-07-20", labels: ["l_mkt"], prio: "high",
      desc: "Set up tiers: early-bird, standard, family. Connect payments + waiver checkbox.",
      check: [["Pricing tiers agreed", true], ["Page built", true], ["Test payment flow", false], ["Add waiver", false]] }),
    mk(2, { title: "Recruit course marshals", members: ["u_phil"], labels: ["l_vol"], prio: "medium", vols: 15,
      desc: "Need marshals at every turn + 2 at each water station.",
      check: [["Map marshal points", true], ["Sign-up sheet out", false]] }),
    mk(2, { title: "Arrange first-aid & water stations", members: ["u_diana"], due: "2026-09-05", labels: ["l_safe", "l_log"], prio: "high", vols: 6 }),

    mk(3, { title: "Confirm catering for post-race BBQ", members: ["u_dylan"], due: "2026-09-20", labels: ["l_log", "l_fin"], budget: 1500, prio: "low",
      check: [["Headcount estimate", true], ["Quote from Lions BBQ", true], ["Confirm menu", false]] }),

    mk(4, { title: "Book the venue / start-finish area", members: ["u_phil"], labels: ["l_log"], budget: 600,
      check: [["Riverside Park booked", true], ["Deposit paid", true]] }),
    mk(4, { title: "Design event poster & social pack", members: ["u_diana"], labels: ["l_mkt"],
      check: [["Poster v1", true], ["Final approved", true]] }),
  ];
  return bake(stages, raw, { name: "2026 Charity Fun Run", admins: ["u_phil"] });
}

function buildHamper() {
  const stages = defaultStages();
  const raw = [
    mk(0, { title: "Add a 'gift a hamper' option for donors", labels: ["l_mkt"] }),
    mk(1, { title: "Confirm recipient list with welfare agency", members: ["u_diana"], due: "2026-11-15", labels: ["l_log"], prio: "high",
      check: [["Email agency", true], ["Numbers confirmed", false]] }),
    mk(1, { title: "Source bulk grocery donations", members: ["u_phil"], labels: ["l_spon", "l_fin"], prio: "medium", budget: 2000 }),
    mk(2, { title: "Schedule the packing night", members: ["u_dylan"], due: "2026-12-05", labels: ["l_vol"], vols: 12,
      check: [["Book hall", true], ["Volunteer roster", false]] }),
    mk(3, { title: "Arrange delivery routes", members: ["u_phil"], labels: ["l_log"], prio: "low" }),
  ];
  return bake(stages, raw, { name: "Christmas Hamper Drive", admins: ["u_diana", "u_phil"] });
}

function seedState() {
  const projects = [buildFunRun(), buildHamper()];
  return { projects, currentId: projects[0].id };
}

/* ---- persistence ---- */
const STORE_KEY = "rotary_planner_v2";
function loadState() {
  try {
    const raw = localStorage.getItem(STORE_KEY);
    if (raw) { const s = JSON.parse(raw); if (s && s.projects && s.projects.length) return s; }
  } catch (e) {}
  return seedState();
}
function saveState(s) { try { localStorage.setItem(STORE_KEY, JSON.stringify(s)); } catch (e) {} }

/* ---- duplication (template copy: clear members + dates + reset to first stage; keep admins) ---- */
function duplicateProjectTemplate(project) {
  const stages = project.stages.map((s) => ({ id: uid("s_"), name: s.name }));
  const firstStage = stages[0].id;
  const tasks = project.tasks.map((t) => ({
    id: uid("t_"), stageId: firstStage, title: t.title,
    members: [], due: null, labels: [...t.labels], prio: "none",
    desc: t.desc, budget: t.budget, vols: t.vols,
    remind: t.remind != null ? t.remind : -2, completedAt: null,
    check: t.check.map((c) => ({ id: uid("c_"), text: c.text, done: false })),
  }));
  return { id: uid("p_"), name: nextCopyName(project.name), stages, tasks, admins: [...(project.admins || [])] };
}
function nextCopyName(name) {
  const yr = name.match(/(20\d{2})/);
  if (yr) return name.replace(yr[1], String(+yr[1] + 1));
  return name + " (copy)";
}

/* ---- date helpers ---- */
const TODAY = new Date("2026-06-03T00:00:00");
function fmtDue(iso) {
  if (!iso) return null;
  const d = new Date(iso + "T00:00:00");
  return d.toLocaleString("en-US", { month: "short" }) + " " + d.getDate();
}
function dueState(iso) {
  if (!iso) return "";
  const diff = Math.round((new Date(iso + "T00:00:00") - TODAY) / 86400000);
  if (diff < 0) return "over";
  if (diff <= 10) return "soon";
  return "";
}
function fmtMoney(n) { return n == null ? null : CCIntl.money(Number(n)); }

/* ---- reminder helper: one-line summary of what `remind` will do, for the task modal ---- */
function remindSummary(remind, due) {
  if (!due) return "Add a due date to switch reminders on — a task with no due date is never reminded.";
  const n = Number(remind);
  if (!Number.isFinite(n)) return "";
  if (n > 0) return "One follow-up reminder " + n + (n === 1 ? " day" : " days") + " after the task is marked complete. No deadline reminders.";
  const overdue = " Overdue nudges follow at 1, 2 and 5 days past due (the 5-day one is the last).";
  if (n === 0) return "Reminder on the due date." + overdue;
  if (n === -1) return "Reminders the day before and on the due date." + overdue;
  return "Reminders " + Math.abs(n) + " days before due, the day before, and on the due date." + overdue;
}

/* ---- live member registry (swapped to real signed-in users in Firebase mode) ---- */
let memberRegistry = MEMBERS.slice();
function setMembers(list) { memberRegistry = (list || []).slice(); }
function members() { return memberRegistry; }

/* People actually ON a project — memberUids + admins. Only these can be assigned
 * to that project's tasks (a club member who can merely *view* must be added to
 * the project first). Demo/legacy projects with no memberUids array fall back to
 * the whole registry so offline testing still works. */
function projectMembers(project) {
  const all = memberRegistry;
  if (!project || !Array.isArray(project.memberUids)) return all;
  const ids = new Set([...(project.memberUids || []), ...(project.admins || [])]);
  return all.filter((m) => ids.has(m.id));
}

/* ---- avatar helpers for real Google accounts ---- */
const AVATAR_COLORS = ["#0f8a8a", "#7a52c7", "#d2603a", "#1f7a44", "#1f5fae", "#b0407a", "#9a6a08", "#3a4bb0", "#0d7d5a", "#a0431f"];
function initialsFrom(name, email) {
  const src = (name || "").trim() || (email || "").split("@")[0].replace(/[._-]/g, " ");
  const parts = src.split(/\s+/).filter(Boolean);
  if (parts.length === 0) return "?";
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}
function colorFor(key) {
  let h = 0; const s = String(key || "");
  for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
  return AVATAR_COLORS[h % AVATAR_COLORS.length];
}

/* ---- dynamic label registry (club-managed labels override the defaults) ---- */
const LABEL_COLORS = [
  { fg: "#1f5fae", bg: "#e4eefb" }, { fg: "#1f7a44", bg: "#e3f3e9" }, { fg: "#8a3fb0", bg: "#f3e8fa" },
  { fg: "#3a4bb0", bg: "#e8eafb" }, { fg: "#c0392b", bg: "#fbe6e3" }, { fg: "#9a6a08", bg: "#fbeed5" },
  { fg: "#0f8a8a", bg: "#e0f2f2" }, { fg: "#b0407a", bg: "#fbe6f0" }, { fg: "#5a6b2f", bg: "#eef3df" },
];
let labelRegistry = LABELS.slice();
function setLabels(list) { labelRegistry = (list && list.length) ? list.slice() : LABELS.slice(); }
function labelsList() { return labelRegistry; }

window.PlannerData = {
  uid, MEMBERS, LABELS, DEFAULT_LABELS: LABELS, PRIORITIES, STAGE_DOTS, LABEL_COLORS,
  defaultStages, seedState, loadState, saveState,
  duplicateProjectTemplate, fmtDue, dueState, fmtMoney, remindSummary,
  setMembers, members, projectMembers, initialsFrom, colorFor,
  setLabels, labels: labelsList,
  memberById: (id) => memberRegistry.find((m) => m.id === id) || null,
  usersByIds: (ids) => (ids || []).map((id) => memberRegistry.find((m) => m.id === id)).filter(Boolean),
  labelById: (id) => labelRegistry.find((l) => l.id === id) || null,
};
