// ─────────────────────────────────────────────────────────────
// screens-payments.jsx — payment hardening
// PayPending (verifying with bank), PayFailure (reason + retry),
// MultiChildPay (single composer for siblings), EMIPickerSheet,
// ReceiptDetail (digital / cheque / refund variants), LateFeeBadge
// ─────────────────────────────────────────────────────────────
const { useState: useStatePay, useEffect: useEffectPay, useMemo: useMemoPay } = React;

const inr = (n) => '₹' + Number(n).toLocaleString('en-IN');

// ─────────────────────────────────────────────────────────────
// PayPendingScreen — between PayMethodSheet and PaySuccess.
// Models the 30–120s real-world bank verification window with idempotency lock.
// ─────────────────────────────────────────────────────────────
function PayPendingScreen({ nav, params }) {
  const total = params?.total ?? 18500;
  const txnId = params?.txnId ?? 'TXN' + Math.floor(Math.random() * 1e10).toString().padStart(10, '0');
  const method = params?.method ?? 'UPI';
  const [phase, setPhase] = useStatePay('initiated'); // initiated → debited → verifying → cleared
  const [seconds, setSeconds] = useStatePay(0);
  const [showHelp, setShowHelp] = useStatePay(false);

  useEffectPay(() => {
    const phases = [
      { at: 1.2, p: 'debited' },
      { at: 3.0, p: 'verifying' },
      { at: 5.5, p: 'cleared' }
    ];
    const start = Date.now();
    const tick = setInterval(() => {
      const t = (Date.now() - start) / 1000;
      setSeconds(Math.floor(t));
      const cur = phases.filter((p) => t >= p.at).pop();
      if (cur) setPhase(cur.p);
      if (t >= 5.5) {
        clearInterval(tick);
        setTimeout(() => nav.replace('paySuccess', { total, txnId, method }), 600);
      }
    }, 200);
    return () => clearInterval(tick);
  }, []);

  const steps = [
    { id: 'initiated', label: 'Payment initiated', sub: method + ' · ' + inr(total) },
    { id: 'debited', label: 'Amount debited from your account', sub: 'Bank confirms debit' },
    { id: 'verifying', label: 'Verifying with school', sub: 'Posting to fee ledger · do not pay again' },
    { id: 'cleared', label: 'Cleared & receipt issued', sub: 'GST invoice queued for email' }
  ];
  const idx = steps.findIndex((s) => s.id === phase);

  return (
    <div className="screen-bg" style={{ minHeight: '100%', display: 'flex', flexDirection: 'column' }} data-screen-label="PayPending">
      <OfflineBanner message="Network slow — payment is still being verified. Don't close the app."/>
      <div style={{
        background: 'linear-gradient(160deg, #0F172A 0%, #1E293B 100%)',
        padding: '60px 20px 28px', color: '#fff'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 11, color: 'rgba(255,255,255,.6)', textTransform: 'uppercase', letterSpacing: '.08em' }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#FBBF24', boxShadow: '0 0 0 4px rgba(251,191,36,.2)', animation: 'sp-spin 2s linear infinite' }}/> Verifying with bank
        </div>
        <div style={{ fontSize: 28, fontWeight: 800, marginTop: 12, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '-.02em' }}>{inr(total)}</div>
        <div style={{ fontSize: 12, color: 'rgba(255,255,255,.7)', marginTop: 6 }}>Reference · <span style={{ fontFamily: 'JetBrains Mono, monospace' }}>{txnId}</span></div>
      </div>

      <div style={{ padding: '20px 16px', flex: 1 }}>
        <div className="card" style={{ padding: 18, borderRadius: 16 }}>
          {steps.map((s, i) => {
            const done = i < idx;
            const active = i === idx;
            const pending = i > idx;
            return (
              <div key={s.id} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', paddingBottom: i < steps.length - 1 ? 18 : 0, position: 'relative' }}>
                {i < steps.length - 1 && (
                  <div aria-hidden="true" style={{ position: 'absolute', left: 13, top: 28, bottom: 0, width: 2, background: done ? 'var(--success-300)' : 'var(--n100)' }}/>
                )}
                <div style={{
                  width: 28, height: 28, borderRadius: '50%', flexShrink: 0,
                  background: done ? 'var(--success-500)' : active ? 'var(--p500)' : 'var(--n100)',
                  color: '#fff', display: 'grid', placeItems: 'center',
                  boxShadow: active ? '0 0 0 6px rgba(99,102,241,.16)' : 'none',
                  transition: 'all .3s'
                }}>
                  {done && <Icon name="check" size={14}/>}
                  {active && <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#fff', animation: 'sp-pulse 1.4s ease-in-out infinite' }}/>}
                </div>
                <div style={{ flex: 1, paddingTop: 4 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: pending ? 'var(--n400)' : 'var(--n900)' }}>{s.label}</div>
                  <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2 }}>{s.sub}</div>
                </div>
              </div>
            );
          })}
        </div>

        <div className="card" style={{ marginTop: 12, padding: 14, background: 'var(--warn-50)', borderColor: 'var(--warn-200)', display: 'flex', gap: 10 }}>
          <Icon name="lock" size={16} color="#92400E"/>
          <div style={{ fontSize: 11.5, color: '#92400E', lineHeight: 1.5 }}>
            <strong>Don't pay again.</strong> Your transaction is locked to reference <span style={{ fontFamily: 'JetBrains Mono, monospace' }}>{txnId}</span>. Closing the app is safe — we'll notify you when it clears (usually under 2 min).
          </div>
        </div>

        {seconds > 6 && (
          <div className="card" style={{ marginTop: 12, padding: 14, display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--n50)', display: 'grid', placeItems: 'center', color: 'var(--n500)' }}><Icon name="help" size={16}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--n900)' }}>Taking longer than usual?</div>
              <div style={{ fontSize: 11, color: 'var(--n500)' }}>Some banks need up to 5 minutes</div>
            </div>
            <button onClick={() => setShowHelp(true)} className="btn-sm btn-soft">Help</button>
          </div>
        )}
      </div>

      <BottomSheet open={showHelp} onClose={() => setShowHelp(false)} title="Payment delayed?">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ fontSize: 12, color: 'var(--n600)', lineHeight: 1.6 }}>
            If money has been debited but the school hasn't confirmed within 5 minutes, the bank will auto-reverse it within 24 hours.
          </div>
          <button onClick={() => { setShowHelp(false); nav.push('contactSupport'); }} className="row card" style={{ padding: 12, gap: 12, textAlign: 'left', background: 'transparent' }}>
            <div style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--p50)', color: 'var(--p600)', display: 'grid', placeItems: 'center' }}><Icon name="message" size={16}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700 }}>Chat with support</div>
              <div style={{ fontSize: 11, color: 'var(--n500)' }}>Avg reply in 4 min · 24×7</div>
            </div>
            <Icon name="chevron-right" size={16} color="var(--n300)"/>
          </button>
          <button onClick={() => nav.replace('payFailure', { total, txnId, method, reason: 'timeout' })} className="row card" style={{ padding: 12, gap: 12, textAlign: 'left', background: 'transparent' }}>
            <div style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--n50)', color: 'var(--n500)', display: 'grid', placeItems: 'center' }}><Icon name="x" size={16}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700 }}>Cancel & retry</div>
              <div style={{ fontSize: 11, color: 'var(--n500)' }}>Only do this if your bank shows debit reversed</div>
            </div>
            <Icon name="chevron-right" size={16} color="var(--n300)"/>
          </button>
        </div>
      </BottomSheet>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// PayFailureScreen — multiple failure reasons + retry path
