/* ===== Cards — usage & milestone status board ===== */
const TONE = {
  green:{ bg:'var(--green-dim)', fg:'var(--green)' },
  gold:{ bg:'rgba(212,175,92,.16)', fg:'var(--gold-bright)' },
  red:{ bg:'var(--red-dim)', fg:'var(--red)' },
  blue:{ bg:'rgba(127,168,217,.14)', fg:'#7fa8d9' },
  dim:{ bg:'var(--surface-2)', fg:'var(--dim)' },
};

function Bar({ pct, color = 'var(--gold)', track = 'rgba(243,239,231,.08)', h = 7 }) {
  return (
    <div style={{ height:h, borderRadius:4, background:track, overflow:'hidden' }}>
      <div style={{ height:'100%', width:Math.min(100,Math.max(0,pct*100))+'%', borderRadius:4,
        background:color, transition:'width .5s cubic-bezier(.2,.8,.2,1)' }}/>
    </div>
  );
}

function SpendCards({ openCard }) {
  const ordered = cardsByUrgency();
  const nudges = cardNudges();
  const top = nudges[0];
  const second = nudges[1];
  const earnedYTD = 18640, leftTable = 4280;

  return (
    <div className="fade-soft">
      {/* hero nudge — closest milestone */}
      {top && (
        <button onClick={()=>openCard(top.card)} style={{ ...plainBtn, width:'100%', marginTop:16 }}>
          <div style={{ borderRadius:22, padding:2, background:'linear-gradient(135deg,var(--gold-bright),var(--gold-deep))' }}>
            <div style={{ borderRadius:20, background:'linear-gradient(160deg,#1c1f1a,#141417)', padding:'16px 16px 15px', textAlign:'left' }}>
              <div className="row" style={{ justifyContent:'space-between', marginBottom:12 }}>
                <span className="tag" style={{ background:'var(--gold)', color:'#1a1407', fontWeight:700, padding:'4px 9px' }}>◎ Closest reward</span>
                <span style={{ fontSize:11.5, color:'var(--dim)', whiteSpace:'nowrap' }}>{top.m.period}</span>
              </div>
              <div className="row" style={{ alignItems:'flex-end', justifyContent:'space-between' }}>
                <div>
                  <div className="serif tnum" style={{ fontSize:34, lineHeight:1, color:'var(--gold-bright)' }}>{fmtINR(top.remaining,0)}</div>
                  <div style={{ fontSize:12, color:'var(--dim)', marginTop:5 }}>more on <b style={{ color:'var(--text)' }}>{top.card.name}</b></div>
                </div>
                <Icon name="arrowR" size={20} color="var(--gold)"/>
              </div>
              <div style={{ fontSize:12.5, color:'var(--gold-bright)', margin:'12px 0 11px', fontWeight:600 }}>→ {top.m.reward}</div>
              <Bar pct={top.m.cur/top.m.tgt} color="linear-gradient(90deg,var(--gold-deep),var(--gold-bright))"/>
              <div className="row" style={{ justifyContent:'space-between', marginTop:7 }}>
                <span style={{ fontSize:10.5, color:'var(--faint)' }} className="mono">{fmtINR(top.m.cur,0)} / {fmtINR(top.m.tgt,0)}</span>
                <span style={{ fontSize:10.5, color:'var(--gold)' }} className="mono">{Math.round(top.m.cur/top.m.tgt*100)}%</span>
              </div>
            </div>
          </div>
        </button>
      )}

      {/* secondary nudge */}
      {second && (
        <div className="row" style={{ gap:10, padding:'12px 14px', marginTop:12, borderRadius:16,
          background:'var(--surface)', border:'1px solid var(--line)' }}>
          <Icon name="bolt" size={18} color="var(--gold)" style={{ flexShrink:0 }}/>
          <div style={{ fontSize:12, color:'var(--dim)', lineHeight:1.45 }}>
            Then <b style={{ color:'var(--gold-bright)' }}>{fmtINR(second.remaining,0)}</b> on <b style={{ color:'var(--text)' }}>{second.card.name}</b> → {second.m.reward}
          </div>
        </div>
      )}

      {/* status board */}
      <SectionTitle>Card status · {ordered.length}</SectionTitle>
      <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
        {ordered.map(c=> <CardStatusCard key={c.id} card={c} onClick={()=>openCard(c)}/>)}
      </div>

      {/* rewards summary */}
      <div className="card" style={{ padding:16, marginTop:18, display:'flex', gap:14 }}>
        <Stat label="Earned 2026" value={fmtINR(earnedYTD,1)} sub="rewards & cashback" accent="var(--green)"/>
        <div style={{ width:1, background:'var(--line)' }}/>
        <Stat label="Left on table" value={fmtINR(leftTable,1)} sub="wrong-card spends" accent="var(--gold)"/>
      </div>

      {/* new card offers */}
      <SectionTitle>Cards worth adding</SectionTitle>
      <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
        {NEW_CARDS.map(nc=> <NewCardOffer key={nc.id} nc={nc}/>)}
      </div>

      {/* compact category quick-check (secondary) */}
      <SectionTitle>Quick check</SectionTitle>
      <QuickPick openCard={openCard}/>
    </div>
  );
}

