/* ============================================================================
   BetPrince Sportsbook — Screens & chrome. Depends on sb-atoms.jsx.
   ============================================================================ */

/* ---- Live match card (home) ----------------------------------------------- */
function LiveCard({ m, pick, onPick, onOpen }) {
  return (
    <div style={{ width: 290, flexShrink: 0, background: 'var(--card)', borderRadius: 16,
      border: '1px solid var(--line)', boxShadow: 'var(--shadow-card)', padding: 14 }}>
      <div onClick={() => onOpen && onOpen(m)} style={{ cursor: onOpen ? 'pointer' : 'default' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
        <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 12.5, color: 'var(--ink-2)' }}>{m.lg}</span>
        {m.live ? (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'var(--live-bg)',
            color: 'var(--live)', padding: '3px 9px', borderRadius: 999, fontFamily: 'var(--font-text)',
            fontWeight: 700, fontSize: 11 }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--live)' }} />LIVE
          </span>
        ) : (
          <span className="sb-num" style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{m.when}</span>
        )}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: 14 }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, width: 76 }}>
          <Crest id={m.h} size={36} />
          <span style={{ fontSize: 12.5, fontWeight: 600, textAlign: 'center', color: 'var(--ink)', lineHeight: 1.2 }}>{SB_TEAMS[m.h].name}</span>
        </div>
        <div style={{ textAlign: 'center', flexShrink: 0, minWidth: 64 }}>
          {m.live
            ? <div className="sb-num" style={{ fontWeight: 700, fontSize: 26, color: 'var(--ink)', whiteSpace: 'nowrap', lineHeight: 1 }}>{m.hs}&thinsp;-&thinsp;{m.as}</div>
            : <div style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14, color: 'var(--ink-3)' }}>VS</div>}
          {m.live && <div className="sb-num" style={{ fontSize: 11, color: 'var(--live)', marginTop: 4, whiteSpace: 'nowrap' }}>{m.min}'</div>}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, width: 76 }}>
          <Crest id={m.a} size={36} />
          <span style={{ fontSize: 12.5, fontWeight: 600, textAlign: 'center', color: 'var(--ink)', lineHeight: 1.2 }}>{SB_TEAMS[m.a].name}</span>
        </div>
      </div>
      </div>
      <div style={{ display: 'flex', gap: 7 }}>
        {['1', 'X', '2'].map((lab, i) => (
          <OddsBtn key={lab} label={lab} value={m.o[i]} picked={pick === i} onClick={() => onPick(m, i, lab)} />
        ))}
      </div>
    </div>
  );
}

function SportsHome({ matches, picks, onPick, onBrowse, onSupport, onOpen, winners, onLoadCode, onNavigate }) {
  const live = matches.filter(m => m.live);
  return (
    <div>
      {/* promo banner — bold branded, with a drop-in player photo slot */}
      <div style={{ margin: '14px 14px 14px', borderRadius: 16, overflow: 'hidden', position: 'relative',
        background: '#13151A',
        backgroundImage: 'repeating-linear-gradient(45deg, rgba(255,255,255,0.03) 0 2px, transparent 2px 10px)' }}>
        {/* hazard stripes, top-right */}
        <div style={{ position: 'absolute', top: 0, right: 0, width: 150, height: 26,
          background: 'repeating-linear-gradient(45deg, #F7C53D 0 11px, #13151A 11px 17px, #E0431E 17px 28px, #13151A 28px 34px)',
          clipPath: 'polygon(28% 0, 100% 0, 100% 100%, 0 100%)' }} />
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
          padding: '15px 16px', position: 'relative' }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font-text)', fontWeight: 800, fontSize: 10.5, letterSpacing: '0.12em',
              textTransform: 'uppercase', color: 'var(--gold)' }}>First deposit</div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 28, lineHeight: 1,
              color: '#fff', letterSpacing: '-0.02em', margin: '3px 0 5px', whiteSpace: 'nowrap' }}>
              BONUS <span style={{ color: 'var(--gold)' }}>×2</span>
            </div>
            <div style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 12.5, color: 'rgba(255,255,255,0.7)' }}>100% up to ₦50,000</div>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 11, background: 'var(--gold)',
              color: 'var(--gold-ink)', padding: '7px 14px', borderRadius: 8, fontFamily: 'var(--font-text)',
              fontWeight: 700, fontSize: 12.5, whiteSpace: 'nowrap' }}>
              Claim now <Icon name="chevron-right" size={14} />
            </span>
          </div>
          <image-slot id="promo-player" shape="rounded" radius="14" placeholder="Drop photo"
            src="uploads/pasted-1780613947891-0.png"
            style={{ width: '100px', height: '100px', flexShrink: 0, background: 'rgba(255,255,255,0.06)',
              boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.16)', borderRadius: '14px' }}></image-slot>
        </div>
      </div>
      <QuickActions onPick={(k) => {
        if (k === 'code' && onLoadCode) onLoadCode();
        else if (k === 'football') onBrowse('all');
        else if (k === 'live') onBrowse('live');
      }} />
      {/* Live section */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 16px 12px' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 8, height: 8, borderRadius: 999, background: 'var(--live)' }} />
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 19, color: 'var(--ink)' }}>Live</span>
        </span>
        <button onClick={() => onBrowse('live')} style={{ background: 'var(--blue-tint)', color: 'var(--blue)', border: 'none',
          borderRadius: 999, padding: '7px 14px', fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 12.5,
          cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0 }}>View all</button>
      </div>
      <div className="sb-hx" style={{ display: 'flex', gap: 12, padding: '0 14px 6px', overflowX: 'auto', scrollbarWidth: 'none' }}>
        {live.map(m => {
          const p = picks.find(x => x.matchId === m.id);
          return <LiveCard key={m.id} m={m} pick={p ? p.outcome : null} onPick={onPick} onOpen={onOpen} />;
        })}
      </div>
      {/* Today / scheduled */}
      <TodaySection matches={matches} picks={picks} onOpen={onOpen} onPick={onPick} onBrowse={() => onBrowse('all')} />
      {/* Recent winners */}
      <RecentWinners winners={winners} />
      {/* Footer */}
      <BPFooter onNavigate={onNavigate} />
    </div>
  );
}

