/* ===== MaxFi app shell + routing ===== */
const { useState, useEffect } = React;

function StatusBar() {
  return (
    <div className="statusbar">
      <span className="tnum">9:41</span>
      <i className="punch"/>
      <div className="row" style={{ gap:6 }}>
        <svg width="17" height="12" viewBox="0 0 17 12"><g fill="var(--text)">
          <rect x="0" y="7" width="3" height="5" rx="1"/><rect x="4.5" y="4.5" width="3" height="7.5" rx="1"/>
          <rect x="9" y="2" width="3" height="10" rx="1"/><rect x="13.5" y="0" width="3" height="12" rx="1" opacity=".4"/>
        </g></svg>
        <svg width="16" height="12" viewBox="0 0 16 12" fill="none"><path d="M8 9.5l.01 0M3 6a7 7 0 0 1 10 0M5.3 8a4 4 0 0 1 5.4 0" stroke="var(--text)" strokeWidth="1.4" strokeLinecap="round"/></svg>
        <svg width="24" height="12" viewBox="0 0 24 12"><rect x="1" y="1" width="20" height="10" rx="2.5" fill="none" stroke="var(--text)" strokeWidth="1.2" opacity=".5"/><rect x="3" y="3" width="13" height="6" rx="1" fill="var(--text)"/><rect x="22" y="4" width="1.6" height="4" rx="1" fill="var(--text)" opacity=".5"/></svg>
      </div>
    </div>
  );
}

const TABS = [
  { id:'home',  label:'Home',  icon:'home' },
  { id:'spend', label:'Spend', icon:'receipt' },
  { id:'save',  label:'Save',  icon:'pie' },
  { id:'fi',    label:'FI',    icon:'flame' },
];

function BottomNav({ tab, go }) {
  return (
    <div className="nav">
      {TABS.map(t=>(
        <button key={t.id} className={tab===t.id?'on':''} onClick={()=>go(t.id)}>
          <span className="ico"><Icon name={t.icon} size={23} color={tab===t.id?'var(--gold)':'var(--faint)'} stroke={tab===t.id?2:1.7}/></span>
          <span>{t.label}</span>
        </button>
      ))}
    </div>
  );
}

function TxnSheet({ t, close }) {
  if (!t) return null;
  const card = cardById(t.card);
  const better = t.missed ? cardById(t.missed.better) : null;
  // highlight amount + merchant in raw sms
  return (
    <>
      <div className="sheet-back" onClick={close}/>
      <div className="sheet">
        <div className="grab"/>
        <div className="row" style={{ gap:13, marginBottom:18 }}>
          <MerchantBadge name={t.merchant} size={46}/>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:17, fontWeight:700 }}>{t.merchant}</div>
            <div style={{ fontSize:12, color:'var(--dim)', marginTop:2 }}>{t.cat} · {t.time}</div>
          </div>
          <div className="serif tnum" style={{ fontSize:24 }}>−{fmtINR(t.amt,0)}</div>
        </div>

        <div className="eyebrow" style={{ marginBottom:9 }}>Parsed from SMS</div>
        <div style={{ background:'var(--bg)', border:'1px solid var(--line)', borderRadius:14, padding:'13px 14px', marginBottom:16 }}>
          <div className="row" style={{ gap:8, marginBottom:9 }}>
            <span className="tag" style={{ background:'rgba(127,168,217,.14)', color:'#7fa8d9' }}><Icon name="sms" size={10} color="#7fa8d9"/>{card.issuer} Bank</span>
            <span className="tag" style={{ background:'var(--green-dim)', color:'var(--green)' }}><Icon name="check" size={10} color="var(--green)"/>on-device</span>
          </div>
          <div className="mono" style={{ fontSize:11, color:'var(--dim)', lineHeight:1.6 }}>{highlightSms(t.sms, t.amt, t.merchant, card.last4)}</div>
        </div>

        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginBottom:t.missed?16:6 }}>
          <SheetField label="Card used" value={card.name} sub={'•••• '+card.last4}/>
          <SheetField label="Category" value={t.cat} sub="auto-tagged"/>
        </div>

        {t.missed && (
          <div style={{ padding:'13px 14px', borderRadius:16,
            background:'linear-gradient(120deg,rgba(212,175,92,.16),rgba(212,175,92,.04))', border:'1px solid rgba(212,175,92,.3)' }}>
            <div className="row" style={{ gap:9 }}>
              <Icon name="bolt" size={18} color="var(--gold)" style={{ flexShrink:0, marginTop:1 }}/>
              <div style={{ fontSize:12.5, color:'var(--dim)', lineHeight:1.5 }}>
                Paid with {card.name} (1%). <b style={{ color:'var(--gold-bright)' }}>{better.name}</b> earns 5% here —
                you missed <b style={{ color:'var(--gold-bright)' }}>{fmtINR(t.missed.extra,0)}</b>.
              </div>
            </div>
          </div>
        )}
      </div>
    </>
  );
}

