/* soccerarena.ai — mobile: collapsed single-column card stack. */
const { useState: useSt, useEffect: useEf } = 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 useMobileSecondsUntil(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] = useSt(secs);
  useEf(() => {
    if (!target) return;
    const id = setInterval(() => setS(secs), 1000);
    return () => clearInterval(id);
  }, [target]);
  return s;
}

function MobilePreTournamentOverlay({ kickoffAt, startDate }) {
  const s = useMobileSecondsUntil(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: 'short', day: 'numeric', timeZone: 'UTC' })
    : '';

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 10,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '0 16px',
    }}>
      <div style={{
        background: 'rgba(10,31,15,0.92)',
        border: `1px solid rgba(200,245,58,0.20)`,
        backdropFilter: 'blur(16px)',
        WebkitBackdropFilter: 'blur(16px)',
        boxShadow: '0 8px 40px rgba(0,0,0,0.5), inset 0 1px 0 rgba(200,245,58,0.07)',
        padding: '20px 24px 18px',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14,
        width: '100%',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{ width: 5, height: 5, borderRadius: '50%', background: SA.lime, boxShadow: `0 0 8px ${SA.lime}` }} />
          <span style={{ fontFamily: SA.mono, fontSize: 9.5, letterSpacing: '0.14em', color: SA.lime }}>SCORING OPENS IN</span>
        </div>

        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 3 }}>
          {[
            { n: pad(days), label: 'DAYS' },
            { n: pad(hrs),  label: 'HRS'  },
            { n: pad(mins), label: 'MIN'  },
            { n: pad(sec),  label: 'SEC'  },
          ].map(({ n, label }, i) => (
            <React.Fragment key={label}>
              {i > 0 && (
                <span style={{ fontFamily: SA.mono, fontWeight: 700, fontSize: 28, color: 'rgba(244,247,242,0.22)', lineHeight: 1, paddingTop: 2, margin: '0 1px' }}>:</span>
              )}
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, minWidth: 44 }}>
                <span style={{ fontFamily: SA.sans, fontWeight: 800, fontSize: 32, color: SA.white, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.04em', lineHeight: 1 }}>{n}</span>
                <span style={{ fontFamily: SA.mono, fontSize: 8, letterSpacing: '0.1em', color: SA.faint }}>{label}</span>
              </div>
            </React.Fragment>
          ))}
        </div>

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

function MobileHeader({ countdown }) {
  const t = ARENA.tournament;
  const pct = t.dayTotal > 0 ? Math.min(100, (t.dayCurrent / t.dayTotal) * 100) : 0;
  const phaseShort = t.dayCurrent > 0 ? `D${t.dayCurrent}/${t.dayTotal}` : preLabel(t.startDate);
  return (
    <div style={{ padding: '6px 18px 0', background: SA.turf, position: 'sticky', top: 0, zIndex: 5 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingBottom: 12 }}>
        <div style={{ display: 'flex', alignItems: 'baseline' }}>
          <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: 7 }}>
          <LiveDot />
          <span style={{ fontFamily: SA.mono, fontSize: 11, color: SA.dim }}>{phaseShort}</span>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingBottom: 10, gap: 10 }}>
        <span style={{ fontFamily: SA.mono, fontSize: 10, color: SA.faint, letterSpacing: '0.04em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {t.phase.toUpperCase()}
        </span>
        <span style={{ fontFamily: SA.mono, fontSize: 10, color: SA.dim, whiteSpace: 'nowrap' }}>
          Next in <span style={{ color: SA.lime, fontVariantNumeric: 'tabular-nums' }}>{countdown}</span>
        </span>
      </div>
      <div style={{ position: 'relative', height: 3, background: SA.line2, marginBottom: 2 }}>
        <div style={{ position: 'absolute', inset: 0, width: `${pct}%`, background: SA.lime }} />
      </div>
    </div>
  );
}

function MobileModelCard({ m, rank }) {
  const isLeader = rank === 1;
  const cardStyle = {
    background: isLeader ? SA.surface : SA.turf2,
    border: `1px solid ${SA.line2}`,
    borderLeftWidth: 2,
    borderLeftColor: isLeader ? SA.lime : SA.line2,
  };
  return (
    <div style={cardStyle}>
      <a href={'models/' + m.slug + '.html'} style={{ display: 'block', textDecoration: 'none', padding: '14px 16px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <span style={{ fontFamily: SA.sans, fontWeight: 800, fontSize: 25, color: isLeader ? SA.lime : SA.white, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.03em', width: 24, flexShrink: 0 }}>{rank}</span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
              <span style={{ fontFamily: SA.sans, fontWeight: 600, fontSize: 14.5, color: SA.white, whiteSpace: 'nowrap' }}>{m.name}</span>
              <span style={{ fontSize: 11, flexShrink: 0 }}>{m.origin}</span>
            </div>
            <div style={{ fontFamily: SA.mono, fontSize: 9.5, color: SA.faint, whiteSpace: 'nowrap', marginTop: 2 }}>{m.provider}</div>
          </div>
          <div style={{ textAlign: 'right', flexShrink: 0 }}>
            <div style={{ fontFamily: SA.mono, fontWeight: 700, fontSize: 20, color: isLeader ? SA.lime : SA.white, fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>{m.total}</div>
            <div style={{ fontFamily: SA.mono, fontSize: 9, color: SA.faint, letterSpacing: '0.06em', marginTop: 3 }}>TOTAL</div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 13, paddingTop: 12, borderTop: `1px solid ${SA.line2}` }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ fontFamily: SA.mono, fontSize: 9.5, color: SA.faint, letterSpacing: '0.04em' }}>PICK</span>
            <span style={{ fontSize: 14 }}>{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', alignItems: 'center', gap: 8 }}>
            <Sparkline data={m.spark} w={48} h={18} color={m.d7 >= 0 ? SA.lime : SA.orange} />
            <Delta value={m.d7} />
          </div>
        </div>
      </a>
    </div>
  );
}

