/* ============================================================================
   BetPrince Sportsbook — Match Detail + home sections (Today, Recent Winners).
   Depends on sb-atoms.jsx. Exports to window.
   ============================================================================ */

/* ---- helpers --------------------------------------------------------------- */
function refCode(id) {
  // deterministic pseudo-ref from match id
  let h = 0;
  for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) >>> 0;
  return h.toString(16).padStart(8, '0').slice(0, 8);
}

/* A single odds cell used across detail markets — toggles a selection. */
function MktCell({ top, bottom, picked, onClick, wide }) {
  return (
    <button onClick={onClick} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center',
      justifyContent: 'center', gap: 3, padding: wide ? '12px 8px' : '11px 6px', borderRadius: 10, cursor: 'pointer',
      transition: 'box-shadow 140ms', background: picked ? 'var(--blue)' : 'var(--card-2)',
      border: '1px solid ' + (picked ? 'var(--blue)' : 'var(--line)') }}>
      {top != null && <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 13,
        color: picked ? 'rgba(255,255,255,0.82)' : 'var(--ink)' }}>{top}</span>}
      <span className="sb-num" style={{ fontWeight: 700, fontSize: 15, color: picked ? '#fff' : 'var(--blue)' }}>{bottom}</span>
    </button>
  );
}

/* Collapsible market group card */
function MarketGroup({ title, defaultOpen = true, children }) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div style={{ background: 'var(--card)', borderRadius: 16, border: '1px solid var(--line)',
      boxShadow: 'var(--shadow-card)', overflow: 'hidden', marginBottom: 12 }}>
      <button onClick={() => setOpen(o => !o)} style={{ width: '100%', display: 'flex', alignItems: 'center',
        justifyContent: 'space-between', gap: 8, background: 'transparent', border: 'none', cursor: 'pointer',
        padding: '15px 16px' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 9 }}>
          <Icon name={open ? 'chevron-down' : 'chevron-right'} size={18} color="var(--blue)" />
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16, color: 'var(--ink)' }}>{title}</span>
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 12, color: 'var(--ink-3)' }}>
          <span style={{ width: 24, height: 24, borderRadius: 999, border: '1.5px solid var(--line-2)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
            <span style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontWeight: 700, fontSize: 12 }}>i</span>
          </span>
          <Icon name="star" size={18} />
        </span>
      </button>
      {open && <div style={{ padding: '0 14px 16px' }}>{children}</div>}
    </div>
  );
}

/* ---- Empty state used by Stats / Lineups / Events -------------------------- */
function StatEmpty({ text }) {
  return (
    <div style={{ background: 'var(--card)', borderRadius: 14, border: '1px solid var(--line)',
      boxShadow: 'var(--shadow-card)', padding: '34px 26px', textAlign: 'center' }}>
      <div style={{ fontFamily: 'var(--font-text)', fontWeight: 500, fontSize: 15.5, lineHeight: 1.5,
        color: 'var(--ink-2)', textWrap: 'pretty' }}>{text}</div>
    </div>
  );
}

/* ---- Match Detail (full screen) ------------------------------------------- */
const OU_LINES = [
  { line: '1.5', over: '1.37', under: '3.34' },
  { line: '2.5', over: '2.08', under: '1.94' },
  { line: '3.5', over: '3.50', under: '1.61' },
  { line: '4.5', over: '4.43', under: '1.23' },
];
const CS_SCORES = [
  ['0-0', '9.44'], ['0-1', '19.03'], ['0-2', '17.60'], ['1-0', '6.85'], ['1-1', '8.12'],
  ['1-2', '12.45'], ['2-0', '10.80'], ['2-1', '11.36'], ['2-2', '14.44'], ['3-0', '20.57'],
  ['3-1', '22.73'], ['3-2', '28.48'], ['0-3', '36.15'], ['1-3', '30.70'], ['Other', '7.20'],
];