function highlightSms(sms, amt, merchant, last4) {
  const parts = [];
  const tokens = [
    { re: new RegExp('(Rs\\.?|INR)\\s?'+amt+'(\\.00)?','i'), c:'var(--gold-bright)' },
    { re: new RegExp('xx?'+last4,'i'), c:'var(--blue)' },
    { re: new RegExp(merchant.toUpperCase().split(' ')[0],'i'), c:'var(--green)' },
  ];
  let segs = [{ t:sms, c:null }];
  tokens.forEach(tok=>{
    const next = [];
    segs.forEach(s=>{
      if (s.c) { next.push(s); return; }
      let str = s.t, m;
      while ((m = str.match(tok.re))) {
        const idx = m.index;
        if (idx>0) next.push({ t:str.slice(0,idx), c:null });
        next.push({ t:m[0], c:tok.c });
        str = str.slice(idx+m[0].length);
      }
      if (str) next.push({ t:str, c:null });
    });
    segs = next;
  });
  return segs.map((s,i)=> s.c
    ? <b key={i} style={{ color:s.c, fontWeight:700 }}>{s.t}</b>
    : <span key={i}>{s.t}</span>);
}

function SheetField({ label, value, sub }) {
  return (
    <div style={{ background:'var(--bg)', border:'1px solid var(--line)', borderRadius:12, padding:'10px 12px' }}>
      <div className="eyebrow" style={{ fontSize:8.5 }}>{label}</div>
      <div style={{ fontSize:13.5, fontWeight:700, marginTop:5 }}>{value}</div>
      {sub && <div style={{ fontSize:10.5, color:'var(--faint)', marginTop:2 }}>{sub}</div>}
    </div>
  );
}

