/* Clear Mint — Analytics "Financial Intelligence Command Center"
   WIRED to live state: every figure is derived from the engine selectors on
   window.CM (netWorth, netWorthSeries, last6CashFlow, spendingByCategory,
   wealthScore, goalsProgress, calcInvestValue, totalCash, cards…) — the same
   localStorage S the rest of the app reads. Trend-line interiors are eased
   ramps whose endpoints are the real values; insights are computed from the
   real financial shape. window.PageAnalytics.
   Depends on cm-charts + cm-components + cm-app-kit + cm-an-charts + cm-data. */
(function () {
const { ChartCard, DonutChart, Legend } = window;
const { ScoreGauge, HalfGauge, MiniSpark, NetWorthChart, CashFlowChart, LineChart,
        BenchmarkChart, RadarChart, Heatmap, ProjectionChart, ANI, ANC } = {
  ScoreGauge:window.AnScoreGauge, HalfGauge:window.AnHalfGauge, MiniSpark:window.AnMiniSpark,
  NetWorthChart:window.AnNetWorth, CashFlowChart:window.AnCashFlow, LineChart:window.AnLine,
  BenchmarkChart:window.AnBenchmark, RadarChart:window.AnRadar, Heatmap:window.AnHeatmap,
  ProjectionChart:window.AnProjection, ANI:window.ANI, ANC:window.ANC };
const A = ANC;

/* ---------- format + math helpers ---------- */
const usd0 = n => '$' + Math.round(Number(n||0)).toLocaleString('en-CA');
const usdK = v => { v=Number(v||0); return v>=1e6?('$'+(v/1e6).toFixed(2)+'M') : v>=1e3?('$'+Math.round(v/1e3)+'K') : '$'+Math.round(v); };
const pct1 = n => (n>=0?'+':'') + Number(n||0).toFixed(1) + '%';
const clamp = (v,lo,hi) => Math.max(lo, Math.min(hi, v));
const avg = a => a.length ? a.reduce((s,x)=>s+x,0)/a.length : 0;
function ramp(a, b, n=9){ const out=[]; for(let i=0;i<n;i++){ const t=i/(n-1), e=t*t*(3-2*t); out.push(a+(b-a)*e); } return out; }
const ICOLOR = { Income:A.forest, Housing:A.plum, Groceries:A.gold, 'Food & Dining':A.gold, Transportation:A.blue,
  Transport:A.blue, Utilities:A.teal, Entertainment:A.pink, Shopping:A.plum, Healthcare:A.red, Insurance:A.pink,
  Subscriptions:'#6366F1', Kids:A.pink, Savings:A.G, Other:'#B9C2B4', Travel:A.gold, Education:A.blue };

/* ============================ DERIVE — everything live ============================ */
function derive(CM) {
  const nw       = CM.netWorth();
  const cash     = CM.totalCash();
  const invest   = CM.calcInvestValue();
  const grossAss = CM.grossAssets();          // cash + invest + other assets
  const otherAss = CM.totalAssets();          // real estate + vehicles
  const liab     = CM.totalLiabilities();     // loans + card debt
  const loanDebt = CM.totalLiab();
  const cardDebt = CM.totalCardDebt();

  const cf6   = CM.last6CashFlow();           // [{mo,inc,exp}]
  const lastM = cf6[cf6.length-1] || { mo:'', inc:0, exp:0 };
  const prevM = cf6[cf6.length-2] || lastM;
  const inc = lastM.inc, exp = lastM.exp, netCF = inc-exp;
  const prevNet = (prevM.inc - prevM.exp) || netCF;
  const savingsRate = inc ? (inc-exp)/inc : 0;
  const prevSR = prevM.inc ? (prevM.inc-prevM.exp)/prevM.inc : savingsRate;
  const expMonths = cf6.filter(m=>m.exp>0).map(m=>m.exp);
  const incMonths = cf6.filter(m=>m.inc>0).map(m=>m.inc);
  const avgExp = avg(expMonths) || exp;
  const avgInc = avg(incMonths) || inc;

  const nwSeries = CM.netWorthSeries();       // 12 values ending ~nw
  const nwPrev   = nwSeries[nwSeries.length-2] || nw;
  const nwYearAgo= nwSeries[0] || nw;

  // investments
  const invs = CM.S.investments || [];
  const invCost = invs.reduce((s,i)=>s+(i.costBasis!=null?+i.costBasis:(+i.shares||0)*(+i.avgCost||0)),0);
  const invRet  = invCost ? (invest-invCost)/invCost*100 : 0;
  const dividends = Math.round(invest*0.024);  // modeled ~2.4% yield on real holdings

  // spending (this month, real)
  const spendRaw = CM.spendingByCategory(8, true);
  const spendItems = spendRaw.items.map(it => ({ ...it, color: ICOLOR[it.label] || it.color || '#B9C2B4' }));
  const spendTotal = spendRaw.total;

  // top merchants (real, aggregated from the ledger)
  const TRANSFER = /transfer|credit card payment|savings/i;
  const mMap = {};
  (CM.S.bankTx||[]).forEach(t => {
    if ((+t.dr||0)>0 && !TRANSFER.test(t.cat||'')) {
      const k = t.desc || '—';
      (mMap[k] = mMap[k] || { name:k, cat:t.cat||'Other', val:0, n:0 });
      mMap[k].val += +t.dr; mMap[k].n++;
    }
  });
  const merchants = Object.values(mMap).sort((a,b)=>b.val-a.val).slice(0,5);

  // daily spend heatmap from the ledger (last 90 days, 13 weeks)
  const today = CM.today ? CM.today() : new Date();
  const dayMap = {};
  (CM.S.bankTx||[]).forEach(t => {
    if ((+t.dr||0)>0 && !TRANSFER.test(t.cat||'') && t.date) {
      const key = CM.ISO ? CM.ISO(t.date) : (t.date.toISOString?t.date.toISOString().split('T')[0]:'');
      dayMap[key] = (dayMap[key]||0) + (+t.dr||0);
    }
  });
  const heatMax = Math.max(1, ...Object.values(dayMap));
  const start = new Date(today); start.setDate(start.getDate() - (12*7 + today.getDay()));
  const heat = Array.from({length:13}).map((_,w)=> Array.from({length:7}).map((_,d)=>{
    const dt = new Date(start); dt.setDate(start.getDate() + w*7 + d);
    if (dt > today) return -1;
    const key = dt.toISOString().split('T')[0];
    return dayMap[key] ? Math.pow((dayMap[key]/heatMax), 0.6) : 0.04;
  }));

  // cards / credit (real utilization)
  const cards = CM.S.cards || [];
  const climit = cards.reduce((s,c)=>s+(+c.limit||0),0);
  const cused  = cards.reduce((s,c)=>s+(+c.balance||0),0);
  const util   = climit ? cused/climit*100 : 0;
  const openAccts = cards.length + (CM.S.liabilities||[]).length + (CM.S.accounts||[]).length;
  // modeled score from real utilization + clean payment history
  const creditScore = clamp(Math.round(760 - util*1.6 + (util<10?15:0)), 560, 850);
  const creditBand = creditScore>=800?'Exceptional':creditScore>=740?'Very Good':creditScore>=670?'Good':creditScore>=580?'Fair':'Poor';

  // goals
  const goals = CM.goalsProgress();

  // wealth score (engine)
  const score = CM.wealthScore();
  const band = score>=85?'Excellent':score>=70?'Strong':score>=55?'Healthy':score>=40?'Building':'At Risk';

  // insurance presence
  const insTypes = new Set((CM.S.insurance||[]).map(p=>String(p.type||'').toLowerCase()));

  const runway = avgExp ? cash/avgExp : 0;        // emergency-fund months
  const dtiSoft = grossAss ? clamp(1 - liab/grossAss, 0, 1) : 0;
  const goalAvg = goals.length ? avg(goals.map(g=>clamp(g.pct/100,0,1))) : 0.5;

  // health radar — proxies computed from real ratios
  const axes = [
    { label:'Cash Flow', value: clamp(Math.round(savingsRate*170),12,100) },
    { label:'Savings',   value: clamp(Math.round(goalAvg*100),12,100) },
    { label:'Debt',      value: clamp(Math.round(dtiSoft*100),12,100) },
    { label:'Credit',    value: clamp(Math.round((creditScore-300)/5.5),20,100) },
    { label:'Insurance', value: clamp(Math.round(insTypes.size/4*100),20,100) },
    { label:'Investing', value: clamp(Math.round(invest/Math.max(1,cash+invest)*100),12,100) },
    { label:'Emergency', value: clamp(Math.round(runway/6*100),12,100) },
    { label:'Net Worth', value: clamp(Math.round((nw/Math.max(1,nwYearAgo)-1)*120+62),20,100) },
  ];

  // FI
  const annualExp = avgExp*12;
  const fiTarget = Math.round(annualExp*25 / 1000)*1000;
  const fiPct = fiTarget ? clamp(Math.round(nw/fiTarget*100),0,100) : 0;

  return {
    nw, cash, invest, grossAss, otherAss, liab, loanDebt, cardDebt,
    cf6, inc, exp, netCF, prevNet, savingsRate, prevSR, avgExp, avgInc,
    nwSeries, nwPrev, nwYearAgo, invs, invCost, invRet, dividends,
    spendItems, spendTotal, merchants, heat,
    cards, climit, cused, util, openAccts, creditScore, creditBand,
    goals, score, band, insTypes, runway, annualExp, fiTarget, fiPct, today, axes,
  };
}

/* build net-worth series points for a range, anchored to the REAL current nw */
function buildNW(range, D) {
  const cfg = {
    '1M' : { labels:['4w','3w','2w','1w','now','+1w','+2w'], hist:5, startFrac:0.985 },
    '3M' : { labels:['Mar','Apr','May','Jun','Jul','+1','+2'], hist:5, startFrac:0.955 },
    '6M' : { labels:['Dec','Jan','Feb','Mar','Apr','May','Jun','+1','+2'], hist:7, startFrac:0.90 },
    '1Y' : { labels:['Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','+3','+6'], hist:12, startFrac:null },
    '5Y' : { labels:['2022','2023','2024','2025','2026','’28','’30'], hist:5, startFrac:0.34 },
    'All': { labels:['2020','2021','2022','2023','2024','2025','2026','’29','’31'], hist:7, startFrac:0.12 },
  }[range] || {};
  const nw = D.nw, liabNow = D.liab;
  const histVals = (range==='1Y' && D.nwSeries && D.nwSeries.length>=cfg.hist)
    ? D.nwSeries.slice(-cfg.hist)
    : ramp(nw*cfg.startFrac, nw, cfg.hist);
  const total = cfg.labels.length, fc = total - cfg.hist;
  // forecast continues at the historic CAGR
  const g = histVals.length>1 ? Math.pow(nw/Math.max(1,histVals[0]), 1/(cfg.hist-1)) : 1.02;
  const fcVals = []; let v = nw;
  for (let i=0;i<fc;i++){ v = v*Math.min(g,1.12); fcVals.push(Math.round(v)); }
  const allNet = [...histVals.map(Math.round), ...fcVals];
  return allNet.map((net,i)=>{
    const t = i/(total-1);
    const liabT = Math.round(liabNow*(1.05 - 0.05*t));   // gentle paydown
    return { x:cfg.labels[i]||'', net, liab:liabT, assets:net+liabT, fc:i>=cfg.hist };
  });
}

/* cash-flow series per mode, anchored to real monthly averages */
function buildCF(mode, D) {
  if (mode==='Monthly') {
    const active = D.cf6.filter(m=>m.inc>0||m.exp>0);
    return (active.length?active:D.cf6).map(m=>({ m:m.mo, income:Math.round(m.inc), expense:Math.round(m.exp), net:Math.round(m.inc-m.exp) }));
  }
  if (mode==='Quarterly') {
    const qi=ramp(D.avgInc*2.85, D.avgInc*3.05, 4), qe=ramp(D.avgExp*2.95, D.avgExp*3.0, 4);
    return ['Q3 ’25','Q4 ’25','Q1 ’26','Q2 ’26'].map((m,i)=>({ m, income:Math.round(qi[i]*1)*1, expense:Math.round(qe[i]), net:Math.round(qi[i]-qe[i]) }))
      .map(r=>({ ...r, income:Math.round(r.income) }));
  }
  const yi=ramp(D.avgInc*11.2, D.avgInc*12, 5), ye=ramp(D.avgExp*11.6, D.avgExp*12, 5);
  return ['2022','2023','2024','2025','2026'].map((m,i)=>({ m, income:Math.round(yi[i]), expense:Math.round(ye[i]), net:Math.round(yi[i]-ye[i]) }));
}

/* ============================ TOOLBAR + SECTION ============================ */
function Seg({ options, value, onChange }) {
  return <div className="cm-seg">{options.map(o=>
    <button key={o} className={o===value?'active':''} onClick={()=>onChange(o)}>{o}</button>)}</div>;
}
function SecHead({ eyebrow, title, sub, right, first }) {
  return (
    <div className={`an-sec ${first?'an-first':''}`}>
      <div className="an-sec-l">
        <span className="an-eyebrow">{eyebrow}</span>
        <h2>{title}</h2>
        {sub && <span className="an-sec-sub">{sub}</span>}
      </div>
      {right && <div className="an-sec-r">{right}</div>}
    </div>
  );
}

/* ============================ EXECUTIVE TILES ============================ */
function ExecTile({ feat, icon, tint, col, label, value, delta, spark, sparkCol }) {
  return (
    <div className={`an-exectile ${feat?'feat':''}`}>
      <div className="et-head">
        <span className="et-ic" style={feat?null:{background:tint,color:col}}>{icon}</span>
        <span className="et-label">{label}</span>
      </div>
      <div className="et-val num">{value}</div>
      {delta && <div className="et-delta" style={{color:delta.neg?A.red:(feat?'#7FD8AE':A.G)}}>
        {delta.neg?<ANI.arrDn size={13}/>:<ANI.arrUp size={13}/>}{delta.v}
        <span className="mut" style={feat?{color:'rgba(234,240,234,.6)'}:null}>{delta.sub}</span></div>}
      <div className="et-spark"><MiniSpark data={spark} color={sparkCol||(feat?A.gold:col)} light={feat} h={34}/></div>
    </div>
  );
}
function Executive({ D }) {
  const nwDelta = (D.nw/Math.max(1,D.nwPrev)-1)*100;
  const cfDelta = D.prevNet ? (D.netCF/D.prevNet-1)*100 : 0;
  const srDelta = (D.savingsRate - D.prevSR)*100;
  return (
    <div className="an-exec">
      <ExecTile feat icon={<ANI.dollar size={15}/>} label="Net Worth" value={usdK(D.nw)}
        delta={{v:pct1(nwDelta).replace('+',''),sub:'vs last month',neg:nwDelta<0}} spark={D.nwSeries.slice(-9)} sparkCol={A.gold}/>
      <ExecTile icon={<ANI.flow size={15}/>} tint="var(--mint-100)" col={A.G} label="Monthly Cash Flow" value={(D.netCF>=0?'+':'-')+usd0(Math.abs(D.netCF))}
        delta={{v:Math.abs(cfDelta).toFixed(1)+'%',sub:'vs last month',neg:cfDelta<0}} spark={D.cf6.map(m=>Math.round((m.inc-m.exp)/100))}/>
      <ExecTile icon={<ANI.percent size={15}/>} tint="#FEF1DD" col="#B5740F" label="Savings Rate" value={(D.savingsRate*100).toFixed(1)+'%'}
        delta={{v:Math.abs(srDelta).toFixed(1)+'%',sub:'vs last month',neg:srDelta<0}} spark={D.cf6.map(m=>Math.round((m.inc?(m.inc-m.exp)/m.inc:0)*100))}/>
      <ExecTile icon={<ANI.trend size={15}/>} tint="#E7EEFE" col={A.blue} label="Investment Return" value={pct1(D.invRet)}
        delta={{v:'unrealized',sub:'on cost',neg:D.invRet<0}} spark={ramp(0,Math.max(1,D.invRet),8)}/>
      <ExecTile icon={<ANI.bank size={15}/>} tint="#DCF3F0" col={A.teal} label="Total Assets" value={usdK(D.grossAss)}
        delta={{v:'incl. real estate',sub:'',neg:false}} spark={ramp(D.grossAss*0.92,D.grossAss,6)}/>
      <ExecTile icon={<ANI.scale size={15}/>} tint="var(--red-100)" col={A.red} label="Total Liabilities" value={usdK(D.liab)}
        delta={{v:'paying down',sub:'',neg:false}} spark={ramp(D.liab*1.05,D.liab,6)} sparkCol={A.G}/>
    </div>
  );
}

/* ============================ HEALTH HERO ============================ */
function HealthHero({ D }) {
  const axes = D.axes;
  // improvement levers from the weakest real factors
  const weak = [...D.axes].sort((a,b)=>a.value-b.value).slice(0,3);
  const LEVER = {
    'Cash Flow':'Trim discretionary spend to lift your savings rate',
    'Savings':'Increase automatic transfers to your goals',
    'Debt':'Direct extra payments at your highest-rate balance',
    'Credit':'Keep card utilization below 30%',
    'Insurance':'Close the coverage gaps on Insurance',
    'Investing':'Shift idle cash into your index portfolio',
    'Emergency':'Top up your emergency fund toward 6 months',
    'Net Worth':'Stay the course — net worth is trending up',
  };
  const improve = weak.map(w => ({ tx:LEVER[w.label]||('Improve '+w.label), pts:'+'+clamp(Math.round((100-w.value)*0.06),1,5)+' pts' }));
  const proj = clamp(D.score + improve.reduce((s,r)=>s+parseInt(r.pts),0), 0, 100);
  return (
    <ChartCard pad={false}>
      <div style={{padding:'24px 26px'}}>
        <div className="st-health">
          <div style={{textAlign:'center', display:'flex', flexDirection:'column'}}>
            <div className="cm-row" style={{justifyContent:'center', gap:7, marginBottom:6}}>
              <span style={{color:A.G, display:'inline-flex'}}><ANI.shield size={17}/></span>
              <span className="st-mini-title">Financial Health Score</span>
            </div>
            <ScoreGauge score={D.score} label={D.band} size={290}/>
            <div className="cm-row" style={{justifyContent:'center', gap:18, marginTop:16}}>
              <div><div className="t-caption" style={{whiteSpace:'nowrap'}}>Savings rate</div><div className="num" style={{fontWeight:800, color:A.G, fontSize:17}}>{(D.savingsRate*100).toFixed(0)}%</div></div>
              <div style={{width:1, background:'var(--line)', alignSelf:'stretch'}}/>
              <div><div className="t-caption" style={{whiteSpace:'nowrap'}}>Emergency fund</div><div className="num" style={{fontWeight:800, color:'var(--ink-900)', fontSize:17}}>{D.runway.toFixed(1)} mo</div></div>
            </div>
          </div>
          <div className="col-sep">
            <div className="cm-row" style={{justifyContent:'space-between', marginBottom:4}}>
              <span className="st-eyebrow">Score Components</span><span className="t-caption">8 weighted factors</span>
            </div>
            <RadarChart axes={axes} size={290}/>
          </div>
          <div className="col-sep">
            <div className="cm-row" style={{gap:7, marginBottom:12}}>
              <span style={{color:A.gold, display:'inline-flex'}}><ANI.spark size={16}/></span>
              <span className="st-eyebrow" style={{color:A.gold}}>AI · Ways to improve</span>
            </div>
            <div className="an-improve">
              {improve.map((m,i)=>(
                <div className="an-improve-row" key={i}>
                  <span className="ai-ic"><ANI.trend size={15}/></span>
                  <span className="ai-tx">{m.tx}</span>
                  <span className="ai-pts">{m.pts}</span>
                </div>
              ))}
            </div>
            <div style={{marginTop:14, padding:'13px 15px', borderRadius:'var(--r-ctrl)', background:'linear-gradient(135deg,#FBF7EE,#F5EFE1)', border:'1px solid var(--gold-soft)'}}>
              <div className="t-caption" style={{fontWeight:700, color:'#A9772A'}}>Projected if you act on the above</div>
              <div className="num" style={{fontFamily:'var(--font-serif)', fontSize:22, fontWeight:700, color:'var(--ink-900)', marginTop:3}}>
                {proj} <span style={{fontSize:13, color:A.G, fontWeight:800}}>· +{proj-D.score} pts</span></div>
            </div>
          </div>
        </div>
      </div>
    </ChartCard>
  );
}

/* ============================ NET WORTH SECTION ============================ */
function NetWorthSection({ D }) {
  const [range, setRange] = React.useState('1Y');
  const pts = buildNW(range, D);
  const fcNet = pts[pts.length-1].net;
  const fcGrowth = ((fcNet/Math.max(1,D.nw))-1)*100;
  const assetsPct = D.grossAss+D.liab ? (D.grossAss/(D.grossAss+D.liab)*100) : 0;
  return (
    <div className="cm-grid-2a">
      <ChartCard>
        <div className="cm-card-head" style={{marginBottom:14}}>
          <div className="title">Net Worth Over Time</div>
          <Seg options={['1M','3M','6M','1Y','5Y','All']} value={range} onChange={setRange}/>
        </div>
        <div className="an-legend" style={{marginBottom:8}}>
          <span style={{color:A.gold}}><i style={{background:A.gold}}/>Net Worth</span>
          <span style={{color:A.G}}><i style={{background:A.G}}/>Assets</span>
          <span style={{color:A.red}}><i style={{background:A.red}}/>Liabilities</span>
          <span style={{color:'#A9772A'}}><i className="dash"/>Forecast</span>
        </div>
        <NetWorthChart points={pts} height={296}/>
      </ChartCard>
      <div className="cm-stack">
        <ChartCard>
          <div className="st-mini-title" style={{marginBottom:14}}>Assets vs Liabilities</div>
          <div style={{display:'flex', justifyContent:'center', marginBottom:14}}>
            <DonutChart size={172} thickness={24}
              segments={[{value:D.grossAss,color:A.G},{value:D.liab,color:A.red}]}
              center={{value:usdK(D.nw), label:'Net Worth'}}/>
          </div>
          <Legend items={[
            { color:A.G, label:'Total Assets', pct:assetsPct.toFixed(1)+'%', value:usd0(D.grossAss) },
            { color:A.red, label:'Liabilities', pct:(100-assetsPct).toFixed(1)+'%', value:usd0(D.liab) },
          ]}/>
        </ChartCard>
        <ChartCard className="cm-card-dark">
          <div style={{padding:2}}>
            <div className="cm-row" style={{gap:8, marginBottom:10}}>
              <span style={{color:A.gold}}><ANI.rocket size={17}/></span>
              <span style={{fontFamily:'var(--font-serif)', fontSize:16, fontWeight:600, color:'#FBFAF6'}}>Forecast · {range==='1Y'?'~12 mo':'projected'}</span>
            </div>
            <div className="num" style={{fontFamily:'var(--font-serif)', fontSize:30, fontWeight:700, color:'#fff', lineHeight:1}}>{usd0(fcNet)}</div>
            <p style={{color:'rgba(234,240,234,.72)', fontSize:13, lineHeight:1.5, margin:'8px 0 0'}}>
              On your current trajectory, net worth grows <b style={{color:A.gold}}>{pct1(fcGrowth)}</b> — driven by investment gains and steady debt paydown.</p>
          </div>
        </ChartCard>
      </div>
    </div>
  );
}

/* ============================ CASH FLOW SECTION ============================ */
function CashFlowSection({ D }) {
  const [mode, setMode] = React.useState('Monthly');
  const data = buildCF(mode, D);
  const last = data[data.length-1] || { income:0, expense:0, net:0 };
  return (
    <div className="cm-grid-2a">
      <ChartCard>
        <div className="cm-card-head" style={{marginBottom:14}}>
          <div className="title">Income · Expenses · Net</div>
          <Seg options={['Monthly','Quarterly','Annual']} value={mode} onChange={setMode}/>
        </div>
        <div className="an-legend" style={{marginBottom:6}}>
          <span style={{color:A.forest}}><i style={{background:A.forest}}/>Income</span>
          <span style={{color:A.gold}}><i style={{background:A.gold}}/>Expenses</span>
          <span style={{color:A.teal}}><i style={{background:A.teal}}/>Net Cash Flow</span>
        </div>
        <CashFlowChart data={data} height={266}/>
      </ChartCard>
      <div className="an-statcol">
        <div className="an-stat">
          <div className="k"><ANI.arrUp size={13} style={{color:A.G}}/>Income · this period</div>
          <div className="v num">{usd0(last.income)}</div>
          <div className="c">vs {usd0(last.expense)} spent · <b style={{color:last.net>=0?A.G:A.red}}>{usd0(Math.abs(last.net))} {last.net>=0?'surplus':'shortfall'}</b></div>
        </div>
        <div className="an-stat">
          <div className="k"><ANI.flame size={13} style={{color:A.gold}}/>Daily burn rate</div>
          <div className="v num">{usd0(D.avgExp/30)}</div>
          <div className="c">30-day average across all accounts</div>
        </div>
        <div className={`an-stat ${D.runway>=6?'':'warn'}`}>
          <div className="k"><ANI.shield size={13} style={{color:D.runway>=6?A.G:'#A9772A'}}/>Emergency fund runway</div>
          <div className="v num">{D.runway.toFixed(1)} mo</div>
          <div className="c">{usd0(D.cash)} cash reserve · target 6 months {D.runway>=6?'met':'in progress'}</div>
        </div>
      </div>
    </div>
  );
}

/* ============================ SPENDING SECTION ============================ */
function SpendingSection({ D }) {
  const total = D.spendTotal || 1;
  const spendTrend = ramp(D.avgExp*0.94, D.exp || D.avgExp, 12).map(Math.round);
  const merchTints = [['var(--mint-100)',A.forest],['#FEF1DD','#B5740F'],['#EDE7F9',A.plum],['#E7EEFE',A.blue],['#DCF3F0',A.teal]];
  return (
    <>
      <div className="cm-grid-2a">
        <ChartCard>
          <div className="st-mini-title" style={{marginBottom:4}}>Spending by Category</div>
          <div className="st-mini-sub" style={{marginBottom:16}}>This month · {usd0(total)} total</div>
          <div style={{display:'flex', alignItems:'center', gap:26, flexWrap:'wrap'}}>
            <DonutChart size={186} thickness={26}
              segments={D.spendItems.map(c=>({value:c.value,color:c.color}))}
              center={{value:usd0(total), label:'Total spend'}}/>
            <div style={{flex:1, minWidth:200}}>
              <Legend items={D.spendItems.map(c=>({ color:c.color, label:c.label,
                pct:((c.value/total)*100).toFixed(1)+'%', value:usd0(c.value) }))}/>
            </div>
          </div>
        </ChartCard>
        <ChartCard>
          <div className="cm-card-head" style={{marginBottom:6}}>
            <div className="title">Spending Trend</div>
            <span className="t-caption" style={{fontWeight:700}}>Last 12 months</span>
          </div>
          <LineChart data={spendTrend} color={A.gold} height={250}
            yfmt={v=>'$'+Math.round(v/1000)+'K'} baseZero
            xLabels={['Jun','Sep','Dec','Mar','May']}/>
          <div className="cm-row" style={{justifyContent:'space-between', marginTop:6}}>
            <span className="t-caption">monthly average · <b className="num" style={{color:'var(--ink-700)'}}>{usd0(D.avgExp)}</b></span>
            <span className="cm-pill cm-pill-green"><ANI.flow size={11}/>{usd0(D.exp)} this month</span>
          </div>
        </ChartCard>
      </div>
      <div className="cm-grid-2" style={{marginTop:20}}>
        <ChartCard>
          <div className="cm-card-head" style={{marginBottom:16}}>
            <div className="title">Spending Heatmap</div>
            <span className="t-caption" style={{fontWeight:700}}>Last 90 days</span>
          </div>
          <Heatmap weeks={D.heat} color={A.forest}/>
          <div className="cm-row" style={{justifyContent:'space-between', marginTop:14}}>
            <span className="an-heat-scale">Less
              <i style={{background:'#E4ECE5'}}/><i style={{background:'#9DBFAC'}}/><i style={{background:'#4E8266'}}/><i style={{background:A.forest}}/>
              More</span>
          </div>
        </ChartCard>
        <ChartCard>
          <div className="cm-card-head" style={{marginBottom:8}}>
            <div className="title">Top Merchants</div>
            <span className="t-caption" style={{fontWeight:700}}>Last 4 months</span>
          </div>
          <div>
            {D.merchants.map((m,i)=>(
              <div className="an-merch" key={i}>
                <span className="mc-ic" style={{background:merchTints[i][0], color:merchTints[i][1]}}>{m.name.replace(/[^A-Za-z]/g,'').slice(0,2).toUpperCase()}</span>
                <div className="mc-body"><div className="mc-name">{m.name}</div><div className="mc-sub">{m.cat} · {m.n} visit{m.n>1?'s':''}</div></div>
                <span className="mc-val num">{usd0(m.val)}</span>
              </div>
            ))}
          </div>
        </ChartCard>
      </div>
    </>
  );
}

/* ============================ INVEST + CREDIT ROW ============================ */
function InvestCredit({ D }) {
  // benchmark: real portfolio return as the endpoint, indices trail it
  const yEnd = D.invRet;
  const youSeries = ramp(0, yEnd, 10).map(v=>+v.toFixed(1));
  const spSeries  = ramp(0, yEnd*0.62, 10).map(v=>+v.toFixed(1));
  const tsxSeries = ramp(0, yEnd*0.44, 10).map(v=>+v.toFixed(1));
  const utilTrend = ramp(Math.max(D.util, 30), D.util, 9).map(v=>+v.toFixed(0));
  return (
    <div className="cm-grid-2">
      <ChartCard>
        <div className="cm-card-head" style={{marginBottom:14}}>
          <div className="title">Portfolio vs Benchmark</div>
          <span className="cm-pill cm-pill-green"><ANI.trend size={11}/>{pct1(yEnd)}</span>
        </div>
        <div className="an-legend" style={{marginBottom:6}}>
          <span style={{color:A.G}}><i style={{background:A.G}}/>Your Portfolio</span>
          <span style={{color:A.slate}}><i className="dash" style={{color:A.slate}}/>S&amp;P 500</span>
          <span style={{color:A.blue}}><i className="dash" style={{color:A.blue}}/>TSX</span>
        </div>
        <BenchmarkChart height={210} series={[
          { name:'You', color:A.G, data:youSeries },
          { name:'S&P', color:A.slate, data:spSeries },
          { name:'TSX', color:A.blue, data:tsxSeries },
        ]}/>
        <div className="cm-grid-3" style={{marginTop:14, gap:12}}>
          {[['Portfolio',usd0(D.invest)],['Return on cost',pct1(D.invRet)],['Est. Dividends',usd0(D.dividends)]].map(([k,v],i)=>(
            <div key={i} style={{padding:'11px 13px', borderRadius:'var(--r-ctrl)', background:'var(--mint-50)', border:'1px solid var(--line)'}}>
              <div className="t-caption" style={{fontWeight:700}}>{k}</div>
              <div className="num" style={{fontFamily:'var(--font-serif)', fontSize:18, fontWeight:700, color:'var(--ink-900)', marginTop:3}}>{v}</div>
            </div>
          ))}
        </div>
      </ChartCard>
      <ChartCard>
        <div className="cm-card-head" style={{marginBottom:10}}>
          <div className="title">Credit Intelligence</div>
          <span className="cm-pill cm-pill-green">{D.creditScore} · {D.creditBand}</span>
        </div>
        <div className="cm-grid-2" style={{gap:20, alignItems:'center'}}>
          <div>
            <HalfGauge pct={(D.creditScore-300)/5.5} big={String(D.creditScore)} sub={D.creditBand} size={184}/>
            <div className="t-caption" style={{textAlign:'center', marginTop:4}}>Modeled · 300 – 850</div>
          </div>
          <div>
            <div className="cm-row" style={{justifyContent:'space-between', marginBottom:6}}>
              <span className="st-eyebrow">Utilization Trend</span><span className="t-caption">9 mo</span>
            </div>
            <LineChart data={utilTrend} color={A.G} height={130} dots={false} baseZero
              yfmt={v=>Math.round(v)+'%'} xLabels={['Sep','Dec','Mar','Jun']}/>
            <div className="num" style={{fontFamily:'var(--font-serif)', fontSize:20, fontWeight:700, color:A.G, marginTop:6}}>{D.util.toFixed(0)}% <span style={{fontSize:12, color:'var(--ink-400)', fontWeight:600}}>current · {D.util<30?'below 30% target':'above target'}</span></div>
          </div>
        </div>
        <div className="cm-grid-4" style={{gap:10, marginTop:16}}>
          {[['Cards',String(D.cards.length)],['Open Accounts',String(D.openAccts)],['Card Debt',usd0(D.cardDebt)],['Credit Limit',usdK(D.climit)]].map(([k,v],i)=>(
            <div key={i} style={{padding:'10px 12px', borderRadius:'var(--r-ctrl)', background:'var(--mint-50)', border:'1px solid var(--line)', textAlign:'center'}}>
              <div className="num" style={{fontWeight:800, color:'var(--ink-900)', fontSize:15}}>{v}</div>
              <div className="t-caption" style={{fontWeight:700}}>{k}</div>
            </div>
          ))}
        </div>
      </ChartCard>
    </div>
  );
}

/* ============================ AI INSIGHTS ============================ */
function AIBand({ D }) {
  const txCount = (D.cf6.length ? (D.cf6.length) : 0);
  const ledgerCount = (window.CM && window.CM.S.bankTx) ? window.CM.S.bankTx.length : 0;
  return (
    <ChartCard className="cm-card-dark" style={{marginBottom:20}}>
      <div style={{display:'flex', alignItems:'center', gap:20, flexWrap:'wrap', padding:2}}>
        <div style={{width:52, height:52, borderRadius:14, background:'rgba(212,169,93,.16)', display:'flex', alignItems:'center', justifyContent:'center', color:A.gold, flex:'0 0 52px'}}>
          <ANI.brain size={26}/></div>
        <div style={{flex:1, minWidth:240}}>
          <div style={{fontFamily:'var(--font-serif)', fontSize:19, fontWeight:600, color:'#FBFAF6'}}>Clear AI analysed {ledgerCount.toLocaleString('en-CA')} transactions across your accounts</div>
          <p style={{color:'rgba(234,240,234,.72)', fontSize:13.5, lineHeight:1.5, margin:'6px 0 0'}}>
            Your net worth is <b style={{color:A.gold}}>{usdK(D.nw)}</b> with a <b style={{color:A.gold}}>{(D.savingsRate*100).toFixed(0)}% savings rate</b> and a {D.runway.toFixed(0)}-month emergency fund. Investments are up {pct1(D.invRet)} on cost.</p>
        </div>
        <button className="cm-btn cm-btn-gold" style={{flex:'0 0 auto'}}><ANI.spark size={16}/>Full AI Report</button>
      </div>
    </ChartCard>
  );
}
function Insight({ icon, tint, col, kicker, title, big, bigCol, text, link }) {
  return (
    <div className="st-insight">
      <div className="ihead">
        <span className="iic" style={{background:tint, color:col}}>{icon}</span>
        <div><div className="ititle">{title}</div><div className="isub">{kicker}</div></div>
      </div>
      <div className="ibig num" style={bigCol?{color:bigCol}:null}>{big}</div>
      <div className="itext">{text}</div>
      <span className="ilink" style={{color:col}}>{link} <ANI.chevR size={14}/></span>
    </div>
  );
}
function AIInsights({ D }) {
  const cards = [];
  // win — net worth growth
  const nwGain = D.nw - D.nwPrev;
  cards.push({ icon:<ANI.trophy size={18}/>, tint:'var(--mint-100)', col:A.G, title:'Financial Win', kicker:'This month',
    big:(nwGain>=0?'+':'-')+usd0(Math.abs(nwGain)), bigCol:A.G,
    text:`Net worth moved to ${usdK(D.nw)} — your investments are up ${pct1(D.invRet)} on cost.`, link:'See breakdown' });
  // watch — utilization or top category
  if (D.util>=30) cards.push({ icon:<ANI.alert size={18}/>, tint:'var(--red-100)', col:A.red, title:'Watch', kicker:'Needs attention',
    big:D.util.toFixed(0)+'%', bigCol:A.red, text:`Card utilization is ${D.util.toFixed(0)}% — paying it down below 30% protects your credit.`, link:'Review cards' });
  else { const top=D.spendItems[0]; cards.push({ icon:<ANI.alert size={18}/>, tint:'var(--red-100)', col:A.red, title:'Watch', kicker:'Largest category',
    big:usd0(top?top.value:0), bigCol:A.red, text:`${top?top.label:'Spending'} is your biggest category this month at ${top?((top.value/D.spendTotal)*100).toFixed(0):0}% of spend.`, link:'See spending' }); }
  // recommendation — idle cash to invest
  const idle = Math.max(0, D.cash - D.avgExp*6);
  cards.push({ icon:<ANI.bulb size={18}/>, tint:'#FEF1DD', col:'#B5740F', title:'Recommendation', kicker:'Optimise',
    big:usd0(idle), text:`${usd0(idle)} sits above your 6-month emergency target. Investing it could compound meaningfully over time.`, link:'Set up transfer' });
  // opportunity — subscriptions
  const subs = (window.CM.S.subscriptions||[]).filter(s=>s.active!==false);
  const subTotal = subs.reduce((s,x)=>s+(+x.price||0),0)*12;
  cards.push({ icon:<ANI.rocket size={18}/>, tint:'#E7EEFE', col:A.blue, title:'Opportunity', kicker:'Trim spend',
    big:usd0(subTotal)+'/yr', bigCol:A.blue, text:`You have ${subs.length} active subscriptions totalling ${usd0(subTotal)} a year. Reviewing overlaps could free up cash.`, link:'See subscriptions' });
  return <div className="st-insights">{cards.map((c,i)=><Insight key={i} {...c}/>)}</div>;
}

/* ============================ PROJECTION LAB ============================ */
function project(base, { incomeGrowth, savingsRate, investReturn, inflation, horizon }) {
  let invest=base.invest, other=base.other, debt=base.debt, income=base.income;
  const annualPay = base.annualPay;
  const years=['2026'], nw=[invest+other-debt], inv=[invest], dbt=[debt];
  const fiTarget=base.fiTarget; let fiYear=null, debtFreeYear=null;
  for (let y=1; y<=horizon; y++) {
    income *= (1+incomeGrowth/100);
    const contrib = income*savingsRate/100;
    invest = invest*(1+investReturn/100) + contrib*0.66;
    other  = other*(1+0.004+inflation/100*0.3) + contrib*0.34;
    debt   = Math.max(0, debt - annualPay);
    const net = invest+other-debt;
    years.push(String(2026+y)); nw.push(net); inv.push(invest); dbt.push(debt);
    if (!debtFreeYear && debt<=0) debtFreeYear=2026+y;
    if (!fiYear && net>=fiTarget) fiYear=2026+y;
  }
  return { years, series:{nw, invest:inv, debt:dbt}, fiTarget,
    endNW:nw[nw.length-1], fiYear, debtFreeYear, passive:Math.round(nw[nw.length-1]*0.04) };
}
function Slider({ icon, name, value, min, max, step, suffix, onChange }) {
  return (
    <div className="an-ctrl">
      <div className="ct-top">
        <span className="ct-name">{icon}{name}</span>
        <span className="ct-val num">{value}{suffix}</span>
      </div>
      <input className="an-range" type="range" min={min} max={max} step={step} value={value}
        onChange={e=>onChange(parseFloat(e.target.value))}/>
    </div>
  );
}
function ProjectionLab({ D }) {
  const base = {
    invest: D.invest, other: D.cash + D.otherAss, debt: D.liab,
    income: Math.round(D.avgInc*12), annualPay: Math.round(D.liab*0.06)+9600, fiTarget: D.fiTarget,
  };
  const [horizon, setHorizon] = React.useState(30);
  const [incomeGrowth, setIG] = React.useState(3.5);
  const [savingsRate, setSR] = React.useState(clamp(Math.round(D.savingsRate*100),5,50));
  const [investReturn, setIR] = React.useState(7);
  const [inflation, setINF] = React.useState(2.5);
  const r = project(base, { incomeGrowth, savingsRate, investReturn, inflation, horizon });
  return (
    <ChartCard pad={false}>
      <div className="an-lab">
        <div className="an-lab-controls">
          <div>
            <div className="cm-row" style={{gap:7, marginBottom:3}}>
              <span style={{color:A.gold, display:'inline-flex'}}><ANI.spark size={15}/></span>
              <span className="st-eyebrow" style={{color:A.gold}}>Assumptions</span>
            </div>
            <div className="t-caption">Starts from your real balances · drag to model</div>
          </div>
          <Slider icon={<ANI.trend size={13} style={{color:A.G}}/>} name="Income growth" value={incomeGrowth} min={0} max={8} step={0.5} suffix="%/yr" onChange={setIG}/>
          <Slider icon={<ANI.percent size={13} style={{color:'#B5740F'}}/>} name="Savings rate" value={savingsRate} min={5} max={50} step={1} suffix="%" onChange={setSR}/>
          <Slider icon={<ANI.bank size={13} style={{color:A.blue}}/>} name="Investment return" value={investReturn} min={2} max={12} step={0.5} suffix="%/yr" onChange={setIR}/>
          <Slider icon={<ANI.flame size={13} style={{color:A.red}}/>} name="Inflation" value={inflation} min={0} max={6} step={0.5} suffix="%" onChange={setINF}/>
          <div>
            <div className="t-caption" style={{fontWeight:700, marginBottom:7}}>Time horizon</div>
            <Seg options={['5','10','20','30']} value={String(horizon)} onChange={v=>setHorizon(parseInt(v))}/>
            <span className="t-caption" style={{marginLeft:8}}>years</span>
          </div>
        </div>
        <div className="an-lab-canvas">
          <div className="cm-card-head" style={{marginBottom:10}}>
            <div className="title">Projected Net Worth</div>
            <div className="an-legend">
              <span style={{color:A.G}}><i style={{background:A.G}}/>Net Worth</span>
              <span style={{color:A.blue}}><i style={{background:A.blue}}/>Investments</span>
              <span style={{color:A.red}}><i style={{background:A.red}}/>Debt</span>
            </div>
          </div>
          <ProjectionChart series={r.series} years={r.years} height={288}/>
          <div className="an-lab-outs">
            <div className="an-out gold">
              <div className="k">Net worth · {r.years[r.years.length-1]}</div>
              <div className="v num">{usdK(r.endNW)}</div></div>
            <div className="an-out">
              <div className="k">Financial independence</div>
              <div className="v num">{r.fiYear||'—'}</div></div>
            <div className="an-out">
              <div className="k">Debt-free by</div>
              <div className="v num">{r.debtFreeYear||'—'}</div></div>
            <div className="an-out">
              <div className="k">Passive income / yr</div>
              <div className="v num">{usdK(r.passive)}</div></div>
          </div>
        </div>
      </div>
    </ChartCard>
  );
}

/* ============================ FI + GOALS ============================ */
const GOAL_ICONS = [
  { ic:<ANI.shield size={18}/>, tint:'var(--mint-100)', col:A.G },
  { ic:<ANI.home size={18}/>,   tint:'#FEF1DD', col:'#B5740F' },
  { ic:<ANI.flag size={18}/>,   tint:'#E7EEFE', col:A.blue },
  { ic:<ANI.car size={18}/>,    tint:'#EDE7F9', col:A.plum },
  { ic:<ANI.plane size={18}/>,  tint:'#DCF3F0', col:A.teal },
  { ic:<ANI.grad size={18}/>,   tint:'#FBE3EE', col:A.pink },
];
function FIandGoals({ D }) {
  const fmtDeadline = d => { try { const x=new Date(d); return isNaN(x)?'':('Target '+x.toLocaleDateString('en-CA',{month:'short',year:'numeric'})); } catch(e){ return ''; } };
  const fiDate = (() => { const yrsLeft = D.savingsRate>0 ? Math.round(Math.log(Math.max(1.01,D.fiTarget/Math.max(1,D.nw)))/Math.log(1.07)) : 30; return { yr:2026+clamp(yrsLeft,1,40), left:clamp(yrsLeft,1,40) }; })();
  return (
    <div className="cm-grid-2a">
      <div className="an-goals">
        {D.goals.map((g,i)=>{
          const m = GOAL_ICONS[i % GOAL_ICONS.length];
          const pct = g.pct;
          return (
            <div className="an-goal" key={i}>
              <div className="g-head">
                <span className="g-ic" style={{background:m.tint, color:m.col}}>{m.ic}</span>
                <div><div className="g-name">{g.name}</div><div className="g-sub">{fmtDeadline(g.deadline)}</div></div>
              </div>
              <div className="g-amt"><b className="num">{usd0(g.saved)}</b><span className="num">/ {usd0(g.target)}</span></div>
              <div className="cm-progress"><div className="pb-track"><div className="pb-fill" style={{width:pct+'%', background:m.col}}/></div></div>
              <div className="g-foot">
                <span style={{color:m.col}}>{pct}% funded</span>
                <span className="cm-pill cm-pill-green" style={{fontSize:10}}>{pct>=70?'On track':'Building'}</span>
              </div>
            </div>
          );
        })}
      </div>
      <ChartCard className="cm-card-dark">
        <div style={{padding:2}}>
          <div className="cm-row" style={{gap:8, marginBottom:4}}>
            <span style={{color:A.gold}}><ANI.target size={18}/></span>
            <span style={{fontFamily:'var(--font-serif)', fontSize:17, fontWeight:600, color:'#FBFAF6'}}>Financial Independence</span>
          </div>
          <div className="num" style={{fontFamily:'var(--font-serif)', fontSize:40, fontWeight:700, color:'#fff', lineHeight:1, marginTop:8}}>{D.fiPct}%</div>
          <div style={{color:'rgba(234,240,234,.7)', fontSize:13, marginTop:4}}>of your {usdK(D.fiTarget)} independence target</div>
          <div className="an-fi-rail"><i style={{width:Math.max(2,D.fiPct)+'%'}}/></div>
          <div className="an-fi-mile" style={{color:'rgba(234,240,234,.55)'}}><span>$0</span><span>Now · {usdK(D.nw)}</span><span>{usdK(D.fiTarget)}</span></div>
          <div className="cm-grid-2" style={{gap:12, marginTop:18}}>
            <div style={{padding:'13px 15px', borderRadius:'var(--r-ctrl)', background:'rgba(255,255,255,.05)', border:'1px solid rgba(212,169,93,.18)'}}>
              <div style={{fontSize:11.5, fontWeight:700, color:'rgba(234,240,234,.6)'}}>Est. FI date</div>
              <div className="num" style={{fontFamily:'var(--font-serif)', fontSize:22, fontWeight:700, color:A.gold, marginTop:3}}>{fiDate.yr}</div>
            </div>
            <div style={{padding:'13px 15px', borderRadius:'var(--r-ctrl)', background:'rgba(255,255,255,.05)', border:'1px solid rgba(212,169,93,.18)'}}>
              <div style={{fontSize:11.5, fontWeight:700, color:'rgba(234,240,234,.6)'}}>Years remaining</div>
              <div className="num" style={{fontFamily:'var(--font-serif)', fontSize:22, fontWeight:700, color:'#fff', marginTop:3}}>{fiDate.left} yrs</div>
            </div>
          </div>
        </div>
      </ChartCard>
    </div>
  );
}

/* ============================ PAGE ============================ */
function PageAnalytics() {
  const CM = window.useStore ? window.useStore() : window.CM;
  const [period, setPeriod] = React.useState('Year');
  const D = derive(CM);
  const asOf = CM.FD ? CM.FD(CM.today ? CM.today() : new Date()) : '';
  return (
    <div>
      <div className="st-toolbar">
        <div className="left">
          <span className="st-control" style={{cursor:'default'}}><ANI.cal size={15}/>As of {asOf}</span>
          <Seg options={['Month','Quarter','Year','Custom']} value={period} onChange={setPeriod}/>
        </div>
        <div className="right">
          <span className="st-control"><ANI.share size={15}/>Share Report</span>
          <span className="st-control"><ANI.download size={15}/>Export</span>
          <span className="st-control"><ANI.cal size={15}/>Monthly Report</span>
          <button className="cm-btn cm-btn-primary"><ANI.spark size={16}/>AI Financial Analysis</button>
        </div>
      </div>

      <SecHead first eyebrow="Reports" title="Financial Reports" sub="Your complete financial dashboard at a glance"/>
      {window.AnalyticsReports ? <window.AnalyticsReports/> : null}

      <SecHead eyebrow="Executive Dashboard" title="At a glance" sub="Your complete financial position this period"/>
      <Executive D={D}/>

      <SecHead eyebrow="Section 02" title="Financial Health Score" sub="How strong your finances are — and how to make them stronger"/>
      <HealthHero D={D}/>

      <SecHead eyebrow="Section 03" title="Net Worth Intelligence" sub="Assets, liabilities and a forward-looking forecast"/>
      <NetWorthSection D={D}/>

      <SecHead eyebrow="Section 04" title="Cash Flow Analytics" sub="Where money comes from, where it goes, what's left"/>
      <CashFlowSection D={D}/>

      <SecHead eyebrow="Section 05" title="Spending Intelligence" sub="Categories, trends, patterns and merchants"/>
      <SpendingSection D={D}/>

      <SecHead eyebrow="Section 06" title="Investments &amp; Credit" sub="Portfolio performance and credit health"/>
      <InvestCredit D={D}/>

      <SecHead eyebrow="Section 07" title="AI Insights Center" sub="What Clear AI noticed — wins, risks, recommendations & opportunities"/>
      <AIBand D={D}/>
      <AIInsights D={D}/>

      <SecHead eyebrow="Section 08" title="Future Projection Lab" sub="Model your trajectory — drag any assumption to see the future change live"/>
      <ProjectionLab D={D}/>

      <SecHead eyebrow="Section 09" title="Independence &amp; Goals" sub="The finish line and the milestones along the way"/>
      <FIandGoals D={D}/>
    </div>
  );
}
window.PageAnalytics = PageAnalytics;
})();