// ─────────────────────────────────────────────────────────────
const FAILURE_REASONS = {
  insufficient: { ic: 'wallet', tag: 'Insufficient balance', msg: 'Your bank reported insufficient balance.', tip: 'Try a different account or method. Money has not been debited.' },
  bank_decline: { ic: 'bank', tag: 'Bank declined', msg: "Your bank declined this transaction.", tip: 'Could be a daily limit or fraud check. Try UPI or call your bank.' },
  upi_timeout: { ic: 'history', tag: 'UPI app didn\'t respond', msg: 'The UPI app timed out before confirming.', tip: "If money was debited, it auto-reverses in 24h. Don't pay again." },
  timeout: { ic: 'history', tag: 'Verification timed out', msg: 'School-side verification took too long.', tip: 'Your bank may auto-reverse the debit. Wait 30 min before retrying.' },
  network: { ic: 'globe', tag: 'Connection lost', msg: 'You went offline mid-transaction.', tip: 'No money was charged. Reconnect and try again.' },
  card_decline: { ic: 'card', tag: 'Card declined', msg: 'The card issuer rejected this charge.', tip: 'Check expiry, CVV, and that international/online txns are enabled.' }
};

function PayFailureScreen({ nav, params }) {
  const total = params?.total ?? 18500;
  const reason = FAILURE_REASONS[params?.reason || 'bank_decline'] || FAILURE_REASONS.bank_decline;
  const txnId = params?.txnId ?? 'TXN' + Math.floor(Math.random() * 1e10).toString().padStart(10, '0');

  return (
    <div className="screen-bg" style={{ minHeight: '100%', display: 'flex', flexDirection: 'column' }} data-screen-label="PayFailure">
      <OfflineBanner/>
      <div style={{
        background: 'linear-gradient(160deg, #7F1D1D 0%, #991B1B 100%)',
        padding: '60px 20px 32px', color: '#fff', textAlign: 'center'
      }}>
        <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'rgba(255,255,255,.18)', display: 'inline-grid', placeItems: 'center', marginBottom: 14 }}>
          <Icon name="x" size={32}/>
        </div>
        <div style={{ fontSize: 22, fontWeight: 800 }}>Payment didn't go through</div>
        <div style={{ fontSize: 13, color: 'rgba(255,255,255,.78)', marginTop: 6 }}>{reason.msg}</div>
      </div>

      <div style={{ padding: '20px 16px', display: 'flex', flexDirection: 'column', gap: 12, flex: 1 }}>
        <div className="card" style={{ padding: 18 }}>
          <div className="spread">
            <div>
              <div style={{ fontSize: 11, color: 'var(--n500)', textTransform: 'uppercase', letterSpacing: '.06em' }}>{reason.tag}</div>
              <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--n900)', marginTop: 4, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '-.02em' }}>{inr(total)}</div>
            </div>
            <div style={{ width: 44, height: 44, borderRadius: 13, background: 'var(--danger-50)', color: 'var(--danger-600)', display: 'grid', placeItems: 'center' }}>
              <Icon name={reason.ic} size={20}/>
            </div>
          </div>
          <div style={{ fontSize: 11, color: 'var(--n400)', marginTop: 10, paddingTop: 10, borderTop: '1px dashed var(--n100)', fontFamily: 'JetBrains Mono, monospace' }}>Ref · {txnId}</div>
        </div>

        <div className="card" style={{ padding: 14, background: 'var(--warn-50)', borderColor: 'var(--warn-200)', display: 'flex', gap: 10 }}>
          <Icon name="info" size={16} color="#92400E"/>
          <div style={{ fontSize: 12, color: '#92400E', lineHeight: 1.5 }}>{reason.tip}</div>
        </div>

        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <button onClick={() => nav.replace('pay')} className="row" style={{ width: '100%', padding: '14px 16px', gap: 12, background: 'transparent', textAlign: 'left', borderBottom: '1px solid var(--n100)' }}>
            <div style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--p50)', color: 'var(--p600)', display: 'grid', placeItems: 'center' }}><Icon name="history" size={16}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>Try again</div>
              <div style={{ fontSize: 11, color: 'var(--n500)' }}>Same amount, pick a method</div>
            </div>
            <Icon name="chevron-right" size={16} color="var(--n300)"/>
          </button>
          <button onClick={() => nav.push('contactSupport')} className="row" style={{ width: '100%', padding: '14px 16px', gap: 12, background: 'transparent', textAlign: 'left', borderBottom: '1px solid var(--n100)' }}>
            <div style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--n50)', color: 'var(--n600)', display: 'grid', placeItems: 'center' }}><Icon name="message" size={16}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>Contact support</div>
              <div style={{ fontSize: 11, color: 'var(--n500)' }}>Avg reply in 4 min · 24×7</div>
            </div>
            <Icon name="chevron-right" size={16} color="var(--n300)"/>
          </button>
          <button onClick={() => nav.push('history')} className="row" style={{ width: '100%', padding: '14px 16px', gap: 12, background: 'transparent', textAlign: 'left' }}>
            <div style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--n50)', color: 'var(--n600)', display: 'grid', placeItems: 'center' }}><Icon name="receipt" size={16}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>Check transaction history</div>
              <div style={{ fontSize: 11, color: 'var(--n500)' }}>Verify if any debit hit your bank</div>
            </div>
            <Icon name="chevron-right" size={16} color="var(--n300)"/>
          </button>
        </div>

        <button onClick={() => nav.replace('home')} className="btn btn-outline" style={{ marginTop: 4 }}>Back to home</button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// MultiChildPayScreen — single composer, multiple children