function CardSheet({ card, close }) {
  if (!card) return null;
  const rules = REWARDS[card.id];
  const waivePct = card.waiver ? Math.min(1, card.spent/card.waiver) : 1;
  const topCats = Object.entries(rules).filter(([k])=>k[0]!=='_').sort((a,b)=>b[1]-a[1]).slice(0,4);
  return (
    <>
      <div className="sheet-back" onClick={close}/>
      <div className="sheet">
        <div className="grab"/>
        <div style={{ display:'flex', justifyContent:'center', marginBottom:18 }}>
          <CreditCardTile card={card} w={272} h={166}/>
        </div>
        <div className="eyebrow" style={{ marginBottom:9 }}>Top reward categories</div>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:9, marginBottom:16 }}>
          {topCats.map(([k,v])=>(
            <div key={k} className="row" style={{ justifyContent:'space-between', background:'var(--bg)', border:'1px solid var(--line)', borderRadius:11, padding:'9px 12px' }}>
              <span style={{ fontSize:12, color:'var(--dim)' }}>{k}</span>
              <span className="serif tnum" style={{ fontSize:15, color:'var(--gold-bright)' }}>{v}%</span>
            </div>
          ))}
        </div>
        <div className="card" style={{ padding:14 }}>
          <div className="row" style={{ justifyContent:'space-between', marginBottom:card.waiver?10:0 }}>
            <span style={{ fontSize:12.5, color:'var(--dim)' }}>Annual fee</span>
            <span style={{ fontSize:13, fontWeight:700 }}>{card.fee?fmtINR(card.fee,0):'Lifetime free'}</span>
          </div>
          {card.waiver>0 && <>
            <div style={{ height:7, borderRadius:4, background:'rgba(243,239,231,.08)', overflow:'hidden' }}>
              <div style={{ height:'100%', width:(waivePct*100)+'%', borderRadius:4, background:'linear-gradient(90deg,var(--gold-deep),var(--gold))' }}/>
            </div>
            <div className="row" style={{ justifyContent:'space-between', marginTop:7 }}>
              <span style={{ fontSize:10.5, color:'var(--faint)' }} className="mono">{fmtINR(card.spent,1)} spent</span>
              <span style={{ fontSize:10.5, color:waivePct>=1?'var(--green)':'var(--faint)' }} className="mono">{waivePct>=1?'fee waived ✓':fmtINR(card.waiver,1)+' to waive'}</span>
            </div>
          </>}
        </div>
        <div style={{ fontSize:11, color:'var(--faint)', textAlign:'center', marginTop:13 }} className="mono">{rules._cap}</div>
      </div>
    </>
  );
}

function FundSheet({ f, close }) {
  if (!f) return null;
  const g = f.current - f.invested;
  const gPct = g / f.invested * 100;
  const ac = ALLOC_COLOR[assetClass(f.cat)];
  const isRegular = f.plan === 'Regular';
  const lag = assetClass(f.cat)==='Equity' && f.ret3y < f.catRet3y - 1.5;
  const loss = f.current < f.invested;
  const leak = f.current*(f.erReg-f.erDir)/100;
  return (
    <>
      <div className="sheet-back" onClick={close}/>
      <div className="sheet">
        <div className="grab"/>
        <div className="row" style={{ gap:13, marginBottom:16 }}>
          <div style={{ width:46, height:46, borderRadius:13, flexShrink:0, background:ac+'22',
            display:'flex', alignItems:'center', justifyContent:'center', color:ac, fontWeight:700, fontSize:18 }}>{f.cat[0]}</div>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:16, fontWeight:700, lineHeight:1.25 }}>{f.name}</div>
            <div className="row" style={{ gap:6, marginTop:4 }}>
              <span className="tag" style={{ background: isRegular?'rgba(212,175,92,.14)':'var(--green-dim)', color: isRegular?'var(--gold)':'var(--green)' }}>{f.plan}</span>
              <span style={{ fontSize:11, color:'var(--faint)' }}>{f.cat}</span>
            </div>
          </div>
        </div>

        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginBottom:14 }}>
          <SheetField label="Current value" value={fmtINR(f.current,2)} sub={`invested ${fmtINR(f.invested,1)}`}/>
          <SheetField label="Returns" value={(gPct>=0?'+':'')+gPct.toFixed(1)+'%'} sub={`${g>=0?'+':''}${fmtINR(g,1)}`}/>
          <SheetField label="3Y CAGR" value={f.ret3y.toFixed(1)+'%'} sub={`cat avg ${f.catRet3y.toFixed(1)}%`}/>
          <SheetField label="Expense ratio" value={f.erDir>0?f[isRegular?'erReg':'erDir'].toFixed(2)+'%':'—'} sub={isRegular?`Direct ${f.erDir.toFixed(2)}%`:'Direct plan'}/>
        </div>

        {/* contextual actions */}
        {isRegular && (
          <ActionRow icon="swap" color="var(--gold)" title="Switch to Direct plan"
            body={`You're paying ${(f.erReg-f.erDir).toFixed(2)}% extra — about ${fmtINR(leak,0)}/yr in commissions.`}/>
        )}
        {lag && (
          <ActionRow icon="trendDown" color="var(--red)" title="Trailing its benchmark"
            body={`Lags the ${f.cat} category by ${(f.catRet3y-f.ret3y).toFixed(1)}% over 3 years. Consider a low-cost index alternative.`}/>
        )}
        {loss && (
          <ActionRow icon="leaf" color="var(--green)" title="Harvest the loss"
            body={`${fmtINR(f.invested-f.current,0)} below cost. Book it to offset ${f.heldMo>=12?'LTCG':'STCG'} and save ~${fmtINR((f.invested-f.current)*0.125,0)} tax.`}/>
        )}
        {!isRegular && !lag && !loss && (
          <ActionRow icon="check" color="var(--green)" title="Healthy holding"
            body="Direct plan, beating its category. No action needed."/>
        )}
      </div>
    </>
  );
}