function MatchDetail({ m, picks, onAdd, onBack }) {
  const [view, setView] = useState('markets');   // markets | stats
  const [statTab, setStatTab] = useState('stats'); // stats | lineups | events
  const [mFilter, setMFilter] = useState('All');
  const home = SB_TEAMS[m.h], away = SB_TEAMS[m.a];
  const ref = refCode(m.id);
  const isPicked = (k) => picks.some(p => p.key === k);
  const matchName = home.name + ' vs ' + away.name;
  const add = (key, sel, odds, market, selectionId) => onAdd({ key, matchId: m.id, sel, odds, market, match: matchName, when: m.when || (m.time ? m.time + ' · ' + m.date : 'Live'), selectionId });
  const apiMarkets = m.markets || [];
  const apiMkt = (kind) => apiMarkets.find(mk => mk.kind === kind);
  const mkt1X2 = apiMkt('ONE_X_TWO');
  const mktOUList = apiMarkets.filter(mk => mk.kind === 'OVER_UNDER').sort((a, b) => (a.line || 0) - (b.line || 0));
  const mktCS = apiMkt('CORRECT_SCORE');

  return (
    <div style={{ paddingBottom: 8 }}>
      {/* ---- Hero header (blue gradient) ---- */}
      <div style={{ position: 'relative', background: 'linear-gradient(180deg, var(--header-bg) 0%, var(--blue-strong) 100%)',
        borderRadius: '0 0 22px 22px', padding: '8px 16px 20px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <button onClick={onBack} style={{ width: 38, height: 38, borderRadius: 999, border: 'none',
            background: 'rgba(255,255,255,0.16)', color: '#fff', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="chevron-left" size={20} />
          </button>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: '#fff' }}>
            <span className="sb-num" style={{ fontWeight: 700, fontSize: 13, opacity: 0.8 }}>NGN</span>
            <span className="sb-num" style={{ fontWeight: 700, fontSize: 15 }}>0.00</span>
          </span>
        </div>

        {/* competition row */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9, marginBottom: 16 }}>
          <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 14, color: 'rgba(255,255,255,0.92)' }}>
            Football · {m.country || 'NG'} · {m.lg}
          </span>
          <span className="sb-num" style={{ background: 'rgba(255,255,255,0.16)', color: '#fff', fontWeight: 700,
            fontSize: 12.5, padding: '4px 10px', borderRadius: 999 }}>{m.time || (m.live ? 'LIVE' : '—')}</span>
        </div>

        {/* teams + score */}
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 6 }}>
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 9 }}>
            <span style={{ background: '#fff', borderRadius: 14, padding: 8, display: 'inline-flex',
              boxShadow: '0 6px 16px rgba(0,0,0,0.18)' }}><Crest id={m.h} size={42} /></span>
            <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14.5, color: '#fff',
              textAlign: 'center', lineHeight: 1.2 }}>{home.name}</span>
          </div>
          <div style={{ textAlign: 'center', paddingTop: 4, minWidth: 96 }}>
            <div className="sb-num" style={{ fontWeight: 700, fontSize: 22, color: '#fff', lineHeight: 1 }}>{m.time || 'LIVE'}</div>
            <div style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 12.5, color: 'rgba(255,255,255,0.72)',
              margin: '5px 0 8px' }}>Wed, Jun 3</div>
            <div className="sb-num" style={{ fontWeight: 700, fontSize: 30, color: '#fff', letterSpacing: '0.04em', lineHeight: 1 }}>
              {m.live ? <>{m.hs}&nbsp;-&nbsp;{m.as}</> : <span style={{ fontFamily: 'var(--font-text)', letterSpacing: 0, color: 'rgba(255,255,255,0.6)', fontSize: 22 }}>VS</span>}
            </div>
          </div>
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 9 }}>
            <span style={{ background: '#fff', borderRadius: 14, padding: 8, display: 'inline-flex',
              boxShadow: '0 6px 16px rgba(0,0,0,0.18)' }}><Crest id={m.a} size={42} /></span>
            <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14.5, color: '#fff',
              textAlign: 'center', lineHeight: 1.2 }}>{away.name}</span>
          </div>
        </div>
        <div className="sb-num" style={{ textAlign: 'center', fontSize: 12.5, color: 'rgba(255,255,255,0.5)', marginTop: 14 }}>
          Ref {ref}…
        </div>
      </div>

      {/* ---- Markets / Stats toggle ---- */}
      <div style={{ padding: '14px 16px 0' }}>
        <div style={{ display: 'flex', gap: 6, background: 'var(--card)', borderRadius: 14, padding: 6,
          border: '1px solid var(--line)', boxShadow: 'var(--shadow-card)' }}>
          {[['markets', 'Markets', 'layout-grid'], ['stats', 'Stats', 'chart-no-axes-column']].map(([k, label, icon]) => {
            const on = view === k;
            return (
              <button key={k} onClick={() => setView(k)} style={{ flex: 1, display: 'flex', alignItems: 'center',
                justifyContent: 'center', gap: 8, padding: '13px 0', borderRadius: 10, cursor: 'pointer',
                border: 'none', background: on ? 'var(--blue)' : 'transparent',
                color: on ? '#fff' : 'var(--ink-2)', fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 15 }}>
                <Icon name={icon} size={18} />{label}
              </button>
            );
          })}
        </div>
      </div>

      {/* ---- Body ---- */}
      {view === 'markets' ? (
        <div style={{ padding: '14px 16px 0' }}>
          {/* market filters */}
          <div style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 14, scrollbarWidth: 'none' }}>
            {['All', 'Main', 'Goals', 'Half', 'Handicap'].map(f => (
              <Chip key={f} on={mFilter === f} onClick={() => setMFilter(f)}>{f}</Chip>
            ))}
          </div>

          {/* Match Result 1X2 */}
          {mkt1X2 ? (
            <MarketGroup title="Match Result">
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, marginTop: 4 }}>
                {mkt1X2.selections.map((s) => {
                  const key = m.id + '|1X2|' + s.code;
                  const label = s.code === '1' ? home.name : (s.code === '2' ? away.name : 'Draw');
                  const od = s.odds.toFixed(2);
                  return <MktCell key={s.id} wide top={s.code} bottom={od} picked={isPicked(key)}
                    onClick={() => add(key, label, od, '1X2', s.id)} />;
                })}
              </div>
            </MarketGroup>
          ) : (
            <MarketGroup title="Match Result">
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, marginTop: 4 }}>
                {['1', 'X', '2'].map((lab, i) => {
                  const key = m.id + '|1X2|' + lab;
                  return <MktCell key={lab} wide top={lab} bottom={m.o[i]} picked={isPicked(key)}
                    onClick={() => add(key, lab === 'X' ? 'Draw' : SB_TEAMS[lab === '1' ? m.h : m.a].name, m.o[i], '1X2')} />;
                })}
              </div>
            </MarketGroup>
          )}

          {/* Over / Under — one row per line */}
          {mktOUList.length > 0 && (
            <MarketGroup title="Over / Under">
              <div style={{ display: 'grid', gridTemplateColumns: '52px 1fr 1fr', gap: 8, alignItems: 'center', marginTop: 4 }}>
                <span></span>
                <span style={{ textAlign: 'center', fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 12,
                  letterSpacing: '0.05em', color: 'var(--ink-3)' }}>OVER</span>
                <span style={{ textAlign: 'center', fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 12,
                  letterSpacing: '0.05em', color: 'var(--ink-3)' }}>UNDER</span>
                {mktOUList.map((mkt) => {
                  const over = mkt.selections.find(s => s.code === 'OVER');
                  const under = mkt.selections.find(s => s.code === 'UNDER');
                  const lineLabel = String(mkt.line);
                  return (
                    <React.Fragment key={mkt.id}>
                      <span className="sb-num" style={{ fontWeight: 700, fontSize: 15, color: 'var(--ink)' }}>{lineLabel}</span>
                      {over && <MktCell bottom={over.odds.toFixed(2)} picked={isPicked(m.id + '|OU|O' + lineLabel)}
                        onClick={() => add(m.id + '|OU|O' + lineLabel, 'Over ' + lineLabel, over.odds.toFixed(2), 'Over/Under', over.id)} />}
                      {under && <MktCell bottom={under.odds.toFixed(2)} picked={isPicked(m.id + '|OU|U' + lineLabel)}
                        onClick={() => add(m.id + '|OU|U' + lineLabel, 'Under ' + lineLabel, under.odds.toFixed(2), 'Over/Under', under.id)} />}
                    </React.Fragment>
                  );
                })}
              </div>
            </MarketGroup>
          )}

          {/* Correct Score */}
          {mktCS && (
            <MarketGroup title="Correct Score">
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginTop: 4 }}>
                {mktCS.selections.map(s => {
                  const key = m.id + '|CS|' + s.code;
                  const od = s.odds.toFixed(2);
                  return <MktCell key={s.id} top={s.code} bottom={od} picked={isPicked(key)}
                    onClick={() => add(key, s.code, od, 'Correct Score', s.id)} />;
                })}
              </div>
            </MarketGroup>
          )}
        </div>
      ) : (
        <div style={{ padding: '14px 16px 0' }}>
          {/* stats sub-tabs */}
          <div style={{ display: 'flex', gap: 8, marginBottom: 14 }}>
            {[['stats', 'Stats'], ['lineups', 'Lineups'], ['events', 'Events']].map(([k, label]) => (
              <Chip key={k} on={statTab === k} onClick={() => setStatTab(k)}>{label}</Chip>
            ))}
          </div>
          {statTab === 'stats' && <StatEmpty text="Match stats (possession, shots, etc.) will appear here once the game starts or finishes." />}
          {statTab === 'lineups' && <StatEmpty text="Team lineups and formations will show here when available." />}
          {statTab === 'events' && <StatEmpty text="Goals, cards, and key events will appear here during the match." />}
        </div>
      )}
    </div>
  );
}

