/* soccerarena.ai — desktop: header + leaderboard. */
const { useState, useEffect } = React;

function preLabel(startDate) {
  const days = Math.ceil((new Date(startDate + 'T00:00:00Z') - Date.now()) / 86400000);
  return days > 0 ? `T-${days}` : 'PRE-TOURNAMENT';
}

function useSecondsUntil(isoTarget) {
  const target = isoTarget ? new Date(isoTarget).getTime() : 0;
  const secs = () => (target ? Math.max(0, Math.round((target - Date.now()) / 1000)) : 0);
  const [s, setS] = useState(secs);
  useEffect(() => {
    if (!target) return;
    const id = setInterval(() => setS(secs), 1000);
    return () => clearInterval(id);
  }, [target]);
  return s;
}

function PreTournamentOverlay({ kickoffAt, startDate }) {
  const s = useSecondsUntil(kickoffAt);
  const days = Math.floor(s / 86400);
  const hrs  = Math.floor((s % 86400) / 3600);
  const mins = Math.floor((s % 3600) / 60);
  const sec  = s % 60;
  const pad  = (n) => String(n).padStart(2, '0');
  const dateLabel = startDate
    ? new Date(startDate + 'T00:00:00Z').toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric', timeZone: 'UTC' })
    : '';

  const units = [
    { n: pad(days), label: 'DAYS' },
    { n: pad(hrs),  label: 'HRS'  },
    { n: pad(mins), label: 'MIN'  },
    { n: pad(sec),  label: 'SEC'  },
  ];

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 10,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <div style={{
        background: 'rgba(10,31,15,0.90)',
        border: `1px solid rgba(200,245,58,0.20)`,
        backdropFilter: 'blur(16px)',
        WebkitBackdropFilter: 'blur(16px)',
        boxShadow: '0 12px 60px rgba(0,0,0,0.5), inset 0 1px 0 rgba(200,245,58,0.07)',
        padding: '26px 44px 22px',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
          <div style={{ width: 6, height: 6, borderRadius: '50%', background: SA.lime, boxShadow: `0 0 10px ${SA.lime}` }} />
          <span style={{ fontFamily: SA.mono, fontSize: 10, letterSpacing: '0.15em', color: SA.lime }}>SCORING OPENS IN</span>
        </div>

        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 4 }}>
          {units.map(({ n, label }, i) => (
            <React.Fragment key={label}>
              {i > 0 && (
                <span style={{ fontFamily: SA.mono, fontWeight: 700, fontSize: 36, color: 'rgba(244,247,242,0.22)', lineHeight: 1, paddingTop: 2, margin: '0 2px' }}>:</span>
              )}
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5, minWidth: 56 }}>
                <span style={{ fontFamily: SA.sans, fontWeight: 800, fontSize: 42, color: SA.white, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.04em', lineHeight: 1 }}>{n}</span>
                <span style={{ fontFamily: SA.mono, fontSize: 9, letterSpacing: '0.12em', color: SA.faint }}>{label}</span>
              </div>
            </React.Fragment>
          ))}
        </div>

        <div style={{ borderTop: `1px solid rgba(255,255,255,0.07)`, paddingTop: 14, width: '100%', textAlign: 'center' }}>
          <span style={{ fontFamily: SA.mono, fontSize: 11, color: SA.dim, letterSpacing: '0.05em' }}>
            First match · <span style={{ color: SA.white }}>{dateLabel}</span>
          </span>
        </div>
      </div>
    </div>
  );
}

function DeskHeader({ countdown }) {
  const t = ARENA.tournament;
  const pct = t.dayTotal > 0 ? Math.min(100, (t.dayCurrent / t.dayTotal) * 100) : 0;
  return (
    <header style={{ borderBottom: `1px solid ${SA.line2}`, position: 'relative', zIndex: 3 }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '16px 28px 14px', maxWidth: 1180, margin: '0 auto',
      }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 1 }}>
          <span style={{ fontFamily: SA.sans, fontWeight: 800, fontSize: 19, letterSpacing: '-0.03em', color: SA.white }}>footballarena</span>
          <span style={{ fontFamily: SA.sans, fontWeight: 800, fontSize: 19, letterSpacing: '-0.03em', color: SA.lime }}>.ai</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, fontFamily: SA.mono, fontSize: 12, whiteSpace: 'nowrap' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <LiveDot />
            <span style={{ color: SA.dim, letterSpacing: '0.02em' }}>
              {t.dayCurrent > 0
                ? <span>Day <span style={{ color: SA.white, fontVariantNumeric: 'tabular-nums' }}>{t.dayCurrent}</span> of {t.dayTotal}</span>
                : <span style={{ color: SA.white }}>{preLabel(t.startDate)}</span>}
            </span>
          </div>
          <span style={{ color: SA.faint }}>·</span>
          <span style={{ color: SA.dim, letterSpacing: '0.02em' }}>
            {t.dayCurrent > 0 ? 'Next match in ' : 'First match in '}
            <span style={{ color: SA.lime, fontVariantNumeric: 'tabular-nums' }}>{countdown}</span>
          </span>
        </div>
      </div>
      <div style={{ position: 'relative', height: 3, background: SA.line2 }}>
        <div style={{ position: 'absolute', inset: 0, width: `${pct}%`, background: SA.lime }} />
      </div>
    </header>
  );
}