/* ---- Open Bets / Bet History ---------------------------------------------- */
function StatusTag({ bet, onTint }) {
  let label = 'Open', color = onTint ? 'rgba(255,255,255,0.9)' : 'var(--ink-2)', icon = 'clock';
  if (bet.cashedout) { label = 'Cashed out'; color = onTint ? '#fff' : 'var(--green)'; icon = 'check'; }
  else if (!bet.open && bet.won) { label = 'Won'; color = onTint ? '#fff' : 'var(--green)'; icon = 'trophy'; }
  else if (!bet.open) { label = 'Lost'; color = onTint ? 'rgba(255,255,255,0.7)' : 'var(--live)'; icon = 'x'; }
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontFamily: 'var(--font-text)',
      fontWeight: 700, fontSize: 14, color }}>
      <Icon name={icon} size={15} />{label}
    </span>
  );
}

function BetCard({ bet, onCashout, onOpen }) {
  return (
    <div style={{ background: 'var(--card)', borderRadius: 16, border: '1px solid var(--line)',
      boxShadow: 'var(--shadow-card)', padding: 16, marginBottom: 12 }}>
      <div onClick={() => onOpen && onOpen(bet)} style={{ cursor: 'pointer' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          paddingBottom: 12, borderBottom: '1px solid var(--line)', marginBottom: 12 }}>
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15, color: 'var(--ink)' }}>
            {bet.picks.length > 1 ? 'Multiple' : 'Single'}
          </span>
          {!bet.open ? <StatusTag bet={bet} /> : (
            <button onClick={(e) => { e.stopPropagation(); onOpen && onOpen(bet); }}
              style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'var(--blue-tint)',
                color: 'var(--blue)', border: 'none', borderRadius: 999, padding: '7px 14px', cursor: 'pointer',
                fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 13 }}>
              Open <Icon name="chevron-right" size={15} />
            </button>
          )}
        </div>
        {bet.picks.map(p => (
          <div key={p.key} style={{ marginBottom: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 4 }}>
              <Icon name="volleyball" size={15} color="var(--ink-2)" />
              <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14.5, color: 'var(--ink)' }}>
                {p.sel} <span className="sb-num" style={{ color: 'var(--blue)' }}>@ {p.odds}</span>
              </span>
              <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 11.5, color: 'var(--ink-3)' }}>{p.market || '1X2'}</span>
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)', textDecoration: 'underline', textDecorationColor: 'var(--line-2)' }}>{p.match}</div>
            {p.when && <div className="sb-num" style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{p.when}</div>}
          </div>
        ))}
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
          <span style={{ fontSize: 13.5, color: 'var(--ink-2)' }}>Stake</span>
          <span className="sb-num" style={{ fontWeight: 700, fontSize: 14, color: 'var(--ink)' }}>{bet.stake.toFixed(2)}</span>
        </div>
        {(!bet.open && !bet.won && !bet.cashedout) ? null : (
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: bet.open ? 14 : 0 }}>
          <span style={{ fontSize: 13.5, color: 'var(--ink-2)' }}>Pot. Win</span>
          <span className="sb-num" style={{ fontWeight: 700, fontSize: 14, color: 'var(--green)' }}>{bet.cashedout ? bet.cashout.toFixed(2) : bet.potwin}</span>
        </div>
        )}
      </div>
      {bet.open
        ? <GreenBtn full onClick={() => onCashout(bet.id)}>Cashout {fmtNGN(bet.cashout)}</GreenBtn>
        : bet.cashedout
          ? <div style={{ textAlign: 'center', padding: '12px', borderRadius: 10, background: 'var(--card-2)',
              color: 'var(--green)', fontWeight: 700, fontFamily: 'var(--font-text)', fontSize: 14 }}>Cashed out {fmtNGN(bet.cashout)}</div>
          : <div style={{ textAlign: 'center', padding: '12px', borderRadius: 10, background: 'var(--card-2)',
              color: bet.won ? 'var(--green)' : 'var(--ink-3)', fontWeight: 700, fontFamily: 'var(--font-text)', fontSize: 14 }}>{bet.won ? `Won ${fmtNGN(bet.potwin)}` : 'Lost'}</div>}
    </div>
  );
}

function BetsScreen({ bets, onCashout, onOpenTicket, initialTab }) {
  const [tab, setTab] = useState(initialTab || 'open');
  const [filter, setFilter] = useState('All');
  const open = bets.filter(b => b.open);
  const history = bets.filter(b => !b.open);
  const liveIds = new Set((typeof SB_MATCHES !== 'undefined' ? SB_MATCHES : []).filter(m => m.live).map(m => m.id));
  const isLiveBet = (b) => (b.picks || []).some(p =>
    liveIds.has(p.matchId) || (typeof p.when === 'string' && p.when.toUpperCase().includes('LIVE')));
  let shown = tab === 'open' ? open : history;
  if (tab === 'open') {
    if (filter === 'Live') shown = shown.filter(isLiveBet);
  } else {
    if (filter === 'Won') shown = shown.filter(b => b.won);
    else if (filter === 'Lost') shown = shown.filter(b => !b.won && !b.cashedout);
  }
  const filters = tab === 'open' ? ['All', 'Live'] : ['All', 'Won', 'Lost'];
  return (
    <div>
      {/* sub tabs */}
      <div style={{ display: 'flex', background: 'var(--card)', borderBottom: '1px solid var(--line)' }}>
        {[['open', 'Open Bets'], ['history', 'Bet History']].map(([k, l]) => (
          <button key={k} onClick={() => { setTab(k); setFilter('All'); }} style={{ flex: 1, background: 'transparent', border: 'none',
            cursor: 'pointer', padding: '15px 0', fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14.5,
            color: tab === k ? 'var(--blue)' : 'var(--ink-3)',
            borderBottom: '2px solid ' + (tab === k ? 'var(--blue)' : 'transparent') }}>{l}</button>
        ))}
      </div>
      {/* filters */}
      <div className="sb-hx" style={{ display: 'flex', gap: 8, padding: '14px 16px 6px', overflowX: 'auto', scrollbarWidth: 'none' }}>
        {filters.map(f => (
          <Chip key={f} on={filter === f} onClick={() => setFilter(f)}>{f}</Chip>
        ))}
      </div>
      <div style={{ padding: '12px 16px 24px' }}>
        {shown.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '70px 30px', color: 'var(--ink-3)' }}>
            <Icon name="ticket" size={40} color="var(--ink-3)" />
            <div style={{ marginTop: 14, fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 15, color: 'var(--ink-2)' }}>
              {tab === 'open' ? 'No open bets here.' : 'No settled bets yet.'}
            </div>
            <div style={{ marginTop: 4, fontSize: 13 }}>Pick a market and place a bet to see it here.</div>
          </div>
        ) : shown.map(b => <BetCard key={b.id} bet={b} onCashout={onCashout} onOpen={onOpenTicket} />)}
      </div>
    </div>
  );
}

