/* ══════════════════════════════════════════════════════════════════
   ATLAS COCKPIT — FINANCE
   ══════════════════════════════════════════════════════════════════ */

function FinanceView() {
  const D = window.ATLAS_DATA;
  const state = useStore();
  const kpis = state.kpis || {};
  const costOv = state.costs || {};

  // burn from cost table
  let services = 0, tokens = 0, any = false;
  D.costs.perProject.forEach(c => {
    const ov = costOv[c.projectId] || {};
    const s = ov.services !== undefined ? ov.services : c.services;
    const t = ov.tokenDaily !== undefined ? ov.tokenDaily : c.tokenDaily;
    if (s != null) { services += s; any = true; }
    if (t != null) { tokens += t; any = true; }
  });
  const shOv = costOv._shared || {};
  const shS = shOv.services !== undefined ? shOv.services : D.costs.sharedOverhead.services;
  const shT = shOv.tokenDaily !== undefined ? shOv.tokenDaily : D.costs.sharedOverhead.tokenDaily;
  if (shS != null) { services += shS; any = true; }
  if (shT != null) { tokens += shT; any = true; }
  const dailyBurn = any ? services + tokens : null;
  const monthlyBurn = dailyBurn != null ? dailyBurn * 30 : null;

  const cash = kpis.balanceCAD != null ? kpis.balanceCAD : D.cash.balanceCAD;
  const runway = (cash != null && monthlyBurn) ? Math.floor(cash / monthlyBurn) : (kpis.runwayMonths != null ? kpis.runwayMonths : null);
  const anyRev = D.projects.some(p => p.mtdRevenue != null);
  const confirmedMtd = D.projects.reduce((a, p) => p.mtdRevenue != null ? a + p.mtdRevenue : a, 0);
  const mtdVal = kpis.mtdRevenue != null ? kpis.mtdRevenue : (anyRev ? confirmedMtd : null);

  const setKpi = (key, v) => Store.set(s => { const k = { ...s.kpis }; if (v == null) delete k[key]; else k[key] = v; return { ...s, kpis: k }; });

  const scope = state.dateScope === 'qtd' ? 'qtd' : 'mtd';
  const setScope = (v) => setKV({ dateScope: v });
  const scaleQ = scope === 'qtd' ? 3 : 1;
  const scopeLabel = scope === 'qtd' ? 'QTD' : 'MTD';
  const scopedRev = mtdVal == null ? null : mtdVal * scaleQ;

  const cards = [
    { key: 'balanceCAD', label: 'Cash position', icon: 'wallet', sub: 'CAD working balance', val: cash, editable: true },
    { key: 'mrr', label: 'MRR', icon: 'refresh', sub: 'Recurring monthly', val: kpis.mrr != null ? kpis.mrr : D.cash.mrr, editable: true },
    { key: 'mtdRevenue', label: scopeLabel + ' revenue', icon: 'trending', sub: scope === 'qtd' ? 'Quarter-to-date' : 'Month-to-date', val: scope === 'qtd' ? scopedRev : mtdVal, editable: scope === 'mtd', confirmed: scope === 'mtd' && kpis.mtdRevenue == null && anyRev, scopeTag: scopeLabel, qtdEst: scope === 'qtd' && scopedRev != null },
    { key: '_burn', label: 'Monthly burn', icon: 'finance', sub: any ? 'From daily run rate' : 'Enter cost rates below', val: monthlyBurn, editable: false, est: true },
    { key: 'runwayMonths', label: 'Runway', icon: 'scale', sub: runway != null && cash != null && monthlyBurn ? 'Cash ÷ burn' : 'Months remaining', val: runway, editable: true, unit: runway != null ? 'mo' : '' }
  ];

  const ScopeControl = () => React.createElement('div', { className: 'fin-scope' },
    React.createElement('div', { className: 'seg' },
      [['mtd', 'MTD'], ['qtd', 'QTD']].map(([k, l]) => React.createElement('button', { key: k, className: scope === k ? 'on' : '', onClick: () => setScope(k) }, l))),
    React.createElement('span', { className: 'fin-scope-note' }, 'Computed estimates until orchestrator connects.'));

  return React.createElement('div', null,
    React.createElement('div', { className: 'page-head' },
      React.createElement('h1', { className: 'page-h1' }, 'Finance'),
      React.createElement('p', { className: 'page-lead' }, 'Cash, contribution, and burn. Only confirmed values are filled — everything else is editable and held locally until the orchestrator syncs.')),

    React.createElement(ScopeControl),

    React.createElement('div', { className: 'kpi-grid', style: { gridTemplateColumns: 'repeat(auto-fit, minmax(178px, 1fr))', marginBottom: 'var(--s-10)' } },
      cards.map(c => React.createElement('div', { key: c.key, className: cls('kpi', c.editable && 'editable') },
        React.createElement('div', { className: 'kpi-label' }, React.createElement(Icon, { name: c.icon, size: 14, style: { color: 'var(--ink-faint)' } }), React.createElement('span', { className: 't' }, c.label)),
        c.editable
          ? React.createElement('div', { className: cls('kpi-val', c.val == null && 'muted') }, React.createElement(EditableNum, { value: c.val, prefix: c.unit ? '' : '$', onSave: v => setKpi(c.key === 'runwayMonths' ? 'runwayMonths' : c.key, v), width: 110 }), c.unit && c.val != null ? ' ' + c.unit : '')
          : React.createElement('div', { className: cls('kpi-val', c.val == null && 'muted') }, c.val == null ? '—' : fmt$(c.val)),
        React.createElement('div', { className: 'kpi-sub' }, c.sub,
          c.scopeTag && React.createElement('span', { className: 'est-tag' }, c.scopeTag),
          c.confirmed && React.createElement('span', { className: 'est-tag', style: { color: 'var(--success)', background: 'var(--success-weak)' } }, 'confirmed'),
          c.qtdEst && React.createElement('span', { className: 'est-tag' }, 'estimated ×3'),
          c.est && c.val != null && React.createElement('span', { className: 'est-tag' }, 'estimated'))))),

    React.createElement('div', { className: 'block' },
      React.createElement('div', { className: 'block-head' },
        React.createElement('span', { className: 'block-title' }, 'P&L — ', scope === 'qtd' ? 'quarter to date' : 'month to date'),
        React.createElement('span', { className: 'block-aside' },
          React.createElement('div', { className: 'seg', style: { marginRight: 4 } },
            [['mtd', 'MTD'], ['qtd', 'QTD']].map(([k, l]) => React.createElement('button', { key: k, className: scope === k ? 'on' : '', onClick: () => setScope(k) }, l))),
          React.createElement('button', { className: 'btn xs ghost', onClick: () => exportPnl(scope), title: 'Download CSV' }, React.createElement(Icon, { name: 'download', size: 13, className: 'bico' }), 'Export P&L'))),
      React.createElement(PnlTable, { scope })),

    React.createElement('div', { className: 'block' },
      React.createElement('div', { className: 'block-head' },
        React.createElement('span', { className: 'block-title' }, 'Cost & burn — daily run rate'),
        React.createElement('span', { className: 'block-aside' }, React.createElement('span', { className: 'block-count' }, 'Token cost flows from job_runs once live'))),
      React.createElement(CostTable)),

    React.createElement('div', { className: 'block' },
      React.createElement('div', { className: 'block-head' },
        React.createElement('span', { className: 'block-title' }, '30 / 60 / 90 projections'),
        React.createElement('span', { className: 'block-aside' }, React.createElement('span', { className: 'block-count' }, 'Generated once live revenue history exists'))),
      React.createElement(ProjectionsBlock))
  );
}