/* ---- Today: scheduled match row ------------------------------------------- */
function ScheduledCard({ m, picks, onOpen, onPick }) {
  const home = SB_TEAMS[m.h], away = SB_TEAMS[m.a];
  return (
    <div style={{ background: 'var(--card)', borderRadius: 16, border: '1px solid var(--line)',
      boxShadow: 'var(--shadow-card)', padding: 14, marginBottom: 12 }}>
      <div onClick={() => onOpen(m)} style={{ cursor: 'pointer' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 13, color: 'var(--ink-2)' }}>{m.lg}</span>
          <span style={{ background: 'var(--blue-tint)', color: 'var(--blue)', fontFamily: 'var(--font-text)',
            fontWeight: 700, fontSize: 11.5, padding: '4px 11px', borderRadius: 999 }}>Scheduled</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1, minWidth: 0 }}>
            <Crest id={m.h} size={30} />
            <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14, color: 'var(--ink)',
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{home.name}</span>
          </div>
          <div style={{ textAlign: 'center', flexShrink: 0 }}>
            <div className="sb-num" style={{ fontWeight: 700, fontSize: 16, color: 'var(--ink)' }}>{m.time}</div>
            <div className="sb-num" style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{m.date}</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1, minWidth: 0, justifyContent: 'flex-end' }}>
            <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14, color: 'var(--ink)',
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', textAlign: 'right' }}>{away.name}</span>
            <Crest id={m.a} size={30} />
          </div>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 7 }}>
        {['1', 'X', '2'].map((lab, i) => {
          const p = picks.find(x => x.key === m.id + '|1X2');
          return <OddsBtn key={lab} label={lab} value={m.o[i]} picked={p && p.outcome === i} onClick={() => onPick(m, i, lab)} />;
        })}
      </div>
    </div>
  );
}