function MobileConsensus() {
  if (!ARENA.consensus || ARENA.consensus.length === 0) return null;
  return (
    <div style={{ padding: '12px 16px 4px' }}>
      <div style={{ fontFamily: SA.mono, fontSize: 9.5, letterSpacing: '0.08em', color: SA.faint, margin: '4px 0 10px' }}>
        TODAY'S CONSENSUS · {ARENA.models.length} MODELS
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        {ARENA.consensus.map((c, i) => (
          <a key={i} href={'awards/' + c.slug + '.html'} style={{
            background: SA.surface,
            border: `1px solid ${SA.line2}`,
            borderTop: `2px solid ${SA.lime}`,
            borderRadius: 4,
            padding: '10px 12px',
            display: 'block',
            textDecoration: 'none',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
              <span style={{ fontSize: 14, lineHeight: 1 }}>{c.emoji}</span>
              <span style={{ fontFamily: SA.mono, fontSize: 8.5, letterSpacing: '0.05em', color: SA.faint }}>{c.label.toUpperCase()}</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 5 }}>
              {c.flag && <span style={{ fontSize: 12, lineHeight: 1 }}>{c.flag}</span>}
              <span style={{ fontFamily: SA.sans, fontWeight: 700, fontSize: 13, color: SA.white, letterSpacing: '-0.02em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.value}</span>
            </div>
            <span style={{ fontFamily: SA.mono, fontSize: 9.5, color: SA.lime }}>{c.share}</span>
          </a>
        ))}
      </div>
    </div>
  );
}

function MobileQuickNav() {
  const links = [
    { href: 'odds.html',     label: 'AI Odds' },
    { href: 'fixtures.html', label: 'Fixtures' },
    { href: 'methodology.html', label: 'Methodology' },
  ];
  return (
    <div style={{ display: 'flex', gap: 8, padding: '10px 16px 6px', overflowX: 'auto' }}>
      {links.map(l => (
        <a key={l.href} href={l.href} style={{
          flexShrink: 0,
          fontFamily: SA.mono, fontSize: 11, fontWeight: 500,
          letterSpacing: '0.06em', textTransform: 'uppercase',
          color: SA.dim, textDecoration: 'none',
          border: `1px solid ${SA.line2}`,
          padding: '6px 12px',
          whiteSpace: 'nowrap',
        }}>{l.label}</a>
      ))}
    </div>
  );
}

function MobileApp({ countdown }) {
  const models = ARENA.models || [];
  const rows = [...models].sort((a, b) => b.total - a.total);
  const t = ARENA.tournament;
  const isPreTournament = t.dayCurrent === 0;
  const visibleRows = isPreTournament ? rows.slice(0, 4) : rows;

  return (
    <div style={{ background: SA.turf, minHeight: '100%', fontFamily: SA.sans, paddingBottom: 40 }}>
      <MobileHeader countdown={countdown} />
      <MobileQuickNav />
      <MobileConsensus />
      <div style={{ padding: '12px 16px 4px', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <h1 style={{ margin: 0, fontFamily: SA.sans, fontWeight: 800, fontSize: 13, letterSpacing: '0.12em', color: SA.white, textTransform: 'uppercase' }}>Leaderboard</h1>
        <span style={{ fontFamily: SA.mono, fontSize: 10, color: SA.faint }}>{models.length} MODELS</span>
      </div>
      <div style={{ position: 'relative' }}>
        <div style={{
          filter: isPreTournament ? 'blur(4px)' : 'none',
          opacity: isPreTournament ? 0.45 : 1,
          pointerEvents: isPreTournament ? 'none' : 'auto',
          userSelect: isPreTournament ? 'none' : 'auto',
          transition: 'filter 600ms, opacity 600ms',
        }}>
          {visibleRows.length === 0 ? (
            <div style={{ padding: '16px', fontFamily: SA.mono, fontSize: 11, color: SA.faint, textAlign: 'center' }}>
              Predictions will appear once the tournament begins.
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '4px 16px 16px' }}>
              {visibleRows.map((m, i) => <MobileModelCard key={m.id} m={m} rank={i + 1} />)}
            </div>
          )}
        </div>
        {isPreTournament && (
          <MobilePreTournamentOverlay kickoffAt={t.nextMatchKickoffAt} startDate={t.startDate} />
        )}
      </div>
      <AppFooter />
    </div>
  );
}

Object.assign(window, { MobileApp });