function NewCardOffer({ nc }) {
  return (
    <div className="card" style={{ padding:0, overflow:'hidden' }}>
      <div style={{ display:'flex', gap:13, padding:'15px 16px' }}>
        <div style={{ width:44, height:30, borderRadius:7, flexShrink:0, marginTop:2,
          background:`linear-gradient(135deg,${nc.hue},${nc.hue}aa)`, display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Icon name="cards" size={16} color="#fff"/>
        </div>
        <div style={{ flex:1, minWidth:0 }}>
          <div className="row" style={{ justifyContent:'space-between', gap:8 }}>
            <span style={{ fontSize:14, fontWeight:700, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{nc.name}</span>
            <span className="tag" style={{ background:'var(--green-dim)', color:'var(--green)', fontWeight:700, flexShrink:0 }}>+{fmtINR(nc.extraYr,0)}/yr</span>
          </div>
          <div style={{ fontSize:11, color:'var(--gold-bright)', marginTop:4 }}>{nc.reason}</div>
          <div style={{ fontSize:11.5, color:'var(--dim)', marginTop:6, lineHeight:1.4 }}>{nc.perk}</div>
          <div className="row" style={{ gap:7, marginTop:10, flexWrap:'wrap' }}>
            {nc.tags.map(t=> <span key={t} style={{ fontSize:10.5, color:'var(--dim)', padding:'4px 9px', borderRadius:8, background:'var(--surface-2)', border:'1px solid var(--line)' }}>{t}</span>)}
            <span style={{ fontSize:10.5, color:'var(--faint)', alignSelf:'center' }} className="mono">{nc.fee}</span>
          </div>
        </div>
      </div>
      <button onClick={()=>window.dispatchEvent(new CustomEvent('maxfi-act',{detail:{ title:nc.name, body:nc.perk+' '+nc.reason, impact:'Worth ~'+fmtINR(nc.extraYr,0)+'/yr on your spend', cta:'Start application', icon:'cards', color:nc.hue }}))}
        style={{ width:'100%', padding:'11px', border:0, borderTop:'1px solid var(--line)',
        background:'var(--surface-2)', color:'var(--gold-bright)', fontSize:12.5, fontWeight:700, cursor:'pointer',
        fontFamily:'var(--font-sans)', display:'flex', alignItems:'center', justifyContent:'center', gap:6 }}>
        See details &amp; apply <Icon name="arrowR" size={14} color="var(--gold-bright)"/>
      </button>
    </div>
  );
}

function CardStatusCard({ card, onClick }) {
  const s = CARD_STATUS[card.id];
  const st = cardStatusOf(card);
  const tone = TONE[st.tone];
  return (
    <button onClick={onClick} style={{ ...plainBtn, width:'100%' }}>
      <div className="card" style={{ padding:'15px 16px 16px', textAlign:'left', position:'relative', overflow:'hidden' }}>
        <div style={{ position:'absolute', left:0, top:0, bottom:0, width:3, background:card.hue, opacity:.7 }}/>
        <div className="row" style={{ justifyContent:'space-between', gap:10, marginBottom:12 }}>
          <div className="row" style={{ gap:11, flex:1, minWidth:0 }}>
            <div style={{ width:38, height:26, borderRadius:6, flexShrink:0,
              background:`linear-gradient(135deg,${card.hue},${card.hue}aa)`, display:'flex', alignItems:'center', justifyContent:'center' }}>
              <Icon name="cards" size={15} color="#fff"/>
            </div>
            <div style={{ minWidth:0, flex:1 }}>
              <div style={{ fontSize:14, fontWeight:700, lineHeight:1.15, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{card.name}</div>
              <div style={{ fontSize:10.5, color:'var(--faint)', marginTop:3 }} className="mono">•••• {card.last4} · {card.net}</div>
            </div>
          </div>
          <span className="tag" style={{ background:tone.bg, color:tone.fg, fontWeight:700, padding:'4px 9px', flexShrink:0 }}>{st.label}</span>
        </div>

        {/* this-month mini stats */}
        <div className="row" style={{ gap:18, marginBottom:s.milestones.length||s.cap||s.note?14:0 }}>
          <div>
            <div style={{ fontSize:10, color:'var(--faint)' }}>Spent this month</div>
            <div className="tnum" style={{ fontSize:13.5, fontWeight:700, marginTop:2 }}>{fmtINR(s.spentMonth,1)}</div>
          </div>
          <div>
            <div style={{ fontSize:10, color:'var(--faint)' }}>Rewards earned</div>
            <div className="tnum" style={{ fontSize:13.5, fontWeight:700, marginTop:2, color:'var(--green)' }}>+{fmtINR(s.rewardsMonth,0)}</div>
          </div>
        </div>

        {/* milestones */}
        {s.milestones.map((m,i)=> <MilestoneBar key={i} m={m}/>)}

        {/* cap */}
        {s.cap && <CapBar cap={s.cap}/>}

        {/* free card note */}
        {s.note && !s.milestones.length && (
          <div style={{ display:'flex', gap:9, padding:'11px 12px', borderRadius:12, background:'var(--bg)', border:'1px solid var(--line)' }}>
            <Icon name="check" size={15} color="var(--green)" style={{ flexShrink:0, marginTop:1 }}/>
            <div style={{ fontSize:11.5, color:'var(--dim)', lineHeight:1.45 }}>{s.note}</div>
          </div>
        )}
      </div>
    </button>
  );
}

function MilestoneBar({ m }) {
  const done = m.cur >= m.tgt;
  const rem = Math.max(0, m.tgt - m.cur);
  const color = done ? 'var(--green)' : 'var(--gold)';
  return (
    <div style={{ marginTop:14 }}>
      <div className="row" style={{ justifyContent:'space-between', gap:8, marginBottom:7 }}>
        <span style={{ fontSize:12.5, fontWeight:600, color:'var(--dim)', whiteSpace:'nowrap' }}>{m.label}</span>
        <span className="tnum" style={{ fontSize:12, fontWeight:700, color, whiteSpace:'nowrap', flexShrink:0 }}>{done ? 'Unlocked ✓' : fmtINR(rem,0)+' to go'}</span>
      </div>
      <Bar pct={m.cur/m.tgt} color={done?'var(--green)':'linear-gradient(90deg,var(--gold-deep),var(--gold))'}/>
      <div className="row" style={{ justifyContent:'space-between', alignItems:'flex-start', marginTop:7 }}>
        <span style={{ fontSize:11, color, fontWeight:600, lineHeight:1.35 }}>{m.reward}</span>
        <span style={{ fontSize:10, color:'var(--faint)', whiteSpace:'nowrap', flexShrink:0, marginLeft:10 }} className="mono">{fmtINR(m.cur,0)}/{fmtINR(m.tgt,0)}</span>
      </div>
    </div>
  );
}

function CapBar({ cap }) {
  const hit = cap.used >= cap.cap;
  const color = hit ? 'var(--red)' : 'var(--gold)';
  return (
    <div style={{ marginTop:14, padding:'12px 13px', borderRadius:13,
      background: hit?'rgba(229,129,99,.07)':'var(--bg)', border:`1px solid ${hit?'rgba(229,129,99,.22)':'var(--line)'}` }}>
      <div className="row" style={{ justifyContent:'space-between', marginBottom:8 }}>
        <span className="row" style={{ gap:6, fontSize:12, fontWeight:600, color: hit?'var(--red)':'var(--dim)' }}>
          {hit && <Icon name="alert" size={13} color="var(--red)"/>}{cap.label}
        </span>
        <span className="tnum" style={{ fontSize:11.5, fontWeight:700, color }}>{fmtINR(cap.used,0)} / {fmtINR(cap.cap,0)}</span>
      </div>
      <Bar pct={cap.used/cap.cap} color={color}/>
      <div style={{ fontSize:11, color: hit?'var(--red)':'var(--faint)', marginTop:8, lineHeight:1.4 }}>{cap.note}</div>
    </div>
  );
}

/* compact "best card for a purchase" — secondary utility */
function QuickPick({ openCard }) {
  const [cat, setCat] = React.useState('Fuel');
  const ranked = rankCards(cat, 5000);
  const best = ranked[0];
  const cats = ['Fuel','Travel','Groceries','Offline','Food delivery','Bills'];
  return (
    <div className="card" style={{ padding:16 }}>
      <div style={{ fontSize:12, color:'var(--dim)', marginBottom:12 }}>Best card for a non-obvious purchase:</div>
      <div style={{ display:'flex', gap:8, overflowX:'auto', margin:'0 -16px', padding:'0 16px 12px' }} className="scroll">
        {cats.map(c=>(
          <button key={c} className={'chip'+(c===cat?' on':'')} onClick={()=>setCat(c)}>{c}</button>
        ))}
      </div>
      <button onClick={()=>openCard(best.card)} style={{ ...plainBtn, width:'100%' }}>
        <div className="row" style={{ gap:12, padding:'12px 13px', borderRadius:13, background:'var(--bg)', border:'1px solid var(--line-2)' }}>
          <div style={{ width:36, height:36, borderRadius:10, flexShrink:0, display:'flex', alignItems:'center', justifyContent:'center',
            background:`${best.card.hue}22`, color:best.card.hue }}>
            <Icon name="cards" size={18} color={best.card.hue}/>
          </div>
          <div style={{ flex:1, textAlign:'left' }}>
            <div style={{ fontSize:13.5, fontWeight:700 }}>{best.card.name}</div>
            <div style={{ fontSize:11, color:'var(--faint)', marginTop:2 }}>{best.pct}% on {cat}</div>
          </div>
          <span className="serif tnum" style={{ fontSize:18, color:'var(--gold-bright)' }}>{best.pct}%</span>
        </div>
      </button>
    </div>
  );
}

Object.assign(window, { SpendCards, CardStatusCard, MilestoneBar, CapBar, QuickPick, NewCardOffer, Bar });