/* ---- Bet slip sheet -------------------------------------------------------- */
function BetSlipSheet({ open, picks, stake, setStake, onRemove, onClose, onPlace, potwin }) {
  return (
    <>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 60, background: 'var(--scrim)',
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none', transition: 'opacity 220ms' }} />
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 70, background: 'var(--card)',
        borderRadius: '24px 24px 0 0', boxShadow: 'var(--shadow-pop)', padding: '10px 0 28px', maxHeight: '84%',
        display: 'flex', flexDirection: 'column', transform: open ? 'translateY(0)' : 'translateY(110%)',
        transition: 'transform 300ms cubic-bezier(0.22,1,0.36,1)' }}>
        <div style={{ width: 38, height: 4, borderRadius: 999, background: 'var(--line-2)', margin: '0 auto 12px' }} />
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 18px 12px' }}>
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 19, color: 'var(--ink)' }}>
            {picks.length > 1 ? 'Multiple' : 'Bet slip'}
          </span>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--ink-3)' }}>
            <Icon name="x" size={22} />
          </button>
        </div>
        <div style={{ overflowY: 'auto', padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
          {picks.length === 0 && (
            <div style={{ textAlign: 'center', padding: '30px 20px', color: 'var(--ink-3)', fontSize: 14 }}>
              Your bet slip is empty. Tap an odd to add a selection.
            </div>
          )}
          {picks.map(p => (
            <div key={p.key} style={{ background: 'var(--card-2)', borderRadius: 12, border: '1px solid var(--line)', padding: 13 }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14.5, color: 'var(--ink)' }}>{p.sel}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{p.match}</div>
                </div>
                <span className="sb-num" style={{ fontWeight: 700, fontSize: 15, color: 'var(--blue)' }}>{p.odds}</span>
                <button onClick={() => onRemove(p.key)} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', padding: 0 }}>
                  <Icon name="x" size={16} />
                </button>
              </div>
            </div>
          ))}
        </div>
        {picks.length > 0 && (
          <div style={{ padding: '14px 18px 0', marginTop: 8, borderTop: '1px solid var(--line)' }}>
            <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
              {[100, 500, 1000].map(v => (
                <button key={v} onClick={() => setStake(v)} style={{ flex: 1, padding: '9px', borderRadius: 9,
                  background: 'var(--card-2)', border: '1px solid var(--line)', color: 'var(--ink-2)', cursor: 'pointer',
                  fontFamily: 'var(--font-num)', fontWeight: 600, fontSize: 13 }}>₦{v}</button>
              ))}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
              <span style={{ fontWeight: 600, fontSize: 14, color: 'var(--ink-2)' }}>Stake</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: 'var(--card-2)',
                border: '1px solid var(--line-2)', borderRadius: 10, padding: '9px 14px' }}>
                <span className="sb-num" style={{ color: 'var(--ink-3)' }}>₦</span>
                <span className="sb-num" style={{ fontWeight: 700, fontSize: 16, color: 'var(--ink)' }}>{stake.toFixed(2)}</span>
              </span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
              <span style={{ fontSize: 13.5, color: 'var(--ink-2)' }}>Potential win</span>
              <span className="sb-num" style={{ fontWeight: 700, fontSize: 19, color: 'var(--green)' }}>{potwin}</span>
            </div>
            <GoldBtn full onClick={onPlace}>Place bet · ₦{stake.toFixed(2)}</GoldBtn>
          </div>
        )}
      </div>
    </>
  );
}

/* ---- Bottom nav with center gold Bet-slip FAB ----------------------------- */
function BottomNav({ active, onChange, slipCount, onOpenSlip }) {
  const left = [{ k: 'sports', label: 'Sports', icon: 'house' }, { k: 'support', label: 'Support', icon: 'headphones' }];
  const right = [{ k: 'deposit', label: 'Deposit', icon: 'circle-dollar-sign' }, { k: 'bets', label: 'Bets', icon: 'receipt-text' }, { k: 'me', label: 'Me', icon: 'user' }];
  const item = (it) => {
    const on = active === it.k;
    return (
      <button key={it.k} onClick={() => onChange(it.k)} style={{ flex: 1, background: 'transparent', border: 'none',
        cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, padding: '8px 0',
        color: on ? 'var(--nav-active)' : 'var(--nav-ink)' }}>
        <Icon name={it.icon} size={21} />
        <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 10.5 }}>{it.label}</span>
      </button>
    );
  };
  return (
    <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 50, background: 'var(--nav-bg)',
      borderTop: '1px solid var(--line)', padding: '4px 6px calc(10px + env(safe-area-inset-bottom))',
      display: 'flex', alignItems: 'flex-end' }}>
      {left.map(item)}
      {/* center FAB */}
      <div style={{ flex: 1, display: 'flex', justifyContent: 'center', position: 'relative' }}>
        <button onClick={onOpenSlip} style={{ position: 'absolute', bottom: 6, width: 58, height: 58, borderRadius: 999,
          background: 'var(--gold)', border: '4px solid var(--nav-bg)', cursor: 'pointer', color: 'var(--gold-ink)',
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 6px 16px rgba(0,0,0,0.18)' }}>
          <Icon name="receipt-text" size={22} />
          {slipCount > 0 && (
            <span className="sb-num" style={{ position: 'absolute', top: -2, right: -2, minWidth: 20, height: 20,
              borderRadius: 999, background: 'var(--live)', color: '#fff', fontSize: 11, fontWeight: 700,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', padding: '0 5px',
              border: '2px solid var(--nav-bg)' }}>{slipCount}</span>
          )}
        </button>
        <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 10.5, color: 'var(--gold-strong)',
          marginTop: 'auto', paddingBottom: 8 }}>Bet slip</span>
      </div>
      {right.map(item)}
    </div>
  );
}

