/* Clear Mint — Debt Elimination Center. window.PageDebtCenter
   WIRED TO REAL DATA: derives every figure from CM.S.cards + CM.S.liabilities.
   No demo debts, no placeholder APRs — missing fields show as "—  · needs review"
   and projections are labelled estimated when a minimum payment is absent. */
(function(){
const I = window.CMIcon;
const { CMC, tintFor, DonutChart, Ring, Chip, PageHead, BrandIcon } = window;
const { G, PU, AM, BL, SL, RD, TEAL, PINK } = CMC;
const money = window.cmMoney;

/* multi-line payoff chart (generic) */
function PayoffChart({ series, xLabels, height=300 }) {
  const W=720, H=height, P={l:46,r:18,t:18,b:30};
  const all=series.flatMap(s=>s.data); const max=Math.max(...all,1);
  const n=Math.max(...series.map(s=>s.data.length),2);
  const X=i=>P.l+(i/(n-1))*(W-P.l-P.r);
  const Y=v=>P.t+(1-v/max)*(H-P.t-P.b);
  const yt=[max,max*0.75,max*0.5,max*0.25,0];
  return (
    <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{display:'block'}}>
      {yt.map((v,i)=>{const y=P.t+i*((H-P.t-P.b)/4);return(
        <g key={i}><line x1={P.l} y1={y} x2={W-P.r} y2={y} stroke="var(--line)" strokeWidth="1"/>
        <text x={P.l-8} y={y+4} textAnchor="end" fontSize="11" fill="var(--ink-400)" className="num">${Math.round(v/1000)}K</text></g>)})}
      {series.map((s,si)=>{
        const d=s.data.map((v,i)=>`${i?'L':'M'}${X(i)},${Y(v)}`).join(' ');
        return <path key={si} d={d} fill="none" stroke={s.color} strokeWidth={s.dash?2:2.6}
          strokeDasharray={s.dash?'5 5':'none'} strokeLinejoin="round" strokeLinecap="round" opacity={s.dash?.7:1}/>;
      })}
      {xLabels.map((lb,i)=>{const x=X(i*(n-1)/(Math.max(xLabels.length-1,1)));
        return <text key={i} x={x} y={H-8} textAnchor="middle" fontSize="10.5" fill="var(--ink-400)">{lb}</text>;})}
    </svg>
  );
}

function StratOption({ active, name, badge, date, interest, total, onClick }) {
  return (
    <div onClick={onClick} style={{border:`1.5px solid ${active?G:'var(--line)'}`, background:active?'var(--mint-50)':'#fff',
      borderRadius:12, padding:'13px 15px', cursor:'pointer', marginBottom:12}}>
      <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:8}}>
        <span style={{width:16,height:16,borderRadius:999,border:`2px solid ${active?G:'var(--ink-400)'}`,display:'inline-flex',alignItems:'center',justifyContent:'center'}}>
          {active && <span style={{width:7,height:7,borderRadius:999,background:G}}/>}</span>
        <span style={{fontWeight:800,fontSize:13.5,color:'var(--ink-900)'}}>{name}</span>
        {badge && <span className="cm-pill cm-pill-green" style={{marginLeft:'auto'}}>{badge}</span>}
      </div>
      <div style={{display:'flex',justifyContent:'space-between',fontSize:12,color:'var(--ink-500)',padding:'2px 0'}}><span>Debt Free Date</span><span className="num" style={{fontWeight:700,color:'var(--ink-900)'}}>{date}</span></div>
      <div style={{display:'flex',justifyContent:'space-between',fontSize:12,color:'var(--ink-500)',padding:'2px 0'}}><span>Total Interest</span><span className="num" style={{fontWeight:700,color:'var(--ink-900)'}}>{interest}</span></div>
      <div style={{display:'flex',justifyContent:'space-between',fontSize:12,color:'var(--ink-500)',padding:'2px 0'}}><span>Total Payments</span><span className="num" style={{fontWeight:700,color:'var(--ink-900)'}}>{total}</span></div>
    </div>
  );
}