function ActionRow({ icon, color, title, body }) {
  return (
    <div style={{ display:'flex', gap:11, padding:'12px 13px', marginBottom:9, borderRadius:14,
      background:'var(--bg)', border:'1px solid var(--line)' }}>
      <div style={{ width:32, height:32, borderRadius:9, flexShrink:0, background:color+'1f',
        display:'flex', alignItems:'center', justifyContent:'center' }}>
        <Icon name={icon} size={17} color={color}/>
      </div>
      <div style={{ flex:1 }}>
        <div style={{ fontSize:13, fontWeight:700 }}>{title}</div>
        <div style={{ fontSize:11.5, color:'var(--dim)', marginTop:2, lineHeight:1.45 }}>{body}</div>
      </div>
    </div>
  );
}

function ConfirmSheet({ act, close }) {
  if (!act) return null;
  const [done, setDone] = React.useState(false);
  return (
    <>
      <div className="sheet-back" onClick={close}/>
      <div className="sheet">
        <div className="grab"/>
        {!done ? (
          <>
            <div className="row" style={{ gap:13, marginBottom:14 }}>
              <div style={{ width:44, height:44, borderRadius:13, flexShrink:0, background:(act.color||'var(--gold)')+'1f',
                display:'flex', alignItems:'center', justifyContent:'center' }}>
                <Icon name={act.icon||'bolt'} size={21} color={act.color||'var(--gold)'}/>
              </div>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:17, fontWeight:700, lineHeight:1.2 }}>{act.title}</div>
                {act.impact && <div style={{ fontSize:12, color:act.color||'var(--gold-bright)', marginTop:3, fontWeight:600 }}>{act.impact}</div>}
              </div>
            </div>
            {act.body && <div style={{ fontSize:12.5, color:'var(--dim)', lineHeight:1.55, marginBottom:18 }} dangerouslySetInnerHTML={{ __html: act.body }}/>}
            <button onClick={()=>setDone(true)} style={{ width:'100%', padding:'14px', borderRadius:14, border:0,
              background:'linear-gradient(135deg,var(--gold-bright),var(--gold))', color:'#1a1407', fontSize:14.5, fontWeight:700,
              cursor:'pointer', fontFamily:'var(--font-sans)' }}>{act.cta||'Confirm'}</button>
            <button onClick={close} style={{ width:'100%', padding:'12px', marginTop:8, borderRadius:14, border:0,
              background:'none', color:'var(--dim)', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'var(--font-sans)' }}>Not now</button>
          </>
        ) : (
          <div style={{ textAlign:'center', padding:'12px 0 8px' }}>
            <div style={{ width:60, height:60, borderRadius:'50%', margin:'0 auto 16px',
              background:'var(--green-dim)', display:'flex', alignItems:'center', justifyContent:'center' }}>
              <Icon name="check" size={32} color="var(--green)"/>
            </div>
            <div style={{ fontSize:18, fontWeight:700 }}>You're all set</div>
            <div style={{ fontSize:12.5, color:'var(--dim)', marginTop:7, lineHeight:1.5, maxWidth:280, marginInline:'auto' }}>
              {act.impact ? <>We’ll handle “{act.title}” and keep you posted. <b style={{ color:'var(--green)' }}>{act.impact}</b></> : <>We’ll handle “{act.title}” and notify you when it’s done.</>}
            </div>
            <button onClick={close} style={{ marginTop:20, padding:'12px 28px', borderRadius:13, border:'1px solid var(--line-2)',
              background:'var(--surface-2)', color:'var(--text)', fontSize:13.5, fontWeight:700, cursor:'pointer', fontFamily:'var(--font-sans)' }}>Done</button>
          </div>
        )}
      </div>
    </>
  );
}