/* ---- Simple stub screens --------------------------------------------------- */
function StubScreen({ icon, title, sub }) {
  return (
    <div style={{ textAlign: 'center', padding: '90px 36px', color: 'var(--ink-3)' }}>
      <Icon name={icon} size={42} color="var(--ink-3)" />
      <div style={{ marginTop: 16, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 19, color: 'var(--ink-2)' }}>{title}</div>
      <div style={{ marginTop: 6, fontSize: 13.5 }}>{sub}</div>
    </div>
  );
}

/* ---- Win celebration overlay (shared) ------------------------------------- */
(function injectWinCSS() {
  if (typeof document === 'undefined' || document.getElementById('sbw-style')) return;
  const s = document.createElement('style');
  s.id = 'sbw-style';
  s.textContent = `
  .sbw-overlay { position:absolute; inset:0; z-index:200; display:flex; flex-direction:column; align-items:center; justify-content:center; padding:24px 22px;
    background: radial-gradient(120% 80% at 50% 32%, rgba(10,12,22,0.66) 0%, rgba(6,7,12,0.80) 72%); overflow:hidden;
    animation: sbw-fade .32s cubic-bezier(0.22,1,0.36,1) both; }
  @keyframes sbw-fade { from{opacity:0;} to{opacity:1;} }
  .sbw-close { position:absolute; top:16px; right:16px; z-index:4; width:38px; height:38px; border-radius:999px; border:none; cursor:pointer; background:rgba(255,255,255,0.10); color:#fff; display:flex; align-items:center; justify-content:center; transition:background .12s; }
  .sbw-close:hover { background:rgba(255,255,255,0.2); }
  .sbw-halo { position:absolute; left:50%; top:37%; transform:translate(-50%,-50%); width:440px; height:440px; pointer-events:none; z-index:1;
    background: radial-gradient(circle, rgba(247,197,61,0.28) 0%, rgba(247,197,61,0.10) 34%, rgba(247,197,61,0) 64%);
    animation: sbw-breathe 3.2s ease-in-out infinite; }
  @keyframes sbw-breathe { 0%,100%{opacity:.75; transform:translate(-50%,-50%) scale(1);} 50%{opacity:1; transform:translate(-50%,-50%) scale(1.06);} }
  .sbw-content { position:relative; z-index:3; width:100%; max-width:420px; display:flex; flex-direction:column; align-items:center; text-align:center; }
  .sbw-eyebrow { display:inline-flex; align-items:center; gap:7px; font-family:var(--font-text); font-weight:800; font-size:12px; letter-spacing:0.04em; color:var(--gold); opacity:0; animation:sbw-rise .32s cubic-bezier(0.22,1,0.36,1) .12s both; }
  .sbw-trophy { width:210px; height:auto; display:block; margin:2px 0; filter:drop-shadow(0 18px 34px rgba(247,197,61,0.34)); opacity:0; animation:sbw-pop 620ms cubic-bezier(0.22,1,0.36,1) .18s both; }
  @keyframes sbw-pop { 0%{opacity:0; transform:translateY(14px) scale(0.86);} 60%{opacity:1; transform:translateY(0) scale(1.04);} 100%{opacity:1; transform:translateY(0) scale(1);} }
  .sbw-title { font-family:var(--font-display); font-weight:700; font-size:26px; letter-spacing:-0.01em; color:#fff; margin:4px 0 0; opacity:0; animation:sbw-rise .32s cubic-bezier(0.22,1,0.36,1) .30s both; }
  .sbw-amount { font-family:var(--font-num); font-weight:700; font-size:40px; line-height:1.04; letter-spacing:-0.02em; margin:6px 0 4px; white-space:nowrap; font-feature-settings:"tnum" 1,"lnum" 1; color:#2CD980; text-shadow:0 6px 28px rgba(44,217,128,0.45); opacity:0; animation:sbw-rise .32s cubic-bezier(0.22,1,0.36,1) .38s both; }
  .sbw-sub { font-family:var(--font-text); font-weight:500; font-size:13.5px; color:rgba(255,255,255,0.62); margin:0 0 18px; opacity:0; animation:sbw-rise .32s cubic-bezier(0.22,1,0.36,1) .46s both; }
  .sbw-sub b { color:rgba(255,255,255,0.92); font-weight:700; }
  .sbw-verify { display:inline-flex; align-items:center; gap:9px; margin-bottom:22px; opacity:0; animation:sbw-rise .32s cubic-bezier(0.22,1,0.36,1) .54s both; }
  .sbw-vk { font-family:var(--font-text); font-weight:600; font-size:11px; letter-spacing:0.04em; text-transform:uppercase; color:rgba(255,255,255,0.5); }
  .sbw-vc { font-family:var(--font-num); font-weight:700; font-size:13.5px; letter-spacing:0.06em; color:var(--gold); }
  .sbw-cp { width:26px; height:26px; border-radius:999px; background:rgba(255,255,255,0.10); display:flex; align-items:center; justify-content:center; color:rgba(255,255,255,0.85); }
  .sbw-actions { display:flex; gap:12px; width:100%; max-width:360px; opacity:0; animation:sbw-rise .32s cubic-bezier(0.22,1,0.36,1) .62s both; }
  .sbw-btn { flex:1; height:54px; border-radius:14px; cursor:pointer; white-space:nowrap; font-family:var(--font-text); font-weight:700; font-size:16px; display:inline-flex; align-items:center; justify-content:center; gap:8px; transition: filter .12s, background .12s, transform .12s; }
  .sbw-btn:active { transform:scale(0.975); }
  .sbw-ghost { background:transparent; color:#fff; border:1.5px solid rgba(255,255,255,0.28); }
  .sbw-ghost:hover { background:rgba(255,255,255,0.08); }
  .sbw-primary { background:var(--gold); color:var(--gold-ink); border:none; box-shadow:0 10px 30px rgba(247,197,61,0.36); }
  .sbw-primary:hover { filter:brightness(1.05); }
  @keyframes sbw-rise { from{opacity:0; transform:translateY(12px);} to{opacity:1; transform:translateY(0);} }
  .sbw-confetti-layer { position:absolute; inset:0; z-index:2; pointer-events:none; overflow:hidden; }
  .sbw-confetti { position:absolute; top:-8%; will-change:transform,opacity; animation: sbw-fall linear forwards; }
  @keyframes sbw-fall { 0%{transform:translateY(-10vh) rotate(0deg); opacity:0;} 8%{opacity:1;} 100%{transform:translateY(112vh) rotate(720deg); opacity:1;} }
  @media (prefers-reduced-motion: reduce){ .sbw-overlay,.sbw-eyebrow,.sbw-trophy,.sbw-title,.sbw-amount,.sbw-sub,.sbw-verify,.sbw-actions{animation:none!important;opacity:1!important;} .sbw-halo{animation:none!important;} .sbw-confetti{display:none;} }
  `;
  document.head.appendChild(s);
})();

