/* Clear Mint — V6 Reports & Insights (Business Intelligence Center) */
(function(){
const { ChartCard, DonutChart, TrendChart, Legend, CMC, tintFor } = window;
const { Robot, ScoreGauge, Spark, SecHead } = window;
const I = window.CMIcon;
const { G, PU, AM, BL, SL, RD, TEAL, PINK, INDIGO } = CMC;
const tint = tintFor;

/* KPI tile (compact, 8-up) */
function K({ ic, color, label, value, foot, footColor, spark, dir='pos', gauge }) {
  return (
    <div className="an-exectile" style={{minHeight:128,padding:'15px 16px 13px'}}>
      <div className="et-head"><span className="et-ic" style={{background:tint(color),color}}>{ic}</span><span className="et-label">{label}</span></div>
      {gauge ? <div style={{display:'flex',justifyContent:'center'}}>{gauge}</div> : <>
        <div className="et-val" style={{fontSize:24}}>{value}</div>
        {foot && <div className="et-delta" style={{color:footColor||G}}>{foot}</div>}
        {spark && <div className="et-spark"><Spark data={spark} color={dir==='neg'?RD:G}/></div>}
      </>}
    </div>
  );
}

function HBar({ name, value, max, color }) {
  return (
    <div style={{display:'flex',alignItems:'center',gap:12,padding:'8px 0'}}>
      <div style={{width:118,flex:'0 0 118px',fontSize:12.5,fontWeight:700,color:'var(--ink-700)',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{name}</div>
      <div style={{flex:1,height:8,borderRadius:999,background:'var(--line)',overflow:'hidden'}}>
        <div style={{width:(value/max*100)+'%',height:'100%',borderRadius:999,background:color}}/>
      </div>
      <div className="num" style={{width:34,textAlign:'right',fontSize:12.5,fontWeight:800,color:'var(--ink-900)'}}>{value}</div>
    </div>
  );
}

const RANGES = ['1M','3M','6M','YTD','1Y','All'];

/* ──────────────────────────────────────────────────────────────
   Clear Financial Report — opens in a NEW TAB with its own period
   filter rail (Last 30/60/90 days · This Year · All Periods ·
   Custom Range). Format matches the classic standalone report:
   brand row, title + period line, 4 KPIs, full transaction ledger.
   ────────────────────────────────────────────────────────────── */
function openFinancialReportTab(CM){
  const S = CM.S || {};
  const pad = n => (n<10?'0':'')+n;
  const iso = dt => dt.getFullYear()+'-'+pad(dt.getMonth()+1)+'-'+pad(dt.getDate());
  const rows = (S.bankTx||[]).map((r,i)=>{
    const dt = r.date ? new Date(r.date) : null;
    return {
      d: (dt && !isNaN(dt)) ? iso(dt) : '',
      desc: String(r.desc||''),
      acct: String(r.account||''),
      cat: String(r.cat||''),
      dr: +r.dr||0, cr: +r.cr||0,
      bal: (typeof r.balance==='number') ? r.balance : null,
      i
    };
  }).filter(r=>r.d).sort((a,b)=> a.d>b.d?-1:a.d<b.d?1:b.i-a.i);   // most recent first
  const t = CM.today ? CM.today() : new Date();
  const todayISO = iso(t);
  const logoURL = new URL('assets/logo/cm-leaf-gold.png', location.href).href;
  const dataJSON = JSON.stringify(rows).replace(/</g,'\\u003c');
  const doc = `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">
<title>Clear Financial Report — Clear Mint</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" type="image/png" href="${new URL('assets/logo/cm-favicon-gold-192.png', location.href).href}">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Newsreader:opsz,wght@18..72,500..700&display=swap" rel="stylesheet">
<style>
:root{--green:#1B5E4A;--ink:#1E2A24;--ink2:#3D4A42;--mut:#6B7A70;--faint:#98A39B;--line:#EAE5DA;--bg:#F8F6F2;--mint:#F0F3EE;--mint2:#E4ECE5}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);font-family:Inter,-apple-system,'Segoe UI',sans-serif;color:var(--ink2);padding:18px 22px 60px}
.serif{font-family:Newsreader,Georgia,serif}
.actions{display:flex;justify-content:flex-end;gap:10px;max-width:1240px;margin:0 auto 14px}
.actions button{font-family:inherit;font-size:13.5px;font-weight:600;border-radius:10px;padding:9px 18px;cursor:pointer;border:1px solid var(--green)}
.actions .primary{background:var(--green);color:#fff}.actions .primary:hover{filter:brightness(1.08)}
.actions .sec{background:#fff;color:var(--green)}.actions .sec:hover{background:var(--mint)}
.layout{display:flex;gap:18px;max-width:1240px;margin:0 auto;align-items:flex-start}
.filters{flex:0 0 222px;background:#fff;border:1px solid var(--line);border-radius:14px;padding:16px 14px;position:sticky;top:18px;box-shadow:0 4px 24px rgba(30,42,36,.05)}
.f-h{font-size:11px;font-weight:700;letter-spacing:.09em;color:var(--faint);text-transform:uppercase;padding:2px 10px 8px}
.f-opt{font-size:13.5px;font-weight:600;color:var(--ink2);padding:9px 10px;border-radius:9px;cursor:pointer;transition:.12s}
.f-opt:hover{background:var(--mint)}
.f-opt.active{background:var(--mint2);color:var(--green)}
.f-div{border-top:1px solid var(--line);margin:12px 0 10px}
.f-sub{font-size:12.5px;font-weight:700;color:var(--mut);padding:0 10px 10px}
.f-lab{font-size:10.5px;font-weight:700;letter-spacing:.09em;color:var(--faint);text-transform:uppercase;padding:0 10px 5px}
.f-date{margin:0 10px 12px}
.f-date input{width:100%;font-family:inherit;font-size:13px;color:var(--ink2);border:1px solid var(--line);border-radius:9px;padding:8px 9px;background:#fff;outline:none}
.f-date input:focus{border-color:var(--green)}
.sheet{flex:1;min-width:0;background:#fff;border:1px solid var(--line);border-radius:14px;padding:28px 32px;box-shadow:0 4px 24px rgba(30,42,36,.05)}
.brand{display:flex;align-items:center;gap:9px;margin-bottom:10px}
.brand img{width:24px;height:27px;object-fit:contain}
.brand span{font-size:19px;font-weight:600;color:var(--green)}
.hd{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;margin-bottom:26px}
h1{margin:0;font-size:25px;line-height:1.2;color:var(--ink);font-weight:700;letter-spacing:0}
.sub{font-size:12.5px;color:var(--mut);margin-top:6px}
.back{font-family:inherit;font-size:12.5px;font-weight:600;color:var(--ink2);background:#fff;border:1px solid var(--line);border-radius:9px;padding:7px 13px;cursor:pointer;white-space:nowrap}
.back:hover{background:var(--mint)}
.kpis{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin:0 0 28px}
.kpi-l{font-size:12px;color:var(--mut);margin-bottom:7px}
.kpi-v{font-size:22px;font-weight:800;color:var(--ink);font-variant-numeric:tabular-nums}
.lt{font-size:14px;font-weight:700;color:var(--ink);margin:0 0 10px}
table{width:100%;border-collapse:collapse;font-size:13px}
th{text-align:left;padding:9px 12px;border-bottom:2px solid var(--line);font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--faint)}
td{padding:9px 12px;border-bottom:1px solid var(--line);color:var(--ink2)}
th.r,td.r{text-align:right;font-variant-numeric:tabular-nums}
td.dt{white-space:nowrap;color:var(--mut)}
.empty{padding:26px;text-align:center;color:var(--faint)}
.ft{display:flex;justify-content:space-between;margin-top:26px;padding-top:14px;border-top:1px solid var(--line);font-size:11px;color:var(--faint)}
@media print{body{background:#fff;padding:0}.actions,.filters,.back{display:none}.layout{display:block;max-width:none}.sheet{border:none;box-shadow:none;border-radius:0;padding:10px 0}}
</style></head><body>
<div class="actions"><button class="primary" onclick="window.print()">Print / Save PDF</button><button class="sec" onclick="window.close()">Close</button></div>
<div class="layout">
<aside class="filters">
  <div class="f-h">Period</div>
  <div class="f-opt active" data-p="month">This Month</div>
  <div class="f-opt" data-p="30">Last 30 days</div>
  <div class="f-opt" data-p="60">Last 60 days</div>
  <div class="f-opt" data-p="90">Last 90 days</div>
  <div class="f-opt" data-p="year">This Year</div>
  <div class="f-opt" data-p="all">All Periods</div>
  <div class="f-div"></div>
  <div class="f-sub">Custom Range</div>
  <div class="f-lab">From</div><div class="f-date"><input type="date" id="fFrom" placeholder="yyyy-mm-dd"></div>
  <div class="f-lab">To</div><div class="f-date"><input type="date" id="fTo" placeholder="yyyy-mm-dd"></div>
</aside>
<div class="sheet">
  <div class="brand"><img src="${logoURL}" alt="Clear Mint"><span class="serif">Clear Mint</span></div>
  <div class="hd"><div><h1 class="serif">Clear Financial Report</h1><div class="sub" id="periodLine"></div></div>
  <button class="back" onclick="window.close()">&#8592; Back</button></div>
  <div class="kpis" id="kpis"></div>
  <div class="lt">Transaction Ledger</div>
  <div id="ledger" style="overflow-x:auto"></div>
  <div class="ft"><span>Clear Mint Financial \u00b7 clearmint.ca</span><span>Confidential \u2014 for personal use only</span></div>
</div>
</div>
<script>
var TX=${dataJSON};
var TODAY='${todayISO}';
function pad(n){return n<10?'0'+n:''+n}
function shift(isoStr,days){var p=isoStr.split('-');var d=new Date(+p[0],+p[1]-1,+p[2]-days);return d.getFullYear()+'-'+pad(d.getMonth()+1)+'-'+pad(d.getDate())}
function fmtD(isoStr){if(!isoStr)return '\u2014';var p=isoStr.split('-');var d=new Date(+p[0],+p[1]-1,+p[2]);return d.toLocaleDateString('en-US',{month:'short',day:'numeric',year:'numeric'})}
function M(n){var neg=n<0;n=Math.abs(+n||0);var s='$'+n.toLocaleString('en-CA',{minimumFractionDigits:2,maximumFractionDigits:2});return neg?'\u2212'+s:s}
function esc(s){return String(s==null?'':s).replace(/[&<>]/g,function(m){return {'&':'&amp;','<':'&lt;','>':'&gt;'}[m]})}
var state={mode:'month',from:null,to:null};
function bounds(){
  if(state.mode==='month')return [TODAY.slice(0,7)+'-01',TODAY];
  if(state.mode==='30')return [shift(TODAY,30),TODAY];
  if(state.mode==='60')return [shift(TODAY,60),TODAY];
  if(state.mode==='90')return [shift(TODAY,90),TODAY];
  if(state.mode==='year')return [TODAY.slice(0,4)+'-01-01',TODAY];
  if(state.mode==='custom')return [state.from,state.to];
  return [null,null];
}
function render(){
  var b=bounds(),from=b[0],to=b[1];
  var rows=TX.filter(function(r){return (!from||r.d>=from)&&(!to||r.d<=to)});
  var dr=0,cr=0;rows.forEach(function(r){dr+=r.dr;cr+=r.cr});
  var net=cr-dr;
  var pf=from||(rows.length?rows[0].d:''),pt=to||(rows.length?rows[rows.length-1].d:TODAY);
  document.getElementById('periodLine').textContent='Period: '+(pf?fmtD(pf):'All')+' \u2013 '+fmtD(pt)+' \u00b7 Generated: '+TODAY;
  document.getElementById('kpis').innerHTML=[['Total Debits',M(dr)],['Total Credits',M(cr)],['Net Bank',M(net)],['Transactions',String(rows.length)]]
    .map(function(k){return '<div><div class="kpi-l">'+k[0]+'</div><div class="kpi-v">'+k[1]+'</div></div>'}).join('');
  var body;
  if(!rows.length){body='<div class="empty">No transactions in this period</div>'}
  else{body='<table><thead><tr><th>Date</th><th>Description</th><th>Account</th><th>Category</th><th class="r">DR</th><th class="r">CR</th><th class="r">Balance</th></tr></thead><tbody>'
    +rows.map(function(r){return '<tr><td class="dt">'+fmtD(r.d)+'</td><td>'+esc(r.desc)+'</td><td>'+esc(r.acct||'\u2014')+'</td><td>'+esc(r.cat||'\u2014')+'</td><td class="r">'+(r.dr>0?M(r.dr):'\u2014')+'</td><td class="r">'+(r.cr>0?M(r.cr):'\u2014')+'</td><td class="r">'+(r.bal==null?'\u2014':M(r.bal))+'</td></tr>'}).join('')
    +'</tbody></table>'}
  document.getElementById('ledger').innerHTML=body;
  var opts=document.querySelectorAll('.f-opt');
  for(var i=0;i<opts.length;i++){opts[i].className='f-opt'+(opts[i].getAttribute('data-p')===state.mode?' active':'')}
}
Array.prototype.forEach.call(document.querySelectorAll('.f-opt'),function(el){
  el.onclick=function(){state.mode=el.getAttribute('data-p');state.from=null;state.to=null;document.getElementById('fFrom').value='';document.getElementById('fTo').value='';render()};
});
document.getElementById('fFrom').onchange=function(){state.from=this.value||null;state.mode='custom';render()};
document.getElementById('fTo').onchange=function(){state.to=this.value||null;state.mode='custom';render()};
render();
<\/script></body></html>`;
  const w = window.open('','_blank');
  if(!w){ alert('Allow pop-ups to open the report in a new tab.'); return; }
  w.document.open(); w.document.write(doc); w.document.close();
}
window.openFinancialReportTab = openFinancialReportTab;

function PageReports() {
  const [tab, setTab] = React.useState('All Reports');
  /* per-report period filter — same options as the Clear Financial report */
  const [rptType, setRptType] = React.useState(null);
  const [fMode, setFMode] = React.useState('all');
  const [fFrom, setFFrom] = React.useState('');
  const [fTo, setFTo] = React.useState('');

  /* ---- live financial figures (same engine the rest of the app reads) ---- */
  const CM = window.useStore ? window.useStore() : window.CM;
  const compact = v => { v=Number(v||0); return v>=1e6?('$'+(v/1e6).toFixed(2)+'M'):v>=1e3?('$'+Math.round(v/1e3)+'K'):'$'+Math.round(v); };
  const nw = CM.netWorth(), gAssets = CM.grossAssets(), gLiab = CM.totalLiabilities();
  const nwSeries = CM.netWorthSeries();
  const nwPrev = nwSeries[nwSeries.length-2] || nw;
  const nwChange = nw - nwPrev, nwChangePct = nwPrev ? nwChange/nwPrev*100 : 0;
  const pos = nwChange >= 0;
  const cf6 = CM.last6CashFlow();
  const lastCF = cf6[cf6.length-1] || { inc:0, exp:0 };
  const monthlyCF = lastCF.inc - lastCF.exp;
  const score = CM.wealthScore();
  const scoreBand = score>=85?'Excellent':score>=70?'Strong':score>=55?'Healthy':score>=40?'Building':'At Risk';
  const subs = (CM.S.subscriptions||[]).filter(s=>s.active!==false);
  const subAnnual = subs.reduce((s,x)=>s+(+x.price||0),0)*12;
  const cardsList = CM.S.cards||[];
  const climit = cardsList.reduce((s,c)=>s+(+c.limit||0),0);
  const cused = cardsList.reduce((s,c)=>s+(+c.balance||0),0);
  const util = climit ? cused/climit*100 : 0;
  const overUtil = cardsList.filter(c=>c.limit && (c.balance/c.limit*100)>=30).length;
  const invMV = CM.calcInvestValue();
  const invCost = (CM.S.investments||[]).reduce((s,i)=>s+(i.costBasis!=null?+i.costBasis:(+i.shares||0)*(+i.avgCost||0)),0);
  const invRet = invCost ? (invMV-invCost)/invCost*100 : 0;

  /* ---- generatable reports (same format as the index file) ---- */
  const pad2 = n=>(n<10?'0':'')+n;
  const isoOf = dt=>dt.getFullYear()+'-'+pad2(dt.getMonth()+1)+'-'+pad2(dt.getDate());
  const todayD = CM.today?CM.today():new Date();
  const todayISO = isoOf(todayD);
  const shiftISO = days=>{ const d=new Date(todayD); d.setDate(d.getDate()+days); return isoOf(d); };
  function filterBounds(){
    if(fMode==='30') return [shiftISO(-30), todayISO];
    if(fMode==='60') return [shiftISO(-60), todayISO];
    if(fMode==='90') return [shiftISO(-90), todayISO];
    if(fMode==='year') return [todayD.getFullYear()+'-01-01', todayISO];
    if(fMode==='custom') return [fFrom||null, fTo||null];
    return [null,null];
  }
  /* forward window for scheduled transactions (mirrors the backward filter) */
  function futureBound(){
    if(fMode==='30') return shiftISO(30);
    if(fMode==='60') return shiftISO(60);
    if(fMode==='90') return shiftISO(90);
    if(fMode==='year') return todayD.getFullYear()+'-12-31';
    if(fMode==='custom') return fTo||null;
    return null;
  }
  const filterLabel = ()=>{
    if(fMode==='custom') return (fFrom||'…')+' – '+(fTo||'…');
    return ({'30':'Last 30 days','60':'Last 60 days','90':'Last 90 days','year':'This year','all':'All periods'})[fMode]||'All periods';
  };
  const M = CM.M || (n=>'$'+(Number(n)||0).toFixed(2));
  const FDr = CM.FD || (d=>String(d));
  const RDc='var(--red-500)', Gc='var(--green-600)', TXT='var(--ink-900)', T3='var(--ink-400)', BD='var(--line)', BGc='var(--mint-50)';
  const esc = s => String(s==null?'':s).replace(/[&<>]/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;'}[m]));
  function tbl(cols, rows, cap){
    if(!rows.length) return '<div style="padding:22px;text-align:center;color:'+T3+'">No data in this period</div>';
    return '<table style="width:100%;border-collapse:collapse;font-size:13px"><thead><tr>'
      +cols.map(c=>'<th style="text-align:'+(c.r?'right':'left')+';padding:9px 12px;border-bottom:2px solid '+BD+';font-size:11px;text-transform:uppercase;letter-spacing:.4px;color:'+T3+'">'+c.l+'</th>').join('')
      +'</tr></thead><tbody>'
      +rows.slice(0,cap||80).map((row,i)=>'<tr style="border-bottom:1px solid '+BD+';background:'+(i%2?BGc:'#fff')+'">'
        +cols.map(c=>'<td style="padding:8px 12px;text-align:'+(c.r?'right':'left')+';color:'+(c.col||TXT)+';font-variant-numeric:tabular-nums">'+(row[c.k]==null||row[c.k]===''?'—':row[c.k])+'</td>').join('')+'</tr>').join('')
      +'</tbody></table>';
  }
  function buildReport(type){
    const bnd=filterBounds(), from=bnd[0], to=bnd[1];
    const dISO=(d)=>{ const dt=d instanceof Date?d:(d?new Date(d):null); return (dt&&!isNaN(dt))?isoOf(dt):null; };
    const inP=(d)=>{ const k=dISO(d); return !!k && (!from||k>=from) && (!to||k<=to); };
    /* past-only aggregates — future scheduled rows are reported separately below */
    const pastP=(d)=>{ const k=dISO(d); return !!k && k<=todayISO && (!from||k>=from) && (!to||k<=to); };
    const tx=(CM.S.bankTx||[]).filter(r=>inP(r.date)), earn=(CM.S.earnings||[]).filter(r=>pastP(r.date)), bills=(CM.S.bills||[]).filter(r=>pastP(r.dueDate||r.date));
    /* scheduled future transactions — earnings + upcoming bills only */
    const futTo=futureBound();
    const futP=(d)=>{ const k=dISO(d); return !!k && k>todayISO && (!futTo||k<=futTo); };
    const futE=(CM.S.earnings||[]).filter(r=>futP(r.date)).map(r=>({k:dISO(r.date),desc:r.desc||r.source||'Income',type:'Income',recur:r.recur,inf:+r.amount||0,outf:0}));
    const futB=(CM.S.bills||[]).filter(r=>!r.paid&&futP(r.dueDate||r.date)).map(r=>({k:dISO(r.dueDate||r.date),desc:r.desc||r.name||'Bill',type:'Bill',recur:r.recur,inf:0,outf:+r.amount||0}));
    const fut=futE.concat(futB).sort((a,b2)=>a.k<b2.k?-1:1);
    const futIn=fut.reduce((s,x)=>s+x.inf,0), futOut=fut.reduce((s,x)=>s+x.outf,0), futNet=futIn-futOut;
    const sum=(a,f)=>a.reduce((s,x)=>s+(f(x)||0),0);
    const tDR=sum(tx,r=>r.dr), tCR=sum(tx,r=>r.cr), bankNet=tCR-tDR;
    const tEarn=sum(earn,r=>r.amount), tBills=sum(bills,r=>r.amount), net=tEarn-tBills;
    const today=todayD; const gen=today.toLocaleDateString('en-CA');
    const perLbl=filterLabel();
    if(type==='financial') return { type, title:'Clear Financial Report', sub:'Full transaction ledger · '+perLbl+' · Generated '+gen,
      kpis:[{l:'Total Debits',v:M(tDR),c:RDc},{l:'Total Credits',v:M(tCR),c:Gc},{l:'Net Bank',v:M(bankNet),c:bankNet>=0?Gc:RDc},{l:'Transactions',v:String(tx.length)}],
      body:'<div style="font-size:14px;font-weight:700;margin-bottom:10px;color:'+TXT+'">Transaction Ledger</div>'
        +tbl([{l:'Date',k:'d'},{l:'Description',k:'desc'},{l:'Account',k:'acct'},{l:'Category',k:'cat'},{l:'DR',k:'dr',r:1,col:RDc},{l:'CR',k:'cr',r:1,col:Gc},{l:'Balance',k:'bal',r:1}],
          tx.slice().sort((a,b)=>new Date(b.date)-new Date(a.date)).map(r=>({d:FDr(r.date),desc:esc(r.desc),acct:esc(r.account||'—'),cat:esc(r.cat||'—'),dr:r.dr>0?M(r.dr):'',cr:r.cr>0?M(r.cr):'',bal:typeof r.balance==='number'?M(r.balance):'—'}))) };
    if(type==='pnl'){
      const inc=earn.map(r=>'<div style="display:flex;justify-content:space-between;padding:5px 0;border-bottom:1px solid '+BD+';font-size:12.5px"><span>'+esc(r.desc||r.source||'Income')+'</span><span style="color:'+Gc+';font-weight:600">+'+M(r.amount)+'</span></div>').join('');
      const exp=bills.map(r=>'<div style="display:flex;justify-content:space-between;padding:5px 0;border-bottom:1px solid '+BD+';font-size:12.5px"><span>'+esc(r.desc||r.name||'Expense')+'</span><span style="color:'+RDc+';font-weight:600">–'+M(r.amount)+'</span></div>').join('');
      return { type, title:'Profit & Loss', sub:'Income vs expenses · '+perLbl+' · Generated '+gen,
        kpis:[{l:'Total Income',v:M(tEarn),c:Gc},{l:'Total Expenses',v:M(tBills),c:RDc},{l:'Net Profit',v:(net>=0?'+':'')+M(net),c:net>=0?Gc:RDc},{l:'Margin',v:tEarn>0?(net/tEarn*100).toFixed(1)+'%':'—',c:net>=0?Gc:RDc}],
        body:'<div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">'
          +'<div style="background:'+BGc+';border-radius:12px;padding:16px"><div style="font-size:13px;font-weight:700;margin-bottom:10px;color:'+Gc+'">Income</div>'+inc+'<div style="display:flex;justify-content:space-between;padding:8px 0;font-weight:700;font-size:13px"><span>Total Income</span><span style="color:'+Gc+'">'+M(tEarn)+'</span></div></div>'
          +'<div style="background:'+BGc+';border-radius:12px;padding:16px"><div style="font-size:13px;font-weight:700;margin-bottom:10px;color:'+RDc+'">Expenses</div>'+exp+'<div style="display:flex;justify-content:space-between;padding:8px 0;font-weight:700;font-size:13px"><span>Total Expenses</span><span style="color:'+RDc+'">'+M(tBills)+'</span></div></div>'
          +'</div>' };
    }
    if(type==='cashflow'){
      const mn=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; const byMo={};
      const addMo=(d,f,v)=>{ const dt=d instanceof Date?d:(d?new Date(d):null); if(!dt||isNaN(dt))return; const k=dt.getFullYear()+'-'+String(dt.getMonth()).padStart(2,'0'); (byMo[k]=byMo[k]||{e:0,b:0,mo:dt.getMonth(),yr:dt.getFullYear()})[f]+=v; };
      earn.forEach(r=>addMo(r.date,'e',r.amount||0));
      bills.forEach(r=>addMo(r.date||r.dueDate,'b',r.amount||0));
      const rows=Object.keys(byMo).sort().map(k=>{const d=byMo[k];const n=d.e-d.b;return {p:mn[d.mo]+' '+d.yr,inf:M(d.e),outf:M(d.b),net:(n>=0?'+':'')+M(n)};});
      /* every scheduled future transaction, described row by row */
      const futRows=fut.map(x=>({d:FDr(new Date(x.k+'T00:00')),desc:esc(x.desc),type:x.type+(x.recur&&!/one.?time/i.test(String(x.recur))?' · '+esc(x.recur):''),inf:x.inf?M(x.inf):'',outf:x.outf?M(x.outf):''}));
      return { type, title:'Cash Flow Statement', sub:'Monthly inflows & outflows · '+perLbl+' · Generated '+gen,
        kpis:[{l:'Total Inflow',v:M(tEarn),c:Gc},{l:'Total Outflow',v:M(tBills),c:RDc},{l:'Net Cash Flow',v:(net>=0?'+':'')+M(net),c:net>=0?Gc:RDc},{l:'Upcoming Net',v:(futNet>=0?'+':'')+M(futNet),c:futNet>=0?Gc:RDc}],
        body:'<div style="font-size:14px;font-weight:700;margin-bottom:10px;color:'+TXT+'">Monthly Summary</div>'
          +tbl([{l:'Period',k:'p'},{l:'Inflow',k:'inf',r:1,col:Gc},{l:'Outflow',k:'outf',r:1,col:RDc},{l:'Net',k:'net',r:1}],rows)
          +'<div style="font-size:14px;font-weight:700;margin:22px 0 4px;color:'+TXT+'">Scheduled Future Transactions</div>'
          +'<div style="font-size:12px;color:'+T3+';margin-bottom:10px">Earnings &amp; upcoming bills'+(futTo?(' through '+FDr(new Date(futTo+'T00:00'))):' (next 24 months)')+' · Inflow '+M(futIn)+' · Outflow '+M(futOut)+' · Net '+(futNet>=0?'+':'')+M(futNet)+'</div>'
          +tbl([{l:'Date',k:'d'},{l:'Description',k:'desc'},{l:'Type',k:'type'},{l:'Inflow',k:'inf',r:1,col:Gc},{l:'Outflow',k:'outf',r:1,col:RDc}],futRows,200) };
    }
    /* forecast: running-balance projection from today through year-end */
    const opening=CM.totalCash?CM.totalCash():0;
    /* horizon: year-end, or the filter's forward window if shorter */
    const yEnd=today.getFullYear()+'-12-31';
    const fcEnd=(futTo && futTo<yEnd)?futTo:yEnd;
    const fcP=(d)=>{ const k=dISO(d); return !!k && k>todayISO && k<=fcEnd; };
    const fc=(CM.S.earnings||[]).filter(r=>fcP(r.date)).map(r=>({k:dISO(r.date),desc:r.desc||r.source||'Income',cr:+r.amount||0,dr:0}))
      .concat((CM.S.bills||[]).filter(r=>!r.paid&&fcP(r.dueDate||r.date)).map(r=>({k:dISO(r.dueDate||r.date),desc:r.desc||r.name||'Bill',cr:0,dr:+r.amount||0})))
      .sort((a,b2)=>a.k<b2.k?-1:1);
    let bal=opening, projIn=0, projOut=0; const lr=[];
    if(fc.length){
      /* built from the actual scheduled earnings & bills */
      fc.slice(0,150).forEach(r=>{ bal+=r.cr-r.dr; projIn+=r.cr; projOut+=r.dr;
        lr.push({d:FDr(new Date(r.k+'T00:00')),desc:esc(r.desc),dr:r.dr?M(r.dr):'',cr:r.cr?M(r.cr):'',bal:M(bal)}); });
    } else {
      const monthlyIn=CM.monthlyIncome?CM.monthlyIncome():tEarn, monthlyOut=tBills;
      const cmo=today.getMonth(); let n=11-cmo; if(n<=0)n=3;
      for(let i=1;i<=n;i++){ const dt=new Date(today.getFullYear(),cmo+i,1); const lbl=dt.toLocaleDateString('en-CA',{month:'short',year:'numeric'});
        bal+=monthlyIn; projIn+=monthlyIn; lr.push({d:lbl,desc:'Projected Income',dr:'',cr:M(monthlyIn),bal:M(bal)});
        bal-=monthlyOut; projOut+=monthlyOut; lr.push({d:lbl,desc:'Projected Bills & Expenses',dr:M(monthlyOut),cr:'',bal:M(bal)}); }
    }
    const closing=opening+projIn-projOut;
    const endLbl=FDr(new Date(fcEnd+'T00:00'));
    const ledger='<table style="width:100%;border-collapse:collapse;font-size:13px"><thead><tr>'
      +['Date','Description','DR','CR','Balance'].map((c,i)=>'<th style="text-align:'+(i>=2?'right':'left')+';padding:9px 12px;border-bottom:2px solid '+BD+';font-size:11px;text-transform:uppercase;letter-spacing:.4px;color:'+T3+'">'+c+'</th>').join('')
      +'</tr></thead><tbody>'
      +'<tr style="background:'+BGc+'"><td style="padding:8px 12px;color:'+T3+'">Today</td><td style="padding:8px 12px;font-weight:700">Opening Balance (Bank)</td><td style="text-align:right;padding:8px 12px">—</td><td style="text-align:right;padding:8px 12px">—</td><td style="text-align:right;padding:8px 12px;font-weight:700;font-variant-numeric:tabular-nums">'+M(opening)+'</td></tr>'
      +lr.map((r,i)=>'<tr style="border-bottom:1px solid '+BD+';background:'+(i%2?BGc:'#fff')+'"><td style="padding:8px 12px;white-space:nowrap">'+r.d+'</td><td style="padding:8px 12px">'+r.desc+'</td><td style="text-align:right;padding:8px 12px;color:'+RDc+';font-variant-numeric:tabular-nums">'+(r.dr||'—')+'</td><td style="text-align:right;padding:8px 12px;color:'+Gc+';font-variant-numeric:tabular-nums">'+(r.cr||'—')+'</td><td style="text-align:right;padding:8px 12px;font-weight:600;font-variant-numeric:tabular-nums">'+r.bal+'</td></tr>').join('')
      +'<tr style="border-top:2px solid '+BD+';font-weight:700"><td style="padding:10px 12px" colspan="2">Projected Closing Balance</td><td style="text-align:right;padding:10px 12px;color:'+RDc+'">'+M(projOut)+'</td><td style="text-align:right;padding:10px 12px;color:'+Gc+'">'+M(projIn)+'</td><td style="text-align:right;padding:10px 12px;font-variant-numeric:tabular-nums">'+M(closing)+'</td></tr>'
      +'</tbody></table>';
    return { type, title:'Cash Flow Forecast', sub:'Projected from today through '+endLbl+' · Generated '+gen,
      kpis:[{l:'Opening Balance (Bank)',v:M(opening)},{l:'Projected Outflows',v:M(projOut),c:RDc},{l:'Projected Inflows',v:M(projIn),c:Gc},{l:'Projected Closing',v:M(closing),c:closing>=0?Gc:RDc}],
      body:ledger };
  }
  function exportReport(r){
    const kpiHtml=r.kpis.map(k=>'<div class="kpi"><div class="kpi-l">'+k.l+'</div><div class="kpi-v" style="color:'+(k.c||'#1C2B24')+'">'+k.v+'</div></div>').join('');
    const doc='<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Clear Mint — '+r.title+'</title>'
      +'<style>:root{--red-500:#B74B4B;--green-600:#0B5640;--ink-900:#1C2B24;--ink-400:#8A9690;--line:#E7E3DB;--mint-50:#EAF4EF}'
      +'*{margin:0;padding:0;box-sizing:border-box}body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#1C2B24;background:#fff;padding:40px;max-width:980px;margin:0 auto}'
      +'.hd{display:flex;justify-content:space-between;align-items:flex-start;border-bottom:2px solid #0B3D2E;padding-bottom:18px;margin-bottom:22px}.hd h1{font-size:24px;font-weight:800}.hd .sub{font-size:12.5px;color:#6B7280;margin-top:4px}.conf{font-size:11px;color:#0B5640;background:#EAF4EF;border:1px solid #BBE3CF;border-radius:8px;padding:8px 12px;text-align:right}'
      +'.kpis{display:grid;grid-template-columns:repeat('+r.kpis.length+',1fr);gap:12px;margin-bottom:20px}.kpi{background:#F6F9F7;border:1px solid #E7E3DB;border-left:3px solid #3ECF8E;border-radius:8px;padding:12px 14px}.kpi-l{font-size:11px;color:#6B7280;text-transform:uppercase;letter-spacing:.4px;margin-bottom:4px}.kpi-v{font-size:19px;font-weight:800}'
      +'.ft{margin-top:28px;padding-top:14px;border-top:1px solid #E7E3DB;font-size:11px;color:#9CA3AF;display:flex;justify-content:space-between}'
      +'@media print{body{padding:20px}.noprint{display:none}}</style></head><body>'
      +'<div class="noprint" style="position:fixed;top:14px;right:14px;display:flex;gap:8px"><button onclick="window.print()" style="background:#0B5640;color:#fff;border:none;padding:8px 16px;border-radius:8px;font-weight:600;cursor:pointer">Print / Save PDF</button><button onclick="window.close()" style="background:#F3F4F6;border:none;padding:8px 16px;border-radius:8px;cursor:pointer">Close</button></div>'
      +'<div class="hd"><div><h1>'+r.title+'</h1><div class="sub">'+r.sub+'</div></div><div class="conf">🔒 Confidential<br>Clear Mint Financial<br>clearmint.ca</div></div>'
      +'<div class="kpis">'+kpiHtml+'</div>'+r.body
      +'<div class="ft"><span>Clear Mint Financial · clearmint.ca</span><span>Confidential — for personal use only</span></div></body></html>';
    const w=window.open('','_blank'); if(w){ w.document.write(doc); w.document.close(); } else { alert('Allow pop-ups to export the report.'); }
  }

  const library = [
    { id:'financial', name:'Clear Financial Report', when:'Transaction ledger', ic:<I.Investments size={20}/>, c:G },
    { id:'pnl', name:'Profit & Loss', when:'Income vs expenses', ic:<I.Bars size={20}/>, c:BL, star:true },
    { id:'cashflow', name:'Cash Flow Statement', when:'Monthly in/out', ic:<I.Transfer size={20}/>, c:TEAL },
    { id:'forecast', name:'Cash Flow Forecast', when:'Through year-end', ic:<I.Grow size={20}/>, c:PU },
  ];
  const templates = ['Executive Summary','Monthly Snapshot','Investment Review','Tax Preparation','Net Worth Analysis','Budget vs Actual'];
  const mostViewed = [
    { name:'Budget Report', v:42, c:G }, { name:'Net Worth Report', v:38, c:BL },
    { name:'Investment Report', v:29, c:PU }, { name:'Cash Flow Report', v:22, c:TEAL }, { name:'Tax Report', v:15, c:AM },
  ];
  const byCat = [
    { label:'Financial', value:35, color:G }, { label:'Investment', value:25, color:BL },
    { label:'Planning', value:15, color:PU }, { label:'Tax', value:10, color:AM },
    { label:'Insurance', value:8, color:TEAL }, { label:'Other', value:7, color:SL },
  ];
  const dataSrc = [
    { label:'Bank Accounts', value:45, color:G }, { label:'Investments', value:25, color:BL },
    { label:'Credit Cards', value:15, color:AM }, { label:'Tax', value:10, color:PU }, { label:'Insurance', value:5, color:TEAL },
  ];
  const automated = [
    { name:'Weekly Summary', freq:'Weekly', rec:2, next:'Jun 2, 2026', status:'Active', tone:'green' },
    { name:'Monthly Snapshot', freq:'Monthly', rec:3, next:'Jun 1, 2026', status:'Active', tone:'green' },
    { name:'Quarterly Investment', freq:'Quarterly', rec:1, next:'Jul 1, 2026', status:'Active', tone:'green' },
    { name:'Annual Net Worth', freq:'Annually', rec:2, next:'Jan 1, 2027', status:'Scheduled', tone:'amber' },
    { name:'Tax Preparation', freq:'Annually', rec:1, next:'Jan 15, 2027', status:'Scheduled', tone:'amber' },
  ];
  const exports = [
    { name:'Executive Summary — May', fmt:'PDF', date:'May 31, 2026', c:RD },
    { name:'Investment Report — Q2', fmt:'XLS', date:'May 30, 2026', c:G },
    { name:'Tax Package — 2025', fmt:'PDF', date:'May 29, 2026', c:RD },
    { name:'Budget vs Actual — May', fmt:'XLS', date:'May 28, 2026', c:G },
    { name:'Family Financial Report', fmt:'PDF', date:'May 27, 2026', c:RD },
  ];
  const insights = [
    { pose:'r2-5', tag:'Financial Win', color:G, text:`Your net worth ${pos?'grew':'moved'} to ${compact(nw)} (${(pos?'+':'')+nwChangePct.toFixed(2)}%) this month.${pos?' Great job staying consistent!':''}` },
    { pose:'r1-10', tag:'Opportunity', color:AM, text:`You have ${subs.length} active subscriptions totalling ${CM.M0(subAnnual)} a year — reviewing overlaps could free up cash.` },
    overUtil>0
      ? { pose:'r1-10', tag:'Alert', color:RD, text:`Credit card utilization is above 30% on ${overUtil} account${overUtil>1?'s':''}. Consider paying down balances.` }
      : { pose:'r1-10', tag:'On Track', color:G, text:`Credit card utilization is a healthy ${util.toFixed(0)}% across your ${cardsList.length} cards.` },
    { pose:'r2-3', tag:'Recommendation', color:BL, text:`Your investments are up ${(invRet>=0?'+':'')+invRet.toFixed(1)}% on cost. Topping up your TFSA could compound that further.` },
  ];
  const popTemplates = [
    { name:'Net Worth Dashboard', sub:'Complete overview of net worth, assets and liabilities.', kind:'area', c:G },
    { name:'Retirement Plan', sub:'Track retirement progress and future projections.', kind:'bars', c:PU },
    { name:'Investment Performance', sub:'Detailed analysis of portfolio performance.', kind:'area', c:BL },
    { name:'Debt Reduction', sub:'Monitor payoff progress and interest savings.', kind:'bars', c:RD },
    { name:'Tax Preparation', sub:'All income, deductions and key documents.', kind:'bars', c:AM },
    { name:'Cash Flow Statement', sub:'Detailed cash flow analysis for any period.', kind:'area', c:TEAL },
  ];

  const rpt = rptType ? buildReport(rptType) : null;
  const dateInp = {width:'100%',fontFamily:'inherit',fontSize:13,border:'1px solid var(--line)',borderRadius:9,padding:'8px 9px',background:'#fff',color:'var(--ink-700)',outline:'none',boxSizing:'border-box'};
  const FOPTS=[['30','Last 30 days'],['60','Last 60 days'],['90','Last 90 days'],['year','This Year'],['all','All Periods']];
  if (rpt) return (
    <div style={{display:'flex',gap:18,alignItems:'flex-start'}}>
      <div className="cm-card" style={{flex:'0 0 200px',padding:'14px 12px',position:'sticky',top:18}}>
        <div className="t-label" style={{padding:'2px 10px 8px',color:'var(--ink-400)'}}>Period</div>
        {FOPTS.map(o=>(
          <div key={o[0]} onClick={()=>{setFMode(o[0]); setFFrom(''); setFTo('');}}
            style={{fontSize:13.5,fontWeight:600,padding:'9px 10px',borderRadius:9,cursor:'pointer',
              background:fMode===o[0]?'var(--mint-100)':'transparent',color:fMode===o[0]?'var(--green-600)':'var(--ink-700)'}}>{o[1]}</div>
        ))}
        <div style={{borderTop:'1px solid var(--line)',margin:'12px 0 10px'}}></div>
        <div style={{fontSize:12.5,fontWeight:700,color:'var(--ink-500)',padding:'0 10px 10px'}}>Custom Range</div>
        <div className="t-label" style={{padding:'0 10px 5px',color:'var(--ink-400)'}}>From</div>
        <div style={{margin:'0 10px 12px'}}><input type="date" value={fFrom} onChange={e=>{setFFrom(e.target.value); setFMode('custom');}} style={dateInp}/></div>
        <div className="t-label" style={{padding:'0 10px 5px',color:'var(--ink-400)'}}>To</div>
        <div style={{margin:'0 10px 4px'}}><input type="date" value={fTo} onChange={e=>{setFTo(e.target.value); setFMode('custom');}} style={dateInp}/></div>
      </div>
      <div style={{flex:1,minWidth:0}}>
      <ChartCard>
        <div style={{display:'flex',alignItems:'flex-start',justifyContent:'space-between',gap:12,marginBottom:18,paddingBottom:14,borderBottom:'2px solid var(--line)'}}>
          <div><div className="t-h1" style={{fontSize:24}}>{rpt.title}</div><div className="t-caption" style={{marginTop:4}}>{rpt.sub}</div></div>
          <div style={{display:'flex',gap:8,flexShrink:0}}>
            <button className="cm-btn cm-btn-soft" onClick={()=>setRptType(null)}><I.ChevR size={15} style={{transform:'rotate(180deg)'}}/>Back</button>
            <button className="cm-btn cm-btn-primary" onClick={()=>exportReport(rpt)}><I.ArrowDown size={15}/>Export / Print</button>
          </div>
        </div>
        <div style={{display:'grid',gridTemplateColumns:`repeat(${rpt.kpis.length},1fr)`,gap:12,marginBottom:18}}>
          {rpt.kpis.map((k,i)=>(
            <div key={i} style={{background:'var(--mint-50)',border:'1px solid var(--line)',borderRadius:12,padding:'14px 16px'}}>
              <div style={{fontSize:11.5,color:'var(--ink-400)',marginBottom:4}}>{k.l}</div>
              <div className="num" style={{fontSize:20,fontWeight:800,color:k.c||'var(--ink-900)'}}>{k.v}</div>
            </div>
          ))}
        </div>
        <div style={{overflowX:'auto'}} dangerouslySetInnerHTML={{__html:rpt.body}}/>
      </ChartCard>
      </div>
    </div>
  );

  return (
    <div>
      {/* KPI STRIP */}
      <div className="cm-kpi8 cm-mb-24">
        <K ic={<I.Reports size={15}/>} color={G} label="Reports Generated" value="142" foot="▲ 18% vs last 30 days" spark={[110,118,122,128,134,138,142]}/>
        <K ic={<I.Calendar size={15}/>} color={BL} label="Scheduled" value="18" foot="▲ 12% vs last 30 days" spark={[12,13,14,15,16,17,18]}/>
        <K ic={<I.Repeat size={15}/>} color={PU} label="Automated" value="12" foot="▲ 20% vs last 30 days" spark={[8,9,9,10,11,11,12]}/>
        <K ic={<I.User size={15}/>} color={TEAL} label="Shared" value="27" foot="▲ 8% vs last 30 days" spark={[20,22,23,24,25,26,27]}/>
        <K ic={<I.Clock size={15}/>} color={AM} label="Last Generated" value="2h ago" foot="Executive Summary" footColor="var(--ink-400)"/>
        <K ic={<I.Bank size={15}/>} color={INDIGO} label="Data Sources" value="14" foot="View all sources" footColor="var(--green-600)"/>
        <K ic={<I.Spark size={15}/>} color={G} label="Health Score" gauge={<ScoreGauge score={score} size={108} label={scoreBand} showStars={false} scoreSize={26}/>}/>
        <K ic={<I.Grow size={15}/>} color={G} label="Net Worth Change" value={(pos?'+':'-')+compact(Math.abs(nwChange))} foot={`${pos?'▲ ':'▼ '}${Math.abs(nwChangePct).toFixed(2)}% this month`} footColor={pos?undefined:RD} dir={pos?'pos':'neg'} spark={nwSeries.slice(-7)}/>
      </div>

      {/* LIBRARY + GENERATOR */}
      <div className="cm-grid-2c cm-mb-24">
        <ChartCard title="Report Library" action={<span className="link" style={{fontSize:12.5,fontWeight:800,color:'var(--green-600)'}}>View all reports</span>}>
          <div className="cm-tabs" style={{marginBottom:18}}>
            {['All Reports','Favorites','Recent','Shared with me'].map(t=>(
              <div key={t} className={`cm-tab ${t===tab?'active':''}`} onClick={()=>setTab(t)}>{t}</div>
            ))}
          </div>
          <div className="cm-replib">
            {library.map((r,i)=>(
              <div className="cm-repcard" key={i} style={{cursor:'pointer'}} onClick={()=>{ if(r.id==='financial'){ openFinancialReportTab(CM); } else if(r.id){ setFMode('all'); setFFrom(''); setFTo(''); setRptType(r.id); } }}>
                {r.star && <span className="rc-star"><I.Goals size={14}/></span>}
                <div className="rc-ic" style={{background:tint(r.c),color:r.c}}>{r.ic}</div>
                <div className="rc-name">{r.name}</div><div className="rc-when">{r.when}</div>
                <div style={{marginTop:8,fontSize:11.5,fontWeight:800,color:'var(--green-600)'}}>Generate →</div>
              </div>
            ))}
            <div className="cm-repcard dashed"><I.Plus size={24}/><div className="rc-name" style={{marginTop:8,color:'var(--green-600)'}}>Custom Report</div><div className="rc-when">Build your own</div></div>
          </div>
        </ChartCard>
        <ChartCard title="Report Generator">
          <div style={{display:'flex',gap:14,marginBottom:16}}>
            <div style={{flex:1}}>
              <div className="t-caption" style={{marginBottom:12}}>Build custom reports in minutes. Start from scratch or use a template.</div>
              {[['Choose Data','Select the sources for your report'],['Customize','Add charts, tables and apply filters'],['Preview & Export','Schedule or export instantly']].map((s,i)=>(
                <div className="cm-step" key={i}><span className="n">{i+1}</span><div><div className="s-name">{s[0]}</div><div className="s-sub">{s[1]}</div></div></div>
              ))}
            </div>
            <Robot pose="r3-1" size={120} float="float2" style={{flex:'0 0 120px',alignSelf:'center'}}/>
          </div>
          <button className="cm-btn cm-btn-primary" style={{width:'100%',justifyContent:'center'}}><I.Plus size={16}/>Create Custom Report</button>
          <div className="t-label" style={{margin:'18px 0 10px',color:'var(--ink-700)'}}>Popular Templates</div>
          <div className="cm-tmpls">
            {templates.map((t,i)=><div className="cm-tmpl" key={i}><I.Reports size={13}/>{t}</div>)}
          </div>
        </ChartCard>
      </div>

      {/* FINANCIAL OVERVIEW DASHBOARD */}
      <SecHead eyebrow="Financial Overview" title="Executive Dashboard" link="View full dashboard"/>
      <div className="cm-kpi4 cm-mb-24">
        <K ic={<I.Investments size={15}/>} color={G} label="Net Worth" value={compact(nw)} foot={`${pos?'▲ ':'▼ '}${Math.abs(nwChangePct).toFixed(2)}%`} footColor={pos?undefined:RD} dir={pos?'pos':'neg'} spark={nwSeries.slice(-7)}/>
        <K ic={<I.Wallet size={15}/>} color={TEAL} label="Total Assets" value={compact(gAssets)} foot="gross assets" footColor="var(--ink-400)" spark={nwSeries.slice(-7).map(v=>v+gLiab)}/>
        <K ic={<I.Card size={15}/>} color={RD} label="Total Liabilities" value={compact(gLiab)} foot="loans + cards" footColor="var(--ink-400)" dir="neg" spark={[gLiab*1.05,gLiab*1.04,gLiab*1.03,gLiab*1.02,gLiab*1.01,gLiab*1.004,gLiab]}/>
        <K ic={<I.Transfer size={15}/>} color={BL} label="Monthly Cash Flow" value={(monthlyCF>=0?'+':'-')+compact(Math.abs(monthlyCF))} foot="this month" footColor="var(--ink-400)" spark={cf6.map(m=>(m.inc-m.exp)/100)}/>
      </div>
      <div className="cm-grid-2 cm-mb-24">
        <ChartCard title="Net Worth Over Time" action={<div className="cm-seg">{['YTD','1Y','All'].map(t=><button key={t} className={t==='YTD'?'active':''}>{t}</button>)}</div>}>
          <TrendChart data={nwSeries} height={230}
            yLabels={[compact(Math.max.apply(null,nwSeries)),'',compact(Math.min.apply(null,nwSeries))]} xLabels={['Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May']}/>
        </ChartCard>
        <ChartCard title="Cash Flow Trend" action={<span className="t-caption">This year</span>}>
          <div className="an-legend" style={{marginBottom:10}}>
            <span><i style={{background:G}}/>Income</span><span><i style={{background:RD}}/>Expenses</span><span><i style={{background:BL}}/>Net Cash Flow</span>
          </div>
          <div className="cm-vbars" style={{height:210}}>
            {(()=>{ const act=cf6.filter(m=>m.inc>0||m.exp>0); const rows=act.length?act:cf6; const cfMax=Math.max(1,...rows.map(m=>Math.max(m.inc,m.exp))); return rows.map((m,i)=>(
              <div className="cm-vbar" key={i} style={{justifyContent:'flex-end'}}>
                <div style={{display:'flex',gap:5,alignItems:'flex-end',width:'100%',justifyContent:'center',height:'100%'}}>
                  <div style={{width:15,borderRadius:'6px 6px 3px 3px',background:G,height:`${m.inc/cfMax*100}%`}}/>
                  <div style={{width:15,borderRadius:'6px 6px 3px 3px',background:'#E7B7B7',height:`${m.exp/cfMax*100}%`}}/>
                </div>
                <div className="lbl">{m.mo}</div>
              </div>
            )); })()}
          </div>
        </ChartCard>
      </div>

      {/* REPORT ANALYTICS */}
      <SecHead eyebrow="Report Analytics" title="How your reports are used" link="View all analytics"/>
      <div className="cm-kpi4 cm-mb-24" style={{gridAutoRows:'1fr'}}>
        <div className="cm-card cm-card-pad" style={{padding:20}}>
          <div className="st-mini-title" style={{marginBottom:12}}>Most Viewed Reports</div>
          {mostViewed.map((m,i)=><HBar key={i} name={m.name} value={m.v} max={42} color={m.c}/>)}
        </div>
        <div className="cm-card cm-card-pad" style={{padding:20}}>
          <div className="st-mini-title" style={{marginBottom:12}}>Reports by Category</div>
          <div style={{display:'flex',alignItems:'center',gap:14}}>
            <DonutChart size={120} thickness={18} segments={byCat} center={{value:'142',label:'Total'}}/>
            <div style={{flex:1,minWidth:0}}><Legend items={byCat.map(s=>({color:s.color,label:s.label,pct:s.value+'%'}))}/></div>
          </div>
        </div>
        <div className="cm-card cm-card-pad" style={{padding:20}}>
          <div className="st-mini-title" style={{marginBottom:12}}>Report Usage Trend</div>
          <div className="st-mini-sub" style={{marginBottom:10}}>Last 6 months</div>
          <TrendChart data={[58,64,60,72,68,84]} height={150} yLabels={['100','75','50','25']} xLabels={['Dec','Jan','Feb','Mar','Apr','May']}/>
        </div>
        <div className="cm-card cm-card-pad" style={{padding:20}}>
          <div className="st-mini-title" style={{marginBottom:12}}>Data Source Utilization</div>
          <div style={{display:'flex',alignItems:'center',gap:14}}>
            <DonutChart size={120} thickness={18} segments={dataSrc} center={{value:'14',label:'Sources'}}/>
            <div style={{flex:1,minWidth:0}}><Legend items={dataSrc.map(s=>({color:s.color,label:s.label,pct:s.value+'%'}))}/></div>
          </div>
        </div>
      </div>

      {/* AUTOMATED / INSIGHTS / EXPORTS */}
      <div className="cm-grid-3a cm-mb-24">
        <ChartCard title="Automated Reports" action={<span className="link" style={{fontSize:12.5,fontWeight:800,color:'var(--green-600)'}}>View all</span>}>
          {automated.map((a,i)=>(
            <div className="cm-act" key={i}>
              <div className="cm-act-ic" style={{background:'var(--mint-50)',color:'var(--green-600)'}}><I.Repeat size={16}/></div>
              <div className="cm-act-body"><div className="cm-act-title">{a.name}</div><div className="cm-act-sub">{a.freq} · {a.rec} recipients · {a.next}</div></div>
              <span className={`cm-pill cm-pill-${a.tone}`}>{a.status}</span>
            </div>
          ))}
        </ChartCard>
        <ChartCard title="AI Financial Insights" action={<span className="t-caption">Updated just now</span>}>
          {insights.map((s,i)=>(
            <div className="cm-rec" key={i}>
              <Robot pose={s.pose} size={36} float={false} style={{flex:'0 0 36px'}}/>
              <div className="cm-rec-body"><div className="cm-rec-title" style={{color:s.color}}>{s.tag}</div><div className="cm-rec-sub">{s.text}</div>
                <div className="qi-link" style={{color:'var(--green-600)',marginTop:6,fontSize:11.5,fontWeight:800,display:'inline-flex',alignItems:'center',gap:4,cursor:'pointer'}}>View details<I.ChevR size={12}/></div></div>
            </div>
          ))}
        </ChartCard>
        <ChartCard title="Recent Exports" action={<span className="link" style={{fontSize:12.5,fontWeight:800,color:'var(--green-600)'}}>View all</span>}>
          {exports.map((e,i)=>(
            <div className="cm-act" key={i}>
              <span className="st-pdf" style={e.fmt==='PDF'?null:{background:'var(--mint-100)',color:G}}>{e.fmt==='PDF'?<I.File size={15}/>:<I.Bars size={15}/>}</span>
              <div className="cm-act-body"><div className="cm-act-title">{e.name}</div><div className="cm-act-sub">{e.fmt} · {e.date}</div></div>
              <div className="cm-act-right" style={{display:'flex',alignItems:'center',gap:8}}>
                <I.Check size={16} style={{color:G}}/>
                <I.ArrowDown size={16} style={{color:'var(--ink-400)',cursor:'pointer'}}/>
              </div>
            </div>
          ))}
        </ChartCard>
      </div>

      {/* POPULAR TEMPLATES */}
      <SecHead eyebrow="Report Marketplace" title="Popular Report Templates" link="View all templates"/>
      <div className="cm-replib cm-mb-24" style={{gridTemplateColumns:'repeat(3,1fr)'}}>
        {popTemplates.map((t,i)=>(
          <div className="cm-repcard" key={i} style={{cursor:'default',padding:18}}>
            <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:12}}>
              <div className="rc-ic" style={{background:tint(t.c),color:t.c,width:38,height:38,borderRadius:11,marginBottom:0}}><I.Bars size={18}/></div>
              <div className="rc-name">{t.name}</div>
            </div>
            <div style={{height:64,marginBottom:12,borderRadius:10,overflow:'hidden',background:'var(--mint-50)',padding:'8px 6px'}}>
              {t.kind==='area'
                ? <Spark data={[3,5,4,7,6,9,8,11]} color={t.c} w={300} h={48}/>
                : <div className="cm-vbars" style={{height:48,gap:5,paddingTop:0}}>
                    {[6,9,5,11,7,10,8].map((v,j)=><div className="cm-vbar" key={j}><div className="col" style={{height:`${v/11*100}%`,background:t.c,maxWidth:14}}/></div>)}
                  </div>}
            </div>
            <div className="rc-when" style={{lineHeight:1.4,marginBottom:14}}>{t.sub}</div>
            <button className="cm-btn cm-btn-soft" style={{width:'100%',justifyContent:'center',padding:'8px'}}>Use Template</button>
          </div>
        ))}
      </div>

      {/* ASK BANNER */}
      <div className="cm-askbanner">
        <Robot pose="r2-7" size={62} cls="robot" float="float2"/>
        <div className="ab-tx"><div className="t">Need a custom report or insight?</div><div className="s">Ask Mint anything about your finances and get the perfect report.</div></div>
        <div className="ab-in">
          <input placeholder="Ask me to create a report, analyze spending, compare investments…"/>
          <button className="send"><I.Transfer size={18}/></button>
        </div>
      </div>
    </div>
  );
}
window.PageReports = PageReports;
})();
