// admin-data.jsx — Admin live data store (PRODUCTION)
//
// All admin data lives in these module-level objects, populated from the API
// by AdminApp's useEffect on sign-in and on user-triggered refresh.
//
// The synchronous lookup functions (clientById, repById, etc.) read from these
// objects so existing components don't need to be rewritten as async-aware.

const ADMIN_REPS       = window.ADMIN_REPS       = window.ADMIN_REPS       || [];
const REFERRAL_SOURCES = window.REFERRAL_SOURCES = window.REFERRAL_SOURCES || [];
const ADMIN_CLIENTS    = window.ADMIN_CLIENTS    = window.ADMIN_CLIENTS    || [];
const ADMIN_LENDERS    = window.ADMIN_LENDERS    = window.ADMIN_LENDERS    || {};
const ADMIN_ACTIVITY   = window.ADMIN_ACTIVITY   = window.ADMIN_ACTIVITY   || {};
const ADMIN_PAYMENTS   = window.ADMIN_PAYMENTS   = window.ADMIN_PAYMENTS   || {};
const ADMIN_DOCS       = window.ADMIN_DOCS       = window.ADMIN_DOCS       || {};
const ADMIN_AUDIT      = window.ADMIN_AUDIT      = window.ADMIN_AUDIT      || {};

// ─── Store mutators (used by AdminApp + sheets to refresh after writes) ──
function setRoster(list)         { ADMIN_CLIENTS.length = 0;    ADMIN_CLIENTS.push(...(list || [])); }
function setReps(list)           { ADMIN_REPS.length = 0;       ADMIN_REPS.push(...(list || [])); }
function setReferralSources(l)   { REFERRAL_SOURCES.length = 0; REFERRAL_SOURCES.push(...(l || [])); }
function setLendersFor(cid, l)   { ADMIN_LENDERS[cid] = l || []; }
function setActivityFor(cid, l)  { ADMIN_ACTIVITY[cid] = l || []; }
function setPaymentsFor(cid, l)  { ADMIN_PAYMENTS[cid] = l || []; }
function setDocsFor(cid, l)      { ADMIN_DOCS[cid] = l || []; }
function setAuditFor(cid, l)     { ADMIN_AUDIT[cid] = l || []; }

// ─── Sync lookups (read from the live store) ────────────────
function repById(id)         { return ADMIN_REPS.find(r => r.id === id) || null; }
function refById(id)         { return REFERRAL_SOURCES.find(r => r.id === id) || null; }
function clientById(id)      { return ADMIN_CLIENTS.find(c => c.id === id) || null; }
function lendersForClient(id){ return ADMIN_LENDERS[id] || []; }
function paymentsForClient(id){ return ADMIN_PAYMENTS[id] || []; }
function auditForClient(id)  { return ADMIN_AUDIT[id] || []; }

function activityForClient(id, role) {
  const list = ADMIN_ACTIVITY[id] || [];
  if (role === 'referral') return list.filter(e => e.visibility === 'public');
  return list;
}
function docsForClient(id, role) {
  const list = ADMIN_DOCS[id] || [];
  if (role === 'referral') return list.filter(d => d.visibility === 'public');
  return list;
}

// ─── Async loaders (used by AdminApp to populate the store) ──
async function loadRoster(filters = {}) {
  const r = await api.admin.clients(filters);
  setRoster(r.clients);
  return r.clients;
}
async function loadReps() {
  const r = await api.admin.reps();
  setReps(r.reps);
  return r.reps;
}
async function loadReferrals() {
  const r = await api.admin.referrals();
  setReferralSources(r.referrals);
  return r.referrals;
}
async function loadClientDetail(clientId) {
  // Refresh the client + everything beneath it. Used when opening a client file
  // or after a write action that might have changed multiple things.
  const [det, lenders, events, payments, docs, audit] = await Promise.all([
    api.admin.client(clientId),
    api.admin.lenders(clientId),
    api.admin.events(clientId),
    api.admin.payments(clientId).catch(() => ({ payments: [] })),     // referral can't read
    api.admin.documents(clientId),
    api.admin.audit(clientId).catch(() => ({ audit: [] })),           // referral can't read
  ]);

  // Merge fresh client detail into the roster entry
  const idx = ADMIN_CLIENTS.findIndex(c => c.id === clientId);
  if (idx >= 0) ADMIN_CLIENTS[idx] = { ...ADMIN_CLIENTS[idx], ...det.client };
  else ADMIN_CLIENTS.push(det.client);

  setLendersFor(clientId, lenders.lenders);
  setActivityFor(clientId, events.events);
  setPaymentsFor(clientId, payments.payments);
  setDocsFor(clientId, docs.documents);
  setAuditFor(clientId, audit.audit);
}

// expose
Object.assign(window, {
  ADMIN_REPS, REFERRAL_SOURCES, ADMIN_CLIENTS, ADMIN_LENDERS,
  ADMIN_ACTIVITY, ADMIN_PAYMENTS, ADMIN_DOCS, ADMIN_AUDIT,
  setRoster, setReps, setReferralSources,
  setLendersFor, setActivityFor, setPaymentsFor, setDocsFor, setAuditFor,
  repById, refById, clientById, lendersForClient,
  activityForClient, docsForClient, paymentsForClient, auditForClient,
  loadRoster, loadReps, loadReferrals, loadClientDetail,
});