const SBW_CONFETTI_COLORS = ['#F7C53D', '#FF4D2E', '#2CD980', '#4664FF', '#FFFFFF'];
function SbWinConfetti({ burstKey }) {
  const pieces = React.useMemo(() => Array.from({ length: 64 }).map((_, i) => {
    const round = Math.random() > 0.7, size = 6 + Math.random() * 7;
    return { id: i + '-' + burstKey, left: Math.random() * 100, dur: 2.4 + Math.random() * 2,
      delay: Math.random() * 0.5, size, color: SBW_CONFETTI_COLORS[i % 5], round };
  }), [burstKey]);
  return (
    <div className="sbw-confetti-layer" aria-hidden="true">
      {pieces.map(p => (
        <span key={p.id} className="sbw-confetti" style={{ left: p.left + '%',
          width: p.round ? p.size : p.size * 0.62, height: p.round ? p.size : p.size * 1.1,
          borderRadius: p.round ? '999px' : '2px', background: p.color,
          animationDuration: p.dur + 's', animationDelay: p.delay + 's' }} />
      ))}
    </div>
  );
}

function sbVerifyCode(id) {
  let h = 2166136261 >>> 0; const s = String(id || 'BP');
  for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0; }
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; let out = '';
  for (let i = 0; i < 11; i++) { h ^= h << 13; h >>>= 0; h ^= h >> 17; h ^= h << 5; h >>>= 0; out += chars[(h >>> 3) % chars.length]; }
  return out;
}

function SbWinOverlay({ bet, amount, legs, burstKey, onClose }) {
  useEffect(() => { if (window.lucide) window.lucide.createIcons(); });
  const node = (
    <div className="sbw-overlay" role="dialog" aria-modal="true" aria-label="You won">
      <SbWinConfetti burstKey={burstKey} />
      <div className="sbw-halo" />
      <button className="sbw-close" onClick={onClose} aria-label="Close"><Icon name="x" size={20} /></button>
      <div className="sbw-content">
        <span className="sbw-eyebrow"><Icon name="crown" size={13} color="var(--gold)" />betprince.net</span>
        <img className="sbw-trophy" src="trophy.png" alt="Gold trophy" />
        <h1 className="sbw-title">You won</h1>
        <div className="sbw-amount">{fmtNGN(amount)}</div>
        <p className="sbw-sub">{legs > 1 ? 'Multiple' : 'Single'} · <b>{legs} of {legs}</b> {legs > 1 ? 'legs' : 'leg'} landed at <b>{bet.totalOdds}</b></p>
        <div className="sbw-verify"><span className="sbw-vk">Verify code</span><span className="sbw-vc">{sbVerifyCode(bet.ticketId)}</span></div>
        <div className="sbw-actions">
          <button className="sbw-btn sbw-ghost" onClick={onClose}>Details</button>
          <button className="sbw-btn sbw-primary" type="button" onClick={onClose}>Show off</button>
        </div>
      </div>
    </div>
  );
  const target = (typeof document !== 'undefined') && document.querySelector('.phone');
  return target ? ReactDOM.createPortal(node, target) : node;
}

