/* Clear Mint — Bank Statements. window.PageBankStatements
   Shows every imported transaction grouped BY ACCOUNT (not a bank-connection screen):
   per-account balance, income/spending, the list of imported statement files (each
   deletable — removes its transactions and anything auto-created from it), and the
   full transaction ledger with live logo.dev merchant logos.
   Depends on cm-charts (CMIcon) + cm-components (MetricCard/ChartCard/DataTable/BrandIcon)
   + cm-app-kit (KpiRow/StatusPill/Tabs) + cm-import (CMimport). */
(function () {
const { MetricCard, ChartCard, DataTable, KpiRow, StatusPill, Tabs, Legend, DonutChart } = window;
const I = window.CMIcon;
const G = '#10915F', BL = '#3E7CC4', AM = '#B5740F', PU = '#8A6E9E', RD = 'var(--red-500)', SL = '#9AA7B2';
const TRANSFER = { 'Transfer':1, 'Credit Card Payment':1, 'Savings':1 };

const Trash = ({ size=15 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2M6 7l1 13h10l1-13"/>
  </svg>
);

function fileDate(s){ try { return s ? new Date(s).toLocaleDateString('en-CA',{month:'short',day:'numeric',year:'numeric'}) : ''; } catch(e){ return s||''; } }

/* ---------- one account block ---------- */
function AccountBlock({ CM, acct, idx, query, period }) {
  const BrandIcon = window.BrandIcon;
  const fmt = CM.M, fmt0 = CM.M0;
  const [open, setOpen] = React.useState(true);
  const [showAll, setShowAll] = React.useState(false);
  const [allHistory, setAllHistory] = React.useState(false);

  const allTx = (CM.S.bankTx||[]).filter(r => r.acctIdx===idx)
    .sort((a,b)=>(CM.toTs(b.date)||0)-(CM.toTs(a.date)||0));   // most recent first
  let tx = allTx; if(query) tx = tx.filter(r => ((r.desc||'')+' '+(r.cat||'')).toLowerCase().includes(query.toLowerCase()));
  const txP = window.cmInPeriod ? allTx.filter(r=>window.cmInPeriod(r.date, period)) : allTx;
  const income = txP.reduce((s,r)=>s+(+r.cr||0),0);
  const spend  = txP.filter(r=>!TRANSFER[r.cat]).reduce((s,r)=>s+(+r.dr||0),0);
  const batches = (CM.S._importBatches||[]).filter(b => b.type!=='cc' && b.acctIdx===idx)
    .sort((a,b)=>String(b.when||'').localeCompare(String(a.when||'')));
  // default view = most recent statement only (toggle for full history)
  const latest = batches[0];
  const latestApplies = !!(latest && latest.id!=null && allTx.some(r=>r.batchId===latest.id));
  if(!allHistory && latestApplies) tx = tx.filter(r=>r.batchId===latest.id);          // latest-statement view always shows the full statement
  else if(window.cmInPeriod) tx = tx.filter(r=>window.cmInPeriod(r.date, period));    // full-history view respects the period filter

  const delFile = (b) => {
    if (!window.confirm('Delete “'+(b.fname||'this statement')+'”?\n\nThis permanently removes its '+b.count+' transaction'+(b.count===1?'':'s')+' — plus any earnings, bills, subscriptions, insurance or loans that were auto-created from it.')) return;
    try { window.CMimport && window.CMimport.deleteBatch && window.CMimport.deleteBatch(b.id); } catch(e){}
    try { CM.emit && CM.emit(); } catch(e){}
  };

  const cols = [
    { header:'Date', cell:r=><span className="num" style={{fontSize:13,color:'var(--ink-700)',fontWeight:600,whiteSpace:'nowrap'}}>{CM.FD(r.date)}</span> },
    { header:'Description', cell:r=>(
      <div className="cm-cell-lead"><BrandIcon name={r.desc} size={34} radius={8}/>
        <div style={{minWidth:0}}>
          <div className="cm-cell-primary" style={{whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis',maxWidth:300}}>{r.desc||'Transaction'}</div>
          <div className="cm-cell-sub">{r.cat||'Other'}</div>
        </div></div>) },
    { header:'Withdrawals', align:'right', cell:r=>(+r.dr||0)>0 ? <span className="num" style={{fontWeight:700,color:'var(--ink-900)'}}>{fmt(r.dr)}</span> : <span style={{color:'var(--ink-300)'}}>—</span> },
    { header:'Deposits', align:'right', cell:r=>(+r.cr||0)>0 ? <span className="num" style={{fontWeight:700,color:G}}>{fmt(r.cr)}</span> : <span style={{color:'var(--ink-300)'}}>—</span> },
    { header:'Balance', align:'right', cell:r=><span className="num" style={{fontWeight:700,color:(+r.balance||0)<0?RD:'var(--ink-700)'}}>{r.balance!=null?fmt(r.balance):'—'}</span> },
  ];

  const shown = showAll ? tx : tx.slice(0,40);

  return (
    <ChartCard className="cm-mb-24" pad={false}>
      {/* header */}
      <div style={{display:'flex',alignItems:'center',gap:14,padding:'18px 22px',borderBottom:'1px solid var(--line)',flexWrap:'wrap'}}>
        <BrandIcon name={acct.bank||acct.name} size={44} radius={12}/>
        <div style={{flex:1,minWidth:160}}>
          <div className="t-h2" style={{fontSize:18,display:'flex',alignItems:'center',gap:9,flexWrap:'wrap'}}>
            {acct.name||'Account'}
            {acct.last4 && !String(acct.name||'').includes(acct.last4) && <span className="text-muted num" style={{fontSize:13,fontWeight:700,color:'var(--ink-400)'}}>•••• {acct.last4}</span>}
            {acct._fromImport && <span className="cm-pill cm-pill-green" style={{fontSize:10}}>Auto-detected</span>}
          </div>
          <div className="t-caption">{(acct.bank||'Bank')}{acct.type?(' · '+acct.type):''}{acct.overdraft?(' · overdraft '+fmt0(acct.overdraft)):''}</div>
        </div>
        <div style={{textAlign:'right'}}>
          <div className="num" style={{fontSize:22,fontWeight:800,color:(+acct.balance||0)<0?RD:'var(--ink-900)'}}>{fmt(acct.balance||0)}</div>
          {(+acct.overdraft||0)>0
            ? <div className="t-caption" style={{color:RD,fontWeight:700}}>+ draft {fmt0(acct.overdraft)} <span style={{color:'var(--ink-400)',fontWeight:600}}>(excl. from total)</span></div>
            : <div className="t-caption">{allTx.length} transaction{allTx.length===1?'':'s'}</div>}
        </div>
        {window.ImportControls && <window.ImportControls type="bank" idx={idx}/>}
      </div>

      {/* mini stats */}
      <div style={{display:'flex',gap:0,borderBottom:'1px solid var(--line)',flexWrap:'wrap'}}>
        {[
          { k:'Money in',  v:fmt0(income), c:G },
          { k:'Money out', v:fmt0(spend),  c:RD },
          { k:'Net',       v:(income-spend>=0?'+':'-')+fmt0(Math.abs(income-spend)).slice(1), c:income-spend>=0?G:RD },
        ].map((s,i)=>(
          <div key={i} style={{flex:'1 1 120px',padding:'13px 22px',borderRight:i<2?'1px solid var(--line)':'none'}}>
            <div className="t-caption" style={{textTransform:'uppercase',letterSpacing:'.05em',fontWeight:700,fontSize:10.5}}>{s.k}</div>
            <div className="num" style={{fontSize:18,fontWeight:800,color:s.c,marginTop:3}}>{s.v}</div>
          </div>
        ))}
      </div>

      {/* imported files */}
      {batches.length>0 && (
        <div style={{padding:'14px 22px',borderBottom:'1px solid var(--line)'}}>
          <div className="t-caption" style={{textTransform:'uppercase',letterSpacing:'.05em',fontWeight:700,marginBottom:9}}>Imported statement files</div>
          <div style={{display:'flex',flexWrap:'wrap',gap:9}}>
            {batches.map(b=>(
              <div key={b.id} style={{display:'flex',alignItems:'center',gap:9,padding:'7px 10px 7px 12px',borderRadius:11,border:'1px solid var(--line)',background:'var(--mint-50)'}}>
                <span style={{color:G,display:'inline-flex'}}><I.File size={15}/></span>
                <div style={{minWidth:0}}>
                  <div className="t-label" style={{fontSize:12.5,color:'var(--ink-900)',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis',maxWidth:200}}>{b.fname||'Statement'}</div>
                  <div className="t-caption" style={{fontSize:11}}>{b.count} txn{b.count===1?'':'s'}{b.when?(' · '+fileDate(b.when)):''}</div>
                </div>
                <button onClick={()=>delFile(b)} title="Delete this file & its transactions"
                  style={{border:0,background:'none',color:RD,cursor:'pointer',display:'inline-flex',padding:4,borderRadius:7}}
                  onMouseOver={e=>e.currentTarget.style.background='var(--red-100)'} onMouseOut={e=>e.currentTarget.style.background='none'}>
                  <Trash size={15}/>
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* transactions */}
      <div style={{padding:'16px 22px 18px'}}>
        <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',gap:12,marginBottom:12,flexWrap:'wrap'}}>
          <div className="cm-row" style={{gap:8,cursor:'pointer'}} onClick={()=>setOpen(o=>!o)}>
            <span style={{color:'var(--ink-400)',display:'inline-flex',transition:'.2s',transform:open?'none':'rotate(-90deg)'}}><I.Chevron size={18}/></span>
            <span className="st-mini-title">Transactions</span>
            <span className="cm-pill cm-pill-slate" style={{fontWeight:700}}>{tx.length}</span>
            {!allHistory && latestApplies && <span className="cm-pill cm-pill-green" style={{fontSize:10,fontWeight:700}}>Latest statement{latest.fname?(' · '+latest.fname):''}</span>}
          </div>
          {latestApplies && <a className="t-label text-green" style={{cursor:'pointer'}} onClick={()=>setAllHistory(h=>!h)}>{allHistory?'Show latest statement only':'Show all history'}</a>}
        </div>
        {open && (tx.length
          ? <React.Fragment>
              <DataTable columns={cols} rows={shown} minWidth={680}/>
              {tx.length>40 && <div style={{textAlign:'center',marginTop:12}}>
                <button className="cm-btn cm-btn-ghost" onClick={()=>setShowAll(s=>!s)}>{showAll?'Show less':('Show all '+tx.length+' transactions')}</button>
              </div>}
            </React.Fragment>
          : <div className="t-caption" style={{textAlign:'center',padding:'24px 0'}}>{query?'No transactions match your search.':'No transactions yet — import a statement above.'}</div>)}
      </div>
    </ChartCard>
  );
}

/* ---------- empty state ---------- */
function EmptyBank({ CM }) {
  return (
    <ChartCard>
      <div style={{textAlign:'center',padding:'56px 20px'}}>
        <div style={{color:G,marginBottom:14,display:'flex',justifyContent:'center'}}><I.Bank size={40}/></div>
        <div className="t-h2" style={{fontSize:19}}>No statements imported yet</div>
        <div className="t-caption" style={{marginTop:6,maxWidth:440,marginLeft:'auto',marginRight:'auto'}}>
          Upload a bank statement (OFX, QFX or CSV) and Clear Mint groups every transaction under the right account — with live merchant logos and one-click cleanup.
        </div>
        <div style={{display:'flex',gap:10,justifyContent:'center',marginTop:20,flexWrap:'wrap'}}>
          {window.ImportControls && <window.ImportControls type="bank"/>}
          <a href="#/connect" className="cm-btn cm-btn-ghost" style={{textDecoration:'none'}}><I.Transfer size={16}/>Bank connections</a>
        </div>
      </div>
    </ChartCard>
  );
}

/* ---------- page ---------- */
function PageBankStatements() {
  if(window.CMAccess && !CMAccess.can('bankstatements')){
    return (<div className="cm-card" style={{maxWidth:520,margin:'40px auto',padding:'32px',textAlign:'center'}}>
      <div style={{fontFamily:'var(--font-serif)',fontSize:20,fontWeight:700,color:'var(--ink-900)',marginBottom:8}}>Statements are a Premium feature</div>
      <p style={{fontSize:14,color:'var(--ink-500)',margin:'0 0 16px'}}>Upgrade to upload and read your bank statements. You can still add transactions manually on any plan.</p>
      <button onClick={()=>window.CMAccess&&CMAccess.openUpgradeModal('Bank Statements')} style={{fontFamily:'inherit',fontSize:14,fontWeight:700,border:0,borderRadius:12,padding:'11px 20px',background:'#D4A95D',color:'#16321F',cursor:'pointer'}}>Upgrade to Premium</button>
    </div>);
  }
  const CM = window.useStore ? window.useStore() : window.CM;
  const fmt0 = CM.M0;
  const [q, setQ] = React.useState('');
  const [period, setPeriod] = React.useState('month');
  const [tab, setTab] = React.useState('All Transactions');
  const fmt = CM.M;
  const BI = window.BrandIcon;
  const accts = CM.S.accounts || [];
  const bankTx = CM.S.bankTx || [];

  if (!accts.length && !bankTx.length) return <EmptyBank CM={CM}/>;

  const periodLabel = window.cmPeriodLabel?window.cmPeriodLabel(period):'';
  const periodTx = window.cmInPeriod ? bankTx.filter(r=>window.cmInPeriod(r.date, period)) : bankTx;
  const incomeM = periodTx.reduce((s,r)=>s+(+r.cr||0),0);
  const spendM  = periodTx.filter(r=>!TRANSFER[r.cat]).reduce((s,r)=>s+(+r.dr||0),0);
  const totalBal = accts.reduce((s,a)=>s+(+a.balance||0),0);
  const files = (CM.S._importBatches||[]).filter(b=>b.type!=='cc').length;

  // transactions not linked to any account (defensive — show in their own block)
  const orphan = bankTx.filter(r => r.acctIdx==null || r.acctIdx<0 || r.acctIdx>=accts.length);

  // ---- derived data for the summary tabs (all period-scoped) ----
  const acctName = (r)=> (accts[r.acctIdx]&&accts[r.acctIdx].name) || r.account || 'Unassigned';
  const q2 = q.toLowerCase();
  const allRows = periodTx.filter(r=>!q2 || ((r.desc||'')+' '+(r.cat||'')+' '+acctName(r)).toLowerCase().includes(q2))
    .sort((a,b)=>(CM.toTs(b.date)||0)-(CM.toTs(a.date)||0));   // most recent first
  const catMap={}; periodTx.forEach(r=>{ var c=r.cat||'Other'; (catMap[c]=catMap[c]||{inc:0,exp:0,n:0}); if(r.cr>0)catMap[c].inc+=(+r.cr||0); if(r.dr>0)catMap[c].exp+=(+r.dr||0); catMap[c].n++; });
  const catRows=Object.keys(catMap).map(c=>({cat:c,inc:catMap[c].inc,exp:catMap[c].exp,n:catMap[c].n,net:catMap[c].inc-catMap[c].exp})).sort((a,b)=>(b.inc+b.exp)-(a.inc+a.exp));
  // bank-fee detection + classification
  const feeType=(r)=>{ var d=(r.desc||'').toLowerCase();
    if(/nsf|return/.test(d)) return 'NSF / Returned';
    if(/overdraft|coverage/.test(d)) return 'Overdraft';
    if(/interest/.test(d)) return 'Interest Charge';
    if(/atm|network/.test(d)) return 'ATM / Network';
    if(/monthly|plan|account fee|maint/.test(d)) return 'Monthly / Plan';
    return 'Other Fee'; };
  const isFee=(r)=> (+r.dr||0)>0 && (/fee|nsf|overdraft|interest charge|coverage|service charge|maint|\bplan\b/i.test(r.desc||'') || /fee/i.test(r.cat||''));
  const fees = periodTx.filter(isFee).map(r=>({date:r.date,desc:r.desc||'Fee',amt:+r.dr||0,type:feeType(r),acct:acctName(r)})).sort((a,b)=>(CM.toTs(b.date)||0)-(CM.toTs(a.date)||0));
  const feeTotal=fees.reduce((s,f)=>s+f.amt,0);
  const feeByType={}; fees.forEach(f=>{ feeByType[f.type]=(feeByType[f.type]||0)+f.amt; });
  const feePal={'Monthly / Plan':G,'ATM / Network':BL,'NSF / Returned':RD,'Overdraft':AM,'Interest Charge':'#C99A2E','Other Fee':PU};
  const feeTypeArr=Object.keys(feeByType).map(k=>({label:k,value:feeByType[k],color:feePal[k]||SL})).sort((a,b)=>b.value-a.value);
  const feeMonths=window.cmPeriodMonths?window.cmPeriodMonths(fees.map(f=>f.date)):1;

  const orphanBlock = orphan.length>0 ? (
        <ChartCard className="cm-mb-24">
          <div className="st-mini-title" style={{marginBottom:4}}>Unassigned transactions</div>
          <div className="t-caption" style={{marginBottom:14}}>{orphan.length} transaction{orphan.length===1?'':'s'} not linked to an account. Re-import the statement to an account, or add the account first.</div>
          <DataTable minWidth={680} columns={[
            { header:'Transaction', cell:r=><div className="cm-cell-lead"><window.BrandIcon name={r.desc} size={34} radius={8}/><div className="cm-cell-primary">{r.desc||'Transaction'}</div></div> },
            { header:'Date', cell:r=><span className="num" style={{fontSize:13,color:'var(--ink-500)'}}>{CM.FD(r.date)}</span> },
            { header:'Amount', align:'right', cell:r=>{ const isD=(+r.dr||0)>0; return <span className="num" style={{fontWeight:700,color:isD?'var(--ink-900)':G}}>{(isD?'-':'+')+CM.M(r.dr||r.cr||0).slice(1)}</span>; } },
          ] } rows={orphan.slice(0,40)}/>
        </ChartCard>) : null;

  return (
    <div>
      <KpiRow>
        <MetricCard label="Total Balance" labelColor={totalBal<0?'var(--red-500)':'var(--green-600)'} value={fmt0(totalBal)} sub={accts.length+' account'+(accts.length===1?'':'s')}/>
        <MetricCard label="Money In" labelColor="var(--green-600)" value={fmt0(incomeM)} sub={periodLabel}/>
        <MetricCard label="Money Out" labelColor="var(--red-500)" value={fmt0(spendM)} sub={periodLabel}/>
        <MetricCard label="Transactions" value={periodTx.length.toLocaleString()} sub={periodLabel}/>
      </KpiRow>

      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',gap:12,margin:'4px 0 16px',flexWrap:'wrap'}}>
        <Tabs tabs={['All Transactions','By Account','By Category','Bank Fees']} value={tab} onChange={setTab}/>
        {window.PeriodBar ? <window.PeriodBar value={period} onChange={setPeriod}/> : null}
      </div>

      {tab==='All Transactions' && (<React.Fragment>
        <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',gap:12,marginBottom:14,flexWrap:'wrap'}}>
          <div className="st-searchbox" style={{maxWidth:360,flex:'1 1 240px'}}>
            <I.Search size={16}/><input placeholder="Search all transactions…" value={q} onChange={e=>setQ(e.target.value)}/>
          </div>
          <a href="#/connect" className="cm-btn cm-btn-ghost" style={{textDecoration:'none'}}><I.Transfer size={16}/>Manage bank connections</a>
        </div>
        <ChartCard>
          {allRows.length?<DataTable minWidth={780} columns={[
            { header:'Date', cell:r=><span className="num" style={{fontSize:13,color:'var(--ink-600)',fontWeight:600,whiteSpace:'nowrap'}}>{CM.FD(r.date)}</span> },
            { header:'Description', cell:r=><div className="cm-cell-lead"><BI name={r.desc} size={32} radius={8}/><div style={{minWidth:0}}><div className="cm-cell-primary" style={{maxWidth:300,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{r.desc||'Transaction'}</div><div className="cm-cell-sub">{acctName(r)} · {r.cat||'Other'}</div></div></div> },
            { header:'Withdrawals', align:'right', cell:r=>(+r.dr||0)>0?<span className="num" style={{fontWeight:700,color:'var(--ink-900)'}}>{fmt(r.dr)}</span>:<span style={{color:'var(--ink-300)'}}>—</span> },
            { header:'Deposits', align:'right', cell:r=>(+r.cr||0)>0?<span className="num" style={{fontWeight:700,color:G}}>{fmt(r.cr)}</span>:<span style={{color:'var(--ink-300)'}}>—</span> },
            { header:'Balance', align:'right', cell:r=><span className="num" style={{fontWeight:700,color:(+r.balance||0)<0?RD:'var(--ink-700)'}}>{r.balance!=null?fmt(r.balance):'—'}</span> },
          ]} rows={allRows.slice(0,80)}/>:<div className="t-caption" style={{textAlign:'center',padding:'40px 0'}}>No transactions in {periodLabel}.</div>}
          {allRows.length>80 && <div className="t-caption" style={{textAlign:'center',marginTop:12}}>Showing 80 of {allRows.length.toLocaleString()} — narrow with search or period.</div>}
        </ChartCard>
        {orphanBlock}
      </React.Fragment>)}

      {tab==='By Account' && (<React.Fragment>
        {accts.map((a,i)=><AccountBlock key={i} CM={CM} acct={a} idx={i} query={q} period={period}/>)}
        {orphanBlock}
      </React.Fragment>)}

      {tab==='By Category' && (
        <ChartCard title={'By Category · '+periodLabel}>
          {catRows.length?<div style={{overflowX:'auto'}}><table className="cm-table" style={{minWidth:620}}>
            <thead><tr><th>Category</th><th className="right">Deposits</th><th className="right">Withdrawals</th><th className="right">Net</th><th className="right">Txns</th></tr></thead>
            <tbody>{catRows.map((c,i)=>(<tr key={i}>
              <td><span style={{fontWeight:700,color:'var(--ink-900)'}}>{c.cat}</span></td>
              <td style={{textAlign:'right'}}><span className="num" style={{color:G,fontWeight:700}}>{c.inc?fmt(c.inc):'—'}</span></td>
              <td style={{textAlign:'right'}}><span className="num" style={{color:'var(--red-500)',fontWeight:700}}>{c.exp?fmt(c.exp):'—'}</span></td>
              <td style={{textAlign:'right'}}><span className="num" style={{fontWeight:800,color:c.net>=0?G:'var(--red-500)'}}>{(c.net>=0?'+':'-')+fmt(Math.abs(c.net)).slice(1)}</span></td>
              <td style={{textAlign:'right'}}><span className="num" style={{color:'var(--ink-500)'}}>{c.n}</span></td>
            </tr>))}</tbody>
          </table></div>:<div className="t-caption" style={{textAlign:'center',padding:'40px 0'}}>No activity in {periodLabel}.</div>}
        </ChartCard>
      )}

      {tab==='Bank Fees' && (<React.Fragment>
        <KpiRow>
          <MetricCard label="Total Fees Paid" labelColor="var(--red-500)" value={fmt0(feeTotal)} sub={CM.M0(Math.round(feeTotal/Math.max(1,feeMonths)))+'/mo avg'}/>
          <MetricCard label="Number of Fees" value={String(fees.length)} sub={feeTypeArr[0]?('most: '+feeTypeArr[0].label):periodLabel}/>
          <div className="cm-card cm-card-pad" style={{gridColumn:'span 2'}}>
            <div className="m-label" style={{fontWeight:700,fontSize:13,marginBottom:10}}>By Fee Type</div>
            {feeTypeArr.length?<div style={{display:'flex',alignItems:'center',gap:16}}>
              <DonutChart size={92} thickness={13} segments={feeTypeArr} center={{value:fmt0(feeTotal),label:'fees'}}/>
              <div style={{flex:1,minWidth:0}}><Legend items={feeTypeArr.map(f=>({color:f.color,label:f.label,pct:Math.round(f.value/(feeTotal||1)*100)+'%',value:fmt(f.value)}))}/></div>
            </div>:<div className="t-caption">No fees in {periodLabel}.</div>}
          </div>
        </KpiRow>
        <ChartCard title="All Bank Fees" action={<span className="t-caption">{fees.length} fee{fees.length===1?'':'s'}</span>}>
          {fees.length?<div style={{overflowX:'auto'}}><table className="cm-table" style={{minWidth:640}}>
            <thead><tr><th>Date</th><th>Type</th><th>Description</th><th className="right">Amount</th></tr></thead>
            <tbody>{fees.slice(0,80).map((f,i)=>(<tr key={i}>
              <td><span className="num" style={{color:'var(--ink-600)',fontWeight:600,whiteSpace:'nowrap'}}>{CM.FD(f.date)}</span></td>
              <td><span className="cm-pill" style={{background:window.tintFor?window.tintFor(feePal[f.type]||SL):'var(--mint-50)',color:feePal[f.type]||SL,fontWeight:700,fontSize:11}}>{f.type}</span></td>
              <td><div style={{display:'flex',alignItems:'center',gap:9}}><BI name={f.desc} size={28} radius={7}/><span style={{color:'var(--ink-700)'}}>{f.desc}</span></div></td>
              <td style={{textAlign:'right'}}><span className="num" style={{fontWeight:700,color:'var(--red-500)'}}>{fmt(f.amt)}</span></td>
            </tr>))}</tbody>
          </table></div>:<div className="t-caption" style={{textAlign:'center',padding:'40px 0'}}>No bank fees detected in {periodLabel}.</div>}
        </ChartCard>
      </React.Fragment>)}
    </div>
  );
}

window.PageBankStatements = PageBankStatements;
})();
