// Golden Boot leaderboard. Primary source: the live "Goalscorers" section of the
// Wikipedia 2026 World Cup article (window.GOLDEN_BOOT_LOADER). Assists and minutes are
// enriched from the published match reports (window.MATCH_REPORTS) where the player is
// found. If Wikipedia can't be reached, it falls back to aggregating goals from the
// match reports alone.
const { useMemo: useMemoGB, useState: useStateGB, useEffect: useEffectGB } = React;

const GB_FLAG_ALIAS = { 'Bosnia and Herzegovina': 'Bosnia & Herz.' };
function gbFlagUrl(team) {
  if (!team || !window.TEAMS_DATA || !window.TEAMS_DATA.flagUrl) return null;
  return window.TEAMS_DATA.flagUrl(GB_FLAG_ALIAS[team] || team, 40);
}

// Aggregate match-report lineups: per-player goals/assists/minutes (for enrichment and
// as a fallback leaderboard).
function reportData() {
  const reports = window.MATCH_REPORTS || {};
  const byKey = {};
  const byName = {};
  let matchCount = 0;
  Object.keys(reports).forEach((id) => {
    const m = reports[id];
    if (!m || !m.lineups) return;
    matchCount += 1;
    ['home', 'away'].forEach((side) => {
      const team = m[side] && m[side].name;
      ['starters', 'bench'].forEach((grp) => {
        ((m.lineups[side] && m.lineups[side][grp]) || []).forEach((p) => {
          const key = `${p.name}|${team}`;
          if (!byKey[key]) byKey[key] = { name: p.name, team, goals: 0, assists: 0, mins: 0 };
          byKey[key].goals += p.g || 0;
          byKey[key].assists += p.a || 0;
          byKey[key].mins += p.min || 0;
          if (!byName[p.name]) byName[p.name] = { goals: 0, assists: 0, mins: 0 };
          byName[p.name].goals += p.g || 0;
          byName[p.name].assists += p.a || 0;
          byName[p.name].mins += p.min || 0;
        });
      });
    });
  });
  const fallbackRows = Object.values(byKey)
    .filter((r) => r.goals > 0)
    .sort((a, b) => b.goals - a.goals || b.assists - a.assists || a.mins - b.mins);
  return { byName, fallbackRows, matchCount };
}

