// ════════════════════════════════════════════════════════════════════════════
// UR2D STANDINGS — "TIMING WALL" v2
// One composition, two zones sharing rows:
//   LEFT  — championship ladder: pos / team / driver / # / points, with a
//           team-coloured points bar (relative to leader) + gap-to-leader.
//   RIGHT — race matrix: ONE cell per round. Race finish is the hero number,
//           quali sits small in the corner. Podiums = metal plates, pole = purple.
// Column headers carry the track minimap + country code (broadcast wall).
// Data wiring identical to v1: useStandings + useRaceResults + getCalendar.
// Mounted by "Standings Grid v2.html". Loads after ur2d-pages.jsx.
// ════════════════════════════════════════════════════════════════════════════

const SG2_METAL = {
  1: { bg: 'linear-gradient(135deg, #E8C55A 0%, #C9A227 60%, #A8861D 100%)', flat: '#C9A227', ink: '#0b0b0d' },
  2: { bg: 'linear-gradient(135deg, #E4E8EE 0%, #C7CBD1 60%, #A9AEB6 100%)', flat: '#C7CBD1', ink: '#0b0b0d' },
  3: { bg: 'linear-gradient(135deg, #D69A55 0%, #C0813E 60%, #9E6830 100%)', flat: '#C0813E', ink: '#0b0b0d' },
};
const SG2_POLE = '#B25FFF';

const sg2Norm = (s) => String(s || '').trim().toLowerCase().replace(/\s+/g, ' ');

// ── Split: dedicated quali cell ───────────────────────────────────────────────
const SG2QCell = ({ q }) => {
  const hasQ = typeof q === 'number' && q > 0;
  const pole = hasQ && q === 1;
  return (
    <td style={{ padding: 0, borderLeft: '1px solid rgba(255,255,255,0.11)', borderBottom: '1px solid rgba(255,255,255,0.05)', height: 'inherit' }}>
      <div style={{
        position: 'relative', height: '100%', minHeight: 40,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: pole ? 'rgba(178,95,255,0.14)' : 'transparent',
      }}>
        {pole &&
          <span style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 2, background: SG2_POLE, opacity: 0.85 }}></span>}
        <span style={{
          fontFamily: 'JetBrains Mono', fontWeight: 700, fontSize: hasQ ? 13 : 11,
          color: hasQ ? (pole ? SG2_POLE : 'rgba(255,255,255,0.55)') : 'rgba(255,255,255,0.10)',
          fontVariantNumeric: 'tabular-nums', lineHeight: 1
        }}>{hasQ ? q : '—'}</span>
      </div>
    </td>
  );
};

// ── Split: dedicated race-finish cell (optional in-cell points) ───────────────
const SG2RCell = ({ r, p, showPts }) => {
  const hasR = typeof r === 'number' && r > 0;
  const metal = hasR ? SG2_METAL[r] : null;
  const hasP = showPts && typeof p === 'number';
  return (
    <td style={{ padding: 0, borderLeft: '1px solid rgba(255,255,255,0.055)', borderBottom: '1px solid rgba(255,255,255,0.05)', height: 'inherit' }}>
      <div style={{
        position: 'relative', height: '100%', minHeight: 40,
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 1,
        background: metal ? metal.bg : hasR ? 'rgba(255,255,255,0.045)' : 'transparent',
        boxShadow: r === 1 ? '0 0 14px rgba(201,162,39,0.35) inset' : 'none',
      }}>
        <span style={{
          fontFamily: 'Archivo', fontWeight: 900, fontSize: hasR ? (hasP ? 15 : 17) : 12,
          color: metal ? metal.ink : hasR ? COLORS.text : 'rgba(255,255,255,0.10)',
          fontVariantNumeric: 'tabular-nums', lineHeight: 1
        }}>{hasR ? r : '—'}</span>
        {hasP &&
          <span style={{
            fontFamily: 'JetBrains Mono', fontWeight: 700, fontSize: 8.5, lineHeight: 1,
            color: metal ? 'rgba(0,0,0,0.6)' : 'rgba(255,255,255,0.42)', fontVariantNumeric: 'tabular-nums'
          }}>{p}</span>}
      </div>
    </td>
  );
};

// ── Split: dedicated per-race points cell (column mode) — inherits the R cell's
// podium metal so gold/silver/bronze reads as one block across R + Pts ───────
const SG2PCell = ({ p, r }) => {
  const hasP = typeof p === 'number';
  const hasR = typeof r === 'number' && r > 0;
  const metal = hasR ? SG2_METAL[r] : null;
  return (
    <td style={{ padding: 0, borderLeft: '1px solid rgba(255,255,255,0.16)', borderBottom: '1px solid rgba(255,255,255,0.05)', height: 'inherit' }}>
      <div style={{
        position: 'relative', height: '100%', minHeight: 40,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: metal ? metal.bg : hasR ? 'rgba(255,255,255,0.045)' : 'transparent',
        boxShadow: r === 1 ? '0 0 14px rgba(201,162,39,0.35) inset' : 'none',
      }}>
        <span style={{
          fontFamily: 'JetBrains Mono', fontWeight: 700, fontSize: 12,
          color: metal ? metal.ink : hasP ? 'rgba(255,255,255,0.68)' : 'rgba(255,255,255,0.10)',
          fontVariantNumeric: 'tabular-nums', lineHeight: 1
        }}>{hasP ? p : '—'}</span>
      </div>
    </td>
  );
};

