/* Clear Mint — Wealth Overview + Net Worth pages (wired to engine) */
const { MetricCard, ChartCard, DataTable, DonutChart, TrendChart, ProgressBar, Legend, FinancialHealthCard, InsightCard } = window;
const { KpiRow, ChangeCell, StatusPill, ActivityList, Tabs, CategoryBar, CMC } = window;
const In = window.CMIcon;
const { G, PU, AM, BL, SL, RD, TEAL, PINK, INDIGO } = CMC;
const tn = window.tintFor;
const go = id => () => { location.hash = '#/'+id; };

function nwBits(){
  const CM = window.CM;
  const assets = CM.grossAssets(), liab = CM.totalLiabilities(), nw = CM.netWorth();
  const ratio = liab>0 ? assets/liab : 0;
  const inc = CM.monthlyIncome()||1;
  const monthlyDebt = (CM.S.liabilities||[]).reduce((s,l)=>s+(+l.payment||0),0) + (CM.S.cards||[]).reduce((s,c)=>s+Math.max(25,Math.round((+c.balance||0)*0.02)),0);
  const dti = Math.round(monthlyDebt/inc*100);
  return { assets, liab, nw, ratio, dti, series:CM.netWorthSeries() };
}
function maxBar(segs){ return Math.max.apply(null, segs.map(s=>s.value)) || 1; }

/* ============================ WEALTH OVERVIEW ============================ */
function PageWealth() {
  const CM = window.useStore ? window.useStore() : window.CM;
  const fmt = CM.M0;
  const b = nwBits();
  const aSegs = CM.assetSegments(), lSegs = CM.liabSegments();
  const aMax = maxBar(aSegs), lMax = maxBar(lSegs);
  return (
    <div>
      <KpiRow>
        <MetricCard label="Net Worth" labelColor="var(--green-600)" value={fmt(b.nw)}
          art={<div style={{width:84}}><TrendChart data={b.series} width={84} height={42} color={G} pad={{l:2,r:2,t:6,b:6}} showDots={false}/></div>}/>
        <MetricCard label="Total Assets" value={fmt(b.assets)}
          art={<DonutChart size={56} thickness={9} segments={[{value:74,color:G},{value:26,color:'var(--mint-100)'}]}/>}/>
        <MetricCard label="Total Liabilities" labelColor="var(--red-500)" value={fmt(b.liab)}
          art={<DonutChart size={56} thickness={9} segments={[{value:33,color:RD},{value:67,color:'var(--red-100)'}]}/>}/>
        <div className="cm-card cm-card-pad">
          <div className="m-label" style={{color:'var(--green-600)',fontWeight:700,fontSize:13,marginBottom:10}}>Debt-to-Income</div>
          <div className="cm-gauge-wrap">
            <DonutChart size={72} thickness={10} segments={[{value:Math.min(100,b.dti),color:b.dti<36?G:AM},{value:Math.max(0,100-b.dti),color:'var(--mint-100)'}]} center={{value:b.dti+'%'}}/>
            <div><div style={{fontWeight:800,color:b.dti<36?G:'#B5740F'}}>{b.dti<36?'Good':'Watch'}</div><div className="t-caption">Healthy ratio</div></div>
          </div>
        </div>
      </KpiRow>

      <div className="cm-grid-2a cm-mb-24">
        <ChartCard title="Net Worth Over Time"
          action={<div className="cm-seg">{['1M','3M','6M','1Y','All'].map(t=><button key={t} className={t==='1Y'?'active':''}>{t}</button>)}</div>}>
          <TrendChart data={b.series} width={760} height={300} yLabels={[fmt(Math.max.apply(null,b.series)),'',fmt(0)]} xLabels={['','','','','']}/>
        </ChartCard>
        <div className="cm-stack">
          <ChartCard title="Net Worth Breakdown">
            <div className="cm-donut-card" style={{justifyContent:'center'}}>
              <DonutChart size={150} thickness={22} center={{value:fmt(b.nw),label:'Net Worth'}}
                segments={[{value:b.assets,color:G},{value:b.liab,color:RD}]}/>
            </div>
            <div style={{marginTop:16}}><Legend items={[
              {color:G,label:'Assets',pct:'('+Math.round(b.assets/(b.assets+b.liab)*100)+'%)',value:fmt(b.assets)},
              {color:RD,label:'Liabilities',pct:'('+Math.round(b.liab/(b.assets+b.liab)*100)+'%)',value:fmt(b.liab)},
            ]}/></div>
          </ChartCard>
          <FinancialHealthCard ratio={b.ratio.toFixed(2)+' : 1'} status={b.ratio>=2?'Good':b.ratio>=1?'Fair':'Watch'} position={Math.min(0.95,b.ratio/4)}
            note={'For every $1 of liabilities, you have $'+b.ratio.toFixed(2)+' of assets.'}/>
        </div>
      </div>

      <div className="cm-grid-3">
        <ChartCard title="Assets" action={<a className="t-label text-green" style={{cursor:'pointer'}} onClick={go('assets')}>View all</a>}>
          <div style={{display:'flex',alignItems:'baseline',gap:8,marginBottom:14}}>
            <span className="num" style={{fontSize:24,fontWeight:800,color:'var(--ink-900)'}}>{fmt(b.assets)}</span>
          </div>
          {aSegs.map((s,i)=><CategoryBar key={i} color={s.color} label={s.label} value={fmt(s.value)} width={Math.round(s.value/aMax*100)}/>)}
        </ChartCard>
        <ChartCard title="Liabilities" action={<a className="t-label text-green" style={{cursor:'pointer'}} onClick={go('liabilities')}>View all</a>}>
          <div style={{display:'flex',alignItems:'baseline',gap:8,marginBottom:14}}>
            <span className="num" style={{fontSize:24,fontWeight:800,color:'var(--ink-900)'}}>{fmt(b.liab)}</span>
          </div>
          {lSegs.map((s,i)=><CategoryBar key={i} color={s.color} label={s.label} value={fmt(s.value)} width={Math.round(s.value/lMax*100)}/>)}
        </ChartCard>
        <ChartCard title="Investments" action={<a className="t-label text-green" style={{cursor:'pointer'}} onClick={go('investments')}>View all</a>}>
          {(CM.S.investments||[]).slice(0,5).map((v,i)=>{const mv=v.marketValue!=null?+v.marketValue:(+v.shares||0)*(+v.currentPrice||0);return (
            <div className="cm-act" key={i}><div className="cm-act-ic" style={{background:tn(PU),color:(CM.INV_COLORS&&CM.INV_COLORS[v.type])||PU}}><In.Investments size={16}/></div>
              <div className="cm-act-body"><div className="cm-act-title">{v.symbol||v.name}</div><div className="cm-act-sub">{v.account||v.broker||''}</div></div>
              <div className="cm-act-amt num">{fmt(mv)}</div></div>
          );})}
        </ChartCard>
      </div>
    </div>
  );
}
window.PageWealth = PageWealth;