function GoldenBootView() {
  const reports = useMemoGB(reportData, []);
  const [live, setLive] = useStateGB({ status: 'loading', scorers: [] });

  useEffectGB(() => {
    if (!window.GOLDEN_BOOT_LOADER) { setLive({ status: 'error', scorers: [] }); return undefined; }
    let alive = true;
    window.GOLDEN_BOOT_LOADER.loadScorers()
      .then((s) => { if (alive) setLive({ status: 'ready', scorers: s || [] }); })
      .catch(() => { if (alive) setLive({ status: 'error', scorers: [] }); });
    return () => { alive = false; };
  }, []);

  const useLive = live.status === 'ready' && live.scorers.length > 0;
  const rows = useMemoGB(() => {
    if (useLive) {
      return live.scorers.map((s) => ({ name: s.name, team: s.team, goals: s.goals }))
        .sort((a, b) => b.goals - a.goals || a.name.localeCompare(b.name));
    }
    return reports.fallbackRows;
  }, [useLive, live, reports]);

  const source = useLive
    ? 'Live from Wikipedia'
    : live.status === 'loading'
      ? 'Loading from Wikipedia…'
      : `From ${reports.matchCount} published match ${reports.matchCount === 1 ? 'report' : 'reports'}`;

  const lead = rows.length ? rows[0].goals : 0;
  const wrap = { maxWidth: 920, margin: '0 auto', padding: '6px 4px 60px' };
  const card = { background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 16 };
  const cols = '44px 1fr 72px';

  if (!rows.length) {
    return (
      <div style={wrap}>
        <div style={{ ...card, padding: 40, textAlign: 'center', color: 'var(--ink-mute)' }}>
          <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--ink)' }}>
            {live.status === 'loading' ? 'Loading goalscorers…' : 'No goals recorded yet'}
          </div>
          <p style={{ fontSize: 14, marginTop: 8 }}>
            {live.status === 'loading'
              ? 'Fetching the live goalscorers list from Wikipedia.'
              : 'The Golden Boot race fills in from the Wikipedia goalscorers list and published match reports.'}
          </p>
        </div>
      </div>
    );
  }

  const leader = rows[0];
  return (
    <div style={wrap}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, margin: '4px 2px 14px', flexWrap: 'wrap' }}>
        <div style={{ font: "600 11px/1 'JetBrains Mono', monospace", letterSpacing: '.24em', textTransform: 'uppercase', color: 'var(--amber)' }}>Golden Boot</div>
        <div style={{ fontSize: 12, color: 'var(--ink-mute)' }}>Top scorers · {source}</div>
      </div>

      <div style={{ ...card, padding: 18, display: 'flex', alignItems: 'center', gap: 16, marginBottom: 16,
                    background: 'linear-gradient(135deg, rgba(245,165,36,.16), var(--panel))', borderColor: 'color-mix(in srgb, var(--amber) 40%, var(--line))' }}>
        <div style={{ width: 54, height: 54, borderRadius: '50%', background: 'var(--amber)', color: '#1a1206',
                      display: 'grid', placeItems: 'center', fontSize: 24, fontWeight: 800, flexShrink: 0 }}>👟</div>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.1em', color: 'var(--amber)', fontWeight: 600 }}>Current leader</div>
          <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--ink)', display: 'flex', alignItems: 'center', gap: 8 }}>
            {gbFlagUrl(leader.team) && <img src={gbFlagUrl(leader.team)} alt="" className="team-flag" onError={(e) => { e.target.style.display = 'none'; }} />}
            {leader.name}
          </div>
          <div style={{ fontSize: 13, color: 'var(--ink-mute)' }}>{leader.team || '—'} · {leader.goals} {leader.goals === 1 ? 'goal' : 'goals'}</div>
        </div>
      </div>

      <div style={{ ...card, overflow: 'hidden' }}>
        <div style={{ display: 'grid', gridTemplateColumns: cols, gap: 10, padding: '12px 16px', borderBottom: '1px solid var(--line)',
                      font: "600 9.5px 'JetBrains Mono', monospace", letterSpacing: '.08em', color: 'var(--ink-mute)', textTransform: 'uppercase' }}>
          <span style={{ textAlign: 'center' }}>#</span>
          <span>Player</span>
          <span style={{ textAlign: 'right' }}>Goals</span>
        </div>
        {rows.map((r, i) => {
          const isLead = r.goals === lead;
          return (
            <div key={`${r.name}-${r.team}-${i}`} style={{ display: 'grid', gridTemplateColumns: cols, gap: 10, padding: '11px 16px',
                  alignItems: 'center', borderBottom: i < rows.length - 1 ? '1px solid rgba(255,255,255,.05)' : 'none',
                  background: isLead ? 'rgba(245,165,36,.06)' : 'transparent' }}>
              <span style={{ textAlign: 'center', font: "700 13px 'JetBrains Mono', monospace", color: isLead ? 'var(--amber)' : 'var(--ink-mute)' }}>{i + 1}</span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 9, minWidth: 0 }}>
                {gbFlagUrl(r.team) && <img src={gbFlagUrl(r.team)} alt="" className="team-flag" onError={(e) => { e.target.style.display = 'none'; }} />}
                <span style={{ minWidth: 0 }}>
                  <span style={{ display: 'block', color: 'var(--ink)', fontWeight: 600, fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.name}</span>
                  <span style={{ display: 'block', color: 'var(--ink-mute)', fontSize: 11 }}>{r.team || '—'}</span>
                </span>
              </span>
              <span style={{ textAlign: 'right', font: "800 16px 'JetBrains Mono', monospace", color: isLead ? 'var(--amber)' : 'var(--ink)' }}>{r.goals}</span>
            </div>
          );
        })}
      </div>

      <p style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 12, padding: '0 4px' }}>
        {useLive
          ? 'Goals from the Wikipedia 2026 World Cup goalscorers list.'
          : 'Wikipedia goalscorers unavailable — showing goals aggregated from published match reports.'}
      </p>
    </div>
  );
}

window.GoldenBootView = GoldenBootView;