function TaxSheet({ close }) {
  const s = taxScenarios();
  const max = Math.max(s.newTaxNoNps, s.oldTax);
  const rows = [
    { label:'New + employer NPS', sub:'80CCD(2) routed', tax:s.newTaxWithNps, best:s.bestRegime==='new' },
    { label:'New regime', sub:'current · default', tax:s.newTaxNoNps, current:true },
    { label:'Old regime', sub:'with 80C / 80D / home loan', tax:s.oldTax, best:s.bestRegime==='old' },
  ];
  return (
    <>
      <div className="sheet-back" onClick={close}/>
      <div className="sheet">
        <div className="grab"/>
        <div className="row" style={{ gap:13, marginBottom:6 }}>
          <div style={{ width:44, height:44, borderRadius:13, flexShrink:0, background:'rgba(212,175,92,.16)',
            display:'flex', alignItems:'center', justifyContent:'center' }}>
            <Icon name="tax" size={22} color="var(--gold)"/>
          </div>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:17, fontWeight:700 }}>Old vs New regime</div>
            <div style={{ fontSize:11.5, color:'var(--faint)', marginTop:2 }} className="mono">FY 2025-26 · gross {fmtINR(s.gross,1)}</div>
          </div>
        </div>

        {/* headline saving */}
        <div style={{ padding:'14px 16px', borderRadius:16, margin:'14px 0 18px',
          background:'linear-gradient(120deg,rgba(92,200,154,.16),rgba(92,200,154,.04))', border:'1px solid rgba(92,200,154,.3)' }}>
          <div className="row" style={{ justifyContent:'space-between', alignItems:'flex-end' }}>
            <div>
              <div className="eyebrow" style={{ marginBottom:6 }}>Lowest tax path</div>
              <div style={{ fontSize:15, fontWeight:700 }}>{s.bestRegime==='new'?'New regime + NPS':'Old regime'}</div>
            </div>
            <div style={{ textAlign:'right' }}>
              <div className="serif tnum" style={{ fontSize:26, color:'var(--green)', lineHeight:1 }}>−{fmtINR(s.totalSaving,0)}</div>
              <div style={{ fontSize:10, color:'var(--faint)', marginTop:3 }} className="mono">vs your current tax</div>
            </div>
          </div>
        </div>

        {/* comparison bars */}
        <div style={{ display:'flex', flexDirection:'column', gap:13, marginBottom:18 }}>
          {rows.map((r,i)=>{
            const color = r.best ? 'var(--green)' : r.current ? 'var(--gold)' : 'var(--faint)';
            return (
              <div key={i}>
                <div className="row" style={{ justifyContent:'space-between', marginBottom:6, gap:8 }}>
                  <span className="row" style={{ gap:7, minWidth:0 }}>
                    <span style={{ fontSize:13, fontWeight:600, whiteSpace:'nowrap' }}>{r.label}</span>
                    {r.best && <span className="tag" style={{ background:'var(--green-dim)', color:'var(--green)', padding:'2px 6px' }}>Best</span>}
                    {r.current && <span className="tag" style={{ background:'rgba(212,175,92,.14)', color:'var(--gold)', padding:'2px 6px' }}>Now</span>}
                  </span>
                  <span className="serif tnum" style={{ fontSize:16, color, flexShrink:0, whiteSpace:'nowrap' }}>{fmtINR(r.tax,1)}</span>
                </div>
                <div style={{ height:8, borderRadius:5, background:'rgba(243,239,231,.07)', overflow:'hidden' }}>
                  <div style={{ height:'100%', width:(r.tax/max*100)+'%', borderRadius:5,
                    background: r.best?'linear-gradient(90deg,#2f8f63,var(--green))':r.current?'linear-gradient(90deg,var(--gold-deep),var(--gold))':'var(--elev)' }}/>
                </div>
                <div style={{ fontSize:10, color:'var(--faint)', marginTop:4 }} className="mono">{r.sub}</div>
              </div>
            );
          })}
        </div>

        {/* NPS lever insight */}
        <div style={{ display:'flex', gap:11, padding:'13px 14px', borderRadius:14, marginBottom:18,
          background:'var(--bg)', border:'1px solid var(--line)' }}>
          <Icon name="info" size={17} color="var(--blue)" style={{ flexShrink:0, marginTop:1 }}/>
          <div style={{ fontSize:11.5, color:'var(--dim)', lineHeight:1.55 }}>
            The new regime kills most deductions, but <b style={{ color:'var(--text)' }}>employer NPS under 80CCD(2)</b> survives — up to 14% of your basic ({fmtINR(s.npsEmployer,1)}). Ask payroll to route it and your taxable income drops without locking up your own cash.
          </div>
        </div>

        <button onClick={close} style={{ width:'100%', padding:'14px', borderRadius:14, border:0,
          background:'linear-gradient(135deg,var(--gold-bright),var(--gold))', color:'#1a1407', fontSize:14.5, fontWeight:700,
          cursor:'pointer', fontFamily:'var(--font-sans)' }}>Set up 80CCD(2) with payroll</button>
        <div style={{ fontSize:10, color:'var(--faint)', textAlign:'center', marginTop:11, lineHeight:1.5 }} className="mono">
          Illustrative · excludes surcharge &amp; perquisites · not tax advice
        </div>
      </div>
    </>
  );
}