// ── Split: sprint-finish cell (HL only) — secondary to the feature race: a
// muted number with a subtle metal tint + accent bar for a sprint podium ─────
const SG2SCell = ({ s }) => {
  const hasS = typeof s === 'number' && s > 0;
  const metal = hasS ? SG2_METAL[s] : null;
  return (
    <td style={{ padding: 0, borderLeft: '1px solid rgba(255,255,255,0.055)', borderBottom: '1px solid rgba(255,255,255,0.05)', height: 'inherit' }}>
      <div style={{
        position: 'relative', height: '100%', minHeight: 40,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: metal ? `${metal.flat}22` : 'transparent',
      }}>
        {metal &&
          <span style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 2, background: metal.flat, opacity: 0.9 }}></span>}
        <span style={{
          fontFamily: 'Archivo', fontWeight: 800, fontSize: hasS ? 13 : 11,
          color: hasS ? (metal ? metal.flat : 'rgba(255,255,255,0.58)') : 'rgba(255,255,255,0.10)',
          fontVariantNumeric: 'tabular-nums', lineHeight: 1
        }}>{hasS ? s : '—'}</span>
      </div>
    </td>
  );
};

// ── Constructor cell: weekend points total (hero) + best car finish ──────────
const SG2CCell = ({ pts, pos }) => {
  const has = typeof pts === 'number';
  const scored = has && pts > 0;
  const metal = scored && pos && SG2_METAL[pos] ? SG2_METAL[pos] : null;
  return (
    <td style={{ padding: 0, borderLeft: '1px solid rgba(255,255,255,0.11)', borderBottom: '1px solid rgba(255,255,255,0.05)', height: 'inherit' }}>
      <div style={{
        position: 'relative', height: '100%', minHeight: 40,
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 1,
        background: metal ? metal.bg : scored ? 'rgba(255,255,255,0.045)' : 'transparent',
        boxShadow: metal && pos === 1 ? '0 0 14px rgba(201,162,39,0.35) inset' : 'none',
      }}>
        <span style={{
          fontFamily: 'Archivo', fontWeight: 900, fontSize: has ? 16 : 12,
          color: metal ? metal.ink : has ? (scored ? COLORS.text : 'rgba(255,255,255,0.30)') : 'rgba(255,255,255,0.10)',
          fontVariantNumeric: 'tabular-nums', lineHeight: 1
        }}>{has ? pts : '—'}</span>
        {scored && pos != null &&
          <span style={{
            fontFamily: 'JetBrains Mono', fontWeight: 700, fontSize: 8.5, lineHeight: 1,
            color: metal ? 'rgba(0,0,0,0.6)' : 'rgba(255,255,255,0.42)', fontVariantNumeric: 'tabular-nums'
          }}>P{pos}</span>}
      </div>
    </td>
  );
};

// ── Compact controls (season + league) ───────────────────────────────────────
const SG2Controls = ({ league, setLeague, seasons, activeId, setSeasonId }) => {
  const H = 38;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <div style={{ position: 'relative' }}>
        <select value={activeId || ''} onChange={(e) => setSeasonId(e.target.value)} style={{
          appearance: 'none', WebkitAppearance: 'none', height: H, boxSizing: 'border-box',
          background: 'rgba(255,255,255,0.05)', color: COLORS.text, border: '1px solid rgba(255,255,255,0.12)',
          padding: '0 32px 0 13px', cursor: 'pointer',
          fontFamily: 'Archivo', fontWeight: 800, fontSize: 13, letterSpacing: '0.04em'
        }}>
          {seasons.map((s) => <option key={s.id} value={s.id} style={{ background: COLORS.ink, color: COLORS.text }}>{s.label}{s.hasData ? '' : ' · soon'}</option>)}
        </select>
        <span aria-hidden style={{ position: 'absolute', right: 11, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', color: COLORS.red, fontSize: 8 }}>▼</span>
      </div>
      <div style={{ display: 'inline-flex', border: '1px solid rgba(255,255,255,0.12)', background: 'rgba(0,0,0,0.4)' }}>
        {LEAGUES.map((Lg, i) => {
          const active = league === Lg.id;
          return (
            <button key={Lg.id} onClick={() => setLeague(Lg.id)} style={{
              all: 'unset', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
              width: 44, height: H, boxSizing: 'border-box',
              background: active ? 'rgba(255,255,255,0.08)' : 'transparent',
              borderRight: i < LEAGUES.length - 1 ? '1px solid rgba(255,255,255,0.1)' : 'none',
              position: 'relative'
            }}>
              {active && <span style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: 2, background: Lg.accent }} />}
              <img src={Lg.logo} alt={Lg.short} style={{ height: 22, width: 22, objectFit: 'contain', opacity: active ? 1 : 0.4, filter: active ? 'none' : 'grayscale(.6)' }} />
            </button>);
        })}
      </div>
    </div>
  );
};