/* ---- real-data derivation ---- */
function buildDebts(S){
  const cards=(S.cards||[]).filter(c=>(+c.balance||0)>0).map(c=>({
    name:c.name||'Credit Card', last:c.last4||'', type:'Credit Card', tc:BL,
    bal:+c.balance||0, apr:(c.apr!=null&&c.apr!=='')?+c.apr:null,
    min:(c.minPayment!=null&&c.minPayment!=='')?+c.minPayment:null,
    orig:+c.limit||null, logo:c.issuer||c.name||'Card' }));
  const liabs=(S.liabilities||[]).filter(l=>(+l.balance||0)>0).map(l=>({
    name:l.name||'Loan', last:'', type:l.type||'Loan', tc:/mortgage/i.test(l.type||'')?PU:/line/i.test(l.type||'')?TEAL:AM,
    bal:+l.balance||0, apr:(l.rate!=null&&l.rate!=='')?+l.rate:((l.apr!=null&&l.apr!=='')?+l.apr:null),
    min:(l.payment!=null&&l.payment!=='')?+l.payment:null,
    orig:+l.originalAmount||null, logo:l.lender||l.name||'Loan' }));
  return cards.concat(liabs);
}
/* monthly payoff simulation. mode: 'snowball' | 'avalanche' | 'minimum' */
function simulate(debts, mode){
  if(!debts.length) return null;
  const est = debts.some(d=>d.min==null||d.apr==null);
  const bals=debts.map(d=>d.bal);
  const aprs=debts.map(d=>(d.apr!=null?d.apr:0)/100/12);
  const mins=debts.map(d=>d.min!=null?d.min:Math.max(25,Math.round(d.bal*0.03)));
  const order=debts.map((d,i)=>i).sort((a,b)=> mode==='avalanche' ? (debts[b].apr||0)-(debts[a].apr||0) : debts[a].bal-debts[b].bal);
  let months=0, totalInt=0; const series=[bals.reduce((a,b)=>a+b,0)]; const payoffMonth=debts.map(()=>null);
  while(months<360 && bals.some(b=>b>0.01)){
    months++;
    bals.forEach((b,i)=>{ if(b>0.01){ const it=b*aprs[i]; totalInt+=it; bals[i]=b+it; } });
    let freed=0;
    if(mode!=='minimum') freed=mins.reduce((a,m,i)=>a+(bals[i]<=0.01?m:0),0);
    bals.forEach((b,i)=>{ if(b>0.01) bals[i]=Math.max(0,b-mins[i]); });
    if(freed>0){ const t=order.find(i=>bals[i]>0.01); if(t!=null) bals[t]=Math.max(0,bals[t]-freed); }
    bals.forEach((b,i)=>{ if(b<=0.01&&payoffMonth[i]==null) payoffMonth[i]=months; });
    series.push(bals.reduce((a,b)=>a+b,0));
  }
  const done=!bals.some(b=>b>0.01);
  return { months, done, totalInt:Math.round(totalInt), series, payoffMonth, est,
    totalPaid:Math.round(debts.reduce((a,d)=>a+d.bal,0)+totalInt), minSum:mins.reduce((a,b)=>a+b,0) };
}
function monthLabel(m){ const d=new Date(); d.setMonth(d.getMonth()+m); return d.toLocaleDateString('en-CA',{month:'short',year:'numeric'}); }
function sample(arr,n){ if(arr.length<=n) return arr; const out=[]; for(let i=0;i<n;i++){ out.push(arr[Math.round(i*(arr.length-1)/(n-1))]); } return out; }