/* ---- Ticket Details (full screen) ----------------------------------------- */
function TicketDetails({ bet, onBack, onCashout }) {
  const won = !bet.open && bet.won;
  const lost = !bet.open && !bet.won && !bet.cashedout;
  const bonus = parseFloat(bet.potwin) * 0.03;
  const returnLabel = won ? 'Total Return' : bet.cashedout ? 'Cashed out' : 'Potential Return';
  const returnValue = bet.cashedout ? bet.cashout : (parseFloat(bet.potwin) + bonus);
  const legs = bet.picks.length;
  const payout = parseFloat(bet.potwin) + bonus;
  const [showWin, setShowWin] = useState(false);
  const [burst, setBurst] = useState(0);
  // First time you open one of your own won tickets, the celebration pops up once.
  useEffect(() => {
    if (!won) return;
    const seen = 'bp_won_seen_' + bet.ticketId;
    if (!localStorage.getItem(seen)) {
      localStorage.setItem(seen, '1');
      const t = setTimeout(() => { setShowWin(true); setBurst(b => b + 1); }, 380);
      return () => clearTimeout(t);
    }
  }, [won, bet.ticketId]);
  const openWin = () => { setShowWin(true); setBurst(b => b + 1); };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', minHeight: '100%', background: 'var(--card)' }}>
      {/* sub-header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
        background: 'var(--header-bg)' }}>
        <button onClick={onBack} style={{ width: 36, height: 36, borderRadius: 999, border: 'none',
          background: 'rgba(255,255,255,0.16)', color: 'var(--header-ink)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="chevron-left" size={20} />
        </button>
        <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 17, color: 'var(--header-ink)' }}>Ticket details</span>
      </div>

      {/* summary */}
      <div style={{ background: 'var(--ticket-top)', padding: '16px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, color: 'rgba(255,255,255,0.82)' }}>
            <Icon name="ticket" size={16} />
            <span style={{ fontSize: 12.5 }}>Ticket ID</span>
            <span className="sb-num" style={{ fontWeight: 700, fontSize: 13, color: '#fff' }}>{bet.ticketId}</span>
          </span>
          <span className="sb-num" style={{ fontSize: 12, color: 'rgba(255,255,255,0.82)' }}>{bet.createdAt}</span>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, color: '#fff' }}>
            {bet.picks.length > 1 ? 'Multiple' : 'Single'}
          </span>
          <StatusTag bet={bet} onTint />
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12, marginBottom: 14 }}>
          <span style={{ fontSize: 13, color: 'rgba(255,255,255,0.85)' }}>{returnLabel}</span>
          <span className="sb-num" style={{ fontWeight: 700, fontSize: 30,
            color: won ? '#5BF0A0' : lost ? 'rgba(255,255,255,0.35)' : '#fff',
            letterSpacing: '-0.02em', textAlign: 'right',
            textDecoration: lost ? 'line-through' : 'none',
            textDecorationColor: lost ? 'rgba(255,255,255,0.25)' : undefined }}>
            {fmtNGN(returnValue)}
          </span>
        </div>
        {[['Total Stake', fmtNGN(bet.stake)], ['Total Odds', bet.totalOdds], ['Total Bonus', fmtNGN(bonus.toFixed(2))]].map(([k, v]) => (
          <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '5px 0' }}>
            <span style={{ fontSize: 13.5, color: 'rgba(255,255,255,0.82)' }}>{k}</span>
            <span className="sb-num" style={{ fontWeight: 700, fontSize: 14, color: '#fff' }}>{v}</span>
          </div>
        ))}
      </div>

      {/* inset divider — skip when the dark won banner follows, so the white card strip doesn't show */}
      {!won && (
        <div style={{ background: 'var(--card)' }}><div style={{ height: 1, background: 'var(--line)', margin: '0 16px' }}></div></div>
      )}

      {/* won celebration banner */}
      {won && (
        <div style={{ background: '#13151A', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          gap: 12, padding: '14px 16px' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 11, minWidth: 0 }}>
            <span style={{ fontSize: 22, lineHeight: 1 }}>🎉</span>
            <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 15, color: '#fff' }}>Congratulations! You are Amazing!</span>
          </span>
          <button onClick={openWin} style={{ flexShrink: 0, background: 'var(--gold)', color: 'var(--gold-ink)', border: 'none',
            borderRadius: 9, padding: '9px 16px', fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 13.5,
            cursor: 'pointer' }}>Show Off</button>
        </div>
      )}



      {/* games */}
      <div style={{ background: 'var(--card)', padding: '8px 16px 24px' }}>
        {bet.picks.map((p, i) => (
          <React.Fragment key={p.key}>
          <div style={{ padding: '16px 0', position: 'relative' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 6, position: 'relative' }}>
              <span className="sb-num" style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>Game {(Math.abs([...p.key].reduce((a, c) => (a * 31 + c.charCodeAt(0)) >>> 0, 7)) % 9000 + 1000)}</span>
              {p.when && <span className="sb-num" style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>| {p.when}</span>}
            </div>
            <div style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 16, color: 'var(--ink)', marginBottom: 8 }}>{p.match}</div>
            <div style={{ marginBottom: 12 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: (!bet.open && p.ft) ? 9 : 0 }}>
                <Icon name="activity" size={15} color="var(--green)" />
                <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 13.5, color: 'var(--green)' }}>Match Tracker</span>
                {bet.open && (
                  <span style={{ marginLeft: 8, display: 'inline-flex', alignItems: 'center', gap: 5, color: 'var(--ink-3)' }}>
                    <Icon name="clock" size={14} /><span style={{ fontSize: 12.5 }}>To be played</span>
                  </span>
                )}
              </div>
              {!bet.open && p.ft && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                  <span style={{ width: 22, height: 22, borderRadius: 999,
                    background: p.win === false ? 'var(--live)' : 'var(--green)',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <Icon name={p.win === false ? 'x' : 'check'} size={14} color="#fff" style={{ strokeWidth: 3.25 }} />
                  </span>
                  <span className="sb-num" style={{ fontWeight: 700, fontSize: 14, color: 'var(--ink)', whiteSpace: 'nowrap' }}>FT Score: {p.ft}</span>
                </div>
              )}
              {!bet.open && !p.ft && (
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, color: 'var(--ink-3)' }}>
                  <Icon name="clock" size={14} /><span style={{ fontSize: 12.5 }}>Settled</span>
                </div>
              )}
            </div>
            <div style={{ background: 'var(--card-2)', border: '1px solid ' + (p.win === false ? 'rgba(239,68,68,0.25)' : 'var(--line-2)'), borderRadius: 12, padding: 13, position: 'relative', overflow: 'hidden' }}>
              {/* red accent stripe for lost picks */}
              {p.win === false && (
                <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 4, background: 'var(--live)' }} />
              )}
              {/* trophy watermark for won picks */}
              {p.win && (
                <svg viewBox="0 0 120 130" style={{ position: 'absolute', right: -6, bottom: -10, width: 90, height: 100, opacity: 0.12, pointerEvents: 'none' }}>
                  <path d="M30 20h60v10c0 20-10 34-22 40v10h8c2 0 4 2 4 4v6H40v-6c0-2 2-4 4-4h8V70C40 64 30 50 30 30V20z" fill="var(--green)"/>
                  <path d="M30 26H16c-2 0-3 1-3 3v3c0 13 8 24 18 27v-7c-6-4-10-12-10-20v-3h9v-3zM90 26h14c2 0 3 1 3 3v3c0 13-8 24-18 27v-7c6-4 10-12 10-20v-3h-9v-3z" fill="var(--green)"/>
                  <polygon points="60,34 65,48 79,48 67,57 71,71 60,62 49,71 53,57 41,48 55,48" fill="var(--green)"/>
                  <rect x="36" y="92" width="48" height="6" rx="2" fill="var(--green)"/>
                </svg>
              )}
              {/* X watermark for lost picks */}
              {p.win === false && (
                <svg viewBox="0 0 100 100" style={{ position: 'absolute', right: -2, bottom: -6, width: 80, height: 80, opacity: 0.08, pointerEvents: 'none' }}>
                  <circle cx="50" cy="50" r="40" fill="none" stroke="var(--live)" strokeWidth="6"/>
                  <line x1="30" y1="30" x2="70" y2="70" stroke="var(--live)" strokeWidth="6" strokeLinecap="round"/>
                  <line x1="70" y1="30" x2="30" y2="70" stroke="var(--live)" strokeWidth="6" strokeLinecap="round"/>
                </svg>
              )}
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4, position: 'relative' }}>
                <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 15, color: p.win === false ? 'var(--live)' : 'var(--ink)', whiteSpace: 'nowrap' }}>{p.sel}</span>
                <span className="sb-num" style={{ fontWeight: 700, fontSize: 15, color: 'var(--blue)' }}>@ {p.odds}</span>
                {p.win && <Icon name="check" size={16} color="var(--green)" style={{ strokeWidth: 3 }} />}
                {p.win === false && <Icon name="x" size={16} color="var(--live)" style={{ strokeWidth: 3 }} />}
              </div>
              <div style={{ fontSize: 13, color: 'var(--ink-2)' }}>Market: <span style={{ fontWeight: 700, color: 'var(--ink)' }}>{p.market || '1X2'}</span></div>
            </div>
          </div>
          {i < bet.picks.length - 1 && <div style={{ height: 1, background: 'var(--line)', margin: '0 40px' }}></div>}
          </React.Fragment>
        ))}
      </div>

      {/* gray separator band fills the gap, pushing footer to the bottom */}
      <div style={{ flex: 1, minHeight: 28, background: 'var(--bg)', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}></div>

      {/* Bottom footer: Number of Bets + Check Transaction History */}
      <div style={{ background: 'var(--card)', padding: '6px 16px 20px' }}>
        {/* Number of Bets row */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '16px 0', borderBottom: '1px solid var(--line)' }}>
          <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 15, color: 'var(--ink-2)' }}>
            Number of Bets
          </span>
          <span className="sb-num" style={{ fontWeight: 700, fontSize: 15, color: 'var(--ink)' }}>{bet.picks.length}</span>
        </div>
        {/* Check Transaction History row */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '16px 0', cursor: 'pointer' }}>
          <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 15, color: 'var(--green)' }}>
            Check Transaction History
          </span>
          <Icon name="chevron-right" size={20} color="var(--ink-3)" />
        </div>
      </div>

      {/* Win celebration overlay (portals onto the phone frame) */}
      {won && showWin && (
        <SbWinOverlay bet={bet} amount={payout} legs={legs} burstKey={burst}
          onClose={() => setShowWin(false)} />
      )}
    </div>
  );
}