/* ---- All Games: single card that adapts to live OR scheduled ------------- */
function AllGameCard({ m, picks, onOpen, onPick }) {
  const home = SB_TEAMS[m.h], away = SB_TEAMS[m.a];
  return (
    <div style={{ background: 'var(--card)', borderRadius: 16, border: '1px solid var(--line)',
      boxShadow: 'var(--shadow-card)', padding: 14, marginBottom: 12 }}>
      <div onClick={() => onOpen(m)} style={{ cursor: 'pointer' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 13, 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: '4px 10px', borderRadius: 999, fontFamily: 'var(--font-text)',
              fontWeight: 700, fontSize: 11 }}>
              <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--live)' }} />LIVE
            </span>
          ) : (
            <span style={{ background: 'var(--blue-tint)', color: 'var(--blue)', fontFamily: 'var(--font-text)',
              fontWeight: 700, fontSize: 11.5, padding: '4px 11px', borderRadius: 999 }}>Scheduled</span>
          )}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1, minWidth: 0 }}>
            <Crest id={m.h} size={30} />
            <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14, color: 'var(--ink)',
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{home.name}</span>
          </div>
          <div style={{ textAlign: 'center', flexShrink: 0, minWidth: 54 }}>
            {m.live ? (
              <>
                <div className="sb-num" style={{ fontWeight: 700, fontSize: 18, color: 'var(--ink)', whiteSpace: 'nowrap', lineHeight: 1 }}>{m.hs}&thinsp;-&thinsp;{m.as}</div>
                <div className="sb-num" style={{ fontSize: 11, color: 'var(--live)', marginTop: 3 }}>{m.min}'</div>
              </>
            ) : (
              <>
                <div className="sb-num" style={{ fontWeight: 700, fontSize: 16, color: 'var(--ink)' }}>{m.time || (m.when ? m.when.split(' ')[1] || m.when : 'VS')}</div>
                {(m.date || (m.when && m.when.split(' ')[0])) && <div className="sb-num" style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{m.date || m.when.split(' ')[0]}</div>}
              </>
            )}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1, minWidth: 0, justifyContent: 'flex-end' }}>
            <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14, color: 'var(--ink)',
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', textAlign: 'right' }}>{away.name}</span>
            <Crest id={m.a} size={30} />
          </div>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 7 }}>
        {['1', 'X', '2'].map((lab, i) => {
          const p = picks.find(x => x.key === m.id + '|1X2');
          return <OddsBtn key={lab} label={lab} value={m.o[i]} picked={p && p.outcome === i} onClick={() => onPick(m, i, lab)} />;
        })}
      </div>
    </div>
  );
}

