// data.jsx — live data layer. The collections start empty and are filled from
// the backend at bootstrap (see main.jsx). `window.DATA` is mutated in place so
// every screen that reads DATA.X picks up live data, and Store.emit() re-renders
// subscribers after mutations.

window.DATA = window.DATA || {
  AGENTS: [],
  SESSIONS: [],
  CAMPAIGNS: [],
  CONTACTS: [],
  APPROVALS: [],
  NEXT_ACTIONS: [],
  CONVERSATIONS: [],
  LINK_TYPES: {
    service: { label: "Service page", icon: "store", c: "#00654B" },
    payment: { label: "Payment link", icon: "dollar", c: "#2563EB" },
    affiliate: { label: "Affiliate link", icon: "link", c: "#7E22CE" },
    booking: { label: "Booking link", icon: "calendar", c: "#EA580C" },
    other: { label: "Other link", icon: "external", c: "#6B7280" },
  },
  AGENT_TRAINING: {},
  SETTINGS: {},

  // ---- Core Dynamic Workflow + Knowledge Base ----
  WORKFLOW_AGENTS: [],
  KNOWLEDGE: [],
  KNOWLEDGE_CATEGORIES: [],
  PLATFORMS: [],
  PLATFORM_COMPARISON: { dimensions: [], platforms: {} },
  WHATSAPP_TEMPLATES: [],
  CRM_STAGES: [],
  FOLLOW_UPS: [],
  LEARNING: null,
  WORKFLOW_STATUS: {}, // { [leadId]: { run, agentRuns, research, offer, followUps } }

  meta: { live: false, pendingApprovals: 0 },
};

const TRAINING_FALLBACK = { knowledge: [], links: [], corrections: [] };
function trainingFor(id) {
  return (window.DATA.AGENT_TRAINING && window.DATA.AGENT_TRAINING[id]) || TRAINING_FALLBACK;
}

// Resolve an agent's CURRENT display name from its stable agentId, falling back
// to the denormalised name (kept in sync by the rename cascade). Use this for
// any agent-name display so renames propagate everywhere.
function agentNameOf(rec) {
  if (!rec) return "";
  const a = (window.DATA.AGENTS || []).find((x) => x.id === rec.agentId);
  return (a && a.name) || rec.agent || "";
}

// keep these globals the screens already reference
window.LINK_TYPES = window.DATA.LINK_TYPES;
window.trainingFor = trainingFor;
window.agentNameOf = agentNameOf;