/* ============================ NET WORTH ============================ */
function PageNetWorth() {
  const CM = window.useStore ? window.useStore() : window.CM;
  const fmt = CM.M0;
  const [tab, setTab] = React.useState('Overview');
  const onTab = t => { if (t==='Assets') location.hash='#/assets'; else if (t==='Liabilities') location.hash='#/liabilities'; else setTab(t); };
  const b = nwBits();
  const series = b.series;
  const last = series[series.length-1], prev = series[series.length-2]||last;
  const delta = last-prev;
  const fc = []; let v=last; for(let i=0;i<6;i++){ fc.push(Math.round(v)); v*=1.06; }
  return (
    <div>
      <KpiRow>
        <MetricCard label="Total Net Worth" labelColor="var(--green-600)" value={fmt(b.nw)} delta={{dir:delta>=0?'pos':'neg',text:(delta>=0?'+':'-')+fmt(Math.abs(delta)).slice(1)}}
          art={<div style={{width:84}}><TrendChart data={series} width={84} height={42} color={G} pad={{l:2,r:2,t:6,b:6}} showDots={false}/></div>}/>
        <MetricCard label="Total Assets" value={fmt(b.assets)}
          art={<DonutChart size={56} thickness={9} segments={[{value:74,color:G},{value:26,color:'var(--mint-100)'}]}/>}/>
        <MetricCard label="Total Liabilities" labelColor="var(--red-500)" value={fmt(b.liab)}
          art={<DonutChart size={56} thickness={9} segments={[{value:33,color:RD},{value:67,color:'var(--red-100)'}]}/>}/>
        <MetricCard label="Asset/Liability Ratio" labelColor="var(--green-600)" value={b.ratio.toFixed(2)+' : 1'} sub="coverage"
          art={<div style={{width:84}}><TrendChart data={[4,6,5,7,6,8,7,9,8,11,10,13]} width={84} height={42} color={G} pad={{l:2,r:2,t:6,b:6}} showDots={false}/></div>}/>
      </KpiRow>

      <ChartCard className="cm-mb-24" pad={false} style={{padding:'20px 24px'}}>
        <Tabs tabs={['Overview','Assets','Liabilities','Trends','Net Worth Forecast','Balance Sheet']}
          value={tab} onChange={onTab} right={<div className="cm-select"><In.Calendar size={14}/> Last 12 months <In.Chevron size={14}/></div>}/>
      </ChartCard>

      <div className="cm-grid-2a cm-mb-24">
        <ChartCard title="Net Worth Over Time"
          action={<div className="cm-seg">{['1M','3M','6M','1Y','All'].map(t=><button key={t} className={t==='1Y'?'active':''}>{t}</button>)}</div>}>
          <TrendChart data={series} width={760} height={320} yLabels={[fmt(Math.max.apply(null,series)),'',fmt(0)]} xLabels={['','','','','']}/>
        </ChartCard>
        <div className="cm-stack">
          <ChartCard title="Net Worth Breakdown">
            <div className="cm-donut-card" style={{justifyContent:'center'}}>
              <DonutChart size={160} thickness={22} center={{value:fmt(b.nw),label:'Net Worth'}}
                segments={[{value:b.assets,color:G},{value:b.liab,color:RD}]}/>
            </div>
            <div style={{marginTop:16}}><Legend items={[
              {color:G,label:'Assets',pct:'('+Math.round(b.assets/(b.assets+b.liab)*100)+'%)',value:fmt(b.assets)},
              {color:RD,label:'Liabilities',pct:'('+Math.round(b.liab/(b.assets+b.liab)*100)+'%)',value:fmt(b.liab)},
            ]}/></div>
          </ChartCard>
          <FinancialHealthCard ratio={b.ratio.toFixed(2)+' : 1'} status={b.ratio>=2?'Good':b.ratio>=1?'Fair':'Watch'} position={Math.min(0.95,b.ratio/4)}
            note={'For every $1 of liabilities, you have $'+b.ratio.toFixed(2)+' of assets.'}/>
        </div>
      </div>

      <div className="cm-grid-3">
        <ChartCard title="Asset Composition">
          {CM.assetSegments().map((s,i)=><CategoryBar key={i} color={s.color} label={s.label} value={fmt(s.value)} width={Math.round(s.value/maxBar(CM.assetSegments())*100)}/>)}
        </ChartCard>
        <ChartCard title="Liability Composition">
          {CM.liabSegments().map((s,i)=><CategoryBar key={i} color={s.color} label={s.label} value={fmt(s.value)} width={Math.round(s.value/maxBar(CM.liabSegments())*100)}/>)}
        </ChartCard>
        <ChartCard title="Net Worth Forecast" action={<div className="cm-select">5 Years <In.Chevron size={14}/></div>}>
          <div className="num" style={{fontSize:26,fontWeight:800,color:'var(--ink-900)'}}>{fmt(fc[fc.length-1])}</div>
          <div className="t-caption" style={{marginBottom:8}}>Projected net worth in 5 years (6%/yr)</div>
          <TrendChart data={fc} width={360} height={170} yLabels={[fmt(fc[fc.length-1]),'',fmt(0)]} xLabels={['','','','','']}/>
        </ChartCard>
      </div>

      {window.ValueEstimators && <window.ValueEstimators/>}

      <div style={{display:'flex',alignItems:'center',gap:8,marginTop:20,color:'var(--ink-400)'}}>
        <In.Info size={15}/>
        <span className="t-caption">Net worth = total assets − total liabilities, computed live from your accounts, investments, assets, loans and cards.</span>
      </div>
    </div>
  );
}
window.PageNetWorth = PageNetWorth;