/* ---- All Games screen (Football / Live / View all / Browse all) ----------- */
function AllGamesScreen({ matches, picks, onOpen, onPick, onBack, initialFilter }) {
  const [filter, setFilter] = useState(initialFilter === 'live' ? 'live' : 'all');
  const liveCount = matches.filter(m => m.live).length;
  const shown = filter === 'live' ? matches.filter(m => m.live) : matches;
  const tabs = [['all', 'All', matches.length], ['live', 'Live', liveCount]];
  return (
    <div>
      <InfoHeader title="All Games" onBack={onBack} />
      {/* wide All / Live filter buttons (segmented, like Open Bets but roomier) */}
      <div style={{ display: 'flex', gap: 10, padding: '14px 16px 4px' }}>
        {tabs.map(([k, label, n]) => {
          const on = filter === k;
          return (
            <button key={k} onClick={() => setFilter(k)} style={{ flex: 1, display: 'inline-flex', alignItems: 'center',
              justifyContent: 'center', gap: 8, padding: '12px 18px', borderRadius: 999, cursor: 'pointer',
              fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14.5, transition: 'box-shadow 140ms',
              background: on ? 'var(--blue)' : 'var(--card-2)', color: on ? 'var(--blue-ink)' : 'var(--ink-2)',
              border: '1px solid ' + (on ? 'var(--blue)' : 'var(--line)') }}>
              {k === 'live' && <span style={{ width: 7, height: 7, borderRadius: 999,
                background: on ? '#fff' : 'var(--live)' }} />}
              {label}
              <span className="sb-num" style={{ fontWeight: 700, fontSize: 12, padding: '1px 7px', borderRadius: 999,
                background: on ? 'rgba(255,255,255,0.22)' : 'var(--line)',
                color: on ? '#fff' : 'var(--ink-3)' }}>{n}</span>
            </button>
          );
        })}
      </div>
      <div style={{ padding: '12px 16px 24px' }}>
        {shown.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '70px 30px', color: 'var(--ink-3)' }}>
            <Icon name="radio" size={40} color="var(--ink-3)" />
            <div style={{ marginTop: 14, fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 15, color: 'var(--ink-2)' }}>No live games right now.</div>
            <div style={{ marginTop: 4, fontSize: 13 }}>Check back soon or browse all games.</div>
          </div>
        ) : shown.map(m => <AllGameCard key={m.id} m={m} picks={picks} onOpen={onOpen} onPick={onPick} />)}
      </div>
    </div>
  );
}

function TodaySection({ matches, picks, onOpen, onPick, onBrowse }) {
  const sched = matches.filter(m => m.scheduled);
  if (sched.length === 0) return null;
  return (
    <div style={{ padding: '6px 16px 0' }}>
      <div style={{ fontFamily: 'var(--font-text)', fontWeight: 800, fontSize: 12.5, letterSpacing: '0.1em',
        textTransform: 'uppercase', color: 'var(--ink-3)', margin: '10px 2px 12px' }}>Today</div>
      {sched.map(m => <ScheduledCard key={m.id} m={m} picks={picks} onOpen={onOpen} onPick={onPick} />)}
      <div style={{ display: 'flex', justifyContent: 'center', padding: '4px 0 6px' }}>
        <button onClick={onBrowse} style={{ background: 'var(--card)', color: 'var(--blue)', border: '1px solid var(--line-2)',
          borderRadius: 999, padding: '13px 26px', fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14,
          cursor: 'pointer', boxShadow: 'var(--shadow-card)' }}>Browse all matches</button>
      </div>
    </div>
  );
}