/* ---- Load Code screen (booking code) -------------------------------------- */
/* demo code lookup — any code resolves to random picks for prototype purposes */
function _resolveCode(trimmed) {
  const pool = SB_MATCHES.slice(0, 3);
  const labels = ['1', 'X', '2'];
  return pool.map(m => {
    const idx = Math.floor(Math.random() * 3);
    const drift = (Math.random() * 0.4 - 0.2);
    const oldOdds = Math.max(1.01, parseFloat(m.o[idx]) + drift).toFixed(2);
    const selName = labels[idx] === 'X' ? 'Draw' : SB_TEAMS[idx === 0 ? m.h : m.a].name;
    return {
      key: m.id + '|1X2', sel: selName, odds: m.o[idx], oldOdds,
      market: '1X2', match: SB_TEAMS[m.h].name + ' vs ' + SB_TEAMS[m.a].name,
      when: m.live ? `LIVE ${m.min}'` : (m.when || ''), matchId: m.id, outcome: idx, label: labels[idx],
    };
  });
}

function LoadCodeScreen({ onBack, onAddToSlip }) {
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [loaded, setLoaded] = useState(null); // { code, picks }
  const [error, setError] = useState(null);

  const handleLoad = () => {
    const trimmed = code.trim().toUpperCase();
    if (!trimmed) return;
    setLoading(true);
    setError(null);
    setLoaded(null);
    // simulate network delay
    setTimeout(() => {
      setLoading(false);
      setLoaded({ code: trimmed, picks: _resolveCode(trimmed) });
    }, 900);
  };

  const hasOddsChange = (p) => p.oldOdds && p.oldOdds !== p.odds;
  const oddsWentUp = (p) => hasOddsChange(p) && parseFloat(p.odds) > parseFloat(p.oldOdds);

  const totalOdds = loaded ? loaded.picks.reduce((a, p) => a * parseFloat(p.odds), 1) : 0;
  const changedCount = loaded ? loaded.picks.filter(hasOddsChange).length : 0;

  return (
    <div>
      <InfoHeader title="Load Code" onBack={onBack} />

      {/* Input card */}
      <div style={{ margin: '16px 14px', background: 'var(--card)', borderRadius: 16,
        border: '1px solid var(--line)', boxShadow: 'var(--shadow-card)', padding: '18px 16px' }}>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 17,
          color: 'var(--ink)', marginBottom: 4 }}>Load a shared bet</div>
        <div style={{ fontFamily: 'var(--font-text)', fontSize: 13.5, color: 'var(--ink-3)',
          marginBottom: 14, lineHeight: 1.4 }}>
          Enter a booking code to pull in selections. Odds are checked live.
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <input value={code} onChange={(e) => setCode(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && handleLoad()}
            placeholder="Enter code"
            style={{ flex: 1, background: 'var(--card-2)', border: '1px solid var(--line-2)',
              borderRadius: 10, padding: '13px 14px', fontFamily: 'var(--font-num)',
              fontWeight: 600, fontSize: 15, color: 'var(--ink)', outline: 'none',
              letterSpacing: '0.04em' }} />
          <button onClick={handleLoad} disabled={loading || !code.trim()}
            style={{ background: 'var(--gold)', color: 'var(--gold-ink)', border: 'none',
              borderRadius: 10, padding: '13px 20px', fontFamily: 'var(--font-text)',
              fontWeight: 700, fontSize: 15, cursor: loading || !code.trim() ? 'default' : 'pointer',
              opacity: loading || !code.trim() ? 0.5 : 1, whiteSpace: 'nowrap',
              display: 'flex', alignItems: 'center', gap: 7 }}>
            {loading ? <span className="deposit-spinner"><Icon name="loader" size={18} /></span> : 'Load'}
          </button>
        </div>
      </div>

      {/* Error */}
      {error && (
        <div style={{ margin: '0 14px 12px', padding: '14px 16px', borderRadius: 12,
          background: 'var(--live-bg)', border: '1px solid rgba(239,68,68,0.2)',
          display: 'flex', alignItems: 'center', gap: 10 }}>
          <Icon name="alert-circle" size={18} color="var(--live)" />
          <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 14,
            color: 'var(--live)' }}>{error}</span>
        </div>
      )}

      {/* Loaded results */}
      {loaded && (
        <div style={{ margin: '0 14px' }}>
          {/* Summary bar */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            marginBottom: 12, padding: '0 2px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <Icon name="check-circle" size={18} color="var(--green)" />
              <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14.5,
                color: 'var(--ink)' }}>
                {loaded.picks.length} selection{loaded.picks.length > 1 ? 's' : ''} found
              </span>
            </div>
            {changedCount > 0 && (
              <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 12,
                color: 'var(--gold-strong)', background: 'rgba(247,197,61,0.16)',
                padding: '5px 10px', borderRadius: 999 }}>
                {changedCount} odds changed
              </span>
            )}
          </div>

          {/* Total odds */}
          <div style={{ background: 'var(--card)', borderRadius: 14, border: '1px solid var(--line)',
            boxShadow: 'var(--shadow-card)', padding: '14px 16px', marginBottom: 10,
            display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14,
              color: 'var(--ink-2)' }}>Total Odds</span>
            <span className="sb-num" style={{ fontWeight: 700, fontSize: 20,
              color: 'var(--blue)' }}>{totalOdds.toFixed(2)}</span>
          </div>

          {/* Selection cards */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
            {loaded.picks.map((p, i) => {
              const changed = hasOddsChange(p);
              const up = oddsWentUp(p);
              return (
                <div key={p.key} style={{ background: 'var(--card)', borderRadius: 14,
                  border: '1px solid ' + (changed ? (up ? 'rgba(22,163,74,0.35)' : 'rgba(239,68,68,0.3)') : 'var(--line)'),
                  boxShadow: 'var(--shadow-card)', padding: '14px 16px', position: 'relative', overflow: 'hidden' }}>
                  {/* odds change accent stripe */}
                  {changed && (
                    <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 4,
                      background: up ? 'var(--green)' : 'var(--live)' }} />
                  )}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                    <Icon name="volleyball" size={15} color="var(--ink-3)" />
                    <span style={{ fontFamily: 'var(--font-text)', fontSize: 13, color: 'var(--ink-2)',
                      flex: 1 }}>{p.match}</span>
                    {p.when && (
                      <span className="sb-num" style={{ fontSize: 11.5, color: 'var(--ink-3)',
                        whiteSpace: 'nowrap' }}>{p.when}</span>
                    )}
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <div>
                      <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 15,
                        color: 'var(--ink)' }}>{p.sel}</span>
                      <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 12,
                        color: 'var(--ink-3)', marginLeft: 8 }}>{p.market}</span>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      {changed && (
                        <span className="sb-num" style={{ fontSize: 13, color: 'var(--ink-3)',
                          textDecoration: 'line-through' }}>{p.oldOdds}</span>
                      )}
                      <span className="sb-num" style={{ fontWeight: 700, fontSize: 16,
                        color: changed ? (up ? 'var(--green)' : 'var(--live)') : 'var(--blue)' }}>
                        {p.odds}
                      </span>
                      {changed && (
                        <Icon name={up ? 'trending-up' : 'trending-down'} size={15}
                          color={up ? 'var(--green)' : 'var(--live)'} />
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* Add to slip CTA */}
          <GoldBtn full onClick={() => onAddToSlip && onAddToSlip(loaded.picks)}>
            Add to bet slip · {loaded.picks.length} selection{loaded.picks.length > 1 ? 's' : ''}
          </GoldBtn>

          {/* Booking code reference */}
          <div style={{ textAlign: 'center', padding: '14px 0 8px' }}>
            <span className="sb-num" style={{ fontSize: 12, color: 'var(--ink-3)' }}>
              Code: {loaded.code}
            </span>
          </div>
        </div>
      )}

      {/* Empty state (before loading) */}
      {!loaded && !loading && (
        <div style={{ textAlign: 'center', padding: '50px 30px', color: 'var(--ink-3)' }}>
          <Icon name="clipboard-paste" size={40} color="var(--ink-3)" />
          <div style={{ marginTop: 14, fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 15,
            color: 'var(--ink-2)' }}>
            Got a code from a friend?
          </div>
          <div style={{ marginTop: 4, fontSize: 13, lineHeight: 1.5 }}>
            Paste it above and we'll load the selections for you.
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { LiveCard, SportsHome, StatusTag, BetCard, BetsScreen, TicketDetails, BetSlipSheet, BottomNav, StubScreen, LoadCodeScreen });
