/* Clear Mint — V6 Opportunities Center. window.PageOpportunities */
(function(){
const I = window.CMIcon;
const { CMC, tintFor, DonutChart, Spark, Ring, Chip, PageHead } = window;
const { G, PU, AM, BL, SL, RD, TEAL, PINK, INDIGO } = CMC;
const money = window.cmMoney;

const LVL={High:G,Medium:AM,Low:SL,Easy:G};
function Dot({lvl}){ const c=LVL[lvl]||SL; return <span className="v6-dotlabel" style={{color:c}}><span className="v6-dot" style={{background:c}}/>{lvl}</span>; }

function SavingsLine({ pts, labels, height=200 }){
  const W=380,H=height,P={l:34,r:18,t:30,b:26};
  const max=Math.max(...pts);
  const X=i=>P.l+(i/(pts.length-1))*(W-P.l-P.r);
  const Y=v=>P.t+(1-v/max)*(H-P.t-P.b);
  const line=pts.map((v,i)=>`${i?'L':'M'}${X(i)},${Y(v)}`).join(' ');
  const area=`${line} L${X(pts.length-1)},${H-P.b} L${X(0)},${H-P.b} Z`;
  return (
    <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{display:'block'}}>
      <defs><linearGradient id="svg-grad" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor={G} stopOpacity=".16"/><stop offset="100%" stopColor={G} stopOpacity="0"/></linearGradient></defs>
      {[0,1,2,3,4].map(i=>{const y=P.t+i*((H-P.t-P.b)/4);return <line key={i} x1={P.l} y1={y} x2={W-P.r} y2={y} stroke="var(--line)" strokeWidth="1"/>;})}
      <path d={area} fill="url(#svg-grad)"/>
      <path d={line} fill="none" stroke={G} strokeWidth="2.4" strokeLinejoin="round"/>
      {pts.map((v,i)=>(<g key={i}><circle cx={X(i)} cy={Y(v)} r="3.5" fill="#fff" stroke={G} strokeWidth="2"/>
        <text x={X(i)} y={Y(v)-9} textAnchor="middle" fontSize="10" fontWeight="700" fill="var(--ink-700)" className="num">${(v).toFixed(1)}k</text></g>))}
      {labels.map((lb,i)=><text key={i} x={X(i)} y={H-7} textAnchor="middle" fontSize="10" fill="var(--ink-400)">{lb}</text>)}
    </svg>
  );
}

// Monthly cost of a subscription, honouring its billing cycle.
function subMonthly(s){
  const amt = +s.monthly || +s.price || +s.amount || 0;
  const cyc = String(s.cycle||'monthly').toLowerCase();
  if (/year|annual/.test(cyc)) return amt/12;
  if (/week/.test(cyc)) return amt*52/12;
  if (/quarter/.test(cyc)) return amt/3;
  return amt;
}
// Build opportunities from REAL data only. `saving:true` items carry a defensible $ figure (interest
// you're actually paying, subscription spend); `saving:false` items are improvements with no invented
// dollar amount. Nothing is fabricated \u2014 empty data yields an empty list.
function buildOpps(CM){
  const cards=CM.S.cards||[], liab=CM.S.liabilities||[], subs=CM.S.subscriptions||[], goals=CM.S.goals||[];
  const opps=[];
  cards.forEach(c=>{
    const bal=+c.balance||0, apr=+(c.apr||c.rate||c.interestRate||0);
    if(bal>0 && apr>0){ const yr=Math.round(bal*apr/100);
      opps.push({ ic:<I.Card size={18}/>, c:PU, name:`Reduce interest on ${c.name||c.issuer||'your card'}`, sub:`${apr}% APR on ${money(bal)} balance`, detail:`Paying this down saves about ${money(yr)}/yr in interest`, cat:'Credit Cards', catc:PU, yr, mo:Math.round(yr/12), impact:yr>=600?'High':yr>=200?'Medium':'Low', diff:'Medium', saving:true }); }
  });
  liab.forEach(l=>{
    const bal=+l.balance||0, apr=+(l.apr||l.rate||0), isMort=/mortgage/i.test((l.type||'')+' '+(l.name||''));
    if(bal>0 && apr>0 && !isMort){ const yr=Math.round(bal*apr/100);
      opps.push({ ic:<I.Reports size={18}/>, c:AM, name:`Pay down ${l.name||l.type||'a loan'}`, sub:`${apr}% on ${money(bal)}`, detail:`About ${money(yr)}/yr in interest \u2014 clearing it sooner saves that`, cat:'Loans', catc:AM, yr, mo:Math.round(yr/12), impact:yr>=600?'High':yr>=200?'Medium':'Low', diff:'Medium', saving:true }); }
    else if(bal>0 && apr>0 && isMort){
      opps.push({ ic:<I.House size={18}/>, c:G, name:'Review your mortgage rate', sub:`${apr}% on ${money(bal)}`, detail:'Compare lenders at renewal \u2014 even 0.5% lower is real money', cat:'Mortgage', catc:G, yr:null, mo:null, impact:'Medium', diff:'Medium', saving:false }); }
  });
  if(subs.length){ const moTot=subs.reduce((s,x)=>s+subMonthly(x),0), yr=Math.round(moTot*12);
    if(yr>0) opps.push({ ic:<I.Subscriptions size={18}/>, c:AM, name:`Review ${subs.length} subscription${subs.length>1?'s':''}`, sub:`${money(Math.round(moTot))}/mo across ${subs.length}`, detail:'Cancel any you no longer use to claw this back', cat:'Subscriptions', catc:AM, yr, mo:Math.round(moTot), impact:yr>=600?'High':yr>=200?'Medium':'Low', diff:'Easy', saving:true }); }
  const limit=cards.reduce((s,c)=>s+(+c.limit||0),0), used=cards.reduce((s,c)=>s+(+c.balance||0),0), util=limit?used/limit*100:0;
  if(util>=30) opps.push({ ic:<I.Bars size={18}/>, c:RD, name:'Lower your credit utilization', sub:`Currently ${util.toFixed(0)}% \u2014 aim under 30%`, detail:'Paying cards below 30% of their limit lifts your credit score', cat:'Credit', catc:RD, yr:null, mo:null, impact:util>=50?'High':'Medium', diff:'Medium', saving:false });
  const cf=CM.last6CashFlow?CM.last6CashFlow():[], last=cf[cf.length-1]||{inc:0,exp:0}, surplus=Math.round((last.inc||0)-(last.exp||0));
  if(surplus>0) opps.push({ ic:<I.Grow size={18}/>, c:TEAL, name:'Put your surplus to work', sub:`${money(surplus)}/mo not yet invested`, detail:'Automating it into savings or investments compounds over time', cat:'Investing', catc:TEAL, yr:null, mo:null, impact:surplus>=500?'High':'Medium', diff:'Easy', saving:false });
  if(!goals.some(g=>/emergency/i.test(g.name||''))) opps.push({ ic:<I.Shield size={18}/>, c:BL, name:'Start an emergency fund', sub:'No emergency fund goal yet', detail:'Aim for 3\u20136 months of expenses', cat:'Safety', catc:BL, yr:null, mo:null, impact:'High', diff:'Medium', saving:false });
  return opps;
}

function PageOpportunities(){
  const CM = window.useStore ? window.useStore() : window.CM;
  const [tab,setTab]=React.useState('All');
  const all = buildOpps(CM);
  const savingOpps = all.filter(o=>o.saving && o.yr>0);
  const totalYr = savingOpps.reduce((s,o)=>s+o.yr,0);
  const highCount = all.filter(o=>o.impact==='High').length;
  const tabs = [['All',all],['High Impact',all.filter(o=>o.impact==='High')],['Quick Wins',all.filter(o=>o.diff==='Easy')]];
  const shown = (tabs.find(t=>t[0]===tab)||tabs[0])[1];
  // savings breakdown by category (dollar-backed opps only)
  const segMap={}; savingOpps.forEach(o=>{ segMap[o.cat]=(segMap[o.cat]||0)+o.yr; });
  const segCols={ 'Credit Cards':PU, 'Loans':AM, 'Subscriptions':RD, 'Mortgage':G, 'Investing':TEAL, 'Credit':RD, 'Safety':BL };
  const seg=Object.keys(segMap).map(k=>({ label:k, value:segMap[k], color:segCols[k]||SL, pct:totalYr?Math.round(segMap[k]/totalYr*100)+'%':'0%' }));
  // data-presence coverage (honest: how much of your picture Mint can see)
  const present=[(CM.S.bankTx||[]).length,(CM.S.cards||[]).length,(CM.S.subscriptions||[]).length,(CM.S.investments||[]).length,(CM.S.goals||[]).length].filter(n=>n>0).length;
  const coverage=Math.round(present/5*100);
  const top = savingOpps.slice().sort((a,b)=>b.yr-a.yr)[0];

  if(!all.length){
    return (
      <div>
        <PageHead title="Opportunities Center" sub="Mint scans your accounts to find ways to save. Add your cards, loans and subscriptions to get started."/>
        <div className="cm-card cm-card-pad" style={{textAlign:'center',padding:'56px 20px'}}>
          <div style={{color:G,marginBottom:14,display:'flex',justifyContent:'center'}}><I.Spark size={38}/></div>
          <div className="v6-cardtitle" style={{fontSize:17}}>No opportunities yet</div>
          <div style={{fontSize:13,color:'var(--ink-500)',marginTop:6,maxWidth:440,marginInline:'auto',lineHeight:1.5}}>Once you add credit cards, loans or subscriptions, Mint will surface real ways to save \u2014 interest you can cut, spend you can trim, and habits worth automating.</div>
        </div>
      </div>
    );
  }

  return (
    <div>
      <PageHead title="Opportunities Center" sub="Mint scans your real accounts to find ways to save — interest to cut, spend to trim, habits worth automating."
        actions={<button className="v6-btn"><I.Repeat size={15}/>Refresh Opportunities</button>}/>

      {/* KPI row */}
      <div className="v6-grid-5 cm-mb-24">
        <div className="cm-card cm-card-pad" style={{display:'flex',gap:13,alignItems:'flex-start'}}>
          <Chip ic={<I.Wallet size={18}/>} color={G} size={44} radius={13}/>
          <div style={{flex:1,minWidth:0}}><div style={{fontSize:11.5,fontWeight:700,color:'var(--ink-500)'}}>Total Potential Annual Savings</div>
            <div className="num" style={{fontSize:24,fontWeight:800,color:G,margin:'2px 0'}}>{money(totalYr)}</div>
            <div style={{fontSize:11.5,color:'var(--ink-400)'}}>{totalYr>0?`About ${money(Math.round(totalYr/12))} / month`:'Add cards or loans to surface savings'}</div></div>
        </div>
        {[
          { ic:<I.Bars size={18}/>, c:G, l:'Opportunities Found', v:String(all.length), f:`${seg.length} dollar-saving categor${seg.length===1?'y':'ies'}` },
          { ic:<I.User size={18}/>, c:AM, l:'High Impact', v:String(highCount), f:highCount?'Worth tackling first':'None flagged high' },
          { ic:<I.Calendar size={18}/>, c:BL, l:'Last Scan', v:'Today', f:CM.FD?CM.FD(new Date()):'' },
        ].map((k,i)=>(
          <div className="cm-card cm-card-pad" key={i} style={{display:'flex',gap:13,alignItems:'flex-start'}}>
            <Chip ic={k.ic} color={k.c} size={44} radius={13}/>
            <div style={{minWidth:0}}><div style={{fontSize:11.5,fontWeight:700,color:'var(--ink-500)'}}>{k.l}</div>
              <div className="num" style={{fontSize:24,fontWeight:800,color:'var(--ink-900)',margin:'2px 0'}}>{k.v}</div>
              <div style={{fontSize:11.5,color:'var(--ink-400)'}}>{k.f}</div></div>
          </div>
        ))}
        <div className="cm-card cm-card-pad" style={{display:'flex',gap:13,alignItems:'center'}}>
          <div style={{minWidth:0,flex:1}}><div style={{fontSize:11.5,fontWeight:700,color:'var(--ink-500)'}}>Coverage</div>
            <div style={{fontSize:12,color:'var(--ink-500)',marginTop:4,lineHeight:1.4}}>Mint can see {coverage}% of your financial picture</div></div>
          <Ring pct={coverage} size={62} stroke={7} color={G}/>
        </div>
      </div>

      <div className="v6-main-side">
        {/* LEFT */}
        <div style={{display:'flex',flexDirection:'column',gap:20}}>
          <div className="cm-card cm-card-pad">
            <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',borderBottom:'1px solid var(--line)',marginBottom:4,paddingBottom:0}}>
              <div className="v6-tabs" style={{borderBottom:'none',marginBottom:0}}>
                {tabs.map(t=>(
                  <button key={t[0]} className={`v6-tab ${t[0]===tab?'active':''}`} onClick={()=>setTab(t[0])}>{t[0]} ({t[1].length})</button>))}
              </div>
            </div>
            <div style={{overflowX:'auto'}}>
            <table className="cm-table" style={{minWidth:720}}>
              <thead><tr><th>Opportunity</th><th>Category</th><th className="right">Potential Savings</th><th>Impact</th><th>Difficulty</th></tr></thead>
              <tbody>
                {shown.map((o,i)=>(
                  <tr key={i}>
                    <td><div className="cm-cell-lead"><Chip ic={o.ic} color={o.c} size={40} radius={11}/>
                      <div><div className="cm-cell-primary">{o.name}</div><div className="cm-cell-sub">{o.sub}</div>
                        <div style={{fontSize:11.5,color:o.saving?G:'var(--ink-400)',fontWeight:700,marginTop:3}}>{o.detail}</div></div></div></td>
                    <td><span className="cm-pill" style={{background:tintFor(o.catc),color:o.catc}}>{o.cat}</span></td>
                    <td style={{textAlign:'right'}}>{o.saving && o.yr>0
                      ? <><div className="num" style={{fontWeight:800,color:'var(--ink-900)'}}>{money(o.yr)} / year</div>
                          <div className="num" style={{fontSize:12,color:'var(--ink-400)'}}>{o.mo?money(o.mo)+' / month':''}</div></>
                      : <span style={{fontSize:12,color:'var(--ink-400)',fontWeight:600}}>Improvement</span>}</td>
                    <td><Dot lvl={o.impact}/></td>
                    <td><Dot lvl={o.diff}/></td>
                  </tr>
                ))}
              </tbody>
            </table>
            </div>
            <div style={{display:'flex',alignItems:'center',marginTop:14}}>
              <span style={{fontSize:12.5,color:'var(--ink-400)'}}>Showing {shown.length} of {all.length} opportunit{all.length===1?'y':'ies'}</span>
            </div>
          </div>

          <div className="v6-banner" style={{justifyContent:'space-between'}}>
            <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,color:'var(--ink-900)'}}>Don't see an opportunity you're looking for?</div>
                <div style={{fontSize:12.5,color:'var(--ink-500)',marginTop:2}}>Tell us what you want to improve and we'll keep an eye out for opportunities.</div></div>
            </div>
            <button className="v6-btn">Customize Preferences <I.ChevR size={14}/></button>
          </div>
        </div>

        {/* RIGHT */}
        <div style={{display:'flex',flexDirection:'column',gap:20}}>
          {seg.length>0 && <div className="cm-card cm-card-pad">
            <div className="v6-cardtitle" style={{marginBottom:16}}>Potential Savings Breakdown</div>
            <div style={{display:'flex',alignItems:'center',gap:14}}>
              <DonutChart size={120} thickness={18} segments={seg} center={{value:money(totalYr),label:'Per Year'}}/>
              <div style={{flex:1,minWidth:0}}>
                {seg.map((s,i)=>(
                  <div key={i} style={{display:'flex',alignItems:'center',gap:7,padding:'3px 0',fontSize:11.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:28,textAlign:'right'}}>{s.pct}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>}

          {totalYr>0 && <div className="cm-card cm-card-pad">
            <div className="v6-cardhead"><div className="v6-cardtitle" style={{display:'flex',alignItems:'center',gap:6}}>Savings Over Time <I.Info size={14} style={{color:'var(--ink-400)'}}/></div></div>
            <div style={{fontSize:12,color:'var(--ink-500)'}}>If you act on every dollar-saving opportunity</div>
            <div className="num" style={{fontSize:24,fontWeight:800,color:G,margin:'2px 0 6px'}}>{money(totalYr*5)} <span style={{fontSize:12,fontWeight:600,color:'var(--ink-500)'}}>over 5 years</span></div>
            <SavingsLine pts={[1,2,3,4,5].map(y=>totalYr*y/1000)} labels={['Year 1','Year 2','Year 3','Year 4','Year 5']}/>
            <div style={{fontSize:11.5,color:'var(--ink-400)',marginTop:6}}>Cumulative, assuming the same savings each year</div>
          </div>}

          {top && <div className="cm-card cm-card-pad">
            <div className="v6-cardtitle">Your biggest win</div>
            <div style={{fontSize:12.5,color:'var(--ink-500)',margin:'4px 0 14px'}}>The single opportunity worth the most right now</div>
            <div style={{display:'flex',gap:12,alignItems:'flex-start',marginBottom:12}}>
              <Chip ic={top.ic} color={top.c} size={42} radius={12}/>
              <div style={{flex:1,minWidth:0}}><div style={{fontWeight:800,fontSize:14,color:'var(--ink-900)'}}>{top.name}</div>
                <div style={{fontSize:12.5,color:'var(--ink-500)',marginTop:2}}>{top.detail}</div></div>
            </div>
            <div style={{background:'var(--mint-50)',border:'1px solid var(--line)',borderRadius:12,padding:'12px 14px',textAlign:'center'}}>
              <div style={{fontSize:11.5,fontWeight:700,color:'var(--ink-500)'}}>Potential Savings</div>
              <div className="num" style={{fontSize:20,fontWeight:800,color:G,marginTop:2}}>{money(top.yr)} <span style={{fontSize:12,fontWeight:600,color:'var(--ink-500)'}}>/ year</span></div>
              {top.mo?<div className="num" style={{fontSize:12.5,color:G,fontWeight:700}}>{money(top.mo)} / month</div>:null}
            </div>
          </div>}
        </div>
      </div>

      <div className="v6-banner cm-mt-24" style={{justifyContent:'space-between'}}>
        <div style={{display:'flex',alignItems:'center',gap:12}}>
          <I.Shield size={20} style={{color:G}}/>
          <span style={{fontSize:13,color:'var(--ink-600)',fontWeight:600}}>Every opportunity here is computed from your own data — nothing is invented. Your data is encrypted and never shared.</span>
        </div>
      </div>
    </div>
  );
}
window.PageOpportunities = PageOpportunities;
})();
