/* Clear Mint — V6 Financial Health. window.PageFinancialHealth */
(function(){
const I = window.CMIcon;
const { CMC, tintFor, ScoreGauge, TrendChart, GradeBar, Bar, Chip, PageHead, V6Tabs } = window;
const { G, PU, AM, BL, SL, RD, TEAL, PINK } = CMC;

function ShieldArt(){
  return (
    <svg width="170" height="160" viewBox="0 0 170 160" fill="none">
      <ellipse cx="92" cy="120" rx="70" ry="14" fill="#E4ECE5"/>
      <path d="M40 60c14-3 22-9 30-16 8 7 16 13 30 16-1 22-12 38-30 46-18-8-29-24-30-46Z" fill="#DDEAD9"/>
      <path d="M85 22 48 38v22c0 28 16 47 37 56 21-9 37-28 37-56V38L85 22Z" fill="#2E7D5B"/>
      <path d="M85 22 48 38v22c0 28 16 47 37 56V22Z" fill="#37936A"/>
      <path d="M70 60l11 11 20-22" stroke="#fff" strokeWidth="6" strokeLinecap="round" strokeLinejoin="round"/>
      <path d="M132 44c-9 1-15 6-16 15 9-1 15-6 16-15Z" fill="#5FBE8E"/>
      <path d="M40 78c8 3 13 9 13 18-8-3-13-9-13-18Z" fill="#5FBE8E"/>
    </svg>
  );
}

const STATUS_COL={Excellent:G,'Very Good':TEAL,Good:AM,Fair:AM,Poor:RD};
function BreakCard({ ic, c, label, score, status, desc }){
  const col=STATUS_COL[status]||G;
  return (
    <div className="cm-card cm-card-pad" style={{display:'flex',flexDirection:'column'}}>
      <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:12}}>
        <Chip ic={ic} color={c} size={36} radius={10}/>
        <span style={{fontWeight:700,fontSize:13.5,color:'var(--ink-900)'}}>{label}</span>
      </div>
      <div style={{display:'flex',alignItems:'baseline',gap:4}}>
        <span className="num" style={{fontSize:26,fontWeight:800,color:'var(--ink-900)'}}>{score}</span>
        <span className="num" style={{fontSize:13,color:'var(--ink-400)'}}>/100</span>
      </div>
      <div style={{color:col,fontWeight:700,fontSize:13,margin:'2px 0 10px'}}>{status}</div>
      <Bar pct={score} color={col}/>
      <div style={{fontSize:12.5,color:'var(--ink-500)',margin:'12px 0 14px',lineHeight:1.5,flex:1}}>{desc}</div>
      <div className="v6-link">View details <I.ChevR size={13}/></div>
    </div>
  );
}