// Pulls from the parent's actual outstanding due across siblings.
// ─────────────────────────────────────────────────────────────
const MULTI_CHILDREN = [
  { id: 'aarav', name: 'Aarav Mehra', cls: '8-B', initial: 'A', clr: '#6366F1', items: [
    { id: 'aarav-tut', label: 'Term-2 tuition', amt: 24500, due: 'in 4 days', state: 'due' },
    { id: 'aarav-trn', label: 'Transport — Mar', amt: 2400, due: 'in 4 days', state: 'due' },
    { id: 'aarav-tex', label: 'Term-2 textbooks', amt: 1850, due: 'in 11 days', state: 'soft' }
  ] },
  { id: 'siya', name: 'Siya Mehra', cls: '5-A', initial: 'S', clr: '#EC4899', items: [
    { id: 'siya-tut', label: 'Term-2 tuition', amt: 18200, due: 'in 4 days', state: 'due' },
    { id: 'siya-trn', label: 'Transport — Mar', amt: 2400, due: 'in 4 days', state: 'due' },
    { id: 'siya-act', label: 'Annual day costume', amt: 350, due: 'overdue 3d', state: 'late', lateFee: 75 }
  ] },
  { id: 'rian', name: 'Rian Mehra', cls: 'Pre-KG', initial: 'R', clr: '#06B6D4', items: [
    { id: 'rian-tut', label: 'Term-2 tuition', amt: 12800, due: 'in 4 days', state: 'due' }
  ] }
];