function ProjectionsBlock() {
  const D = window.ATLAS_DATA;
  const labels = { d30: 'Day 30', d60: 'Day 60', d90: 'Day 90' };
  if (!D.projections) {
    return React.createElement('div', { className: 'proj-grid' },
      ['d30', 'd60', 'd90'].map(k => React.createElement('div', { key: k, className: 'card pad proj-card' },
        React.createElement('div', { className: 'eyebrow' }, labels[k]),
        React.createElement('div', { className: 'proj-val muted' }, '—'),
        React.createElement('div', { className: 'proj-assume' }, React.createElement('span', { className: 'eyebrow' }, 'Pending'), 'Generated once two months of live revenue history exist in Supabase.'))));
  }
  return React.createElement('div', { className: 'proj-grid' },
    Object.entries(D.projections).map(([k, p]) => React.createElement('div', { key: k, className: 'card pad proj-card' },
      React.createElement('div', { className: 'eyebrow' }, labels[k]),
      React.createElement('div', { className: 'proj-val' }, fmt$(p.value)),
      React.createElement('div', { className: 'proj-assume' }, React.createElement('span', { className: 'eyebrow' }, 'Assumes'), p.assume))));
}

function marginClass(actual, target) {
  if (actual == null) return '';
  if (actual >= target) return 'm-good';
  if (actual >= target - 5) return 'm-warn';
  return 'm-bad';
}
function targetOf(p) {
  const t = Store.get().projectTargets[p.id];
  return t != null ? t : (p.targetMarginPct != null ? p.targetMarginPct : 30);
}
function exportPnl(scope) {
  const D = window.ATLAS_DATA;
  const pnl = Store.get().pnl || {};
  const mult = scope === 'qtd' ? 3 : 1;
  const rows = [['project', 'revenue', 'margin_pct', 'target_margin_pct']];
  D.projects.forEach(p => {
    const ov = pnl[p.id] || {};
    const rev = ov.rev !== undefined ? ov.rev : p.mtdRevenue;
    const margin = ov.margin !== undefined ? ov.margin : p.marginPct;
    rows.push([p.name, rev == null ? '' : rev * mult, margin == null ? '' : margin, targetOf(p)]);
  });
  const csv = rows.map(r => r.map(c => /[",\n]/.test(String(c)) ? '"' + String(c).replace(/"/g, '""') + '"' : c).join(',')).join('\n');
  downloadFile(`atlas-pnl-${scope}-${isoDay()}.csv`, csv, 'text/csv');
  toast('P&L exported');
}

function PnlTable({ scope }) {
  const D = window.ATLAS_DATA;
  const state = useStore();
  const pnl = state.pnl || {};
  const mult = scope === 'qtd' ? 3 : 1;
  const setPnl = (id, field, v) => Store.set(s => { const p = { ...s.pnl }; p[id] = { ...(p[id] || {}), [field]: v }; if (v == null) delete p[id][field]; return { ...s, pnl: p }; });

  const rows = D.projects;

  let tRev = 0, tCogs = 0, tContrib = 0;
  const data = rows.map(p => {
    const ov = pnl[p.id] || {};
    const baseRev = ov.rev !== undefined ? ov.rev : p.mtdRevenue;
    const rev = baseRev == null ? null : baseRev * mult;
    const margin = ov.margin !== undefined ? ov.margin : p.marginPct;
    const cogs = (rev != null && margin != null) ? Math.round(rev * (1 - margin / 100)) : null;
    const contrib = (rev != null && cogs != null) ? rev - cogs : null;
    if (rev != null) tRev += rev;
    if (cogs != null) tCogs += cogs;
    if (contrib != null) tContrib += contrib;
    return { p, rev, margin, cogs, contrib, target: targetOf(p), editable: scope === 'mtd' };
  });
  const tm = tRev > 0 ? Math.round((tContrib / tRev) * 100) : null;

  return React.createElement('div', { className: 'fin-wrap scroll' },
    React.createElement('table', { className: 'fin' },
      React.createElement('thead', null, React.createElement('tr', null,
        ['Project', 'Revenue', 'COGS', 'Contribution', 'Margin %', 'Status'].map(h => React.createElement('th', { key: h }, h)))),
      React.createElement('tbody', null,
        data.map(({ p, rev, margin, cogs, contrib, target, editable }) => React.createElement('tr', { key: p.id },
          React.createElement('td', null, p.name),
          React.createElement('td', null, editable
            ? React.createElement(EditableNum, { value: rev, onSave: v => setPnl(p.id, 'rev', v) })
            : React.createElement('span', { className: cls('num', rev == null && 'muted') }, fmt$(rev))),
          React.createElement('td', { className: cls('num', cogs == null && 'muted') }, fmt$(cogs)),
          React.createElement('td', { className: cls('num', contrib == null && 'muted') }, fmt$(contrib)),
          React.createElement('td', { className: cls('margin-cell', marginClass(margin, target)), title: margin != null ? `Target ${target}%` : null },
            editable
              ? React.createElement(EditableNum, { value: margin, prefix: '', placeholder: '—', onSave: v => setPnl(p.id, 'margin', v), width: 60 })
              : React.createElement('span', { className: cls('num', margin == null && 'muted') }, fmtPct(margin))),
          React.createElement('td', null, React.createElement(StatusPill, { status: p.status })))),
        React.createElement('tr', { className: 'total' },
          React.createElement('td', null, 'Portfolio'),
          React.createElement('td', { className: cls('num', !tRev && 'muted') }, fmt$(tRev || null)),
          React.createElement('td', { className: cls('num', !tCogs && 'muted') }, fmt$(tCogs || null)),
          React.createElement('td', { className: cls('num', !tContrib && 'muted') }, fmt$(tContrib || null)),
          React.createElement('td', { className: cls('num', tm == null && 'muted') }, fmtPct(tm)),
          React.createElement('td', null))))
  );
}

function CostTable() {
  const D = window.ATLAS_DATA;
  const state = useStore();
  const ov = state.costs || {};
  const setCost = (key, field, v) => Store.set(s => { const c = { ...s.costs }; c[key] = { ...(c[key] || {}), [field]: v }; if (v == null) delete c[key][field]; return { ...s, costs: c }; });
  const nameOf = id => (D.projects.find(p => p.id === id) || {}).name || id;

  const rows = [...D.costs.perProject.map(c => ({ key: c.projectId, label: nameOf(c.projectId), base: c, notes: c.notes })),
                { key: '_shared', label: 'Shared overhead', base: D.costs.sharedOverhead, notes: D.costs.sharedOverhead.notes }];

  let tS = 0, tT = 0, any = false;
  const data = rows.map(r => {
    const o = ov[r.key] || {};
    const s = o.services !== undefined ? o.services : r.base.services;
    const t = o.tokenDaily !== undefined ? o.tokenDaily : r.base.tokenDaily;
    if (s != null) { tS += s; any = true; }
    if (t != null) { tT += t; any = true; }
    const total = (s != null || t != null) ? (s || 0) + (t || 0) : null;
    const monthly = total != null ? Math.round(total * 30) : null;
    return { ...r, s, t, total, monthly };
  });
  const dTotal = any ? tS + tT : null;
  const mTotal = dTotal != null ? Math.round(dTotal * 30) : null;

  return React.createElement('div', { className: 'fin-wrap scroll' },
    React.createElement('table', { className: 'fin' },
      React.createElement('thead', null, React.createElement('tr', null,
        ['Project', 'Services /day', 'Tokens /day', 'Total /day', 'Monthly est.', 'Notes'].map(h => React.createElement('th', { key: h, style: h === 'Notes' ? { textAlign: 'left' } : null }, h)))),
      React.createElement('tbody', null,
        data.map(r => React.createElement('tr', { key: r.key },
          React.createElement('td', null, r.label),
          React.createElement('td', null, React.createElement(EditableNum, { value: r.s, onSave: v => setCost(r.key, 'services', v) })),
          React.createElement('td', null, React.createElement(EditableNum, { value: r.t, onSave: v => setCost(r.key, 'tokenDaily', v) })),
          React.createElement('td', { className: cls('num', r.total == null && 'muted') }, fmt$(r.total)),
          React.createElement('td', { className: cls('num', r.monthly == null && 'muted') }, fmt$(r.monthly)),
          React.createElement('td', { className: 'cell-note' }, r.notes))),
        React.createElement('tr', { className: 'total' },
          React.createElement('td', null, 'Portfolio total'),
          React.createElement('td', { className: cls('num', !any && 'muted') }, fmt$(any ? tS : null)),
          React.createElement('td', { className: cls('num', !any && 'muted') }, fmt$(any ? tT : null)),
          React.createElement('td', { className: cls('num', dTotal == null && 'muted') }, fmt$(dTotal)),
          React.createElement('td', { className: cls('num', mTotal == null && 'muted') }, fmt$(mTotal)),
          React.createElement('td', { className: 'cell-note' }, 'Daily × 30'))))
  );
}
Object.assign(window, { FinanceView });