// ── PAGE ─────────────────────────────────────────────────────────────────────
const URStandingsWall = ({ league, setLeague, racePoints = 'off', onBack }) => {
  const split = true;
  const [view, setView] = React.useState('drivers');
  const showPtsCol = racePoints === 'column';
  const showPtsInCell = racePoints === 'incell';
  const L = LEAGUE_BY_ID[league];
  const seasons = getSeasons(league);
  const [seasonId, setSeasonId] = useSharedSeason(league);
  const activeId = seasons.some((s) => s.id === seasonId) ? seasonId : defaultDataSeasonId(seasons);

  const data = useStandings(league, activeId);
  const label = data.season && data.season.label;
  const results = useRaceResults(league, label);
  const teamByShort = {};
  (data.teams || []).forEach((t) => { teamByShort[t.short] = t; });

  // roster fallback: most recent team raced for (independents / emergency reserves)
  const seasonRoster = typeof getRoster !== 'undefined' ? getRoster(league, activeId) : null;
  const recentTeamFor = (name) => {
    if (!seasonRoster) return null;
    const who = typeof resolvePerson !== 'undefined' ? resolvePerson(name) : null;
    const handle = who ? who.handle : null;
    const stints = (seasonRoster.stints || []).filter((s) => s.driver === handle || rosterNorm(s.driver) === rosterNorm(name));
    for (let i = stints.length - 1; i >= 0; i--) {
      if (teamByShort[stints[i].team]) return teamByShort[stints[i].team];
    }
    return null;
  };

  // driver → round → {q, s, r, p}
  const numRaces = (data.season && data.season.numRaces) || 10;
  const hasSprints = !!(data.season && data.season.hasSprints);
  const teamBased = !!(data.teams && data.teams.length);
  const isCon = view === 'constructors' && teamBased;
  const perRaceCols = isCon ? 1 : split ? (2 + (hasSprints ? 1 : 0) + (showPtsCol ? 1 : 0)) : 1;
  const byDriver = {};
  Object.entries(results).forEach(([round, list]) => {
    list.forEach((res) => {
      const key = sg2Norm(res.name);
      (byDriver[key] || (byDriver[key] = {}))[round] = { q: res.quali, s: res.sprint, r: res.finish, p: res.points };
    });
  });

  // race headers — code + minimap via the position-aligned shared calendar.
  // Calendars roll forward with the leagues (index N of UR2D_CALENDARS aligns with
  // index N of every league's seasons[]), so resolve by the selected season's INDEX —
  // NOT by label: HL/JL/AL labels (S21, S22A…) never match the UL-labelled calendar
  // array and would wrongly fall back to the current in-progress schedule.
  const calSeasons = typeof getCalendarSeasons !== 'undefined' ? getCalendarSeasons() : [];
  const seasonIdx = seasons.filter((s) => !s.dbOnly).findIndex((s) => s.id === activeId); // dbOnly archive seasons aren't calendar-aligned
  const calLabel = (seasonIdx >= 0 && calSeasons[seasonIdx]) ? calSeasons[seasonIdx].id : label;
  const cal = getCalendar(league, calLabel);
  const races = [];
  for (let n = 1; n <= numRaces; n++) {
    const r = (cal.races || []).find((x) => x.round === n);
    races.push({
      round: n,
      code: r ? (UR_GP_LOC3[r.grandPrix] || null) : null,
      minimap: r ? ((r.minimap || UR_GP_MINIMAP[r.grandPrix]) || null) : null,
      raced: Object.prototype.hasOwnProperty.call(results, n) || Object.prototype.hasOwnProperty.call(results, String(n)),
    });
  }

  const drivers = (data.drivers || []).slice(0, 18);
  const leaderPts = drivers.length ? Math.max(1, drivers[0].pts) : 1;

  // ── Constructors: each weekend's team points total, straight from the store ──
  // (Leaderboard's constructor block; these reconcile exactly with the season total.)
  const conRounds = typeof useConstructorRounds !== 'undefined' ? useConstructorRounds(league, label) : {};
  const conRows = isCon
    ? (data.teams || []).slice().sort((a, b) => (a.pos || 99) - (b.pos || 99)).map((t, i) => ({
        ...t, pos: t.pos || i + 1, rounds: conRounds[t.short] || {}
      }))
    : [];
  const conHasRounds = isCon && conRows.some((t) => Object.keys(t.rounds).length);
  // A round counts as run once any constructor scored in it — keeps the cells from
  // sitting on dashes while the (separate) race-results fetch is still in flight.
  const conRacedRounds = new Set();
  conRows.forEach((t) => Object.entries(t.rounds).forEach(([rn, c]) => { if (c.pts > 0) conRacedRounds.add(Number(rn)); }));

  // ── Image export (copy / download) ──────────────────────────────────────
  const racedRounds = races.filter((r) => r.raced).map((r) => r.round);
  const lastRound = racedRounds.length ? Math.max.apply(null, racedRounds) : 0;
  const [busy, setBusy] = React.useState(false);
  const [copied, setCopied] = React.useState(false);
  const captureName = () =>
    `${(L.short || 'UR')}_${String(activeId || '').replace(/[^\w-]/g, '')}_R${lastRound}${isCon ? '_CON' : ''}.png`;

  const doCapture = async (mode) => {
    if (busy || typeof html2canvas === 'undefined') return;
    const table = document.querySelector('.sg2-table');
    const redbar = document.querySelector('.sg2-redbar');
    if (!table) return;
    setBusy(true);
    document.body.classList.add('sg2-capturing');
    let wrap = null;
    try {
      // let the class apply before rasterising
      await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
      const fullWidth = table.scrollWidth;
      // build an offscreen wrapper: red divider bar + full table, unclipped by the scroll viewport
      wrap = document.createElement('div');
      wrap.style.position = 'fixed';
      wrap.style.left = '-99999px';
      wrap.style.top = '0';
      wrap.style.background = COLORS.slate;
      wrap.style.width = fullWidth + 'px';
      if (redbar) {
        const bar = redbar.cloneNode(true);
        bar.style.margin = '0';
        bar.style.width = '100%';
        bar.style.boxSizing = 'border-box';
        wrap.appendChild(bar);
      }
      const tableClone = table.cloneNode(true);
      tableClone.style.width = fullWidth + 'px';
      tableClone.style.minWidth = fullWidth + 'px';
      wrap.appendChild(tableClone);
      document.body.appendChild(wrap);
      const canvas = await html2canvas(wrap, { backgroundColor: COLORS.slate, scale: 2, logging: false, useCORS: true });
      const name = captureName();
      const blob = await new Promise((res) => canvas.toBlob(res, 'image/png'));
      if (mode === 'copy' && navigator.clipboard && window.ClipboardItem) {
        try {
          await navigator.clipboard.write([new window.ClipboardItem({ 'image/png': blob })]);
          setCopied(true); setTimeout(() => setCopied(false), 1600);
        } catch (e) { triggerDownload(blob, name); }
      } else {
        triggerDownload(blob, name);
      }
    } catch (e) {
      console.error('capture failed', e);
    } finally {
      if (wrap && wrap.parentNode) wrap.parentNode.removeChild(wrap);
      document.body.classList.remove('sg2-capturing');
      setBusy(false);
    }
  };
  const triggerDownload = (blob, name) => {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove();
    setTimeout(() => URL.revokeObjectURL(url), 1500);
  };

  // sticky geometry — single source of truth for the 5 frozen left columns
  const LW = { pos: 42, team: 46, name: isCon ? 262 : 182, num: isCon ? 0 : 34, pts: 80 };
  const LEFT_W = LW.pos + LW.team + LW.name + LW.num + LW.pts;
  const LEFTS = { pos: 0, team: LW.pos, name: LW.pos + LW.team, num: LW.pos + LW.team + LW.name, pts: LW.pos + LW.team + LW.name + LW.num };

  const headBorder = '1px solid rgba(255,255,255,0.14)';

  return (
    <section data-screen-label="Standings Wall" style={{
      position: 'relative', height: '100vh', display: 'flex', flexDirection: 'column', overflow: 'hidden',
      background: COLORS.slate
    }}>
      <div aria-hidden style={{ position: 'absolute', left: -220, top: -220, width: 600, height: 600, borderRadius: '50%', background: `radial-gradient(circle, ${COLORS.red}22 0%, transparent 62%)`, filter: 'blur(40px)', pointerEvents: 'none' }}></div>

      {/* ── Functional top bar ────────────────────────────────────── */}
      <style>{`
        .sg2-btn{ all:unset; box-sizing:border-box; cursor:pointer; display:inline-flex; align-items:center; gap:7px;
          font-family:'JetBrains Mono',monospace; font-size:10px; letter-spacing:0.16em; text-transform:uppercase;
          padding:9px 15px; border:1px solid rgba(255,255,255,0.16); color:${COLORS.text}; background:rgba(255,255,255,0.05); }
        .sg2-btn:hover{ background:rgba(255,255,255,0.11); border-color:rgba(255,255,255,0.3); }
        .sg2-btn.is-red{ background:${COLORS.red}; border-color:${COLORS.red}; color:#fff; font-weight:700; }
        .sg2-btn.is-red:hover{ filter:brightness(1.1); }
        .sg2-btn:disabled{ opacity:0.45; cursor:default; }
        .sg2-btn .dot{ width:6px; height:6px; border-radius:50%; background:currentColor; }
            .sg2-capturing .sg2-table thead th{ position:static !important; }
            .sg2-capturing .sg2-sticky{ position:static !important; }
            .sg2-capturing .sg2-table thead th.sg2-brand-th{ position:relative !important; }
      `}</style>
      <div style={{ position: 'relative', flexShrink: 0, display: 'flex', alignItems: 'center', gap: 14, padding: '16px 28px 14px' }}>
        <SG2Controls league={league} setLeague={setLeague} seasons={seasons} activeId={activeId} setSeasonId={setSeasonId} />
        {teamBased &&
          <div style={{ display: 'inline-flex', border: '1px solid rgba(255,255,255,0.12)', background: 'rgba(0,0,0,0.4)', height: 38, boxSizing: 'border-box' }}>
            {[['drivers', 'Drivers'], ['constructors', 'Constructors']].map(([id, lbl], i) => {
              const active = (view === 'constructors' ? 'constructors' : 'drivers') === id;
              return (
                <button key={id} onClick={() => setView(id)} style={{
                  all: 'unset', cursor: 'pointer', display: 'flex', alignItems: 'center', padding: '0 15px', position: 'relative',
                  fontFamily: 'JetBrains Mono', fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase',
                  color: active ? COLORS.text : COLORS.textMute,
                  background: active ? 'rgba(255,255,255,0.08)' : 'transparent',
                  borderRight: i === 0 ? '1px solid rgba(255,255,255,0.1)' : 'none'
                }}>
                  {active && <span style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: 2, background: COLORS.red }} />}
                  {lbl}
                </button>);
            })}
          </div>}
        <span style={{ flex: 1 }}></span>
        <button className="sg2-btn" onClick={() => doCapture('copy')} disabled={busy}>
          <span className="dot" style={{ background: copied ? '#3fbf6b' : 'currentColor' }}></span>
          {copied ? 'Copied' : 'Copy image'}
        </button>
        <button className="sg2-btn is-red" onClick={() => doCapture('download')} disabled={busy}>
          {busy ? 'Rendering…' : 'Download'}
        </button>
        {onBack ? (
          <button className="sg2-btn" onClick={onBack}>← Back to standings</button>
        ) : (
          <React.Fragment>
            <a href="Standings Grid.html" style={{
              fontFamily: 'JetBrains Mono', fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase',
              color: COLORS.textMute, textDecoration: 'none', borderBottom: `1px solid ${COLORS.hairline}`, paddingBottom: 3
            }}>Grid v1</a>
            <a href="Ultimate Racing Esports - Final.html#standings" style={{
              fontFamily: 'JetBrains Mono', fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase',
              color: COLORS.textMute, textDecoration: 'none', borderBottom: `1px solid ${COLORS.hairline}`, paddingBottom: 3
            }}>← Back</a>
          </React.Fragment>
        )}
      </div>
      <div className="sg2-redbar" style={{ height: 3, background: COLORS.red, margin: '0 28px', flexShrink: 0 }}></div>

      {/* ── Wall ──────────────────────────────────────────────────── */}
      {data.status === 'loading' && !drivers.length ?
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 18 }}>
          <div style={{ display: 'flex', gap: 8 }}>
            {[0, 1, 2].map((i) => <span key={i} style={{ width: 10, height: 10, background: L.accent, borderRadius: '50%', animation: `ur-pulse 1.2s ease-in-out ${i * 0.2}s infinite` }} />)}
          </div>
          <span style={{ fontFamily: 'JetBrains Mono', fontSize: 10, letterSpacing: '0.28em', color: COLORS.textMute, textTransform: 'uppercase' }}>Loading live data…</span>
        </div>
      : !drivers.length ?
        <div style={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
          <div style={{ textAlign: 'center', background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.1)', padding: '56px 44px' }}>
            <div style={{ fontFamily: 'JetBrains Mono', fontSize: 11, letterSpacing: '0.3em', color: L.accent, textTransform: 'uppercase' }}>◆ {L.short}</div>
            <h3 style={{ margin: '16px 0 0', fontFamily: 'Archivo', fontWeight: 900, fontSize: 34, color: COLORS.text, letterSpacing: '-0.02em' }}>Standings coming soon</h3>
          </div>
        </div>
      :
        <div style={{ position: 'relative', flex: 1, overflow: 'auto', padding: '0 28px 20px' }}>
          <style>{`
            .sg2-table { border-collapse: separate; border-spacing: 0; table-layout: fixed; }
            .sg2-table td, .sg2-table th { padding: 0; }
            .sg2-table thead th { position: sticky; z-index: 4; background: ${COLORS.slate}; }
            .sg2-table thead tr.sg2-hrow-a th { top: 0; }
            .sg2-table thead tr.sg2-hrow-b th { top: 64px; }
            .sg2-sticky { position: sticky; z-index: 3; background: ${COLORS.slate}; }
            .sg2-table thead .sg2-sticky { z-index: 6; }
            .sg2-row:hover .sg2-hoverable { background: linear-gradient(rgba(255,255,255,0.05), rgba(255,255,255,0.05)), ${COLORS.slate} !important; }
          `}</style>
          <table className="sg2-table" style={{ width: '100%', minWidth: LEFT_W + races.length * (isCon ? 60 : split ? perRaceCols * 30 : 50) }}>
            <colgroup>
              <col style={{ width: LW.pos }} />
              <col style={{ width: LW.team }} />
              <col style={{ width: LW.name }} />
              <col style={{ width: LW.num }} />
              <col style={{ width: LW.pts }} />
              {races.map((rc) => {
                if (!split || isCon) return <col key={rc.round} />;
                const cols = [<col key={rc.round + 'q'} />];
                if (hasSprints) cols.push(<col key={rc.round + 's'} />);
                cols.push(<col key={rc.round + 'r'} />);
                if (showPtsCol) cols.push(<col key={rc.round + 'p'} />);
                return cols;
              })}
            </colgroup>
            <thead>
              {/* Row A — branding + subtle round numbers */}
              <tr className="sg2-hrow-a" style={{ height: 64 }}>
                <th className="sg2-sticky sg2-brand-th" rowSpan={2} colSpan={5} style={{ left: 0, padding: 0, verticalAlign: 'top', borderRight: '1px solid rgba(226,6,0,0.35)', borderBottom: headBorder }}>
                  <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column' }}>
                    <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'flex-start', gap: 12, padding: '6px 10px 0 20px', overflow: 'hidden' }}>
                      <img src={L.logo} alt={L.short} style={{ height: 42, width: 'auto', maxWidth: 116, objectFit: 'contain', flexShrink: 0 }} />
                      <div style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: 16, letterSpacing: '0.01em', textTransform: 'uppercase', color: COLORS.text, lineHeight: 1, whiteSpace: 'nowrap' }}>
                        {L.name} <span style={{ color: COLORS.red }}>· {activeId || ''}</span>
                      </div>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'flex-end', paddingBottom: 8 }}>
                      <span style={{ width: LW.pos, textAlign: 'center', fontFamily: 'JetBrains Mono', fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase', color: COLORS.textMute }}>POS</span>
                      <span style={{ width: LW.team }}></span>
                      <span style={{ width: LW.name, paddingLeft: 12, fontFamily: 'JetBrains Mono', fontSize: 9, letterSpacing: '0.2em', textTransform: 'uppercase', color: COLORS.textMute }}>{isCon ? 'Constructor' : 'Driver'}</span>
                      <span style={{ width: LW.num, textAlign: 'center', fontFamily: 'JetBrains Mono', fontSize: 9, textTransform: 'uppercase', color: COLORS.textMute }}>{isCon ? '' : '#'}</span>
                      <span style={{ width: LW.pts, textAlign: 'right', paddingRight: 12, fontFamily: 'JetBrains Mono', fontSize: 9, letterSpacing: '0.2em', textTransform: 'uppercase', color: COLORS.textMute }}>Pts</span>
                    </div>
                  </div>
                </th>
                {races.map((rc) => (
                  <th key={rc.round} colSpan={perRaceCols} style={{ verticalAlign: 'middle', textAlign: 'center', borderLeft: split ? '1px solid rgba(255,255,255,0.11)' : '1px solid rgba(255,255,255,0.055)' }}>
                    <span style={{ fontFamily: 'JetBrains Mono', fontSize: 9, fontWeight: 700, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.28)', opacity: rc.raced ? 1 : 0.5 }}>R{rc.round}</span>
                  </th>
                ))}
              </tr>
              {/* Row B — track minimaps (left block is covered by the branding rowSpan) */}
              <tr className="sg2-hrow-b" style={{ height: 42 }}>
                {races.map((rc) => (
                  <th key={rc.round} colSpan={perRaceCols} style={{ verticalAlign: 'bottom', borderLeft: split ? '1px solid rgba(255,255,255,0.11)' : '1px solid rgba(255,255,255,0.055)', borderBottom: headBorder, paddingBottom: 6 }}>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5, opacity: rc.raced ? 1 : 0.38 }}>
                      {rc.minimap ?
                        <img src={rc.minimap} alt="" style={{ height: 36, width: 52, objectFit: 'contain', opacity: 0.9 }} /> :
                        <span style={{ height: 36, display: 'flex', alignItems: 'center', fontFamily: 'JetBrains Mono', fontSize: 9, color: COLORS.textDim }}>·</span>}
                      <span style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: 11, letterSpacing: '0.06em', color: rc.code ? COLORS.text : COLORS.textDim }}>{rc.code || 'TBA'}</span>
                      {split && !isCon &&
                        <div style={{ display: 'flex', width: '100%', marginTop: 1 }}>
                          <span style={{ flex: 1, textAlign: 'center', fontFamily: 'JetBrains Mono', fontSize: 7.5, fontWeight: 700, letterSpacing: '0.1em', color: COLORS.textDim }}>Q</span>
                          {hasSprints &&
                            <span style={{ flex: 1, textAlign: 'center', fontFamily: 'JetBrains Mono', fontSize: 7.5, fontWeight: 700, letterSpacing: '0.1em', color: COLORS.textDim }}>S</span>}
                          <span style={{ flex: 1, textAlign: 'center', fontFamily: 'JetBrains Mono', fontSize: 7.5, fontWeight: 700, letterSpacing: '0.1em', color: COLORS.textMute }}>R</span>
                          {showPtsCol &&
                            <span style={{ flex: 1, textAlign: 'center', fontFamily: 'JetBrains Mono', fontSize: 7.5, fontWeight: 700, letterSpacing: '0.1em', color: COLORS.textDim }}>PTS</span>}
                        </div>}
                    </div>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {isCon ? conRows.map((t) => {
                const isP1 = t.pos === 1;
                const rowBg = isP1 ? 'rgba(226,6,0,0.12)' : 'rgba(255,255,255,0.02)';
                const stickyBg = `linear-gradient(${rowBg}, ${rowBg}), ${COLORS.slate}`;
                const gap = (conRows[0] ? conRows[0].pts : 0) - t.pts;
                const cellBorder = '1px solid rgba(255,255,255,0.05)';
                return (
                  <tr key={t.short} className="sg2-row" style={{ height: 44 }}>
                    <td className="sg2-sticky sg2-hoverable" style={{ left: LEFTS.pos, textAlign: 'center', background: stickyBg, borderBottom: cellBorder }}>
                      <span style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: isP1 ? 19 : 16, color: isP1 ? COLORS.red : COLORS.text, fontVariantNumeric: 'tabular-nums' }}>{t.pos}</span>
                    </td>
                    <td className="sg2-sticky sg2-hoverable" style={{ left: LEFTS.team, textAlign: 'center', background: stickyBg, borderBottom: cellBorder }}>
                      {UR_TEAM_LOGO[t.short] &&
                        <img src={UR_TEAM_LOGO[t.short]} alt={t.short} style={{ height: 34, width: 34, objectFit: 'contain', display: 'block', margin: '0 auto', filter: UR_TEAM_LOGO_DARK.has(t.short) ? 'brightness(0.4)' : 'none' }} />}
                    </td>
                    <td className="sg2-sticky sg2-hoverable" style={{ left: LEFTS.name, background: stickyBg, borderBottom: cellBorder, position: 'sticky' }}>
                      <div style={{ height: '100%', display: 'flex', alignItems: 'center', gap: 9, padding: '0 10px', overflow: 'hidden' }}>
                        <span style={{ width: 3, height: 20, background: t.color || COLORS.textDim, flexShrink: 0 }}></span>
                        <span style={{ fontFamily: 'Archivo', fontWeight: 800, fontSize: 15, letterSpacing: '0.01em', textTransform: 'uppercase', color: COLORS.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.name || t.short}</span>
                      </div>
                    </td>
                    <td className="sg2-sticky sg2-hoverable" style={{ left: LEFTS.num, background: stickyBg, borderBottom: cellBorder }}></td>
                    <td className="sg2-sticky sg2-hoverable" style={{ left: LEFTS.pts, textAlign: 'right', paddingRight: 12, background: stickyBg, borderRight: '1px solid rgba(226,6,0,0.35)', borderBottom: cellBorder }}>
                      <span style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: isP1 ? 19 : 16, color: COLORS.text, fontVariantNumeric: 'tabular-nums' }}>{t.pts}</span>
                      {!isP1 && gap > 0 &&
                        <span style={{ display: 'block', marginTop: -2, fontFamily: 'JetBrains Mono', fontSize: 8.5, color: COLORS.textDim, fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>−{gap}</span>}
                    </td>
                    {races.map((rc) => {
                      const c = ((rc.raced || conRacedRounds.has(rc.round)) && t.rounds[rc.round]) || {};
                      return <SG2CCell key={rc.round} pts={c.pts} pos={c.pos} />;
                    })}
                  </tr>
                );
              }) : drivers.map((d) => {
                const isP1 = d.pos === 1;
                const rounds = byDriver[sg2Norm(d.name)] || {};
                const team = teamByShort[d.team] || recentTeamFor(d.name);
                const tColor = team ? team.color : COLORS.textDim;
                const rowBg = isP1 ? 'rgba(226,6,0,0.12)' : 'rgba(255,255,255,0.02)';
                const stickyBg = `linear-gradient(${rowBg}, ${rowBg}), ${COLORS.slate}`;
                const gap = drivers[0].pts - d.pts;
                const cellBorder = '1px solid rgba(255,255,255,0.05)';
                return (
                  <tr key={d.name + d.pos} className="sg2-row" style={{ height: 44 }}>
                    <td className="sg2-sticky sg2-hoverable" style={{ left: LEFTS.pos, textAlign: 'center', background: stickyBg, borderBottom: cellBorder }}>
                      <span style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: isP1 ? 19 : 16, color: isP1 ? COLORS.red : COLORS.text, fontVariantNumeric: 'tabular-nums' }}>{d.pos}</span>
                    </td>
                    <td className="sg2-sticky sg2-hoverable" style={{ left: LEFTS.team, textAlign: 'center', background: stickyBg, borderBottom: cellBorder }}>
                      {team && UR_TEAM_LOGO[team.short] &&
                        <img src={UR_TEAM_LOGO[team.short]} alt={team.short} style={{ height: 34, width: 34, objectFit: 'contain', display: 'block', margin: '0 auto', filter: UR_TEAM_LOGO_DARK.has(team.short) ? 'brightness(0.4)' : 'none' }} />}
                    </td>
                    <td className="sg2-sticky sg2-hoverable" style={{ left: LEFTS.name, background: stickyBg, borderBottom: cellBorder, position: 'sticky' }}>
                      <div style={{ position: 'relative', height: '100%', display: 'flex', alignItems: 'center', padding: '0 10px', overflow: 'hidden' }}>
                        <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 7, minWidth: 0 }}>
                          <span style={{ fontFamily: 'Archivo', fontWeight: 800, fontSize: 15, letterSpacing: '0.01em', textTransform: 'uppercase', color: COLORS.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.name}</span>
                          <FlagSvg kind={d.country || getDriverFlag(d.name) || null} w={16} h={11} radius={1.5} />
                        </div>
                      </div>
                    </td>
                    <td className="sg2-sticky sg2-hoverable" style={{ left: LEFTS.num, textAlign: 'center', background: stickyBg, borderBottom: cellBorder }}>
                      <span style={{ fontFamily: 'JetBrains Mono', fontWeight: 700, fontSize: 11, color: COLORS.textMute, fontVariantNumeric: 'tabular-nums' }}>{d.carNumber != null ? d.carNumber : ''}</span>
                    </td>
                    <td className="sg2-sticky sg2-hoverable" style={{ left: LEFTS.pts, textAlign: 'right', paddingRight: 12, background: stickyBg, borderRight: '1px solid rgba(226,6,0,0.35)', borderBottom: cellBorder }}>
                      <span style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: isP1 ? 19 : 16, color: COLORS.text, fontVariantNumeric: 'tabular-nums' }}>{d.pts}</span>
                      {!isP1 && gap > 0 &&
                        <span style={{ display: 'block', marginTop: -2, fontFamily: 'JetBrains Mono', fontSize: 8.5, color: COLORS.textDim, fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>−{gap}</span>}
                    </td>
                    {races.map((rc) => {
                      const cell = rounds[rc.round] || rounds[String(rc.round)] || {};
                      if (!split) return <SG2Cell key={rc.round} q={cell.q} r={cell.r} />;
                      const parts = [<SG2QCell key={rc.round + 'q'} q={cell.q} />];
                      if (hasSprints) parts.push(<SG2SCell key={rc.round + 's'} s={cell.s} />);
                      parts.push(<SG2RCell key={rc.round + 'r'} r={cell.r} p={cell.p} showPts={showPtsInCell} />);
                      if (showPtsCol) parts.push(<SG2PCell key={rc.round + 'p'} p={cell.p} r={cell.r} />);
                      return parts;
                    })}
                  </tr>
                );
              })}
            </tbody>
          </table>

          {/* legend — quiet, single line */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 20, padding: '12px 2px 0' }}>
            <span style={{ fontFamily: 'JetBrains Mono', fontSize: 9, letterSpacing: '0.16em', textTransform: 'uppercase', color: COLORS.textDim }}>{isCon ? (conHasRounds ? 'Big = weekend points · small = best car finish' : 'Per-round constructor points unavailable for this season') : split ? (hasSprints ? 'Q = grid · S = sprint · R = feature' : 'Q = grid · R = race finish') : 'Big = race finish · small = grid'}</span>
            {[1, 2, 3].map((p) => (
              <span key={p} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ width: 12, height: 12, background: SG2_METAL[p].flat, display: 'inline-block' }}></span>
                <span style={{ fontFamily: 'JetBrains Mono', fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase', color: COLORS.textDim }}>{p === 1 ? 'Win' : p === 2 ? '2nd' : '3rd'}</span>
              </span>
            ))}
            <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 3, height: 12, background: SG2_POLE, display: 'inline-block' }}></span>
              <span style={{ fontFamily: 'JetBrains Mono', fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase', color: COLORS.textDim }}>Pole</span>
            </span>
          </div>
        </div>
      }
    </section>
  );
};

Object.assign(window, { URStandingsWall, SG2QCell, SG2RCell, SG2PCell, SG2SCell, SG2CCell });
