/* soccerarena.ai — AI Odds page body. Eurovision-style ranked win/advance odds. */
function preLabel(startDate) {
  const days = Math.ceil((new Date(startDate + 'T00:00:00Z') - Date.now()) / 86400000);
  return days > 0 ? `T-${days}` : 'PRE-TOURNAMENT';
}

const { useState: useStateO } = React;

function OddsPanel({ title, sub, children }) {
  return (
    <section style={{ border: `1px solid ${SA.line2}`, background: SA.turf2 }}>
      <div style={{ padding: '13px 20px', borderBottom: `1px solid ${SA.line2}`, display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12 }}>
        <h2 style={{ margin: 0, fontFamily: SA.sans, fontWeight: 800, fontSize: 12, letterSpacing: '0.12em', color: SA.white, textTransform: 'uppercase' }}>{title}</h2>
        {sub && <span style={{ fontFamily: SA.mono, fontSize: 10, color: SA.faint }}>{sub}</span>}
      </div>
      <div>{children}</div>
    </section>
  );
}

function OddsPage() {
  const odds = ARENA.odds;
  const isMobile = useIsMobile();
  const tabs = (odds && odds.tabs) || [];
  const firstAvail = (tabs.find(t => t.available) || tabs[0] || {}).key;
  const [active, setActive] = useStateO(firstAvail);

  if (!odds || tabs.length === 0) {
    return (
      <div style={{ maxWidth: 760, margin: '0 auto', padding: '48px 28px' }}>
        <p style={{ fontFamily: SA.sans, color: SA.dim }}>Odds are not available yet.</p>
      </div>
    );
  }

  const tab = tabs.find(t => t.key === active) || tabs[0];
  const teams = tab.teams || [];
  const leadP = teams.length ? teams[0].p : 1;

  const colW = isMobile ? '26px 1fr 64px 56px' : '40px 1fr 200px 72px 84px';

  const tabBtn = (t) => {
    const on = t.key === active;
    return (
      <button key={t.key} onClick={() => setActive(t.key)} disabled={!t.available}
        style={{
          appearance: 'none', cursor: t.available ? 'pointer' : 'not-allowed',
          background: on ? SA.lime : 'transparent',
          color: on ? SA.turf : (t.available ? SA.dim : SA.faint),
          border: `1px solid ${on ? SA.lime : SA.line2}`,
          padding: isMobile ? '8px 11px' : '9px 16px',
          fontFamily: SA.sans, fontWeight: 700, fontSize: isMobile ? 12 : 13,
          letterSpacing: '0.01em', whiteSpace: 'nowrap', lineHeight: 1.1,
          display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 3,
        }}>
        <span>{t.label}</span>
        <span style={{ fontFamily: SA.mono, fontSize: 9, fontWeight: 500, color: on ? 'rgba(10,31,15,0.7)' : SA.faint, letterSpacing: '0.04em' }}>
          {t.available ? t.sub : 'soon'}
        </span>
      </button>
    );
  };

  return (
    <div style={{ maxWidth: 1180, margin: '0 auto', padding: isMobile ? '14px 12px 24px' : '28px 28px 32px' }}>

      {/* hero */}
      <div style={{ border: `1px solid ${SA.line}`, background: SA.surface, borderLeft: `2px solid ${SA.lime}`, padding: isMobile ? '16px 14px' : '22px 24px', marginBottom: 18 }}>
        <div style={{ fontFamily: SA.mono, fontSize: 9.5, letterSpacing: '0.08em', color: SA.faint, marginBottom: 6 }}>
          AI CONSENSUS · {odds.tournamentDay > 0 ? `DAY ${odds.tournamentDay}` : preLabel(ARENA.tournament.startDate)}
        </div>
        <h1 style={{ margin: '0 0 8px', fontFamily: SA.sans, fontWeight: 800, fontSize: isMobile ? 22 : 30, color: SA.white, letterSpacing: '-0.02em' }}>
          AI Odds
        </h1>
        <p style={{ margin: 0, fontFamily: SA.sans, fontSize: isMobile ? 13 : 14.5, lineHeight: 1.6, color: SA.dim, maxWidth: 640 }}>
          Every team's chance at the 2026 World Cup, aggregated from {ARENA.models.length} frontier AI models'
          predictions — not bookmakers. Pick a market below.
        </p>
      </div>

      {/* tab bar */}
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 16 }}>
        {tabs.map(tabBtn)}
      </div>

      {tab.available ? (
        <OddsPanel
          title={tab.label}
          sub={`${tab.source} · ${tab.denomLabel}${tab.sumsToHundred ? ' · sums to 100%' : ''}`}
        >
          {/* column header */}
          <div style={{ display: 'grid', gridTemplateColumns: colW, alignItems: 'center', gap: isMobile ? 8 : 14, padding: isMobile ? '10px 14px' : '11px 20px', borderBottom: `1px solid ${SA.line}`, fontFamily: SA.mono, fontSize: 9.5, letterSpacing: '0.06em', color: SA.faint }}>
            <span>#</span>
            <span>TEAM</span>
            {!isMobile && <span>CHANCE</span>}
            <span style={{ textAlign: 'right' }}>{isMobile ? '%' : 'CHANCE'}</span>
            <span style={{ textAlign: 'right' }}>ODDS</span>
          </div>

          {teams.map((t, i) => (
            <div key={t.code + i} style={{
              display: 'grid', gridTemplateColumns: colW, alignItems: 'center', gap: isMobile ? 8 : 14,
              padding: isMobile ? '10px 14px' : '11px 20px',
              borderBottom: i < teams.length - 1 ? `1px solid ${SA.line2}` : 'none',
              background: i === 0 ? 'rgba(200,245,58,0.05)' : 'transparent',
            }}>
              <span style={{ fontFamily: SA.mono, fontSize: 12, color: i === 0 ? SA.lime : SA.faint, fontVariantNumeric: 'tabular-nums' }}>{i + 1}</span>
              <div style={{ display: 'flex', alignItems: 'center', gap: 9, minWidth: 0 }}>
                <span style={{ fontSize: isMobile ? 16 : 18, flexShrink: 0, lineHeight: 1 }}>{t.flag}</span>
                <span style={{ fontFamily: SA.sans, fontWeight: i === 0 ? 700 : 600, fontSize: isMobile ? 13.5 : 15, color: SA.white, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.name}</span>
              </div>
              {!isMobile && (
                <div style={{ height: 7, background: SA.line2, position: 'relative' }}>
                  <div style={{ position: 'absolute', inset: 0, width: `${leadP > 0 ? (t.p / leadP) * 100 : 0}%`, background: i === 0 ? SA.lime : SA.limeDim }} />
                </div>
              )}
              <span style={{ textAlign: 'right', fontFamily: SA.mono, fontWeight: 700, fontSize: isMobile ? 13 : 15, color: i === 0 ? SA.lime : (t.p > 0 ? SA.white : SA.faint), fontVariantNumeric: 'tabular-nums' }}>
                {t.p > 0 ? `${t.pct}%` : '<1%'}
              </span>
              <span style={{ textAlign: 'right', fontFamily: SA.mono, fontSize: isMobile ? 11 : 12, color: SA.faint, fontVariantNumeric: 'tabular-nums' }}>
                {t.odds != null ? t.odds.toFixed(2) : '—'}
              </span>
            </div>
          ))}

        </OddsPanel>
      ) : (
        <OddsPanel title={tab.label} sub={`${tab.source} · pending`}>
          <div style={{ padding: isMobile ? '24px 16px' : '32px 24px' }}>
            <p style={{ margin: '0 0 8px', fontFamily: SA.sans, fontWeight: 600, fontSize: 15, color: SA.white }}>
              Waiting on Track 2 match predictions.
            </p>
            <p style={{ margin: 0, fontFamily: SA.sans, fontSize: 13.5, lineHeight: 1.65, color: SA.dim, maxWidth: 560 }}>
              "{tab.sub}" odds are derived from each model's predictions for all 72 group games. Once the
              models forecast the group stage, every team's chance of advancing to the Round of 32 appears
              here — aggregated across the arena.
            </p>
          </div>
        </OddsPanel>
      )}

      {/* methodology note */}
      <div style={{ marginTop: 16, padding: isMobile ? '14px 16px' : '16px 20px', border: `1px solid ${SA.line2}`, background: SA.turf2 }}>
        <div style={{ fontFamily: SA.mono, fontSize: 9.5, letterSpacing: '0.08em', color: SA.faint, marginBottom: 8 }}>HOW THESE ARE CALCULATED</div>
        <p style={{ margin: 0, fontFamily: SA.sans, fontSize: 13, lineHeight: 1.7, color: SA.dim }}>
          <strong style={{ color: SA.white }}>Win</strong> blends each model's stated winner confidence with its bracket — the champion takes its confidence, the rest is shared down across runner-up, semi-finalists, and quarter-finalists (weighted 4 : 2 : 1 by depth) — then averages across models, so the column sums to 100%.{' '}
          <strong style={{ color: SA.white }}>Reach Final / Reach Semis</strong> are the share of models placing a team in the final or the last four.{' '}
          <strong style={{ color: SA.white }}>Out of Group</strong> resolves each model's group-stage match picks into a table and counts how often a team advances to the Round of 32.{' '}
          <a href={SA_ROOT + 'methodology.html'} style={{ color: SA.lime, textDecoration: 'none' }}>Full methodology →</a>
        </p>
      </div>
    </div>
  );
}

Object.assign(window, { OddsPage });