function OverviewLegacy({ tab, setTab }){
  const breakdown=[
    { ic:<I.Grow size={18}/>, c:G, label:'Cash Flow', score:90, status:'Excellent', desc:'You have a positive cash flow and are spending within your means.' },
    { ic:<I.Goals size={18}/>, c:G, label:'Savings Rate', score:85, status:'Very Good', desc:"You're saving 22% of your income. Aim for 20%+ to build wealth faster." },
    { ic:<I.Card size={18}/>, c:AM, label:'Debt Ratio', score:65, status:'Good', desc:'Your debt is in a good range. Continue paying down high-interest debt.' },
    { ic:<I.Shield size={18}/>, c:G, label:'Emergency Fund', score:95, status:'Excellent', desc:"You have 7.2 months of expenses saved. You're well prepared!" },
    { ic:<I.Pie size={18}/>, c:BL, label:'Investments', score:80, status:'Very Good', desc:"You're invested for the future. Keep diversifying and stay the course." },
    { ic:<I.Insurance size={18}/>, c:PU, label:'Insurance', score:85, status:'Very Good', desc:'You have good coverage in place to protect you and your family.' },
  ];
  const bench=[
    { l:'Overall Score', pct:82, top:'Top 18%', c:G },
    { l:'Savings Rate', pct:72, top:'Top 28%', c:G },
    { l:'Emergency Fund', pct:85, top:'Top 15%', c:G },
    { l:'Debt Ratio', pct:54, top:'Top 46%', c:AM },
    { l:'Investments', pct:68, top:'Top 32%', c:G },
    { l:'Insurance Coverage', pct:75, top:'Top 25%', c:G },
  ];
  return (
    <div>
      <PageHead title="Financial Health" sub="Track your financial health and build a stronger future."
        actions={<>
          <button className="v6-btn v6-btn-icon" style={{position:'relative'}}><I.Bell size={17}/><span style={{position:'absolute',top:-4,right:-4,width:16,height:16,borderRadius:999,background:'var(--gold)',color:'#3A2E12',fontSize:10,fontWeight:800,display:'flex',alignItems:'center',justifyContent:'center'}}>2</span></button>
          <button className="v6-btn"><I.Calendar size={15}/>May 18 – May 24, 2024<I.Chevron size={14}/></button>
        </>}/>
      <V6Tabs tabs={['Overview','Score Breakdown','Recommendations','Trends','Benchmarks']} value={tab} onChange={setTab}/>

      {/* score + history */}
      <div style={{display:'grid',gridTemplateColumns:'1.45fr 1fr',gap:20,marginBottom:20}}>
        <div className="cm-card cm-card-pad">
          <div className="v6-cardtitle" style={{display:'flex',alignItems:'center',gap:7,marginBottom:18}}>Your Financial Health Score <I.Info size={15} style={{color:'var(--ink-400)'}}/></div>
          <div style={{display:'flex',alignItems:'center',gap:24}}>
            <div style={{textAlign:'center'}}>
              <ScoreGauge score={87} size={200} label="" showStars={false} scoreSize={48}/>
              <div className="num" style={{fontSize:12,color:'var(--ink-400)',marginTop:-26}}>/100</div>
            </div>
            <div style={{flex:1,minWidth:0}}>
              <div style={{display:'flex',alignItems:'center',gap:8}}>
                <span style={{fontFamily:'var(--font-serif)',fontSize:24,fontWeight:700,color:G}}>A+</span>
                <span style={{fontFamily:'var(--font-serif)',fontSize:24,fontWeight:700,color:'var(--ink-900)'}}>Financial Health</span>
              </div>
              <div style={{fontSize:13.5,color:'var(--ink-500)',margin:'8px 0 12px',lineHeight:1.5}}>Excellent! You're making great progress and on track for financial freedom.</div>
              <span className="cm-pill cm-pill-green" style={{padding:'5px 11px',fontSize:12}}><I.ArrowUp size={13}/>+6 points from last month</span>
            </div>
            <div style={{flexShrink:0}}><ShieldArt/></div>
          </div>
          <div style={{marginTop:18}}><GradeBar pos={0.87} height={9} showTicks ticks={['0','25','50','75','100']}/></div>
        </div>

        <div className="cm-card cm-card-pad">
          <div className="v6-cardhead"><div className="v6-cardtitle">Score History</div>
            <button className="v6-btn" style={{padding:'6px 11px',fontSize:12.5}}>1 Year<I.Chevron size={13}/></button></div>
          <TrendChart data={[52,55,53,58,60,62,61,66,70,73,77,80,82,85,87]} width={460} height={250} color={G}
            yLabels={['100','75','50','25','0']} xLabels={['Jun \u201923','Aug \u201923','Oct \u201923','Dec \u201923','Feb \u201924','Apr \u201924','May \u201924']}/>
        </div>
      </div>

      {/* breakdown */}
      <div className="v6-cardtitle" style={{margin:'4px 0 16px'}}>Score Breakdown</div>
      <div className="v6-grid-6 cm-mb-24">
        {breakdown.map((b,i)=><BreakCard key={i} {...b}/>)}
      </div>

      {/* insights / benchmark / improving */}
      <div className="v6-grid-3">
        <div className="cm-card cm-card-pad">
          <div className="v6-cardtitle" style={{marginBottom:16}}>Key Insights</div>
          {[
            { ic:<I.Grow size={16}/>, c:G, t:<><b>Great job!</b> Your net worth increased by $18,750 (8.7%) this month.</> },
            { ic:<I.Goals size={16}/>, c:G, t:<>Your savings rate is <b>above average!</b> You're in the top 28% of Canadians.</> },
            { ic:<I.Card size={16}/>, c:AM, t:<>Consider paying down your credit card balance. High interest debt is holding you back.</> },
            { ic:<I.Shield size={16}/>, c:TEAL, t:<>You're well protected. Review your insurance coverage annually to stay on track.</> },
          ].map((r,i)=>(
            <div key={i} style={{display:'flex',gap:11,padding:'10px 0',borderBottom:i<3?'1px solid var(--line)':'none'}}>
              <Chip ic={r.ic} color={r.c} size={30} radius={9}/>
              <div style={{fontSize:12.5,color:'var(--ink-600)',lineHeight:1.5}}>{r.t}</div>
            </div>
          ))}
          <button className="cm-btn cm-btn-soft" style={{width:'100%',justifyContent:'center',marginTop:14}}>View All Recommendations <I.ChevR size={14}/></button>
        </div>

        <div className="cm-card cm-card-pad">
          <div className="v6-cardtitle" style={{display:'flex',alignItems:'center',gap:7}}>Financial Health Benchmark <I.Info size={14} style={{color:'var(--ink-400)'}}/></div>
          <div style={{fontSize:12.5,color:'var(--ink-500)',margin:'4px 0 16px'}}>How you compare to other Canadians</div>
          {bench.map((b,i)=>(
            <div key={i} style={{display:'grid',gridTemplateColumns:'130px 1fr 54px',alignItems:'center',gap:10,padding:'7px 0'}}>
              <span style={{fontSize:12.5,fontWeight:600,color:'var(--ink-700)'}}>{b.l}</span>
              <Bar pct={b.pct} color={b.c}/>
              <span className="num" style={{fontSize:12,fontWeight:700,color:'var(--ink-500)',textAlign:'right'}}>{b.top}</span>
            </div>
          ))}
          <div className="v6-link" style={{marginTop:14}}>View full benchmark report <I.ChevR size={13}/></div>
        </div>

        <div className="cm-card cm-card-pad">
          <div className="v6-cardtitle" style={{display:'flex',alignItems:'center',gap:7}}>Score Improving Factors <I.Info size={14} style={{color:'var(--ink-400)'}}/></div>
          <div style={{fontSize:12.5,color:'var(--ink-500)',margin:'4px 0 16px'}}>Top actions that can improve your score</div>
          {[
            { ic:<I.Shield size={16}/>, c:G, t:'Increase your emergency fund', s:'Add $2,500 more to reach 9 months', pts:'+5 pts' },
            { ic:<I.Card size={16}/>, c:AM, t:'Pay down credit card balance', s:'Pay off $1,200 to improve debt ratio', pts:'+4 pts' },
            { ic:<I.Investments size={16}/>, c:BL, t:'Increase monthly investments', s:'Add $200/month to your investments', pts:'+3 pts' },
            { ic:<I.Insurance size={16}/>, c:PU, t:'Review and update insurance', s:'Ensure coverage matches your needs', pts:'+2 pts' },
          ].map((r,i)=>(
            <div key={i} style={{display:'flex',gap:11,alignItems:'center',padding:'9px 0',borderBottom:i<3?'1px solid var(--line)':'none'}}>
              <Chip ic={r.ic} color={r.c} size={32} radius={9}/>
              <div style={{flex:1,minWidth:0}}><div style={{fontWeight:700,fontSize:13,color:'var(--ink-900)'}}>{r.t}</div>
                <div style={{fontSize:12,color:'var(--ink-500)',marginTop:1}}>{r.s}</div></div>
              <span className="cm-pill cm-pill-green">{r.pts}</span>
            </div>
          ))}
          <div className="v6-link" style={{marginTop:14}}>View all actions <I.ChevR size={13}/></div>
        </div>
      </div>

      <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)'}}>Your financial health is strong!</div>
            <div style={{fontSize:13,color:'var(--ink-500)',marginTop:2}}>Keep up the great work and continue building your path to financial freedom.</div></div>
        </div>
        <button className="v6-btn v6-btn-primary" onClick={()=>location.hash='#/roadmap'}>View Your Financial Roadmap <I.ChevR size={15}/></button>
      </div>
    </div>
  );
}

/* ============================ THEMED MODULE SHELL ============================ */
const FHTheme = window.FHTheme;
const PAL = window.FH_PALETTES;
const hexA = window.FHhexA;

const TABS = ['Overview','Score Breakdown','Recommendations','Trends','Benchmarks'];
const TABMETA = {
  'Overview':        { title:'Financial Health', sub:'Track your financial health and build a stronger future.', icon:'Shield' },
  'Score Breakdown': { title:'Score Breakdown', sub:'A detailed look at the key factors that make up your Financial Health Score.', icon:'Shield', compare:true },
  'Recommendations': { title:'Recommendations', sub:'Personalized actions to improve your financial health and reach your goals faster.', icon:'Spark' },
  'Trends':          { title:'Financial Trends', sub:'Explore how your financial health has changed over time.', icon:'Bars' },
  'Benchmarks':      { title:'Benchmarks', sub:'See how you compare to Canadian households like yours.', icon:'Goals', compare:true },
};

function ThemedTabs({ value, onChange }){
  const C = React.useContext(FHTheme);
  return (
    <div style={{display:'flex',gap:26,borderBottom:'1px solid '+C.line,marginBottom:22,overflowX:'auto'}}>
      {TABS.map(t=>{ const on=t===value; return (
        <button key={t} onClick={()=>onChange(t)} style={{appearance:'none',border:0,background:'none',fontFamily:'inherit',cursor:'pointer',
          padding:'0 1px 13px',fontSize:14,fontWeight:on?700:600,color:on?C.emerald:C.sub,whiteSpace:'nowrap',
          borderBottom:'2px solid '+(on?C.emerald:'transparent'),marginBottom:-1,transition:'.15s'}}>{t}</button>); })}
    </div>
  );
}

function ThemedShell({ tab, setTab, theme, setTheme, compare, setCompare, data }){
  const C = theme==='dark'?PAL.dark:PAL.light;
  const meta = TABMETA[tab];
  const Page = { 'Overview':window.FHOverview, 'Score Breakdown':window.FHScore, 'Recommendations':window.FHRecs, 'Trends':window.FHTrends, 'Benchmarks':window.FHBench }[tab];
  return (
    <FHTheme.Provider value={C}>
      <div style={{background:C.bg,margin:'-24px -32px',minHeight:'calc(100vh - 0px)',padding:'26px 32px 64px',transition:'background .25s',color:C.ink}} className="fh-shell">
        {/* header */}
        <div style={{display:'flex',alignItems:'flex-start',justifyContent:'space-between',gap:20,marginBottom:20,flexWrap:'wrap'}}>
          <div style={{display:'flex',alignItems:'center',gap:15,minWidth:0}}>
            <span style={{width:52,height:52,borderRadius:15,background:hexA(C.emerald,C.name==='dark'?0.18:0.13),color:C.emerald,display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>{React.createElement(window.FHIcon,{name:meta.icon,size:26})}</span>
            <div style={{minWidth:0}}>
              <h1 style={{fontFamily:'var(--font-serif)',fontSize:30,fontWeight:700,color:C.ink,margin:0,lineHeight:1.1}}>{meta.title}</h1>
              <p style={{margin:'5px 0 0',fontSize:13.5,color:C.sub,fontWeight:500}}>{meta.sub}</p>
            </div>
          </div>
          <div style={{display:'flex',alignItems:'center',gap:10,flexShrink:0}}>
            {React.createElement(window.FHThemeToggle,{value:theme,onChange:setTheme})}
            <button style={fhBtn(C)}><I.Bell size={16}/><span style={{position:'absolute',top:-5,right:-5,minWidth:16,height:16,padding:'0 4px',borderRadius:999,background:C.gold,color:'#3A2E12',fontSize:10,fontWeight:800,display:'flex',alignItems:'center',justifyContent:'center'}}>2</span></button>
            <button style={fhBtn(C)}><I.Calendar size={15}/>May 18 – May 24, 2024<I.Chevron size={13}/></button>
            <button style={Object.assign(fhBtn(C),{background:C.emDeep,color:'#fff',border:'1px solid '+C.emDeep})}><I.Transfer size={15} style={{transform:'rotate(-90deg)'}}/>Export</button>
          </div>
        </div>
        {/* tabs + compare */}
        <div style={{display:'flex',alignItems:'flex-end',justifyContent:'space-between',gap:16}}>
          <div style={{flex:1,minWidth:0,display:'flex',gap:26,borderBottom:'1px solid '+C.line,overflowX:'auto'}}>
            {TABS.map(t=>{ const on=t===tab; return (
              <button key={t} onClick={()=>setTab(t)} style={{appearance:'none',border:0,background:'none',fontFamily:'inherit',cursor:'pointer',
                padding:'0 1px 13px',fontSize:14,fontWeight:on?700:600,color:on?C.emerald:C.sub,whiteSpace:'nowrap',
                borderBottom:'2px solid '+(on?C.emerald:'transparent'),marginBottom:-1,transition:'color .15s'}}>{t}</button>); })}
          </div>
          {meta.compare && <div style={{display:'flex',alignItems:'center',gap:8,paddingBottom:18,flexShrink:0}}>
            <span style={{fontSize:12.5,color:C.sub,fontWeight:600}}>Compare to:</span>
            {React.createElement(window.FHSelect,{options:data.benchmarks.compareOptions,value:compare,onChange:setCompare})}</div>}
        </div>
        {Page ? <Page data={data} compare={compare}/> : <div style={{color:C.sub}}>Coming soon.</div>}
      </div>
    </FHTheme.Provider>
  );
}
function fhBtn(C){ return {position:'relative',display:'inline-flex',alignItems:'center',gap:7,fontFamily:'inherit',fontSize:13,fontWeight:700,padding:'9px 14px',borderRadius:11,border:'1px solid '+C.line2,background:C.panel,color:C.ink,cursor:'pointer',whiteSpace:'nowrap'}; }

function PageFinancialHealth(){
  const CM = window.useStore ? window.useStore() : window.CM;
  const data = React.useMemo(()=> window.CMHealth.derive(CM), [CM, CM&&CM.S&&CM.S.accounts]);
  const [tab,setTab]=React.useState('Overview');
  const [theme,setTheme]=React.useState(()=>{ try{ return localStorage.getItem('cm_fh_theme')||'dark'; }catch(e){ return 'dark'; } });
  const [compare,setCompare]=React.useState('Similar Households');
  React.useEffect(()=>{ window.__fhGoTab = setTab; try{ localStorage.setItem('cm_fh_theme',theme); }catch(e){} },[theme]);
  return <ThemedShell tab={tab} setTab={setTab} theme={theme} setTheme={setTheme} compare={compare} setCompare={setCompare} data={data}/>;
}
window.PageFinancialHealth = PageFinancialHealth;
})();
