/* Clear Mint — Analytics premium report grid (10 dashboard cards).
   Dark fintech style matching the reference; wired to live CM data + CMChart (ECharts).
   Exposes window.AnalyticsReports. Loaded after cm-echarts.jsx + cm-data.js. */
(function(){
  "use strict";
  const DARK = { bg:'#0E1A14', card:'#13241C', card2:'#16291F', line:'rgba(255,255,255,.07)', line2:'rgba(255,255,255,.12)',
    ink:'#EAF1EC', sub:'rgba(232,239,233,.55)', emerald:'#3ECF8E', emDeep:'#16A34A', gold:'#E6C878', red:'#F0876B',
    blue:'#5B9BD5', amber:'#E0A458', slate:'#8FA39A', track:'rgba(255,255,255,.08)', tab:'rgba(255,255,255,.04)' };
  const LIGHT = { bg:'#F4F0E6', card:'#FFFFFF', card2:'#FBF9F3', line:'#ECE6D8', line2:'#E3DCCB',
    ink:'#16241D', sub:'#7B8A80', emerald:'#10915F', emDeep:'#0F6B4F', gold:'#B8942A', red:'#C35B5B',
    blue:'#3E7CC4', amber:'#C8742E', slate:'#94A29B', track:'rgba(20,40,30,.08)', tab:'#F4F0E6' };
  let C = DARK;
  const F = ()=> window.CMChart || {};
  const fmtCAD = n=> (F().fmtCAD?F().fmtCAD(n):('$'+(+n||0).toFixed(2)));
  const fmtC = n=> (F().fmtCompact?F().fmtCompact(n):('$'+Math.round(+n||0)));
  const MO=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

  function Tabs({ value, onChange }){
    const opts=['1M','3M','6M','YTD','1Y','All'];
    return React.createElement('div',{style:{display:'flex',gap:2,background:C.tab,borderRadius:9,padding:3,marginTop:14}},
      opts.map(o=>React.createElement('button',{key:o,onClick:()=>onChange&&onChange(o),
        style:{flex:1,border:0,background:value===o?'rgba(62,207,142,.16)':'transparent',color:value===o?C.emerald:C.sub,
          fontWeight:700,fontSize:11.5,padding:'6px 0',borderRadius:7,cursor:'pointer',fontFamily:'inherit'}},o)));
  }
  function Card({ n, title, sub, subAccent, children, foot }){
    const [tab,setTab]=React.useState('6M');
    return React.createElement('div',{style:{background:C.card,border:'1px solid '+C.line,borderRadius:18,padding:'20px 22px',display:'flex',flexDirection:'column'}},
      React.createElement('div',{style:{display:'flex',alignItems:'flex-start',justifyContent:'space-between',gap:12}},
        React.createElement('div',{style:{fontSize:12.5,fontWeight:800,letterSpacing:'.04em',textTransform:'uppercase',color:C.ink}}, n+'. '+title),
        React.createElement('span',{style:{fontSize:12,fontWeight:700,color:C.emerald,cursor:'pointer'}},'View full report')),
      sub?React.createElement('div',{style:{fontSize:12.5,color:C.sub,marginTop:6}},sub,subAccent?React.createElement('b',{style:{color:C.emerald}},' '+subAccent):null):null,
      React.createElement('div',{style:{flex:1,marginTop:14}},typeof children==='function'?children(tab):children),
      foot!==false?React.createElement(Tabs,{value:tab,onChange:setTab}):null);
  }
  const Legend = items => React.createElement('div',{style:{display:'flex',flexDirection:'column',gap:7}},
    items.map((it,i)=>React.createElement('div',{key:i,style:{display:'flex',alignItems:'center',gap:8,fontSize:12.5}},
      React.createElement('span',{style:{width:9,height:9,borderRadius:3,background:it.c,flex:'0 0 9px'}}),
      React.createElement('span',{style:{flex:1,color:C.sub}},it.l),
      React.createElement('span',{className:'num',style:{color:C.ink,fontWeight:700}},it.v))));
  const Delta = (v,pos)=>React.createElement('span',{style:{color:pos?C.emerald:C.red,fontWeight:700,fontSize:12}}, (pos?'↑ ':'↓ ')+Math.abs(v)+'%');

  function AnalyticsReports(){
    const CM = window.useStore ? window.useStore() : window.CM;
    if(!CM) return null;
    const [theme,setTheme]=React.useState(()=>{ try{ return localStorage.getItem('cm_reports_theme')||'dark'; }catch(e){ return 'dark'; } });
    const isDark = theme==='dark';
    C = isDark ? DARK : LIGHT;
    React.useEffect(()=>{ try{ localStorage.setItem('cm_reports_theme',theme); }catch(e){} },[theme]);
    const ch = F();
    const cf6 = (CM.last6CashFlow?CM.last6CashFlow():[]) || [];
    const inc = cf6.reduce((s,m)=>s+(m.inc||0),0), exp = cf6.reduce((s,m)=>s+(m.exp||0),0);
    const lastCf = cf6[cf6.length-1]||{inc:0,exp:0};
    const nwSeries = (CM.netWorthSeries?CM.netWorthSeries():[])||[];
    const nw = CM.netWorth?CM.netWorth():0;
    const assets = CM.grossAssets?CM.grossAssets():0, liab=(CM.totalLiabilities?CM.totalLiabilities():0);
    const spend = (CM.spendingByCategory?CM.spendingByCategory(7,true):{items:[],total:0})||{items:[],total:0};
    const cards = CM.S.cards||[];
    const cardDebt = CM.totalCardDebt?CM.totalCardDebt():0;
    const invVal = CM.calcInvestValue?CM.calcInvestValue():0;
    const investments = CM.S.investments||[];
    const budgets = CM.S.budgets||[];
    const subs = (CM.S.subscriptions||[]).filter(s=>s.active!==false);
    const subTotal = subs.reduce((s,x)=>s+(+x.price||0),0);
    const score = CM.wealthScore?CM.wealthScore():0;
    const earnings = CM.S.earnings||[];
    const xLabels = cf6.length?cf6.map(m=>m.mo):MO.slice(0,6);

    const empty = label => React.createElement('div',{style:{height:150,display:'flex',alignItems:'center',justifyContent:'center',color:C.slate,fontSize:12.5,textAlign:'center'}},label);
    const Bar = (pct,col)=>React.createElement('div',{style:{height:7,borderRadius:99,background:C.track,overflow:'hidden',flex:1}},
      React.createElement('div',{style:{height:'100%',width:Math.min(100,pct)+'%',borderRadius:99,background:col}}));

    const grid = { display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:16 };
    const toggle = React.createElement('div',{style:{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:16}},
      React.createElement('div',{style:{fontSize:13,fontWeight:700,color:C.ink}},'Financial Reports'),
      React.createElement('div',{style:{display:'inline-flex',background:C.tab,border:'1px solid '+C.line,borderRadius:999,padding:3}},
        [['light','Light'],['dark','Dark']].map(o=>React.createElement('button',{key:o[0],onClick:()=>setTheme(o[0]),
          style:{border:0,background:theme===o[0]?(isDark?'rgba(62,207,142,.18)':'#0F3D2C'):'transparent',
            color:theme===o[0]?(isDark?C.emerald:'#fff'):C.sub,fontWeight:700,fontSize:12,padding:'6px 16px',borderRadius:999,cursor:'pointer',fontFamily:'inherit',display:'flex',alignItems:'center',gap:6}},
          React.createElement('svg',{width:13,height:13,viewBox:'0 0 24 24',fill:'none',stroke:'currentColor',strokeWidth:2},
            o[0]==='dark'?React.createElement('path',{d:'M21 12.8A9 9 0 1111.2 3 7 7 0 0021 12.8z'}):React.createElement('g',null,React.createElement('circle',{cx:12,cy:12,r:4}),React.createElement('path',{d:'M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.5 1.5M17.5 17.5L19 19M19 5l-1.5 1.5M6.5 17.5L5 19',strokeLinecap:'round'}))),
          o[1]))));

    return React.createElement('div',{key:theme,style:{background:(isDark?DARK:LIGHT).bg,borderRadius:22,padding:18,marginBottom:22,transition:'background .25s'}, className:'an-reportgrid'},
      toggle,
      React.createElement('div',{style:grid},

      /* 1 — CASH FLOW */
      React.createElement(Card,{n:1,title:'Cash Flow',sub:'Track your money coming in and going out.'},
        React.createElement('div',null,
          React.createElement('div',{style:{display:'flex',justifyContent:'space-between',marginBottom:8}},
            React.createElement('div',null,React.createElement('div',{style:{fontSize:11,color:C.sub}},'Net Cash Flow'),
              React.createElement('div',{style:{fontFamily:'var(--font-serif)',fontSize:26,fontWeight:700,color:C.emerald}},fmtC(inc-exp))),
            Legend([{c:C.emerald,l:'Income',v:fmtC(inc)},{c:C.red,l:'Expenses',v:fmtC(exp)}])),
          ch.CMArea?React.createElement(ch.CMArea,{height:150,dark:isDark,data:cf6.map(m=>Math.round(m.inc||0)),x:xLabels,color:C.emDeep,color2:C.emerald,empty:!cf6.length}):empty('No cash-flow data yet'))),

      /* 2 — NET WORTH GROWTH */
      React.createElement(Card,{n:2,title:'Net Worth Growth',sub:'Your net worth this month.'},
        React.createElement('div',null,
          React.createElement('div',{style:{display:'flex',justifyContent:'space-between',marginBottom:8}},
            React.createElement('div',null,React.createElement('div',{style:{fontSize:11,color:C.sub}},'Net Worth'),
              React.createElement('div',{style:{fontFamily:'var(--font-serif)',fontSize:26,fontWeight:700,color:C.ink}},fmtC(nw))),
            Legend([{c:C.emerald,l:'Assets',v:fmtC(assets)},{c:C.red,l:'Liabilities',v:fmtC(liab)}])),
          ch.CMArea?React.createElement(ch.CMArea,{height:150,dark:isDark,data:nwSeries.length?nwSeries.map(Math.round):[nw],x:nwSeries.map((_,i)=>''),color:C.emDeep,color2:C.emerald,empty:!nwSeries.length&&!nw}):empty('No net-worth history yet'))),

      /* 3 — EXPENSE CATEGORIES */
      React.createElement(Card,{n:3,title:'Expense Categories',sub:'Where your money went this month.'},
        spend.items.length?React.createElement('div',{style:{display:'flex',flexDirection:'column',gap:9}},
          spend.items.slice(0,6).map((s,i)=>React.createElement('div',{key:i,style:{display:'flex',alignItems:'center',gap:10}},
            React.createElement('span',{style:{flex:'0 0 92px',fontSize:12,color:C.ink,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}},s.label),
            Bar(spend.total?s.value/spend.total*100:0,s.color||C.emerald),
            React.createElement('span',{className:'num',style:{flex:'0 0 58px',textAlign:'right',fontSize:12,color:C.ink,fontWeight:700}},fmtC(s.value)),
            React.createElement('span',{className:'num',style:{flex:'0 0 38px',textAlign:'right',fontSize:12,color:C.sub}},(spend.total?Math.round(s.value/spend.total*100):0)+'%')))
        ):empty('No spending this month yet')),

      /* 4 — CREDIT CARD UTILIZATION */
      React.createElement(Card,{n:4,title:'Credit Card Utilization',sub:cards.length?('Total card debt '+fmtC(cardDebt)+'.'):''},
        cards.length?React.createElement('div',{style:{display:'flex',flexDirection:'column',gap:11}},
          cards.slice(0,5).map((c,i)=>{ const util=c.limit?Math.min(100,Math.round((c.balance||0)/c.limit*100)):0;
            const col=util>60?C.red:util>30?C.gold:C.emerald;
            return React.createElement('div',{key:i,style:{display:'flex',alignItems:'center',gap:10}},
              React.createElement('span',{style:{flex:'0 0 120px',fontSize:12,color:C.ink,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}},(c.issuer||c.name||'Card')+(c.last4?' ····'+c.last4:'')),
              Bar(util,col),
              React.createElement('span',{className:'num',style:{flex:'0 0 36px',textAlign:'right',fontSize:12,color:col,fontWeight:700}},util+'%'),
              React.createElement('span',{className:'num',style:{flex:'0 0 96px',textAlign:'right',fontSize:11.5,color:C.sub}},fmtC(c.balance||0)+' / '+fmtC(c.limit||0))); })
        ):empty('No credit cards yet')),

      /* 5 — DEBT PAYDOWN PROJECTION */
      React.createElement(Card,{n:5,title:'Debt Paydown Projection',sub:(cardDebt+liab)>0?'Your projected payoff trajectory.':''},
        (cardDebt+liab)>0?React.createElement('div',null,
          React.createElement('div',{style:{display:'flex',gap:20,marginBottom:6}},
            React.createElement('div',null,React.createElement('div',{style:{fontSize:11,color:C.sub}},'Current Debt'),React.createElement('div',{style:{fontFamily:'var(--font-serif)',fontSize:22,fontWeight:700,color:C.red}},fmtC(cardDebt+liab)))),
          ch.CMArea?React.createElement(ch.CMArea,{height:150,dark:isDark,fill:false,data:(function(){var d=cardDebt+liab,o=[];for(var i=0;i<18;i++){o.push(Math.round(d));d=Math.max(0,d-(cardDebt+liab)/18);}return o;})(),x:[],color:C.red,color2:C.gold}):null
        ):empty('No debt to project — nicely done')),

      /* 6 — INVESTMENT PORTFOLIO */
      React.createElement(Card,{n:6,title:'Investment Portfolio',sub:investments.length?'Total value & allocation.':''},
        investments.length?React.createElement('div',null,
          React.createElement('div',{style:{fontFamily:'var(--font-serif)',fontSize:24,fontWeight:700,color:C.ink,marginBottom:12}},fmtC(invVal)),
          React.createElement('div',{style:{display:'flex',flexDirection:'column',gap:8}},
            investments.slice(0,5).map((h,i)=>React.createElement('div',{key:i,style:{display:'flex',justifyContent:'space-between',fontSize:12}},
              React.createElement('span',{style:{color:C.ink}},h.name||h.symbol||'Holding'),
              React.createElement('span',{className:'num',style:{color:C.ink,fontWeight:700}},fmtC((h.shares||h.units||0)*(h.price||h.value||0)||h.value||0)))))
        ):empty('No investments tracked yet')),

      /* 7 — BUDGET VS ACTUAL */
      React.createElement(Card,{n:7,title:'Budget vs Actual',sub:budgets.length?'How your spending tracks to plan.':''},
        budgets.length?React.createElement('div',{style:{display:'flex',flexDirection:'column',gap:10}},
          budgets.slice(0,6).map((b,i)=>{ const tgt=+b.target||+b.budget||0, act=+b.spent||+b.actual||0, over=act>tgt;
            return React.createElement('div',{key:i,style:{display:'flex',alignItems:'center',gap:10}},
              React.createElement('span',{style:{flex:'0 0 96px',fontSize:12,color:C.ink}},b.cat||b.name||'Category'),
              Bar(tgt?Math.min(100,act/tgt*100):0,over?C.red:C.emerald),
              React.createElement('span',{className:'num',style:{flex:'0 0 110px',textAlign:'right',fontSize:11.5,color:C.sub}},fmtC(act)+' / '+fmtC(tgt))); })
        ):empty('Set up budgets to compare')),

      /* 8 — SUBSCRIPTION TRACKER */
      React.createElement(Card,{n:8,title:'Subscription Tracker',sub:subs.length?(subs.length+' active · '+fmtCAD(subTotal)+'/mo'):''},
        subs.length?React.createElement('div',{style:{display:'flex',flexDirection:'column',gap:9}},
          subs.slice(0,6).map((s,i)=>React.createElement('div',{key:i,style:{display:'flex',alignItems:'center',gap:10}},
            window.BrandLogo?React.createElement(window.BrandLogo,{name:s.name,size:26}):null,
            React.createElement('span',{style:{flex:1,fontSize:12.5,color:C.ink,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}},s.name),
            React.createElement('span',{className:'num',style:{fontSize:12.5,color:C.ink,fontWeight:700}},fmtCAD(s.price||0))))
        ):empty('No subscriptions detected yet')),

      /* 9 — FINANCIAL HEALTH SCORE */
      React.createElement(Card,{n:9,title:'Financial Health Score',sub:'Your overall financial health.'},
        React.createElement('div',{style:{display:'flex',flexDirection:'column',alignItems:'center'}},
          React.createElement('div',{style:{position:'relative',width:150,height:150}},
            ch.CMDonut?React.createElement(ch.CMDonut,{height:150,dark:isDark,money:false,centerValue:String(Math.round(score)),centerLabel:score>=80?'Excellent':score>=60?'Good':'Building',
              data:[{value:score,label:'Score',color:score>=60?C.emerald:C.gold},{value:Math.max(0,100-score),label:'Gap',color:'rgba(255,255,255,.08)'}]}):null),
          React.createElement('div',{style:{width:'100%',marginTop:12,display:'flex',flexDirection:'column',gap:7}},
            [['Cash Flow',Math.round((inc-exp)>0?Math.min(100,(inc-exp)/Math.max(1,inc)*200):20)],['Savings Rate',Math.round(inc?Math.max(0,(inc-exp)/inc*100):0)],['Debt Load',Math.round(100-Math.min(100,(cardDebt+liab)/Math.max(1,assets)*100))]].map((r,i)=>
              React.createElement('div',{key:i,style:{display:'flex',alignItems:'center',gap:10}},
                React.createElement('span',{style:{flex:'0 0 88px',fontSize:11.5,color:C.sub}},r[0]),
                Bar(r[1],C.emerald),
                React.createElement('span',{className:'num',style:{flex:'0 0 44px',textAlign:'right',fontSize:11.5,color:C.ink,fontWeight:700}},r[1]+'/100')))))),

      /* 10 — INCOME STABILITY */
      React.createElement(Card,{n:10,title:'Income Stability',sub:earnings.length||inc?'Your income consistency.':''},
        (earnings.length||inc)?React.createElement('div',null,
          React.createElement('div',{style:{fontSize:11,color:C.sub}},'Avg Monthly Income'),
          React.createElement('div',{style:{fontFamily:'var(--font-serif)',fontSize:24,fontWeight:700,color:C.ink,marginBottom:10}},fmtC((CM.monthlyIncome?CM.monthlyIncome():inc/Math.max(1,cf6.length)))),
          ch.CMBars?React.createElement(ch.CMBars,{height:140,dark:isDark,stack:true,x:xLabels,
            series:[{name:'Income',data:cf6.map(m=>Math.round(m.inc||0)),color:C.emerald}]}):null
        ):empty('No income recorded yet'))
      ));
  }
  window.AnalyticsReports = AnalyticsReports;
  try{ if(!document.getElementById('an-reportgrid-style')){ var st=document.createElement('style'); st.id='an-reportgrid-style';
    st.textContent='@media(max-width:1100px){.an-reportgrid > div{grid-template-columns:1fr 1fr !important}}@media(max-width:720px){.an-reportgrid > div{grid-template-columns:1fr !important}}'; document.head.appendChild(st); } }catch(e){}
})();