function MultiChildPayScreen({ nav }) {
  // Pre-select all due items
  const [selected, setSelected] = useStatePay(() => {
    const out = {};
    MULTI_CHILDREN.forEach((c) => c.items.forEach((it) => { if (it.state !== 'soft') out[it.id] = true; }));
    return out;
  });
  const [emi, setEmi] = useStatePay(null); // null | { months, monthly }
  const [showEmi, setShowEmi] = useStatePay(false);
  const [siblingDiscount, setSiblingDiscount] = useStatePay(true);
  const [biometric, setBiometric] = useStatePay(false);

  const allItems = useMemoPay(() => MULTI_CHILDREN.flatMap((c) => c.items.map((it) => ({ ...it, child: c }))), []);
  const chosen = allItems.filter((it) => selected[it.id]);
  const subtotal = chosen.reduce((s, it) => s + it.amt, 0);
  const lateFees = chosen.reduce((s, it) => s + (it.lateFee || 0), 0);
  const childrenWithItems = new Set(chosen.map((it) => it.child.id)).size;
  const sibDiscountPct = siblingDiscount && childrenWithItems >= 2 ? 0.04 : 0; // 4% for 2+ siblings
  const sibDiscount = Math.round(subtotal * sibDiscountPct);
  const gst = Math.round((subtotal - sibDiscount) * 0.18);
  const total = subtotal + lateFees - sibDiscount; // Tuition fees are GST-exempt; we show GST line as informational
  const monthly = emi ? Math.ceil(total / emi.months) : null;

  return (
    <div className="screen-bg" style={{ minHeight: '100%', display: 'flex', flexDirection: 'column' }} data-screen-label="MultiChildPay">
      <OfflineBanner/>
      <PageHeader
        title="Pay all dues"
        subtitle={childrenWithItems + ' children · ' + chosen.length + ' items'}
        onBack={() => nav.pop()}
      />

      <div style={{ padding: '14px 16px 100px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          {MULTI_CHILDREN.map((c, idx) => {
            const dueCount = c.items.filter((it) => selected[it.id]).length;
            const dueTotal = c.items.filter((it) => selected[it.id]).reduce((s, it) => s + it.amt, 0);
            return (
              <div key={c.id} style={{ borderTop: idx === 0 ? 'none' : '1px solid var(--n100)' }}>
                <div className="spread" style={{ padding: '14px 16px 8px', alignItems: 'center' }}>
                  <div className="row" style={{ gap: 12 }}>
                    <div aria-hidden="true" style={{ width: 36, height: 36, borderRadius: 11, background: c.clr, color: '#fff', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 13 }}>{c.initial}</div>
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{c.name}</div>
                      <div style={{ fontSize: 11, color: 'var(--n500)' }}>Class {c.cls} · {dueCount}/{c.items.length} selected</div>
                    </div>
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)', fontFamily: 'JetBrains Mono, monospace' }}>{inr(dueTotal)}</div>
                </div>
                {c.items.map((it) => {
                  const on = !!selected[it.id];
                  return (
                    <button key={it.id} onClick={() => setSelected((s) => ({ ...s, [it.id]: !on }))}
                      role="checkbox" aria-checked={on}
                      style={{ width: '100%', padding: '10px 16px 10px 56px', display: 'flex', alignItems: 'center', gap: 10, background: 'transparent', textAlign: 'left', border: 'none', borderTop: '1px solid var(--n50)' }}>
                      <div style={{ width: 22, height: 22, borderRadius: 7, border: on ? '2px solid var(--p500)' : '2px solid var(--n200)', background: on ? 'var(--p500)' : '#fff', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                        {on && <Icon name="check" size={12} color="#fff"/>}
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--n900)' }}>{it.label}</div>
                        <div style={{ fontSize: 10.5, color: it.state === 'late' ? 'var(--danger-600)' : 'var(--n500)', display: 'flex', gap: 6, alignItems: 'center', marginTop: 2 }}>
                          {it.state === 'late' && <Icon name="alert" size={10}/>}
                          {it.due}{it.lateFee ? ' · +' + inr(it.lateFee) + ' late fee' : ''}
                        </div>
                      </div>
                      <div style={{ fontSize: 12.5, fontWeight: 700, fontFamily: 'JetBrains Mono, monospace', color: 'var(--n900)' }}>{inr(it.amt)}</div>
                    </button>
                  );
                })}
              </div>
            );
          })}
        </div>

        {/* Sibling discount */}
        {childrenWithItems >= 2 && (
          <button onClick={() => setSiblingDiscount((v) => !v)} className="card" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left' }}>
            <div style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--success-50)', color: '#065F46', display: 'grid', placeItems: 'center' }}><Icon name="users" size={18}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>Sibling discount · 4%</div>
              <div style={{ fontSize: 11, color: 'var(--n500)' }}>Applied to tuition when 2+ children pay together · saves {inr(sibDiscount)}</div>
            </div>
            <div style={{ width: 38, height: 22, borderRadius: 999, background: siblingDiscount ? 'var(--success-500)' : 'var(--n200)', position: 'relative', transition: 'background .2s' }}>
              <div style={{ position: 'absolute', top: 2, left: siblingDiscount ? 18 : 2, width: 18, height: 18, borderRadius: '50%', background: '#fff', transition: 'left .2s', boxShadow: '0 1px 3px rgba(15,23,42,.18)' }}/>
            </div>
          </button>
        )}

        {/* EMI option */}
        <button onClick={() => setShowEmi(true)} className="card" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left', background: emi ? 'linear-gradient(135deg, var(--p50), var(--p100))' : '#fff', borderColor: emi ? 'var(--p200)' : 'var(--n100)' }}>
          <div style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--p50)', color: 'var(--p600)', display: 'grid', placeItems: 'center' }}><Icon name="calendar" size={18}/></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{emi ? `Pay in ${emi.months} months` : 'Spread the cost'}</div>
            <div style={{ fontSize: 11, color: 'var(--n500)' }}>{emi ? `${inr(monthly)} / month · 0% interest` : 'No-cost EMI · 3, 6, 9, 12 months · GrayQuest'}</div>
          </div>
          <Icon name="chevron-right" size={16} color="var(--n300)"/>
        </button>

        {/* Summary */}
        <div className="card" style={{ padding: 16 }}>
          <div className="spread" style={{ alignItems: 'center', marginBottom: 10 }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--n900)' }}>Order summary</div>
            <div style={{ fontSize: 11, color: 'var(--n500)' }}>{chosen.length} items</div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <Row k="Subtotal" v={inr(subtotal)}/>
            {lateFees > 0 && <Row k="Late fees" v={'+' + inr(lateFees)} tone="danger"/>}
            {sibDiscount > 0 && <Row k="Sibling discount (4%)" v={'−' + inr(sibDiscount)} tone="success"/>}
            <Row k="GST on services" v="₹0" sub="Tuition is GST-exempt under Notif. 12/2017"/>
            <div style={{ height: 1, background: 'var(--n100)', margin: '4px 0' }}/>
            <div className="spread">
              <div>
                <div style={{ fontSize: 11, color: 'var(--n500)', textTransform: 'uppercase', letterSpacing: '.06em' }}>You'll pay</div>
                {emi && <div style={{ fontSize: 10, color: 'var(--p600)', marginTop: 2 }}>{inr(monthly)} now · {emi.months - 1} more months</div>}
              </div>
              <div style={{ fontSize: 26, fontWeight: 800, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '-.02em', color: 'var(--n900)' }}>{inr(emi ? monthly : total)}</div>
            </div>
          </div>
        </div>

        {/* Trust strip */}
        <div className="row" style={{ gap: 10, padding: '4px 4px', flexWrap: 'wrap', fontSize: 10, color: 'var(--n500)' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="lock" size={11}/> 256-bit TLS</span>
          <span aria-hidden="true">·</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="shield" size={11}/> DPDPA 2023</span>
          <span aria-hidden="true">·</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="bank" size={11}/> RBI-licensed gateway</span>
          <span aria-hidden="true">·</span>
          <span>Receipt to your registered email</span>
        </div>
      </div>

      {/* Sticky pay button */}
      <div style={{ position: 'sticky', bottom: 0, padding: '12px 16px 22px', background: 'rgba(255,255,255,.94)', backdropFilter: 'blur(10px)', borderTop: '1px solid var(--n100)' }}>
        <button onClick={() => setBiometric(true)} disabled={chosen.length === 0} className="btn" style={{ height: 52, fontSize: 14, opacity: chosen.length === 0 ? .5 : 1 }}>
          <Icon name="lock" size={16}/> Pay {inr(emi ? monthly : total)} securely
        </button>
      </div>

      <BiometricGate
        open={biometric}
        amount={emi ? monthly : total}
        title="Confirm payment"
        sub={chosen.length + ' items · ' + childrenWithItems + ' children'}
        onCancel={() => setBiometric(false)}
        onAuthorize={() => {
          setBiometric(false);
          nav.replace('payPending', { total: emi ? monthly : total, method: emi ? `EMI · ${emi.months} months` : 'UPI', kind: 'multi' });
        }}
      />

      {/* EMI sheet */}
      <EMIPickerSheet open={showEmi} onClose={() => setShowEmi(false)} total={total} onPick={(months) => { setEmi(months ? { months, monthly: Math.ceil(total / months) } : null); setShowEmi(false); }}/>
    </div>
  );
}

