/* Clear Mint — dashboard extras: quick actions, Popular Reports, Accounts (manage +
   recent imports + undo last import), Recent Transactions (logo.dev logos), By Category,
   and Subscriptions (floating brand logos + list). Exposes window.DashExtras.
   Matches the existing design system (ChartCard, cm-card, tokens). */
(function(){
  const Ic = window.CMIcon || {};
  const ChartCard = window.ChartCard;
  const DonutChart = window.DonutChart;
  const G='#10915F', GOLD='#C99A2E', BL='#3E7CC4', RD='#C35B5B', SL='#94A29B';

  /* ---- real brand logo via logo.dev, with graceful fallback to initials ---- */
  function BrandLogo({ name, size=36, radius }){
    const r = radius!=null ? radius : (size<=30?8:10);
    const dom = window.resolveLogoDomain ? window.resolveLogoDomain(name) : null;
    const guess = (!dom && window.guessLogoDomain) ? window.guessLogoDomain(name) : null;
    const useDom = dom || guess;
    const initials = (String(name||'?').replace(/[^A-Za-z0-9 ]/g,'').trim().split(/\s+/).map(w=>w[0]).join('').slice(0,2)||'?').toUpperCase();
    const box = { width:size, height:size, borderRadius:r, flex:`0 0 ${size}px`, display:'inline-flex', alignItems:'center', justifyContent:'center', overflow:'hidden', background:'#fff', border:'1px solid var(--line,#E7E3DB)' };
    if(!useDom) return <span style={{...box, background:'#EEF2EC', color:G, fontWeight:800, fontSize:size*0.36, border:0}}>{initials}</span>;
    const src = window.primaryLogoUrl ? window.primaryLogoUrl(useDom, size) : ('https://img.logo.dev/'+useDom+'?token='+(window.LOGODEV_TOKEN||'')+'&size='+size*2+'&format=png&retina=true');
    return (
      <span style={box}>
        <img src={src} alt={name||''} width={size} height={size}
          style={{ width:size, height:size, objectFit:'contain', padding:2 }}
          data-lf="0" data-name={name||''} data-domain={dom||''}
          onError={(e)=>{ if(window.__logoFallback) window.__logoFallback(e.target, name, dom||''); else { e.target.style.display='none'; } }}/>
      </span>
    );
  }
  window.BrandLogo = BrandLogo;

  function SectionCard({ children, style }){
    return <div className="cm-card cm-card-pad" style={{ borderRadius:18, ...style }}>{children}</div>;
  }
  const linkStyle = { fontSize:13, fontWeight:700, color:'var(--forest,#10915F)', textDecoration:'none', cursor:'pointer' };

  /* ============================ Quick actions ============================ */
  function QuickActions(){
    const items = [
      { t:'Bank Statements', s:'Upload and view your bank OFX files', href:'#/statements', c:G, ic:'Reports' },
      { t:'Reconciliation', s:'Match transactions and reconcile accounts', href:'#/reconciliation', c:GOLD, ic:'Check' },
      { t:'Cash Flow', s:'View detailed cash flow and projections', href:'#/cashflow', c:BL, ic:'Transfer' },
      { t:'Debt Paydown Planner', s:'Plan and optimize your debt payoff strategy', href:'#/debtcenter', c:RD, ic:'Wallet' },
    ];
    const Glyph=(n)=> Ic[n]?React.createElement(Ic[n],{size:20}):null;
    return (
      <div className="cm-grid-4 cm-mb-24" style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:18}}>
        {items.map((it,i)=>(
          <a key={i} href={it.href} className="cm-card cm-card-pad" style={{borderRadius:16,textDecoration:'none',transition:'.16s',display:'block'}}
             onMouseOver={e=>{e.currentTarget.style.transform='translateY(-3px)';e.currentTarget.style.boxShadow='0 22px 44px -28px rgba(11,40,30,.4)';}}
             onMouseOut={e=>{e.currentTarget.style.transform='';e.currentTarget.style.boxShadow='';}}>
            <div style={{display:'flex',alignItems:'center',gap:12,marginBottom:10}}>
              <span style={{width:42,height:42,borderRadius:12,background:it.c+'1A',color:it.c,display:'flex',alignItems:'center',justifyContent:'center',flex:'0 0 42px'}}>{Glyph(it.ic)}</span>
              <div className="t-h3" style={{fontSize:15.5,color:'var(--ink-900)'}}>{it.t}</div>
            </div>
            <div className="t-caption" style={{minHeight:34}}>{it.s}</div>
            <div style={{...linkStyle,marginTop:6}}>View →</div>
          </a>
        ))}
      </div>
    );
  }

  /* ============================ Popular Reports + Accounts ============================ */
  function ReportsAndAccounts({ CM }){
    const fmt = CM.M0 || (n=>'$'+Math.round(n||0).toLocaleString());
    const reports = [
      { t:'Clear Financial', s:'Full ledger DR, CR & balance', c:G, ic:'Reports' },
      { t:'Profit & Loss', s:'Income, expenses & net profit', c:BL, ic:'Bars' },
      { t:'Cash Flow', s:'Inflows, outflows & net cash', c:GOLD, ic:'Dollar' },
      { t:'Bank Reconciliation', s:'Match vs unmatched transactions', c:RD, ic:'Card' },
    ];
    const Glyph=(n)=> Ic[n]?React.createElement(Ic[n],{size:18}):null;
    const accounts = CM.S.accounts || [];
    const cards = CM.S.cards || [];
    // import batches with real metadata (filename, count, date) recorded by the engine
    const importBatches = (CM.S._importBatches || []).slice().reverse();
    function undoBatch(id){
      if(!confirm('Undo this import? Its transactions are removed; the account is deleted if it has no transactions left.')) return;
      if(window.CMimport && CMimport.deleteBatch){ CMimport.deleteBatch(id); }
      else {
        CM.S.bankTx = (CM.S.bankTx||[]).filter(r=>r.batchId!==id);
        CM.S.ccTx = (CM.S.ccTx||[]).filter(r=>r.batchId!==id);
        CM.S._importBatches = (CM.S._importBatches||[]).filter(b=>b.id!==id);
        try{ CM.recalc && CM.recalc(); CM.save && CM.save(); }catch(e){}
      }
      try{ window.dispatchEvent(new CustomEvent('cm-state-change')); }catch(e){}
      location.reload();
    }
    function undoLast(){ const b=(CM.S._importBatches||[]); if(b.length) undoBatch(b[b.length-1].id); }
    const acctTypeLabel = a => (a.type||'Account') + (a.last4?' · ····'+a.last4:'');
    return (
      <div style={{display:'grid',gridTemplateColumns:'minmax(0,1fr) 320px',gap:18,marginBottom:24}} className="dash-ra">
        <SectionCard>
          <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:16}}>
            <div className="t-h2" style={{fontSize:18}}>Popular Reports</div>
            <a href="#/reports" style={linkStyle}>All reports →</a>
          </div>
          <div className="cm-grid-4" style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:14}}>
            {reports.map((r,i)=>(
              <a key={i} href="#/reports" className="cm-card" style={{padding:'20px 16px',borderRadius:14,textAlign:'center',textDecoration:'none',transition:'.15s'}}
                 onMouseOver={e=>e.currentTarget.style.boxShadow='0 18px 40px -26px rgba(11,40,30,.4)'}
                 onMouseOut={e=>e.currentTarget.style.boxShadow=''}>
                <span style={{width:42,height:42,borderRadius:12,background:r.c+'1A',color:r.c,display:'inline-flex',alignItems:'center',justifyContent:'center',marginBottom:12}}>{Glyph(r.ic)}</span>
                <div className="t-h3" style={{fontSize:14.5,color:'var(--ink-900)',marginBottom:4}}>{r.t}</div>
                <div className="t-caption" style={{fontSize:11.5,minHeight:28}}>{r.s}</div>
                <div style={{...linkStyle,marginTop:6}}>Generate →</div>
              </a>
            ))}
          </div>
        </SectionCard>

        <SectionCard>
          <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:14}}>
            <div className="t-h2" style={{fontSize:18}}>Accounts</div>
            <a href="#/accounts" style={linkStyle}>Manage →</a>
          </div>
          {(accounts.length||cards.length) ? (
            <div className="cm-stack" style={{gap:12,marginBottom:14}}>
              {accounts.map((a,i)=>(
                <div key={'a'+i} style={{display:'flex',alignItems:'center',gap:11}}>
                  <BrandLogo name={a.bank||a.name} size={34}/>
                  <div style={{flex:1,minWidth:0}}>
                    <div className="t-h3" style={{fontSize:13.5,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{a.bank||a.name}{a.last4?' ····'+a.last4:''}</div>
                    <div className="t-caption" style={{fontSize:11.5}}>{acctTypeLabel(a)}</div>
                  </div>
                  <span className="num" style={{fontWeight:800,fontSize:14,color:'var(--ink-900)'}}>{fmt(a.balance||a.opening||0)}</span>
                </div>
              ))}
              {cards.map((c,i)=>(
                <div key={'c'+i} style={{display:'flex',alignItems:'center',gap:11}}>
                  <BrandLogo name={c.issuer||c.name} size={34}/>
                  <div style={{flex:1,minWidth:0}}>
                    <div className="t-h3" style={{fontSize:13.5,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{c.issuer||c.name}{c.last4?' ····'+c.last4:''}</div>
                    <div className="t-caption" style={{fontSize:11.5}}>Credit Card{c.last4?' · ····'+c.last4:''}</div>
                  </div>
                  <span className="num" style={{fontWeight:800,fontSize:14,color:'var(--ink-900)'}}>{fmt(c.balance||0)}</span>
                </div>
              ))}
            </div>
          ) : (
            <div style={{textAlign:'center',color:'var(--ink-400)',fontSize:13,padding:'20px 0 14px'}}>No accounts yet</div>
          )}
          {importBatches.length ? (
            <div style={{border:'1px solid var(--line)',borderRadius:14,padding:'16px 16px 14px',marginBottom:12}}>
              <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',gap:10,marginBottom:6}}>
                <div className="t-h3" style={{fontSize:15}}>Recent Imports</div>
                <button onClick={undoLast} style={{background:'#FBEAEA',color:RD,border:'1px solid #F1D9D9',borderRadius:999,fontSize:11,fontWeight:800,padding:'4px 11px',cursor:'pointer',fontFamily:'inherit'}}>Undo last import</button>
              </div>
              <div className="t-caption" style={{fontSize:12,lineHeight:1.5,marginBottom:12}}>Undo a specific batch of imported transactions. Accounts and cards are kept.</div>
              {importBatches.slice(0,4).map((b,i)=>(
                <div key={i} style={{display:'flex',alignItems:'center',gap:10,paddingTop:i?10:0,marginTop:i?10:0,borderTop:i?'1px solid var(--line)':'none'}}>
                  <div style={{flex:1,minWidth:0}}>
                    <div className="t-h3" style={{fontSize:13,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{b.fname}</div>
                    <div className="t-caption" style={{fontSize:11.5}}>{b.type==='cc'?'Card':'Bank'} · {b.count} txns · {b.when}</div>
                  </div>
                  <button onClick={()=>undoBatch(b.id)} className="cm-btn cm-btn-ghost" style={{fontSize:12,padding:'6px 14px'}}>Undo</button>
                </div>
              ))}
            </div>
          ) : null}
          <a href="#/accounts" className="cm-btn cm-btn-ghost" style={{width:'100%',justifyContent:'center',textDecoration:'none',borderStyle:'dashed'}}>+ Add Account</a>
        </SectionCard>
      </div>
    );
  }

  /* ============================ Recent Transactions + By Category + Subscriptions ============================ */
  function TxAndSubs({ CM }){
    const fmt = CM.M || (n=>'$'+(n||0).toFixed(2));
    const fmt0 = CM.M0 || (n=>'$'+Math.round(n||0).toLocaleString());
    const FD = CM.FDshort || (d=>d? new Date(d).toLocaleDateString('en-CA',{month:'short',day:'numeric'}):'');
    const tx = (CM.S.bankTx||[]).slice().sort((a,b)=>(new Date(b.date)-new Date(a.date))).slice(0,6);   // latest 6, most recent first
    // spending by category (this set)
    const byCat={}; (CM.S.bankTx||[]).forEach(r=>{ if(r.dr>0){ const c=r.cat||'Other'; byCat[c]=(byCat[c]||0)+r.dr; }});
    const cats = Object.keys(byCat).map(k=>({label:k,value:byCat[k],color:(CM.catColor?CM.catColor(k):SL)})).sort((a,b)=>b.value-a.value).slice(0,6);
    const catTotal = cats.reduce((s,c)=>s+c.value,0);
    // subscriptions
    const subs = (CM.S.subscriptions||[]).slice().sort((a,b)=>(+b.price||0)-(+a.price||0));
    const subTotal = subs.reduce((s,x)=>s+(+x.price||0),0);

    return (
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:18,marginBottom:24}} className="dash-ts">
        {/* By Category */}
        <SectionCard>
          <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:14}}>
            <div className="t-h2" style={{fontSize:18}}>By Category</div>
            <a href="#/analytics" style={linkStyle}>More →</a>
          </div>
          {cats.length ? (
            <React.Fragment>
              {DonutChart ? <div style={{display:'flex',justifyContent:'center',marginBottom:14}}><DonutChart size={140} thickness={18} segments={cats.map(c=>({value:c.value,color:c.color}))} center={{value:fmt0(catTotal),label:'Spent'}}/></div> : null}
              {cats.slice(0,5).map((c,i)=>(
                <div key={i} style={{display:'flex',alignItems:'center',gap:8,marginBottom:8}}>
                  <span style={{width:9,height:9,borderRadius:3,background:c.color}}></span>
                  <span style={{flex:1,fontSize:12.5,color:'var(--ink-700)',fontWeight:600}}>{c.label}</span>
                  <span className="num" style={{fontSize:12.5,fontWeight:700}}>{fmt0(c.value)}</span>
                </div>
              ))}
            </React.Fragment>
          ) : <div style={{textAlign:'center',color:'var(--ink-400)',fontSize:13,padding:'40px 0'}}>No spending data yet</div>}
        </SectionCard>

        {/* Subscription Watch */}
        <SectionCard>
          <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:2}}>
            <div style={{display:'flex',alignItems:'center',gap:8}}>
              <div className="t-h2" style={{fontSize:18}}>Subscription Watch</div>
              {subs.length?<span style={{fontSize:12,fontWeight:800,color:'var(--ink-500)',background:'var(--paper,#F4F0E6)',borderRadius:999,padding:'2px 9px'}}>{subs.length}</span>:null}
            </div>
            <a href="#/subscriptions" style={linkStyle}>View All →</a>
          </div>
          <div className="t-caption" style={{marginBottom:2}}>{subs.length?(fmt0(subTotal)+' / month · '+subs.length+' active subscription'+(subs.length>1?'s':'')):'Track every recurring charge in one place'}</div>
          <div style={{position:'relative',height:236}}>
            <img src="assets/illustrations/sub-platform.png" alt="" aria-hidden="true" style={{position:'absolute',left:'50%',bottom:-6,transform:'translateX(-50%)',height:'104%',width:'auto',maxWidth:'112%',objectFit:'contain',pointerEvents:'none'}}/>
            {(subs.length?subs.slice(0,6):[]).map((s,i)=>{ const slots=[[34,19],[61,15],[27,41],[69,39],[48,9],[50,53]]; const p=slots[i]||[48,30]; return (
              <span key={i} className="cm-sub-float" style={{position:'absolute',left:p[0]+'%',top:p[1]+'%',animationDelay:(i*0.32)+'s',filter:'drop-shadow(0 12px 18px rgba(20,50,40,.28))'}}>
                <BrandLogo name={s.name} size={46} radius={13}/>
              </span>
            ); })}
            {!subs.length && <div style={{position:'absolute',left:'50%',top:'26%',transform:'translateX(-50%)',textAlign:'center',color:'var(--ink-400)',fontSize:12.5,width:210,lineHeight:1.5}}>No subscriptions yet — import transactions or add one to watch them here.</div>}
          </div>
          {subs.length>0 ? (
            <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginTop:2,paddingTop:12,borderTop:'1px solid var(--line)'}}>
              <span className="t-caption">Next charge <b style={{color:'var(--ink-700)'}}>{(function(){ var ds=subs.map(function(s){return s.nextDate||s.nextCharge||s.renewal||s.dueDate;}).filter(Boolean).sort(); return ds.length?(CM.FDshort?CM.FDshort(new Date(ds[0])):new Date(ds[0]).toLocaleDateString('en-CA',{month:'short',day:'numeric'})):'—'; })()}</b></span>
              <a href="#/subscriptions" style={linkStyle}>Manage subscriptions →</a>
            </div>
          ) : (
            <div style={{display:'flex',justifyContent:'center',marginTop:4}}><a href="#/subscriptions" className="cm-btn cm-btn-primary" style={{textDecoration:'none',fontSize:12.5,padding:'8px 16px'}}>+ Add Subscription</a></div>
          )}
        </SectionCard>
      </div>
    );
  }

  /* ============================ Full-width Recent Transactions table ============================ */
  function RecentTxTable({ CM }){
    const fmt = CM.M || (n=>'$'+(n||0).toFixed(2));
    const FD = CM.FDlong || CM.FDshort || (d=>d? new Date(d).toLocaleDateString('en-CA',{year:'numeric',month:'short',day:'numeric'}):'');
    const tx = (CM.S.bankTx||[]).concat(CM.S.ccTx||[]).slice().sort((a,b)=>(new Date(b.date)-new Date(a.date)));   // most recent first
    const cellH = { padding:'12px 16px', textAlign:'left', fontSize:11.5, fontWeight:800, letterSpacing:'.04em', textTransform:'uppercase', color:'var(--ink-400)', borderBottom:'1px solid var(--line)' };
    return (
      <SectionCard style={{padding:0,overflow:'hidden'}}>
        <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'18px 20px 14px'}}>
          <div className="t-h2" style={{fontSize:18}}>Recent Transactions</div>
          <a href="#/transactions" style={linkStyle}>View all →</a>
        </div>
        {tx.length ? (
          <div style={{overflowX:'auto'}}>
            <table style={{width:'100%',borderCollapse:'collapse',minWidth:680}}>
              <thead><tr>
                <th style={cellH}>Company</th><th style={cellH}>Date</th><th style={cellH}>Category</th><th style={{...cellH,textAlign:'right'}}>Amount</th>
              </tr></thead>
              <tbody>
                {tx.map((r,i)=>{ const isD=r.dr>0; const nm=(window.cleanVendorName?window.cleanVendorName(r.desc||r.cat):(r.desc||r.cat))||'—'; return (
                  <tr key={i} style={{borderBottom:i<tx.length-1?'1px solid var(--line)':'none'}}>
                    <td style={{padding:'11px 16px'}}>
                      <div style={{display:'flex',alignItems:'center',gap:11,minWidth:0}}>
                        <BrandLogo name={r.desc||r.cat} size={32}/>
                        <span className="t-h3" style={{fontSize:13.5,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{nm}</span>
                      </div>
                    </td>
                    <td style={{padding:'11px 16px',fontSize:12.5,color:'var(--ink-500)',whiteSpace:'nowrap'}} className="num">{FD(r.date)}</td>
                    <td style={{padding:'11px 16px'}}>
                      <span style={{fontSize:11.5,fontWeight:700,color:(CM.catColor?CM.catColor(r.cat):'var(--ink-700)'),background:'var(--paper,#F4F0E6)',borderRadius:999,padding:'4px 10px',whiteSpace:'nowrap'}}>{r.cat||'Other'}</span>
                    </td>
                    <td style={{padding:'11px 16px',textAlign:'right'}}>
                      <span className="num" style={{fontWeight:800,fontSize:14,color:isD?'var(--ink-900)':G}}>{(isD?'-':'+')+fmt(r.dr||r.cr||0)}</span>
                    </td>
                  </tr>
                ); })}
              </tbody>
            </table>
          </div>
        ) : (
          <div style={{textAlign:'center',color:'var(--ink-400)',fontSize:13,padding:'48px 0'}}>Import transactions to see them here</div>
        )}
      </SectionCard>
    );
  }

  function DashExtras(){
    const CM = window.useStore ? window.useStore() : window.CM;
    if(!CM) return null;
    return (
      <React.Fragment>
        <QuickActions/>
        <ReportsAndAccounts CM={CM}/>
        <TxAndSubs CM={CM}/>
        <RecentTxTable CM={CM}/>
      </React.Fragment>
    );
  }
  window.DashExtras = DashExtras;

  // floating animation for subscription logos
  try{
    if(!document.getElementById('cm-dash-extras-style')){
      var st=document.createElement('style'); st.id='cm-dash-extras-style';
      st.textContent='@keyframes cmSubFloat{0%,100%{transform:translateY(0)}50%{transform:translateY(-6px)}}.cm-sub-float{display:inline-flex;animation:cmSubFloat 3s ease-in-out infinite}@media(max-width:1080px){.dash-ra{grid-template-columns:1fr !important}.dash-ts{grid-template-columns:1fr !important}}';
      document.head.appendChild(st);
    }
  }catch(e){}
})();