/* ---- Recent Winners -------------------------------------------------------- */
function genWinners() {
  const handles = ['bet', 'spor', 'sam', 'tobi', 'chi', 'ade', 'kelv', 'naij', 'big', 'zee', 'emy', 'olu'];
  const cats = ['Sports'];
  const ago = ['just now', '1 min ago', '2 min ago', '4 min ago', '5 min ago', '8 min ago', '11 min ago'];
  const pick = a => a[Math.floor(Math.random() * a.length)];
  const out = [];
  const used = new Set();
  for (let i = 0; i < 7; i++) {
    let h = pick(handles);
    while (used.has(h)) h = pick(handles);
    used.add(h);
    const amt = Math.floor(50000 + Math.random() * (1200000 - 50000)) + Math.random();
    out.push({ id: i, handle: h + '*'.repeat(5 + Math.floor(Math.random() * 2)), amount: amt, cat: pick(cats), ago: pick(ago) });
  }
  return out;
}

function WinnerCard({ w }) {
  return (
    <div style={{ position: 'relative', width: 210, flexShrink: 0, background: 'var(--card)', borderRadius: 14,
      border: '1px solid var(--line)', boxShadow: 'var(--shadow-card)', padding: '13px 14px', overflow: 'hidden' }}>
      {/* faint trophy watermark */}
      <span style={{ position: 'absolute', right: -6, top: '50%', transform: 'translateY(-50%)', opacity: 0.10,
        color: 'var(--green)' }}><Icon name="trophy" size={64} /></span>
      <div style={{ position: 'relative' }}>
        <div style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 13, color: 'var(--ink-2)', marginBottom: 5 }}>
          <span style={{ color: 'var(--ink)', fontWeight: 700 }}>{w.handle}</span> won
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 5, marginBottom: 11 }}>
          <span className="sb-num" style={{ fontWeight: 600, fontSize: 11, color: 'var(--ink-3)' }}>NGN</span>
          <span className="sb-num" style={{ fontWeight: 700, fontSize: 18, color: 'var(--green)', letterSpacing: '-0.01em' }}>
            {w.amount.toLocaleString('en-NG', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
          </span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ background: 'var(--blue-tint)', color: 'var(--blue)', fontFamily: 'var(--font-text)',
            fontWeight: 700, fontSize: 11, padding: '3px 9px', borderRadius: 999 }}>{w.cat}</span>
          <span className="sb-num" style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{w.ago}</span>
        </div>
      </div>
    </div>
  );
}

function RecentWinners({ winners }) {
  // duplicate list for a seamless marquee loop
  const loop = [...winners, ...winners];
  return (
    <div style={{ padding: '20px 0 8px' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 16px 14px' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 11 }}>
          <span style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--blue)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--gold)',
            boxShadow: '0 4px 12px rgba(37,54,216,0.32)' }}><Icon name="trophy" size={21} /></span>
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 19, color: 'var(--ink)' }}>Recent Winners</span>
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: 'rgba(22,163,74,0.12)',
          color: 'var(--green)', padding: '4px 11px', borderRadius: 999, fontFamily: 'var(--font-text)',
          fontWeight: 700, fontSize: 11.5 }}>
          <span style={{ width: 7, height: 7, borderRadius: 999, background: 'var(--green)' }} />LIVE
        </span>
      </div>
      <div style={{ overflow: 'hidden', WebkitMaskImage: 'linear-gradient(90deg, transparent, #000 4%, #000 96%, transparent)',
        maskImage: 'linear-gradient(90deg, transparent, #000 4%, #000 96%, transparent)' }}>
        <div style={{ display: 'flex', gap: 12, width: 'max-content', padding: '0 16px',
          animation: 'marqueeScroll 34s linear infinite' }}>
          {loop.map((w, i) => <WinnerCard key={i} w={w} />)}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MatchDetail, ScheduledCard, AllGameCard, AllGamesScreen, TodaySection, RecentWinners, WinnerCard, genWinners, refCode });