function Row({ k, v, sub, tone }) {
  const c = tone === 'danger' ? 'var(--danger-600)' : tone === 'success' ? '#065F46' : 'var(--n900)';
  return (
    <div className="spread" style={{ alignItems: 'baseline' }}>
      <div>
        <div style={{ fontSize: 12, color: 'var(--n600)' }}>{k}</div>
        {sub && <div style={{ fontSize: 10, color: 'var(--n400)', marginTop: 1 }}>{sub}</div>}
      </div>
      <div style={{ fontSize: 13, fontWeight: 700, color: c, fontFamily: 'JetBrains Mono, monospace' }}>{v}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// EMIPickerSheet — bottom sheet to pick a tenure
// ─────────────────────────────────────────────────────────────
function EMIPickerSheet({ open, onClose, total = 0, onPick }) {
  const tenures = [
    { months: 0, label: 'Pay full', sub: 'Today · single charge', monthly: total, fee: 0 },
    { months: 3, label: '3 months', sub: 'No-cost EMI', monthly: Math.ceil(total / 3), fee: 0, badge: 'POPULAR' },
    { months: 6, label: '6 months', sub: 'No-cost EMI', monthly: Math.ceil(total / 6), fee: 0 },
    { months: 9, label: '9 months', sub: '0.49% / mo · ₹' + Math.round(total * 0.0049 * 9).toLocaleString('en-IN') + ' interest', monthly: Math.ceil(total / 9 * 1.0044), fee: Math.round(total * 0.0049 * 9) },
    { months: 12, label: '12 months', sub: '0.79% / mo · ₹' + Math.round(total * 0.0079 * 12).toLocaleString('en-IN') + ' interest', monthly: Math.ceil(total / 12 * 1.0079), fee: Math.round(total * 0.0079 * 12) }
  ];
  return (
    <BottomSheet open={open} onClose={onClose} title="Choose payment plan">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {tenures.map((t) => (
          <button key={t.months} onClick={() => onPick(t.months)} className="card" style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left', borderColor: 'var(--n100)' }}>
            <div style={{ width: 44, height: 44, borderRadius: 12, background: t.months === 0 ? 'var(--n50)' : 'var(--p50)', color: t.months === 0 ? 'var(--n500)' : 'var(--p600)', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 12 }}>{t.months === 0 ? '✓' : t.months + 'M'}</div>
            <div style={{ flex: 1 }}>
              <div className="row" style={{ gap: 6, alignItems: 'center' }}>
                <span style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--n900)' }}>{t.label}</span>
                {t.badge && <span className="chip" style={{ fontSize: 9, fontWeight: 800, color: 'var(--p700)', background: 'var(--p50)', padding: '2px 6px', borderRadius: 6, letterSpacing: '.05em' }}>{t.badge}</span>}
              </div>
              <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2 }}>{t.sub}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--n900)', fontFamily: 'JetBrains Mono, monospace' }}>{inr(t.monthly)}</div>
              <div style={{ fontSize: 10, color: 'var(--n400)' }}>{t.months === 0 ? 'one time' : '/ month'}</div>
            </div>
          </button>
        ))}
        <div style={{ fontSize: 10.5, color: 'var(--n400)', padding: '8px 4px', display: 'flex', gap: 6 }}>
          <Icon name="info" size={11}/>
          <span>Powered by GrayQuest. Soft credit pull only — won't affect your CIBIL. Subject to eligibility check.</span>
        </div>
      </div>
    </BottomSheet>
  );
}

