// leads-data.jsx — CRM client state. Module-scoped, mirrors the pattern in
// data.jsx for tasks/projects.

let LEADS = [];

const LEAD_STAGES = [
  { id: "new",            label: "New",            color: "#0073ea", emoji: "🆕" },
  { id: "contacted",      label: "Contacted",      color: "#9aadbd", emoji: "📞" },
  { id: "demo_scheduled", label: "Demo Scheduled", color: "#fdab3d", emoji: "📅" },
  { id: "demo_done",      label: "Demo Done",      color: "#a25ddc", emoji: "🎬" },
  { id: "followup",       label: "Follow-up",      color: "#fd713d", emoji: "🔁" },
  { id: "converted",      label: "Converted",      color: "#00c875", emoji: "🎉" },
  { id: "lost",           label: "Lost",           color: "#e2445c", emoji: "✗"  },
];

const LEAD_STAGE_BY_ID = Object.fromEntries(LEAD_STAGES.map(s => [s.id, s]));

// Built-in course list shipped with the app.  Custom ones (per-tenant) are
// kept in localStorage and merged on top.  Always read through
// getCourseOptions() so the dropdown reflects the user's additions.
const COURSE_OPTIONS_BUILTIN = [
  "Class 9 — Foundation",
  "Class 10 — Foundation",
  "Class 11 — JEE",
  "Class 12 — JEE",
  "Class 11 — NEET",
  "Class 12 — NEET",
  "Dropper — JEE",
  "Dropper — NEET",
  "Other",
];
const CUSTOM_COURSES_KEY = "flowboard.crm.custom_courses";

function _loadCustomCourses() {
  try {
    const raw = localStorage.getItem(CUSTOM_COURSES_KEY);
    if (!raw) return [];
    const v = JSON.parse(raw);
    return Array.isArray(v) ? v.filter(s => typeof s === "string" && s.trim()) : [];
  } catch { return []; }
}
let _customCourses = _loadCustomCourses();

function getCourseOptions() {
  const seen = new Set();
  const out = [];
  for (const c of COURSE_OPTIONS_BUILTIN) { if (!seen.has(c)) { seen.add(c); out.push(c); } }
  for (const c of _customCourses)         { if (!seen.has(c)) { seen.add(c); out.push(c); } }
  return out;
}

function addCourseOption(name) {
  const trimmed = String(name || "").trim();
  if (!trimmed) return null;
  if (COURSE_OPTIONS_BUILTIN.includes(trimmed)) return trimmed;
  if (_customCourses.includes(trimmed))         return trimmed;
  _customCourses = [..._customCourses, trimmed];
  try { localStorage.setItem(CUSTOM_COURSES_KEY, JSON.stringify(_customCourses)); } catch {}
  return trimmed;
}

function removeCourseOption(name) {
  const trimmed = String(name || "").trim();
  if (!trimmed || COURSE_OPTIONS_BUILTIN.includes(trimmed)) return false;
  if (!_customCourses.includes(trimmed)) return false;
  _customCourses = _customCourses.filter(c => c !== trimmed);
  try { localStorage.setItem(CUSTOM_COURSES_KEY, JSON.stringify(_customCourses)); } catch {}
  return true;
}

// Backward-compat alias — anything still reading COURSE_OPTIONS as a constant
// gets the merged list at module-load time.  New code should call
// getCourseOptions() so it picks up courses added later in the session.
const COURSE_OPTIONS = getCourseOptions();

function setLeads(rows) { LEADS = Array.isArray(rows) ? rows : []; }
function getLeads() { return LEADS; }

async function loadLeadsFromBootstrap(payload) {
  if (payload && Array.isArray(payload.leads)) {
    LEADS = payload.leads;
    return LEADS;
  }
  return LEADS;
}

async function reloadLeads() {
  try {
    const rows = await api.leads.list();
    LEADS = Array.isArray(rows) ? rows : [];
  } catch (e) {
    console.warn("[leads] reload failed:", e && e.message);
  }
  return LEADS;
}

// Helpers — formatting & date math (used by the CRM view).
function leadOverdue(lead) {
  if (!lead || !lead.next_action_at) return false;
  const d = new Date(lead.next_action_at);
  if (isNaN(d)) return false;
  return d.getTime() < Date.now();
}
function leadDueToday(lead) {
  if (!lead || !lead.next_action_at) return false;
  const d = new Date(lead.next_action_at);
  if (isNaN(d)) return false;
  const t = new Date();
  return d.getFullYear() === t.getFullYear()
      && d.getMonth() === t.getMonth()
      && d.getDate() === t.getDate();
}

function fmtRel(dt) {
  if (!dt) return "—";
  const d = new Date(dt);
  if (isNaN(d)) return "—";
  const diff = (Date.now() - d.getTime()) / 1000;
  const abs = Math.abs(diff);
  if (abs < 60) return diff < 0 ? "in seconds" : "just now";
  if (abs < 3600) return Math.round(abs/60) + (diff<0?" min from now":" min ago");
  if (abs < 86400) return Math.round(abs/3600) + (diff<0?" h from now":" h ago");
  if (abs < 86400*7) return Math.round(abs/86400) + (diff<0?" d from now":" d ago");
  return d.toLocaleDateString(undefined, { month: "short", day: "numeric" });
}

// Expose enums + helpers on `window` so other Babel-script modules can read
// them as bare identifiers. We do NOT expose the bare `LEADS` array — instead
// callers go through `getLeads()` (read) and `setLeads()` (replace) so the
// module-scoped reference and any future window mirror stay in lock-step.
Object.assign(window, {
  LEAD_STAGES, LEAD_STAGE_BY_ID, COURSE_OPTIONS,
  COURSE_OPTIONS_BUILTIN, getCourseOptions, addCourseOption, removeCourseOption,
  setLeads, getLeads, loadLeadsFromBootstrap, reloadLeads,
  leadOverdue, leadDueToday, fmtRel,
});