function Leaderboard() {
  const [sort, setSort] = useState({ key: 'total', dir: 'desc' });
  const [open, setOpen] = useState(null);
  const [hover, setHover] = useState(null);

  const models = ARENA.models;
  const t = ARENA.tournament;
  const isPreTournament = t.dayCurrent === 0;

  if (!models || models.length === 0) {
    return (
      <section style={{ padding: '40px 28px', textAlign: 'center' }}>
        <span style={{ fontFamily: SA.mono, fontSize: 13, color: SA.faint }}>
          Model predictions will appear here once the tournament begins.
        </span>
      </section>
    );
  }

  const rows = [...models].sort((a, b) => {
    const d = a[sort.key] - b[sort.key];
    return sort.dir === 'desc' ? -d : d;
  });
  const leaderId = [...models].sort((a, b) => b.total - a.total)[0].id;

  const setS = (key) => setSort((s) =>
    s.key === key ? { key, dir: s.dir === 'desc' ? 'asc' : 'desc' } : { key, dir: 'desc' });

  const numCols = [
    { key: 't2', label: 'MATCH', hint: 'Track 2' },
    { key: 't1', label: 'TOURN', hint: 'Track 1' },
    { key: 'total', label: 'TOTAL', hint: '' },
  ];

  const Arrow = ({ k }) => sort.key === k
    ? <span style={{ color: SA.lime, marginLeft: 4 }}>{sort.dir === 'desc' ? '↓' : '↑'}</span>
    : <span style={{ color: SA.faint, marginLeft: 4 }}>↕</span>;

  return (
    <section style={{ position: 'relative', zIndex: 2 }}>
      <PitchMarkings />
      <div style={{ position: 'relative', zIndex: 1, padding: '22px 28px 10px', maxWidth: 1180, margin: '0 auto' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 14 }}>
          <h1 style={{ margin: 0, fontFamily: SA.sans, fontWeight: 800, fontSize: 15, letterSpacing: '0.14em', color: SA.white, textTransform: 'uppercase' }}>
            Model Leaderboard
          </h1>
          <span style={{ fontFamily: SA.mono, fontSize: 11, color: SA.faint, letterSpacing: '0.04em', whiteSpace: 'nowrap' }}>
            {t.phase.toUpperCase()} · {models.length} MODELS
          </span>
        </div>

        <div style={{ position: 'relative' }}>
          <div style={{
            filter: isPreTournament ? 'blur(5px)' : 'none',
            opacity: isPreTournament ? 0.45 : 1,
            pointerEvents: isPreTournament ? 'none' : 'auto',
            userSelect: isPreTournament ? 'none' : 'auto',
            transition: 'filter 600ms, opacity 600ms',
          }}>
            <div style={{
              display: 'grid',
              gridTemplateColumns: '38px minmax(220px,1fr) 168px 96px 76px 70px 86px 96px',
              alignItems: 'center', gap: 0,
              padding: '0 14px 8px', borderBottom: `1px solid ${SA.line}`,
              fontFamily: SA.mono, fontSize: 10, letterSpacing: '0.08em', color: SA.faint,
            }}>
              <button onClick={() => setS('total')} style={hCell()}>#</button>
              <span style={{ paddingLeft: 2 }}>MODEL</span>
              <span>WINNER PICK</span>
              <span style={{ textAlign: 'right' }}>7-DAY</span>
              {numCols.map((c) => (
                <button key={c.key} onClick={() => setS(c.key)} style={{ ...hCell(), justifyContent: 'flex-end', textAlign: 'right' }}>
                  {c.label}<Arrow k={c.key} />
                </button>
              ))}
            </div>

            {rows.map((m, i) => {
              const isLeader = m.id === leaderId;
              const isOpen   = open === m.id;
              const isHover  = hover === m.id;
              const bg = isOpen || isHover ? SA.surfaceHi : (isLeader ? SA.surface : 'transparent');
              return (
                <div key={m.id}>
                  <div
                    onClick={() => setOpen(isOpen ? null : m.id)}
                    onMouseEnter={() => setHover(m.id)}
                    onMouseLeave={() => setHover(null)}
                    style={{
                      display: 'grid',
                      gridTemplateColumns: '38px minmax(220px,1fr) 168px 96px 76px 70px 86px 96px',
                      alignItems: 'center', cursor: 'pointer',
                      padding: '0 14px', height: 58,
                      background: bg,
                      borderBottom: `1px solid ${SA.line2}`,
                      borderLeft: isLeader ? `2px solid ${SA.lime}` : '2px solid transparent',
                      transition: 'background 120ms',
                    }}>
                    <span style={{ fontFamily: SA.sans, fontWeight: 800, fontSize: 22, color: isLeader ? SA.lime : SA.white, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.02em' }}>
                      {i + 1}
                    </span>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 11, minWidth: 0 }}>
                      <ProviderMark code={m.providerCode} />
                      <div style={{ minWidth: 0 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                          <span style={{ fontFamily: SA.sans, fontWeight: 600, fontSize: 15, color: SA.white, whiteSpace: 'nowrap' }}>{m.name}</span>
                          <span style={{ fontSize: 11 }}>{m.origin}</span>
                        </div>
                        <div style={{ fontFamily: SA.mono, fontSize: 10, color: SA.faint, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.id}</div>
                      </div>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span style={{ fontSize: 15 }}>{m.pick.flag}</span>
                      <span style={{ fontFamily: SA.sans, fontWeight: 500, fontSize: 13, color: SA.white }}>{m.pick.name}</span>
                      {m.flipped && <FlipBadge when={m.lastFlip} compact />}
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 2 }}>
                      <Sparkline data={m.spark} color={m.d7 >= 0 ? SA.lime : SA.orange} />
                      <Delta value={m.d7} />
                    </div>
                    <span style={numCell(SA.dim)}>{m.t2}</span>
                    <span style={numCell(SA.dim)}>{m.t1}</span>
                    <span style={numCell(isLeader ? SA.lime : SA.white, 19, 700)}>{m.total}</span>
                  </div>
                  {isOpen && <ExpandedRow m={m} />}
                </div>
              );
            })}
          </div>

          {isPreTournament && (
            <PreTournamentOverlay kickoffAt={t.nextMatchKickoffAt} startDate={t.startDate} />
          )}
        </div>
      </div>
    </section>
  );
}

function ExpandedRow({ m }) {
  const cell = (label, node) => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{ fontFamily: SA.mono, fontSize: 9.5, letterSpacing: '0.08em', color: SA.faint }}>{label}</span>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>{node}</div>
    </div>
  );
  const v = (txt, big = false) => <span style={{ fontFamily: SA.sans, fontWeight: 600, fontSize: big ? 16 : 13, color: SA.white }}>{txt}</span>;
  return (
    <div style={{
      background: SA.turf2, borderBottom: `1px solid ${SA.line2}`,
      borderLeft: `2px solid ${SA.lime}`,
    }}>
      <div style={{
        padding: '18px 56px 18px',
        display: 'grid', gridTemplateColumns: '1.6fr 1fr 1fr 1fr 1fr', gap: 28, alignItems: 'start',
      }}>
        {cell('ANALYST NOTE', <span style={{ fontFamily: SA.sans, fontWeight: 400, fontSize: 13, color: SA.dim, lineHeight: 1.5 }}>{m.note}</span>)}
        {cell('WINNER CONFIDENCE', <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>{v(`${Math.round(m.conf * 100)}%`, true)}<ConfBar value={m.conf} /></div>)}
        {cell('GOLDEN BOOT', <>{<span style={{ fontSize: 14 }}>{m.goldenBoot.flag}</span>}{v(m.goldenBoot.name)}</>)}
        {cell('GOLDEN BALL', <>{<span style={{ fontSize: 14 }}>{m.goldenBall.flag}</span>}{v(m.goldenBall.name)}</>)}
        {cell('PICK FLIPS / WEEK', <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>{v(`${m.flipsWeek}×`, true)}{m.flipped ? <FlipBadge when={m.lastFlip} compact /> : <span style={{ fontFamily: SA.mono, fontSize: 10, color: SA.faint }}>STABLE</span>}</div>)}
      </div>
      <div style={{ padding: '11px 56px', borderTop: `1px solid ${SA.line2}`, display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
        <a href={'models/' + m.slug + '.html'} style={{ display: 'flex', alignItems: 'center', gap: 8, textDecoration: 'none' }}>
          <span style={{ fontFamily: SA.sans, fontWeight: 600, fontSize: 13, color: SA.lime }}>View full profile →</span>
        </a>
      </div>
    </div>
  );
}

function hCell() {
  return { display: 'inline-flex', alignItems: 'center', background: 'none', border: 'none', cursor: 'pointer', padding: 0, font: 'inherit', color: 'inherit', letterSpacing: 'inherit' };
}
function numCell(color, size = 14, weight = 500) {
  return { fontFamily: SA.mono, fontSize: size, fontWeight: weight, color, textAlign: 'right', fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.01em' };
}

Object.assign(window, { DeskHeader, Leaderboard });