// ─────────────────────────────────────────────────────────────
// ReceiptDetailScreen — opens from history; supports cheque & refund variants
// ─────────────────────────────────────────────────────────────
function ReceiptDetailScreen({ nav, params }) {
  const variant = params?.variant || 'digital'; // digital | cheque | refund | reversal
  const total = params?.total ?? 18500;
  const date = params?.date || 'Mar 14, 2026 · 11:42';
  const txnId = params?.txnId || 'TXN1284763901';
  const child = params?.child || 'Aarav Mehra · 8-B';

  const variants = {
    digital: { ic: 'check', tone: 'success', tag: 'Cleared', tint: '#065F46', bg: 'var(--success-50)' },
    cheque: { ic: 'document', tone: 'warn', tag: 'Cheque · awaiting clearance', tint: '#92400E', bg: 'var(--warn-50)' },
    refund: { ic: 'history', tone: 'info', tag: 'Refunded', tint: 'var(--p700)', bg: 'var(--p50)' },
    reversal: { ic: 'alert', tone: 'danger', tag: 'Auto-reversed by bank', tint: 'var(--danger-700)', bg: 'var(--danger-50)' }
  }[variant];

  return (
    <div className="screen-bg" style={{ minHeight: '100%' }} data-screen-label="ReceiptDetail">
      <PageHeader
        title="Receipt"
        subtitle={date}
        onBack={() => nav.pop()}
        right={<button aria-label="Download" style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--n50)', display: 'grid', placeItems: 'center' }}><Icon name="download" size={16}/></button>}
      />
      <div style={{ padding: '20px 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ padding: '20px 18px', background: variants.bg, borderBottom: '1px solid var(--n100)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ width: 38, height: 38, borderRadius: 11, background: '#fff', color: variants.tint, display: 'grid', placeItems: 'center' }}>
                <Icon name={variants.ic} size={18}/>
              </div>
              <div>
                <div style={{ fontSize: 11, color: variants.tint, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.06em' }}>{variants.tag}</div>
                <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--n900)', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '-.02em', marginTop: 2 }}>{variant === 'refund' ? '−' : ''}{inr(total)}</div>
              </div>
            </div>
            {variant === 'cheque' && <div style={{ fontSize: 11, color: '#92400E', marginTop: 10 }}>Cheque #{params?.chequeNo || '084'} · drawn on {params?.bank || 'HDFC Bank'} · expected to clear by {params?.clearBy || 'Mar 18'}</div>}
            {variant === 'refund' && <div style={{ fontSize: 11, color: 'var(--p700)', marginTop: 10 }}>Refunded to original UPI · {params?.refundReason || 'Class transfer adjustment'}</div>}
            {variant === 'reversal' && <div style={{ fontSize: 11, color: 'var(--danger-700)', marginTop: 10 }}>Bank auto-reversed within 24h · no action needed · safe to retry</div>}
          </div>
          <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <RowKV k="Student" v={child}/>
            <RowKV k="Reference" v={txnId} mono/>
            <RowKV k="Method" v={params?.method || (variant === 'cheque' ? 'Cheque' : 'UPI · @hdfc')}/>
            <RowKV k="Posted by" v={params?.postedBy || 'Suchitra (Accounts)'} sub="Last 4 of receipt #4827"/>
          </div>
          <div style={{ padding: '14px 18px', borderTop: '1px dashed var(--n100)', background: 'var(--n50)' }}>
            <div style={{ fontSize: 11, color: 'var(--n500)' }}>GST invoice queued for shekar@…@gmail.com</div>
          </div>
        </div>

        {variant === 'digital' && (
          <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
            <button className="row" style={{ width: '100%', padding: '14px 16px', gap: 12, background: 'transparent', textAlign: 'left', borderBottom: '1px solid var(--n100)' }}>
              <Icon name="download" size={16} color="var(--n600)"/>
              <span style={{ flex: 1, fontSize: 13, fontWeight: 600 }}>Download GST invoice (PDF)</span>
              <Icon name="chevron-right" size={16} color="var(--n300)"/>
            </button>
            <button className="row" style={{ width: '100%', padding: '14px 16px', gap: 12, background: 'transparent', textAlign: 'left', borderBottom: '1px solid var(--n100)' }}>
              <Icon name="mail" size={16} color="var(--n600)"/>
              <span style={{ flex: 1, fontSize: 13, fontWeight: 600 }}>Email receipt</span>
              <Icon name="chevron-right" size={16} color="var(--n300)"/>
            </button>
            <button onClick={() => nav.push('contactSupport')} className="row" style={{ width: '100%', padding: '14px 16px', gap: 12, background: 'transparent', textAlign: 'left' }}>
              <Icon name="flag" size={16} color="var(--danger-500)"/>
              <span style={{ flex: 1, fontSize: 13, fontWeight: 600, color: 'var(--danger-700)' }}>Report issue</span>
              <Icon name="chevron-right" size={16} color="var(--n300)"/>
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

function RowKV({ k, v, sub, mono }) {
  return (
    <div className="spread" style={{ alignItems: 'baseline' }}>
      <div style={{ fontSize: 11, color: 'var(--n500)' }}>{k}</div>
      <div style={{ textAlign: 'right' }}>
        <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--n900)', fontFamily: mono ? 'JetBrains Mono, monospace' : 'inherit' }}>{v}</div>
        {sub && <div style={{ fontSize: 10, color: 'var(--n400)', marginTop: 1 }}>{sub}</div>}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// LateFeeBadge — small inline badge usable in fees screen
// ─────────────────────────────────────────────────────────────
function LateFeeBadge({ daysOverdue, ratePerDay = 25, label }) {
  if (!daysOverdue || daysOverdue <= 0) return null;
  const fee = daysOverdue * ratePerDay;
  return (
    <div className="row" style={{ gap: 8, padding: '8px 10px', background: 'var(--danger-50)', border: '1px solid var(--danger-200)', borderRadius: 9, fontSize: 11 }}>
      <Icon name="alert" size={12} color="var(--danger-600)"/>
      <span style={{ color: 'var(--danger-700)', fontWeight: 700 }}>+{inr(fee)}</span>
      <span style={{ color: 'var(--danger-700)', opacity: .8 }}>{label || `late fee · ${daysOverdue}d × ${inr(ratePerDay)}/day`}</span>
    </div>
  );
}

// Pulse keyframe — local CSS once
(() => {
  if (document.getElementById('sp-pay-anim')) return;
  const s = document.createElement('style');
  s.id = 'sp-pay-anim';
  s.textContent = `@keyframes sp-pulse { 0%, 100% { transform: scale(1); opacity: 1 } 50% { transform: scale(1.6); opacity: .4 } }`;
  document.head.appendChild(s);
})();

Object.assign(window, {
  PayPendingScreen, PayFailureScreen, MultiChildPayScreen,
  EMIPickerSheet, ReceiptDetailScreen, LateFeeBadge
});