function App() {
  const [tab, setTab] = useState('home');
  const [txn, setTxn] = useState(null);
  const [card, setCard] = useState(null);
  const [fund, setFund] = useState(null);
  const [act, setAct] = useState(null);
  const [taxOpen, setTaxOpen] = useState(false);
  const go = (t) => { setTab(t); };

  // Keep a ref so the message handler always sees the latest tab
  const tabRef = React.useRef(tab);
  useEffect(() => { tabRef.current = tab; }, [tab]);

  useEffect(() => {
    const handler = (e) => {
      const d = e.detail || {};
      if (d.kind === 'tax') { setAct(null); setTaxOpen(true); }
      else { setTaxOpen(false); setAct(d); }
    };
    window.addEventListener('maxfi-act', handler);
    return () => window.removeEventListener('maxfi-act', handler);
  }, []);

  // Respond to parent page asking which tab is active (for feedback context)
  useEffect(() => {
    const handler = (e) => {
      if (e.data === 'maxfi:get-tab') {
        e.source?.postMessage({ type: 'maxfi:tab', tab: tabRef.current }, '*');
      }
    };
    window.addEventListener('message', handler);
    return () => window.removeEventListener('message', handler);
  }, []);

  return (
    <div className="phone">
      <StatusBar/>
      <div className="screen">
        {tab==='home'  && <ScreenHome go={go} openTxn={setTxn}/>}
        {tab==='spend' && <ScreenSpend openTxn={setTxn} openCard={setCard}/>}
        {tab==='save'  && <ScreenPortfolio openFund={setFund}/>}
        {tab==='fi'    && <ScreenFire go={go}/>}
        <BottomNav tab={tab} go={go}/>
        {txn && <TxnSheet t={txn} close={()=>setTxn(null)}/>}
        {card && <CardSheet card={card} close={()=>setCard(null)}/>}
        {fund && <FundSheet f={fund} close={()=>setFund(null)}/>}
        {act && <ConfirmSheet act={act} close={()=>setAct(null)}/>}
        {taxOpen && <TaxSheet close={()=>setTaxOpen(false)}/>}
      </div>
      <div className="gesture"><i/></div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