function PageDebtCenter(){
  const CM = window.useStore ? window.useStore() : window.CM;
  const [strat,setStrat]=React.useState('Snowball');
  const debts=buildDebts(CM.S);

  if(!debts.length){
    return (
      <div>
        <PageHead title="Debt Elimination Center" sub="Take control of your debt and become debt free faster."/>
        <div className="cm-card cm-card-pad" style={{textAlign:'center',padding:'56px 20px'}}>
          <div style={{color:G,marginBottom:12,display:'flex',justifyContent:'center'}}><I.Check size={36}/></div>
          <div className="t-h2" style={{fontSize:19}}>No outstanding debts</div>
          <div className="t-caption" style={{marginTop:6}}>Import a credit-card PDF statement or add a loan and your payoff plan builds itself from the real balances.</div>
        </div>
      </div>
    );
  }

  const sims={ Snowball:simulate(debts,'snowball'), Avalanche:simulate(debts,'avalanche'), Minimum:simulate(debts,'minimum') };
  const cur=sims[strat]||sims.Snowball;
  const totalDebt=debts.reduce((s,d)=>s+d.bal,0);
  const missing=debts.filter(d=>d.apr==null||d.min==null);
  const N=9;
  const chart=[ {color:G,data:sample(sims.Snowball.series,N).map(v=>v/1000)},
                {color:BL,data:sample(sims.Avalanche.series,N).map(v=>v/1000)},
                {color:SL,dash:true,data:sample(sims.Minimum.series,N).map(v=>v/1000)} ];
  const xl=[0,0.25,0.5,0.75,1].map(f=>monthLabel(Math.round(sims.Minimum.months*f)));
  const saveInt=sims.Snowball.totalInt-sims.Avalanche.totalInt;
  const saveMo=sims.Snowball.months-sims.Avalanche.months;
  // payoff order per current strategy
  const ord=debts.map((d,i)=>i).sort((a,b)=> strat==='Avalanche' ? (debts[b].apr||0)-(debts[a].apr||0) : debts[a].bal-debts[b].bal);
  const orderOf=i=>ord.indexOf(i)+1;
  const nextIdx=ord.find(i=>debts[i].bal>0);
  const next=debts[nextIdx];
  const nextMonths=cur.payoffMonth[nextIdx];
  // donut by type
  const typeMap={}; debts.forEach(d=>{ typeMap[d.type]=(typeMap[d.type]||0)+d.bal; });
  const segPal=[G,AM,BL,SL,PU,TEAL];
  const seg=Object.keys(typeMap).map((k,i)=>({label:k,value:typeMap[k],color:segPal[i%segPal.length],pct:Math.round(typeMap[k]/totalDebt*100)+'%'}));
  // progress (only when original amounts are known)
  const withOrig=debts.filter(d=>d.orig&&d.orig>d.bal&&d.type!=='Credit Card');
  const paidOff=withOrig.reduce((s,d)=>s+(d.orig-d.bal),0);
  const origSum=withOrig.reduce((s,d)=>s+d.orig,0);

  return (
    <div>
      <PageHead title="Debt Elimination Center" sub="Take control of your debt and become debt free faster."/>

      {missing.length>0 && (
        <div className="v6-banner cm-mb-24" style={{background:'#FBF3E8',border:'1px solid var(--gold-soft)',color:'#A9772A',fontWeight:700,fontSize:13}}>
          {missing.length} debt{missing.length>1?'s are':' is'} missing an APR or minimum payment ({missing.map(d=>d.name).join(', ')}). Import the card's PDF statement for exact figures — projections below are estimates.
        </div>
      )}

      <div className="cm-grid-4 cm-mb-24">
        {[
          { ic:<I.Wallet size={18}/>, c:G, l:'Total Debt', v:money(totalDebt), f:'Across '+debts.length+' account'+(debts.length>1?'s':'') },
          { ic:<I.ArrowUp size={18}/>, c:RD, l:'Total Interest ('+strat+')', v:cur.done?money(cur.totalInt):'—', f:cur.est?'estimated':'projected' },
          { ic:<I.Calendar size={18}/>, c:AM, l:'Debt Free Date ('+strat+')', v:cur.done?monthLabel(cur.months):'—', f:cur.done?(Math.floor(cur.months/12)+'y '+(cur.months%12)+'m'):'needs review', fc:G },
          { ic:<I.Clock size={18}/>, c:BL, l:'Monthly Payment', v:money(cur.minSum), f:cur.est?'incl. estimated minimums':'sum of minimums' },
        ].map((k,i)=>(
          <div className="cm-card cm-card-pad" key={i} style={{display:'flex',gap:14,alignItems:'center'}}>
            <Chip ic={k.ic} color={k.c} size={48} radius={14}/>
            <div style={{minWidth:0}}>
              <div style={{fontSize:12.5,fontWeight:700,color:'var(--ink-500)'}}>{k.l}</div>
              <div className="num" style={{fontSize:24,fontWeight:800,color:'var(--ink-900)',letterSpacing:'-.02em',margin:'2px 0'}}>{k.v}</div>
              <div style={{fontSize:12,color:k.fc||'var(--ink-400)',fontWeight:k.fc?700:500}}>{k.f}</div>
            </div>
          </div>
        ))}
      </div>

      <div className="v6-main-side">
        <div style={{display:'flex',flexDirection:'column',gap:20}}>
          <div className="cm-card cm-card-pad">
            <div className="v6-cardhead">
              <div className="v6-cardtitle" style={{display:'flex',alignItems:'center',gap:7}}>Payoff Strategy Comparison <I.Info size={15} style={{color:'var(--ink-400)'}}/></div>
            </div>
            <div style={{display:'grid',gridTemplateColumns:'240px 1fr',gap:24}}>
              <div>
                <StratOption active={strat==='Snowball'} onClick={()=>setStrat('Snowball')} name="Debt Snowball" badge={saveInt<=0?'Recommended':null}
                  date={sims.Snowball.done?monthLabel(sims.Snowball.months):'—'} interest={money(sims.Snowball.totalInt)} total={money(sims.Snowball.totalPaid)}/>
                <StratOption active={strat==='Avalanche'} onClick={()=>setStrat('Avalanche')} name="Debt Avalanche" badge={saveInt>0?'Recommended':null}
                  date={sims.Avalanche.done?monthLabel(sims.Avalanche.months):'—'} interest={money(sims.Avalanche.totalInt)} total={money(sims.Avalanche.totalPaid)}/>
                <StratOption active={strat==='Minimum'} onClick={()=>setStrat('Minimum')} name="Minimum Payments"
                  date={sims.Minimum.done?monthLabel(sims.Minimum.months):'30+ yrs'} interest={money(sims.Minimum.totalInt)} total={money(sims.Minimum.totalPaid)}/>
              </div>
              <div>
                <div style={{display:'flex',gap:18,justifyContent:'center',marginBottom:6,fontSize:11.5,fontWeight:700}}>
                  <span className="v6-dotlabel"><span className="v6-dot" style={{background:G}}/>Debt Snowball</span>
                  <span className="v6-dotlabel"><span className="v6-dot" style={{background:BL}}/>Debt Avalanche</span>
                  <span className="v6-dotlabel"><span className="v6-dot" style={{background:SL}}/>Minimum Payments</span>
                </div>
                <PayoffChart xLabels={xl} series={chart}/>
              </div>
            </div>
            {saveInt>0 && sims.Avalanche.done && (
            <div className="v6-banner" style={{marginTop:16,background:'var(--mint-50)',justifyContent:'space-between'}}>
              <span style={{display:'flex',alignItems:'center',gap:10,fontSize:13.5,fontWeight:700,color:'var(--green-600)'}}>
                <I.Check size={17}/> Avalanche pays you off {saveMo>0?saveMo+' month'+(saveMo>1?'s':'')+' sooner and ':''}saves {money(saveInt)} in interest vs Snowball.</span>
            </div>)}
          </div>

          <div className="cm-card cm-card-pad">
            <div className="v6-cardhead"><div className="v6-cardtitle">Your Debts</div></div>
            <div style={{overflowX:'auto'}}>
            <table className="cm-table" style={{minWidth:760}}>
              <thead><tr>
                <th>Account</th><th>Type</th><th className="right">Balance</th><th className="right">Interest Rate</th>
                <th className="right">Min. Payment</th><th>Strategy</th><th>Payoff Date</th></tr></thead>
              <tbody>
                {debts.map((d,i)=>(
                  <tr key={i}>
                    <td><div className="cm-cell-lead"><BrandIcon name={d.logo} size={36} radius={8}/>
                      <div><div className="cm-cell-primary">{d.name}</div>{d.last?<div className="cm-cell-sub num">{'\u2022\u2022\u2022\u2022 '+d.last}</div>:null}</div></div></td>
                    <td><span className="cm-pill" style={{background:tintFor(d.tc),color:d.tc}}>{d.type}</span></td>
                    <td style={{textAlign:'right'}}><span className="cm-cell-strong num">{money(d.bal)}</span></td>
                    <td style={{textAlign:'right'}}>{d.apr!=null?<span className="num" style={{fontWeight:700,color:'var(--ink-700)'}}>{d.apr.toFixed(2)}%</span>:<span className="cm-pill" style={{background:'#FBF3E8',color:'#A9772A',fontWeight:700,fontSize:11}}>needs review</span>}</td>
                    <td style={{textAlign:'right'}}>{d.min!=null?<span className="num" style={{fontWeight:700,color:'var(--ink-700)'}}>{money(d.min)}</span>:<span className="num" style={{color:'var(--ink-400)'}}>—</span>}</td>
                    <td><span style={{display:'inline-flex',alignItems:'center',gap:6,fontSize:12.5,fontWeight:700,color:'var(--green-600)'}}>{strat}
                      <span className="num" style={{width:20,height:20,borderRadius:999,background:'var(--mint-100)',display:'inline-flex',alignItems:'center',justifyContent:'center',fontSize:11}}>{orderOf(i)}</span></span></td>
                    <td><span className="num" style={{color:'var(--ink-700)',fontWeight:600}}>{cur.payoffMonth[i]!=null?monthLabel(cur.payoffMonth[i]):'—'}</span></td>
                  </tr>
                ))}
              </tbody>
            </table>
            </div>
          </div>
        </div>

        <div style={{display:'flex',flexDirection:'column',gap:20}}>
          <div className="cm-card cm-card-pad">
            <div className="v6-cardtitle" style={{marginBottom:16}}>Debt Overview</div>
            <div style={{display:'flex',alignItems:'center',gap:16}}>
              <DonutChart size={130} thickness={20} segments={seg} center={{value:money(totalDebt),label:'Total Debt'}}/>
              <div style={{flex:1,minWidth:0}}>
                {seg.map((s,i)=>(
                  <div key={i} style={{display:'flex',alignItems:'center',gap:8,padding:'5px 0',fontSize:12.5}}>
                    <span className="v6-dot" style={{background:s.color}}/>
                    <span style={{flex:1,color:'var(--ink-700)',fontWeight:600}}>{s.label}</span>
                    <span className="num" style={{fontWeight:700,color:'var(--ink-900)'}}>{money(s.value)}</span>
                    <span className="num" style={{color:'var(--ink-400)',width:30,textAlign:'right'}}>{s.pct}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {origSum>0 && (
          <div className="cm-card cm-card-pad">
            <div className="v6-cardtitle" style={{marginBottom:16}}>Overall Progress</div>
            <div style={{display:'flex',alignItems:'center',gap:18}}>
              <Ring pct={Math.round(paidOff/origSum*100)} size={88} stroke={9} color={G}/>
              <div>
                <div className="num" style={{fontSize:15,fontWeight:800,color:'var(--ink-900)'}}>{money(paidOff)} <span style={{fontWeight:600,color:'var(--ink-500)',fontSize:13}}>paid off</span></div>
                <div className="num" style={{fontSize:13,color:'var(--ink-500)',marginTop:3}}>{money(origSum-paidOff)} remaining on tracked loans</div>
              </div>
            </div>
          </div>)}

          {next && (
          <div className="cm-card cm-card-pad">
            <div className="v6-cardtitle" style={{marginBottom:14}}>Next Payoff</div>
            <div style={{display:'flex',gap:14,alignItems:'center'}}>
              <BrandIcon name={next.logo} size={42} radius={10}/>
              <div style={{flex:1,minWidth:0}}>
                <div style={{fontWeight:800,fontSize:13.5,color:'var(--ink-900)'}}>{next.name}</div>
                <div style={{display:'flex',justifyContent:'space-between',marginTop:5,fontSize:12}}>
                  <span style={{color:'var(--ink-500)'}}>Balance <b className="num" style={{color:'var(--ink-900)'}}>{money(next.bal)}</b></span>
                  <span style={{color:'var(--ink-500)'}}>Payoff in <b style={{color:G}}>{nextMonths!=null?(nextMonths+' month'+(nextMonths>1?'s':'')):'—'}</b></span></div>
              </div>
            </div>
          </div>)}

          <div className="cm-card cm-card-pad">
            <div className="v6-cardtitle" style={{marginBottom:14}}>Tips to Pay Off Debt Faster</div>
            {[
              { ic:<I.Check size={16}/>, c:G, t:'Make extra payments', s:'Anything above the minimums goes straight to principal and shortens the payoff.' },
              { ic:<I.Bolt size={16}/>, c:AM, t:'Use windfalls', s:'Put tax refunds, bonuses or gifts directly towards your highest-priority debt.' },
              { ic:<I.Alert size={16}/>, c:RD, t:'Avoid new debt', s:'Focus on paying off existing balances before taking on new credit.' },
            ].map((t,i)=>(
              <div key={i} style={{display:'flex',gap:11,marginBottom:13}}>
                <Chip ic={t.ic} color={t.c} size={32} radius={9}/>
                <div><div style={{fontWeight:700,fontSize:13,color:'var(--ink-900)'}}>{t.t}</div>
                  <div style={{fontSize:12,color:'var(--ink-500)',marginTop:2}}>{t.s}</div></div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {cur.done && (
      <div className="v6-banner cm-mt-24" style={{justifyContent:'space-between',background:'var(--mint-50)'}}>
        <div style={{display:'flex',alignItems:'center',gap:14}}>
          <Chip ic={<I.Spark size={18}/>} color={G} size={42} radius={12}/>
          <div><div style={{fontWeight:800,fontSize:14.5,color:'var(--ink-900)'}}>Stay motivated! On the {strat} plan you're debt free by {monthLabel(cur.months)}.</div>
            <div style={{fontSize:13,color:'var(--ink-500)',marginTop:2}}>Keep going — financial freedom is closer than you think.</div></div>
        </div>
      </div>)}
    </div>
  );
}
window.PageDebtCenter = PageDebtCenter;
})();
