/* Clear Mint — "Recurring detected" suggestions panel for the dashboard.
   Reads window.CMrecurring.analyze() and lets the user accept suggestions into
   earnings / expenses / recurring bills / subscriptions / credit cards.
   Exposes window.RecurringSuggestions. Loaded after cm-recurring.js + cm-dash-extras.jsx. */
(function(){
  const Ic = window.CMIcon || {};
  const G='#10915F', GOLD='#C99A2E', BL='#3E7CC4', PU='#8A6E9E', AM='#C8742E';
  const BrandLogo = window.BrandLogo;

  const SECTIONS = [
    { id:'earnings',      label:'Earnings',       href:'#/income',        c:G,    ic:'Dollar' },
    { id:'expenses',      label:'Expenses',       href:'#/bills',         c:AM,   ic:'Wallet' },
    { id:'bills',         label:'Recurring Bills',href:'#/bills',         c:BL,   ic:'Subscriptions' },
    { id:'subscriptions', label:'Subscriptions',  href:'#/subscriptions', c:PU,   ic:'Repeat' },
    { id:'cards',         label:'Credit Cards',   href:'#/cards',         c:GOLD, ic:'Card' },
  ];

  function RecurringSuggestions({ only }={}){
    const CM = window.useStore ? window.useStore() : window.CM;
    const [data,setData] = React.useState(()=> (window.CMrecurring?window.CMrecurring.analyze():{counts:{},total:0}));
    const [dismissed,setDismissed] = React.useState({});
    const fmt = (CM&&CM.M) || (n=>'$'+(n||0).toFixed(2));
    const refresh = ()=> setData(window.CMrecurring.analyze());
    if(!window.CMrecurring || !data.total) return null;

    function accept(sec, g, key){ window.CMrecurring.apply(sec, g); setDismissed(d=>({...d,[key]:true})); setTimeout(refresh,50); }
    function acceptAll(sec){ window.CMrecurring.applyAll(sec, data[sec]); setTimeout(refresh,50); }
    const Glyph=(n)=> Ic[n]?React.createElement(Ic[n],{size:16}):null;

    return (
      <div className="cm-card cm-card-pad" style={{borderRadius:18,marginBottom:24,border:'1px solid var(--gold-soft,#E7D2A6)',background:'linear-gradient(165deg,#FBF7EE,#FCFAF4)'}}>
        <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:6}}>
          <span style={{width:34,height:34,borderRadius:10,background:'rgba(212,175,55,.16)',color:GOLD,display:'flex',alignItems:'center',justifyContent:'center'}}>{Glyph('Spark')||'✦'}</span>
          <div style={{flex:1}}>
            <div className="t-h2" style={{fontSize:17}}>Recurring transactions detected</div>
            <div className="t-caption">We found {data.total} recurring {data.total===1?'pattern':'patterns'} in your transactions. Add them to the right section.</div>
          </div>
        </div>
        <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(260px,1fr))',gap:14,marginTop:12}}>
          {SECTIONS.filter(sec=>(!only||only.indexOf(sec.id)>=0) && data[sec.id] && data[sec.id].length).map(sec=>(
            <div key={sec.id} className="cm-card" style={{padding:'14px 16px',borderRadius:14}}>
              <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:10}}>
                <span style={{width:26,height:26,borderRadius:8,background:sec.c+'1A',color:sec.c,display:'flex',alignItems:'center',justifyContent:'center'}}>{Glyph(sec.ic)}</span>
                <span className="t-h3" style={{fontSize:14,flex:1}}>{sec.label}</span>
                {data[sec.id].length>1 && <button onClick={()=>acceptAll(sec.id)} style={{border:0,background:'none',color:sec.c,fontWeight:700,fontSize:12,cursor:'pointer',fontFamily:'inherit'}}>Add all</button>}
              </div>
              {data[sec.id].map((g,i)=>{ const key=sec.id+i+g.name; if(dismissed[key]) return null; return (
                <div key={i} style={{display:'flex',alignItems:'center',gap:10,padding:'8px 0',borderTop:i?'1px solid var(--line)':'none'}}>
                  {BrandLogo ? <BrandLogo name={g.name} size={28}/> : null}
                  <div style={{flex:1,minWidth:0}}>
                    <div className="t-h3" style={{fontSize:13,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{g.name}{g.last4?' ····'+g.last4:''}</div>
                    <div className="t-caption" style={{fontSize:11}}>{sec.id==='cards' ? ('min payment · monthly') : (g.cadence||'Recurring')}{g.count?' · seen '+g.count+'×':''}</div>
                  </div>
                  <span className="num" style={{fontWeight:700,fontSize:13,color:'var(--ink-900)'}}>{fmt(sec.id==='cards'?g.suggestExpense:g.amount)}</span>
                  <button onClick={()=>accept(sec.id,g,key)} className="cm-btn cm-btn-primary" style={{padding:'6px 12px',fontSize:12}}>Add</button>
                </div>
              ); })}
            </div>
          ))}
        </div>
      </div>
    );
  }
  window.RecurringSuggestions = RecurringSuggestions;
})();
