/* Clear Mint — V6 AI Assistant (AI Command Center) */
(function(){
const { ChartCard, DonutChart, TrendChart, Legend, MetricCard, 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;

const USER = 'Alex';

/* exec KPI tile (6-up, sparkline) */
function Exec({ ic, color, label, value, delta, dir='pos', data, feat, gauge }) {
  return (
    <div className={`an-exectile ${feat?'feat':''}`}>
      <div className="et-head">
        <span className="et-ic" style={feat?null:{background:tint(color),color}}>{ic}</span>
        <span className="et-label">{label}</span>
      </div>
      {gauge ? <div style={{display:'flex',justifyContent:'center',marginTop:2}}>{gauge}</div> : <>
        <div className="et-val">{value}</div>
        {delta && <div className="et-delta" style={{color:dir==='neg'?RD:G}}>
          {dir==='neg'?<I.ArrowDown size={13}/>:<I.ArrowUp size={13}/>}{delta}
          <span className="mut">vs last month</span>
        </div>}
        {data && <div className="et-spark"><Spark data={data} color={dir==='neg'?RD:G}/></div>}
      </>}
    </div>
  );
}

/* ---- Chat ---- */
const CANNED = {
  'Analyze my spending':"You spent $7,430 this month — 4.2% less than last. Housing (35.7%) and Transportation (16.3%) lead. Dining is down 12%. Want me to break down any category?",
  'Improve my credit score':"Your score is 742 (Very Good). Two quick wins: keep utilization under 30% on your Visa (now 34%) and avoid new hard inquiries for 90 days. That could add ~18 points.",
  'Create a savings plan':"Based on $3,420/mo surplus I'd route $1,000 to your Emergency Fund (done in 4 months), $1,200 to retirement, and $1,220 to the House Down Payment goal. Shall I set it up?",
  'Plan for retirement':"At your current $1,200/mo pace you're on track for $1.0M by 2037. Bumping contributions by $250/mo reaches it 2 years sooner. Want a side-by-side projection?",
  'Reduce my debt':"You carry $18,300 across 2 balances. The avalanche method (highest APR first) clears it in 19 months and saves $640 in interest vs. minimums. Want the payoff schedule?",
  'Answer a question':"Of course — ask me anything about your money: spending, net worth, credit, investments, or whether you can afford something. Try \u201cCan I afford a $500,000 house?\u201d",
};
const SUGGEST = Object.keys(CANNED);

function Chat() {
  const CM = window.useStore ? window.useStore() : window.CM;
  const M0 = CM.M0;
  const userName = (CM.S.currentUser && (CM.S.currentUser.name || '').trim().split(/\s+/)[0]) || 'there';
  const cf6 = CM.last6CashFlow();
  const lastCF = cf6[cf6.length-1] || { inc:0, exp:0 };
  const surplus = Math.round(lastCF.inc - lastCF.exp);
  const sp = CM.spendingByCategory(8, true);
  const top = sp.items.slice(0,2);
  const cards = CM.S.cards||[];
  const climit = cards.reduce((s,c)=>s+(+c.limit||0),0);
  const cused = cards.reduce((s,c)=>s+(+c.balance||0),0);
  const util = climit ? cused/climit*100 : 0;
  const creditScore = Math.max(560, Math.min(850, Math.round(760 - util*1.6 + (util<10?15:0))));
  const band = creditScore>=800?'Exceptional':creditScore>=740?'Very Good':creditScore>=670?'Good':'Fair';
  const consumerDebt = (CM.S.liabilities||[]).filter(l=>!/mortgage/i.test(l.type||'')).reduce((s,l)=>s+(+l.balance||0),0) + cused;
  const emFund = (CM.S.goals||[]).find(g=>/emergency/i.test(g.name||''));
  const emMonths = emFund ? Math.max(1, Math.round((emFund.target-emFund.saved)/Math.max(1,surplus*0.4))) : null;
  const CANNED = {
    'Analyze my spending': `You spent ${M0(sp.total)} this month.${top[0]?` ${top[0].label} (${top[0].pct}%)`:''}${top[1]?` and ${top[1].label} (${top[1].pct}%)`:''} lead your spending. Want me to break down any category?`,
    'Improve my credit score': `Your modelled score is ${creditScore} (${band}). Utilization is a healthy ${util.toFixed(0)}% — keeping it under 30% and avoiding new hard inquiries for 90 days protects it. Want the details?`,
    'Create a savings plan': `Based on a ${M0(Math.max(0,surplus))}/mo surplus I'd route part to your Emergency Fund${emMonths?` (about ${emMonths} months to finish)`:''}, some to retirement, and the rest to your House Down Payment goal. Shall I set it up?`,
    'Plan for retirement': `Your investments are worth ${M0(CM.calcInvestValue())} today. Steady monthly contributions plus growth keep you on track — adding $250/mo gets you there sooner. Want a side-by-side projection?`,
    'Reduce my debt': `You carry ${M0(consumerDebt)} in non-mortgage balances. The avalanche method (highest APR first) clears it fastest and saves the most interest vs. minimums. Want the payoff schedule?`,
    'Answer a question': "Of course — ask me anything about your money: spending, net worth, credit, investments, or whether you can afford something. Try \u201cCan I afford a $500,000 house?\u201d",
  };
  const SUGGEST = Object.keys(CANNED);
  const [msgs, setMsgs] = React.useState([
    { who:'bot', text:`Hello ${userName}! I\u2019m Mint, your AI financial partner. Here are a few things I can help with \u2014 or just ask me anything.`, stamp:'10:30 AM' },
  ]);
  const [typing, setTyping] = React.useState(false);
  const [val, setVal] = React.useState('');
  const scroller = React.useRef(null);
  React.useEffect(()=>{ if(scroller.current) scroller.current.scrollTop = scroller.current.scrollHeight; },[msgs,typing]);
  const fallback = (q) => CANNED[q] || "Great question. Looking at your accounts, the short answer is: you're in good shape. I can pull the detailed numbers and a step-by-step plan whenever you're ready.";
  const reply = (q) => {
    setTyping(true);
    // Real AI via the router; falls back to built-in answers if the AI is unreachable. The financial
    // figures go in the SYSTEM prompt as *background* (not glued to the user's message), and the prompt
    // tells Mint to answer ONLY what was asked — so "hello" gets a greeting, not an unprompted analysis.
    const ctx = `Net worth ${M0(CM.netWorth())}; monthly surplus ${M0(Math.max(0,surplus))}; this-month spending ${M0(sp.total)}`
      + `${top[0]?` (top category ${top[0].label} ${top[0].pct}%)`:''}; modelled credit score ${creditScore} (${band}); `
      + `card utilization ${util.toFixed(0)}%; non-mortgage debt ${M0(consumerDebt)}; investments ${M0(CM.calcInvestValue())}.`;
    const guide = `\n\nABOUT CLEAR MINT (use this to explain the app, say where to find things, and suggest features):\n`
      + `Main areas in the left sidebar:\n`
      + `• Dashboard — your financial overview.\n`
      + `• Banking — accounts, bank statements, reconciliation, credit cards & debts.\n`
      + `• Earnings & Bills — income sources, bills/expenses and every transaction (add one with the header "Add" button or here).\n`
      + `• Cash Flow — money in vs out over time. Calendar — your finances by date. Subscriptions — recurring charges.\n`
      + `• Budget & Planner — set and track budgets. Wealth — net worth, assets, liabilities, Goals and Investments (Premium).\n`
      + `• Insurance — track policies. Financial Health — your score & trends. Roadmap & Opportunities — plans and ways to save.\n`
      + `• Reports & Email Center — generate reports and automated summaries. Settings — your account, plus Security (auto sign-out), notifications and preferences.\n`
      + `• Premium-only: AI Assistant (me), Bank Connect (securely link banks), Financial Outlook (forecasting), Analytics, Statement Reader, and the Family Wealth Hub (Family Vault, Members, Estate).\n`
      + `Plans: Essentials is a one-time purchase covering the basics (up to 2 accounts/cards); Premium (monthly or annual) unlocks AI, bank connections, investments, forecasting, statements, the family vault and unlimited items — an Upgrade prompt appears on Premium features.\n`
      + `Quick tips: add accounts or import statements to fill your dashboard; set goals in Wealth → Goals; build a budget in Budget & Planner; check Financial Health for your score; change auto sign-out in Settings → Security.`;
    const system = `You are Mint, Clear Mint's friendly Canadian personal-finance assistant AND in-app guide for ${userName}. `
      + `Answer what the user asks in plain language and a few short sentences; for "how do I…/where is…" questions, give a short numbered list and name the exact area to go to. If they greet you or make small talk, reply warmly and briefly and do NOT volunteer financial analysis. `
      + `You help with two things: (1) their money — only use the figures in CONTEXT when the question is about their finances, never invent numbers beyond it, and say so plainly if you lack the data; (2) using Clear Mint — explain how it works, where features live, and suggest one relevant feature, using the ABOUT CLEAR MINT guide below. Point to areas by their exact name.`
      + guide
      + `\n\nCONTEXT (the user's finances — reference only when relevant):\n${ctx}`;
    let done=false; const finish=(text,source)=>{ if(done) return; done=true; setTyping(false); setMsgs(m=>[...m,{who:'bot',text,stamp:'now',source:source}]); };
    const h={'Content-Type':'application/json'}; const tok=window.cmAuthToken?window.cmAuthToken():''; if(tok) h.Authorization='Bearer '+tok;
    fetch('/api/ai/route',{method:'POST',headers:h,body:JSON.stringify({taskClass:'financial',question:q,system:system})})
      .then(r=>r.json()).then(d=>finish(d&&d.ok&&d.text ? d.text : fallback(q), d&&d.ok ? (d.provider||'ai') : 'offline'))
      .catch(()=>finish(fallback(q),'offline'));
  };
  const send = (q) => {
    const text = (q||val).trim(); if(!text) return;
    setMsgs(m=>[...m,{who:'user',text,stamp:'now'}]); setVal(''); reply(text);
  };
  return (
    <div className="cm-chat">
      <div className="cm-chat-scroll" ref={scroller}>
        {msgs.map((m,i)=>(
          <div className={`cm-msg ${m.who}`} key={i}>
            {m.who==='bot' && <Robot pose="r1-10" size={38} float={false}/>}
            <div>
              <div className="cm-bubble">{m.text}</div>
              <div className="stamp" style={{textAlign:m.who==='user'?'right':'left'}}>{m.stamp}{m.who==='bot' && m.source && <span style={{marginLeft:6,fontWeight:700,color:m.source==='groq'?'#C8742E':m.source==='cerebras'?'#5B53C7':m.source==='gemini'?'var(--green-600)':m.source==='cloudflare'?'#B5740F':'var(--ink-400)'}}>· {m.source==='groq'?'via Groq':m.source==='cerebras'?'via Cerebras':m.source==='gemini'?'via Gemini':m.source==='cloudflare'?'via Cloudflare':m.source==='openrouter'?'via OpenRouter':m.source==='offline'?'built-in':'via AI'}</span>}</div>
            </div>
          </div>
        ))}
        {typing && <div className="cm-msg bot"><Robot pose="r1-10" size={38} float={false}/>
          <div className="cm-bubble"><span className="cm-typing"><i/><i/><i/></span></div></div>}
      </div>
      <div className="cm-suggest">
        {SUGGEST.map(s=><button key={s} onClick={()=>send(s)}>{s}</button>)}
      </div>
      <div className="cm-composer">
        <input placeholder="Ask me anything about your finances…" value={val}
          onChange={e=>setVal(e.target.value)} onKeyDown={e=>{ if(e.key==='Enter') send(); }}/>
        <span className="mic"><I.Spark size={18}/></span>
        <button className="send" onClick={()=>send()}><I.Transfer size={18}/></button>
      </div>
      <div className="t-caption" style={{marginTop:8,textAlign:'center'}}>AI responses are generated. Always review important financial decisions.</div>
    </div>
  );
}

/* ---- Scenario planner ---- */
const SCN = [
  { id:'house', name:'New House', ic:<I.House size={22}/>, head:'Buying a $500,000 home',
    outs:[['Monthly payment','$2,840'],['Down payment','$100,000'],['Affordable?','Yes ✓'],['Net worth in 5y','+$96,000']] },
  { id:'car', name:'New Vehicle', ic:<I.Car size={22}/>, head:'Financing a $45,000 vehicle',
    outs:[['Monthly payment','$760'],['Total interest','$4,120'],['Affordable?','Yes ✓'],['Goal impact','−3 months']] },
  { id:'jobloss', name:'Job Loss', ic:<I.Briefcase size={22}/>, head:'If income paused tomorrow',
    outs:[['Runway','6.2 months'],['Essential burn','$4,180/mo'],['Status','Comfortable'],['Action','Trim 2 subs']] },
  { id:'promo', name:'Promotion', ic:<I.Grow size={22}/>, head:'A 15% raise ($14k/yr)',
    outs:[['Extra take-home','$840/mo'],['Retire by','58'],['Savings rate','38%'],['Net worth in 5y','+$142k']] },
  { id:'retire', name:'Retirement', ic:<I.Goals size={22}/>, head:'Retiring at 60',
    outs:[['Nest egg needed','$1.4M'],['On track','82%'],['Gap','$210/mo'],['Confidence','High']] },
  { id:'child', name:'New Child', ic:<I.Heart size={22}/>, head:'Welcoming a new child',
    outs:[['Added cost','$1,100/mo'],['RESP start','$200/mo'],['Affordable?','Yes ✓'],['Buffer','4.1 months']] },
];
function Scenarios() {
  const [act, setAct] = React.useState('house');
  const s = SCN.find(x=>x.id===act);
  return (
    <ChartCard title="AI Scenario Planner" action={<span className="t-caption">\u201cWhat if\u201d simulations</span>}>
      <div className="cm-scenarios" style={{marginBottom:18}}>
        {SCN.map(x=>(
          <div key={x.id} className={`cm-scn ${x.id===act?'active':''}`} onClick={()=>setAct(x.id)}>
            <div className="s-ic">{x.ic}</div><div className="s-name">{x.name}</div>
          </div>
        ))}
      </div>
      <div className="cm-card-dark" style={{padding:'20px 22px',display:'flex',gap:18,alignItems:'center',flexWrap:'wrap'}}>
        <Robot pose="r2-3" size={92} float="float2" style={{flex:'0 0 92px'}}/>
        <div style={{flex:1,minWidth:200}}>
          <div className="t-caption" style={{color:'var(--gold)',fontWeight:800,letterSpacing:'.08em',textTransform:'uppercase'}}>Simulation</div>
          <div style={{fontFamily:'var(--font-serif)',fontSize:22,fontWeight:700,color:'#FBFAF6',margin:'2px 0 4px'}}>{s.head}</div>
          <div style={{color:'rgba(234,240,234,.74)',fontSize:13}}>Mint modelled this against your real accounts, cash flow and goals.</div>
        </div>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,flex:'0 0 320px'}}>
          {s.outs.map((o,i)=>(
            <div key={i} style={{background:'rgba(255,255,255,.07)',border:'1px solid rgba(212,169,93,.2)',borderRadius:12,padding:'11px 14px'}}>
              <div style={{fontSize:11,fontWeight:700,color:'rgba(234,240,234,.66)'}}>{o[0]}</div>
              <div style={{fontFamily:'var(--font-serif)',fontSize:19,fontWeight:700,color:'#FBFAF6',marginTop:3}}>{o[1]}</div>
            </div>
          ))}
        </div>
      </div>
    </ChartCard>
  );
}

function PageAIAssistant() {
  /* ---- live figures from the engine (consistent with the rest of the app) ---- */
  const CM = window.useStore ? window.useStore() : window.CM;
  const fmt0 = CM.M0;
  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 nwChangePct=nwPrev?(nw-nwPrev)/nwPrev*100:0;
  const cf6=CM.last6CashFlow(); const lastCF=cf6[cf6.length-1]||{inc:0,exp:0};
  const monthlyCF=lastCF.inc-lastCF.exp; const savingsRate=lastCF.inc?(lastCF.inc-lastCF.exp)/lastCF.inc*100:0;
  const score=CM.wealthScore();
  const scoreBand=score>=85?'Excellent':score>=70?'Strong':score>=55?'Healthy':score>=40?'Building':'At Risk';
  const spReal=CM.spendingByCategory(6,true);
  const SPCOL={Housing:G,Transportation:BL,Transport:BL,'Food & Dining':AM,Groceries:AM,Dining:AM,Shopping:PU,Utilities:TEAL,Insurance:PINK,Entertainment:RD,Subscriptions:INDIGO,Kids:PINK,Other:SL,Healthcare:RD,Travel:AM,Education:BL};
  const spendSeg=spReal.items.map(it=>({label:it.label,value:it.value,color:SPCOL[it.label]||SL}));
  const goalsReal=CM.goalsProgress(); const goalColors=[G,BL,PU,AM,TEAL,PINK];
  const subsReal=(CM.S.subscriptions||[]).filter(s=>s.active!==false);
  const subAnnual=subsReal.reduce((s,x)=>s+(+x.price||0),0)*12;
  const invMV=CM.calcInvestValue();
  const invCostA=(CM.S.investments||[]).reduce((s,i)=>s+(i.costBasis!=null?+i.costBasis:(+i.shares||0)*(+i.avgCost||0)),0);
  const invRetA=invCostA?(invMV-invCostA)/invCostA*100:0;
  const cardsA=CM.S.cards||[]; const climitA=cardsA.reduce((s,c)=>s+(+c.limit||0),0); const cusedA=cardsA.reduce((s,c)=>s+(+c.balance||0),0);
  const utilA=climitA?cusedA/climitA*100:0;
  const emFundG=goalsReal.find(g=>/emergency/i.test(g.name||''));
  const emEta=emFundG?Math.max(1,Math.round((emFundG.target-emFundG.saved)/Math.max(1,monthlyCF*0.4))):null;
  const cfFore=[0.9,0.95,1.0,1.03,1.06,1.1].map(f=>Math.round(monthlyCF*f));

  const quick = [
    { pose:'r1-10', tag:'Net Worth', color:G, text:`Your net worth reached ${compact(nw)}, ${nwChangePct>=0?'up':'down'} ${Math.abs(nwChangePct).toFixed(1)}% this month.`, link:'See breakdown' },
    { pose:'r1-10', tag:'Savings Opportunity', color:AM, text:`You have ${subsReal.length} active subscriptions totalling ${fmt0(subAnnual)}/year — review overlaps to save.`, link:'View details' },
    { pose:'r1-10', tag:'Top Category', color:RD, text:`${spReal.items[0]?spReal.items[0].label:'Housing'} is your largest spend at ${spReal.items[0]?spReal.items[0].pct:0}% this month.`, link:'Review now' },
    emFundG ? { pose:'r1-10', tag:'Goal Progress', color:BL, text:`Your Emergency Fund is ${Math.round(emFundG.saved/emFundG.target*100)}% funded${emEta?` — about ${emEta} months to go`:''}.`, link:'Keep it up' }
            : { pose:'r1-10', tag:'Goal Progress', color:BL, text:'Add a goal to track your progress here.', link:'Add a goal' },
    { pose:'r1-10', tag:'Investment Insight', color:PU, text:`Your portfolio is ${invRetA>=0?'up':'down'} ${Math.abs(invRetA).toFixed(1)}% on cost.`, link:'See analysis' },
  ];
  // Recommendations derived from REAL signals — each only appears when it actually applies. No fixed list.
  const recs = (()=>{ const r=[];
    if(utilA>=30) r.push({ ic:<I.Card size={18}/>, color:PU, title:'Lower credit utilization', sub:`Your utilization is ${utilA.toFixed(0)}% — keeping it under 30% protects your credit score.`, impact:utilA>=50?'High':'Medium', col:utilA>=50?G:AM });
    if(!emFundG) r.push({ ic:<I.Shield size={18}/>, color:G, title:'Start an emergency fund', sub:'Aim for 3–6 months of expenses so a surprise bill doesn’t turn into debt.', impact:'High', col:G });
    else if((+emFundG.saved||0)<(+emFundG.target||0)) r.push({ ic:<I.Shield size={18}/>, color:G, title:'Finish your emergency fund', sub:`${Math.round((emFundG.saved||0)/(emFundG.target||1)*100)}% funded${emEta?` — about ${emEta} months to go at your pace`:''}.`, impact:'High', col:G });
    if(subsReal.length && subAnnual>0) r.push({ ic:<I.Wallet size={18}/>, color:TEAL, title:`Review ${subsReal.length} subscription${subsReal.length>1?'s':''}`, sub:`They total ${fmt0(subAnnual)}/year — cancel any you no longer use.`, impact:subAnnual>=600?'High':'Medium', col:subAnnual>=600?G:AM });
    if(monthlyCF>0) r.push({ ic:<I.Investments size={18}/>, color:BL, title:'Put your surplus to work', sub:`You’re running a ${fmt0(monthlyCF)}/mo surplus — automating it into savings or investments compounds over time.`, impact:'Medium', col:AM });
    if(spReal.items&&spReal.items[0]&&spReal.items[0].pct>=35) r.push({ ic:<I.Dining size={18}/>, color:AM, title:`Trim ${spReal.items[0].label}`, sub:`It’s ${spReal.items[0].pct}% of your spending this month — small cuts free up cash toward your goals.`, impact:'Medium', col:AM });
    if(!r.length) r.push({ ic:<I.Goals size={18}/>, color:G, title:'You’re in good shape', sub:'No pressing recommendations right now. Add goals, cards or subscriptions and Mint will spot ways to improve.', impact:'Low', col:G });
    return r;
  })();
  const preds = [
    { tx:<>You'll bank a <b>{compact(Math.max(0,monthlyCF*3))} surplus</b> over the next 3 months</>, when:'Sep 2026' },
    { tx:<>Your credit score will hold <b>740+</b></>, when:'Nov 2026' },
    { tx:<>You'll complete your <b>Emergency Fund</b></>, when: emEta?'in ~'+emEta+' mo':'2026' },
    { tx:<>Investments could grow to <b>{compact(invMV*1.5)}</b></>, when:'May 2028' },
  ];
  const asks = ['What can I do to save $500 more each month?','How can I pay off my debt faster?','Can I afford a $500,000 house?',"What's the best way to invest $10,000?",'How will retiring at 55 impact my finances?'];
  const lessons = [
    { ic:<I.Card size={18}/>, color:PU, t:'Understanding Credit Scores', s:'How scores work and how to improve yours.' },
    { ic:<I.Investments size={18}/>, color:TEAL, t:'Investing for Beginners', s:'Start your investment journey with confidence.' },
    { ic:<I.Goals size={18}/>, color:G, t:'Retirement Planning Guide', s:'Plan today for a comfortable tomorrow.' },
    { ic:<I.Wallet size={18}/>, color:AM, t:'Budgeting Like a Pro', s:'Master budgeting and control your money.' },
  ];
  const tools = [
    { ic:<I.Bars size={18}/>, color:G, name:'Financial Analyzer', sub:'Analyze any aspect of your finances.' },
    { ic:<I.Budget size={18}/>, color:PU, name:'Smart Budget Builder', sub:'AI creates a personalized budget for you.' },
    { ic:<I.Card size={18}/>, color:RD, name:'Debt Payoff Planner', sub:'Find the fastest path to debt-free.' },
    { ic:<I.Investments size={18}/>, color:TEAL, name:'Investment Optimizer', sub:'Get AI recommendations to optimize returns.' },
    { ic:<I.Goals size={18}/>, color:BL, name:'Scenario Planner', sub:'See how life changes impact your finances.' },
    { ic:<I.Reports size={18}/>, color:AM, name:'Report Generator', sub:'Generate beautiful financial reports.' },
  ];
  const spend = spendSeg;
  const goals = goalsReal.map((g,i)=>({ name:g.name, cur:g.saved, tgt:g.target, color:goalColors[i%goalColors.length] }));
  return (
    <div>
      {/* HERO */}
      <div className="cm-hero cm-mb-24">
        <div className="cm-hero-grid">
          <Robot pose="r1-5" size={150} cls="robot-hero"/>
          <div>
            <h1>Hi {(CM.S.currentUser && (CM.S.currentUser.name||'').trim().split(/\s+/)[0]) || 'there'}</h1>
            <p>I'm Mint — your intelligent financial partner. Ask questions, get insights, and reach your goals faster.</p>
            <div className="hero-chips">
              <span className="cm-chip-action"><I.Bars size={15}/>Analyze My Finances</span>
              <span className="cm-chip-action"><I.Card size={15}/>Improve My Credit</span>
              <span className="cm-chip-action"><I.Budget size={15}/>Create Budget</span>
              <span className="cm-chip-action"><I.Investments size={15}/>Optimize Investments</span>
              <span className="cm-chip-action"><I.Goals size={15}/>Plan Retirement</span>
            </div>
          </div>
          <div className="cm-hero-score">
            <div className="hs-cap">Your Financial Health Score</div>
            <ScoreGauge score={score} size={172} label={scoreBand}/>
            <div className="hs-foot">{nwChangePct>=0?'▲':'▼'} {Math.abs(nwChangePct).toFixed(1)}% net worth this month</div>
          </div>
        </div>
      </div>

      {/* QUICK INSIGHTS */}
      <SecHead eyebrow="AI Quick Insights" title="What Mint noticed today" link="Updated just now"/>
      <div className="cm-qi cm-mb-24">
        {quick.map((q,i)=>(
          <div className="cm-qi-card" key={i}>
            <div className="qi-top">
              <Robot pose={q.pose} size={30} float={false} cls="qi-bot"/>
              <span className="qi-tag" style={{color:q.color}}>{q.tag}</span>
            </div>
            <div className="qi-text">{q.text}</div>
            <div className="qi-link" style={{color:q.color}}>{q.link}<I.ChevR size={12}/></div>
          </div>
        ))}
      </div>

      {/* CHAT + RECOMMENDATIONS */}
      <div className="cm-grid-2c cm-mb-24">
        <ChartCard title="Chat with Mint">
          <Chat/>
        </ChartCard>
        <ChartCard title="AI Recommendations" action={<span className="cm-sechead" style={{margin:0}}><span className="link">View all<I.ChevR size={14}/></span></span>}>
          {recs.map((r,i)=>(
            <div className="cm-rec" key={i}>
              <span className="cm-rec-ic" style={{background:tint(r.color),color:r.color}}>{r.ic}</span>
              <div className="cm-rec-body">
                <div className="cm-rec-title">{r.title}</div>
                <div className="cm-rec-sub">{r.sub}</div>
              </div>
              <div className="cm-rec-impact"><div className="k">Impact</div><div className="v" style={{color:r.col}}>{r.impact}</div></div>
            </div>
          ))}
        </ChartCard>
      </div>

      {/* FINANCIAL OVERVIEW */}
      <SecHead eyebrow="Financial Overview" title="Your money this month" link="May 1 – May 31, 2026"/>
      <div className="an-exec cm-mb-24">
        <Exec ic={<I.Investments size={16}/>} color={G} label="Net Worth" value={compact(nw)} delta={Math.abs(nwChangePct).toFixed(2)+'%'} dir={nwChangePct>=0?'pos':'neg'} data={nwSeries.slice(-7)}/>
        <Exec ic={<I.Transfer size={16}/>} color={BL} label="Monthly Cash Flow" value={(monthlyCF>=0?'+':'-')+compact(Math.abs(monthlyCF))} data={cf6.map(m=>(m.inc-m.exp)/100)}/>
        <Exec ic={<I.Wallet size={16}/>} color={TEAL} label="Total Assets" value={compact(gAssets)} data={nwSeries.slice(-7).map(v=>v+gLiab)}/>
        <Exec ic={<I.Card size={16}/>} color={RD} label="Total Liabilities" value={compact(gLiab)} dir="neg" data={[gLiab*1.05,gLiab*1.04,gLiab*1.03,gLiab*1.02,gLiab*1.01,gLiab*1.004,gLiab]}/>
        <Exec ic={<I.Goals size={16}/>} color={PU} label="Savings Rate" value={savingsRate.toFixed(1)+'%'} data={cf6.map(m=>m.inc?(m.inc-m.exp)/m.inc*100:0)}/>
        <Exec feat label="AI Financial Health" gauge={<ScoreGauge score={score} size={132} label={scoreBand} showStars={true}/>}/>
      </div>

      {/* breakdown / forecast / goals */}
      <div className="cm-grid-3a cm-mb-24">
        <ChartCard title="Spending Breakdown" action={<span className="t-caption">This month</span>}>
          <div className="cm-donut-card">
            <DonutChart size={150} thickness={20} segments={spend} center={{value:fmt0(spReal.total),label:'Total'}}/>
            <div style={{flex:1,minWidth:130}}><Legend items={spend.map(s=>({color:s.color,label:s.label,pct:Math.round(s.value/(spReal.total||1)*100)+'%'}))}/></div>
          </div>
        </ChartCard>
        <ChartCard title="Cash Flow Forecast" action={<span className="t-caption">Next 6 months</span>}>
          <div className="an-legend" style={{marginBottom:8}}>
            <span><i style={{background:G}}/>Income</span><span><i style={{background:RD}}/>Expenses</span><span><i style={{background:BL}}/>Net</span>
          </div>
          <TrendChart data={cfFore} height={188} color="var(--green-500)"
            yLabels={[compact(Math.max.apply(null,cfFore)),'',compact(0)]} xLabels={['Jun','Jul','Aug','Sep','Oct','Nov']}/>
        </ChartCard>
        <ChartCard title="Goal Progress" action={<span className="link" style={{fontSize:12.5,fontWeight:800,color:'var(--green-600)'}}>View all</span>}>
          {goals.map((g,i)=>{
            const pct=Math.round(g.cur/g.tgt*100);
            return (
              <div className="cm-goalrow" key={i}>
                <div className="g-main">
                  <div className="g-top"><span className="g-name">{g.name}</span><span className="g-fig num">${g.cur.toLocaleString()} / ${g.tgt.toLocaleString()}</span></div>
                  <div className="pb-track" style={{height:7,borderRadius:999,background:'var(--line)',overflow:'hidden'}}>
                    <div style={{width:pct+'%',height:'100%',borderRadius:999,background:g.color}}/>
                  </div>
                </div>
                <span style={{fontSize:13,fontWeight:800,color:g.color,width:40,textAlign:'right'}}>{pct}%</span>
              </div>
            );
          })}
        </ChartCard>
      </div>

      {/* predictions / ask / learning */}
      <div className="cm-grid-3a cm-mb-24">
        <ChartCard title="AI Predictions" action={<span className="t-caption">Based on your data</span>}>
          {preds.map((p,i)=>(
            <div className="cm-pred" key={i}>
              <span className="cm-pred-ic"><I.Grow size={16}/></span>
              <span className="cm-pred-tx">{p.tx}</span>
              <span className="cm-pred-when">{p.when}</span>
            </div>
          ))}
        </ChartCard>
        <ChartCard title="Ask Mint Anything" action={<span className="t-caption">Try these</span>}>
          <div style={{display:'flex',flexDirection:'column',gap:9}}>
            {asks.map((a,i)=>(
              <div key={i} style={{display:'flex',alignItems:'center',gap:10,padding:'11px 14px',border:'1px solid var(--line)',borderRadius:11,background:'#fff',cursor:'pointer',fontSize:13,fontWeight:600,color:'var(--ink-700)'}}>
                <I.Spark size={15} style={{color:'var(--green-600)',flex:'0 0 15px'}}/>{a}
              </div>
            ))}
          </div>
        </ChartCard>
        <ChartCard title="AI Learning Hub" action={<span className="link" style={{fontSize:12.5,fontWeight:800,color:'var(--green-600)'}}>View all</span>}>
          {lessons.map((l,i)=>(
            <div className="cm-learn" key={i}>
              <span className="cm-learn-ic" style={{background:tint(l.color),color:l.color}}>{l.ic}</span>
              <div className="cm-learn-body"><div className="cm-learn-title">{l.t}</div><div className="cm-learn-sub">{l.s}</div></div>
              <I.ChevR size={16} style={{color:'var(--ink-400)'}}/>
            </div>
          ))}
          <div style={{display:'flex',justifyContent:'flex-end',marginTop:10}}>
            <Robot pose="r3-9" size={74} float="float2"/>
          </div>
        </ChartCard>
      </div>

      {/* SCENARIO PLANNER */}
      <div className="cm-mb-24"><Scenarios/></div>

      {/* TOOLS */}
      <SecHead eyebrow="Powerful AI Tools" title="Put Mint to work"/>
      <div className="cm-tools cm-mb-24">
        {tools.map((t,i)=>(
          <div className="cm-tool" key={i}>
            <div className="t-ic" style={{background:tint(t.color),color:t.color}}>{t.ic}</div>
            <div className="t-name">{t.name}</div>
            <div className="t-sub">{t.sub}</div>
          </div>
        ))}
      </div>

      {/* ASK BANNER */}
      <div className="cm-askbanner">
        <Robot pose="r2-9" size={62} cls="robot" float="float2"/>
        <div className="ab-tx"><div className="t">Need answers about your money?</div><div className="s">Ask Mint anything and get an instant, personalized response.</div></div>
        <div className="ab-in">
          <input placeholder="Ask me anything about your finances…"/>
          <button className="send"><I.Transfer size={18}/></button>
        </div>
      </div>
    </div>
  );
}
window.PageAIAssistant = PageAIAssistant;
})();
