// views/Tournament.jsx — A single World Cup edition, in full detail
function TournamentView({ year, competition, onRoute }) {
  const comp = window.WCL_COMPETITIONS?.[competition] || window.WCL_COMPETITIONS?.wc_men || { editions: window.WCL_HISTORY, name: 'FIFA World Cup' };
  const editions = comp.editions;
  const H = editions.find(h => h.y === year) || editions[editions.length - 1];
  const E = window.WCL_EDITIONS[year] && comp.id === 'wc_men' ? window.WCL_EDITIONS[year] : null;
  if (!H) return <div className="empty">No data for {year}</div>;

  // For nav
  const years = editions.map(h => h.y);
  const idx = years.indexOf(year);
  const prev = years[idx - 1];
  const next = years[idx + 1];
  const compHasRich = comp.id === 'wc_men';

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="breadcrumb" style={{ display: 'flex', gap: 6, color: 'var(--foreground-muted)', fontSize: 12, marginBottom: 8 }}>
            <a className="link" onClick={() => onRoute('home')}>Live Today</a>
            <I.ChevR size={12} />
            <a className="link" onClick={() => onRoute('history')}>{comp.name} history</a>
            <I.ChevR size={12} />
            <span>{H.host} {year}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 18 }}>
            <div style={{ fontSize: 64, fontWeight: 700, letterSpacing: '-0.04em', color: 'var(--trophy)', lineHeight: 1 }}>{year}</div>
            <div>
              <h1 className="type-h1" style={{ margin: 0 }}>{H.host}</h1>
              <div className="sub" style={{ fontSize: 13, marginTop: 4 }}>
                {H.teams} teams · {H.goals} goals · {(H.goals / (H.matches || H.teams * 4)).toFixed(2)} g/match · {E?.cities || '—'}
              </div>
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          {prev && <button className="btn btn-secondary btn-sm" onClick={() => onRoute('tournament', { year: prev, competition })}><I.ChevR size={12} style={{ transform: 'rotate(180deg)' }} /> {prev}</button>}
          {next && <button className="btn btn-secondary btn-sm" onClick={() => onRoute('tournament', { year: next, competition })}>{next} <I.ChevR size={12} /></button>}
        </div>
      </div>

      {/* Hero — the final */}
      <section className="match-hero" style={{ marginBottom: 16 }}>
        <div className="meta-strip">
          <div className="stage-tag">
            <I.Trophy size={12} style={{ color: 'var(--trophy)' }} /> Final · {H.host} {year}
          </div>
          <span>{E?.venues?.[0] || '—'}</span>
        </div>
        <div className="scoreline">
          <div className="team">
            <Flag code={H.winner} size="xl" />
            <div className="crest">{window.WCL_TEAMS[H.winner]?.name || H.winner}<small style={{ color: 'var(--trophy)' }}>CHAMPION</small></div>
          </div>
          <div style={{ textAlign: 'center' }}>
            <div className="score">{H.score.split(' ')[0].replace('-', '–')}</div>
            <div className="clock ft">{H.score.includes('aet') ? 'After extra time' : H.score.includes('pen') ? 'On penalties' : 'Full time'}</div>
          </div>
          <div className="team away">
            <Flag code={H.runner} size="xl" />
            <div className="crest" style={{ textAlign: 'right' }}>{window.WCL_TEAMS[H.runner]?.name || H.runner}<small>Runner-up</small></div>
          </div>
        </div>
        {E?.finalGoals && (
          <div style={{ marginTop: 22, display: 'flex', gap: 6, flexWrap: 'wrap', justifyContent: 'center' }}>
            {E.finalGoals.map((g, i) => (
              <span key={i} style={{
                fontSize: 11,
                fontFamily: 'var(--font-mono)',
                background: g.includes('OG') || g.includes('red') || g.includes('(') ? 'var(--surface)' : 'color-mix(in oklch, var(--trophy) 16%, transparent)',
                border: '1px solid ' + (g.includes('OG') || g.includes('red') || g.includes('(') ? 'var(--border)' : 'color-mix(in oklch, var(--trophy) 30%, transparent)'),
                color: g.includes('OG') || g.includes('red') || g.includes('(') ? 'var(--foreground-muted)' : 'var(--trophy)',
                padding: '4px 10px',
                borderRadius: 999,
              }}>{g}</span>
            ))}
          </div>
        )}
      </section>

      {/* KPIs */}
      <div className="col4" style={{ marginBottom: 16 }}>
        <div className="kpi">
          <div className="kpi-label">Matches</div>
          <div className="kpi-value">{E?.matches || '—'}</div>
          <div className="kpi-delta">{H.teams} teams</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Goals · g/match</div>
          <div className="kpi-value">{H.goals}</div>
          <div className="kpi-delta">{(H.goals / (E?.matches || H.teams * 4)).toFixed(2)} per match</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Attendance</div>
          <div className="kpi-value">{E ? (E.attendance / 1_000_000).toFixed(2) + 'M' : '—'}</div>
          <div className="kpi-delta">{E ? E.attendanceAvg.toLocaleString() + ' avg' : '—'}</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Best player</div>
          <div className="kpi-value" style={{ fontSize: 18, fontWeight: 600 }}>{E?.bestPlayer || H.topScorer}</div>
          <div className="kpi-delta">Golden Ball</div>
        </div>
      </div>

      <div className="col2">
        {/* Champion path */}
        <section className="panel">
          <div className="panel-head">
            <h3>Champion's road · {window.WCL_TEAMS[H.winner]?.name || H.winner}</h3>
            <button className="btn btn-ghost btn-sm" onClick={() => onRoute('team', { code: H.winner })}>Team page <I.ArrowUR size={12} /></button>
          </div>
          {E?.path ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {E.path.map((step, i) => (
                <div key={i} style={{
                  display: 'grid',
                  gridTemplateColumns: '110px 1fr',
                  alignItems: 'center',
                  gap: 14,
                  padding: '10px 14px',
                  background: i === E.path.length - 1 ? 'color-mix(in oklch, var(--trophy) 14%, var(--surface))' : 'var(--surface)',
                  border: '1px solid ' + (i === E.path.length - 1 ? 'color-mix(in oklch, var(--trophy) 30%, transparent)' : 'var(--border)'),
                  borderRadius: 'var(--radius-md)',
                }}>
                  <span className="mono" style={{ fontSize: 11, color: i === E.path.length - 1 ? 'var(--trophy)' : 'var(--foreground-muted)', letterSpacing: '0.04em', textTransform: 'uppercase', fontWeight: 600 }}>
                    {i === E.path.length - 1 && <I.Trophy size={11} style={{ verticalAlign: '-1px', marginRight: 4 }} />}
                    {step[0]}
                  </span>
                  <span className="mono" style={{ fontSize: 13, color: 'var(--foreground)' }}>{step[1]}</span>
                </div>
              ))}
            </div>
          ) : (
            <div className="empty">Path data not available for {year}</div>
          )}
        </section>

        {/* Top scorers */}
        <section className="panel">
          <div className="panel-head"><h3>Top scorers · Golden Boot</h3><span className="subtle" style={{ fontSize: 11 }}>edition leaderboard</span></div>
          {E?.topScorers ? (
            <table className="table">
              <thead>
                <tr>
                  <th style={{ width: 22 }}>#</th>
                  <th>Player</th>
                  <th style={{ width: 60 }}>Nation</th>
                  <th style={{ width: 60, textAlign: 'right' }}>Goals</th>
                </tr>
              </thead>
              <tbody>
                {E.topScorers.map((s, i) => (
                  <tr key={i}>
                    <td className="mono" style={{ color: i === 0 ? 'var(--trophy)' : 'var(--foreground-muted)' }}>{i + 1}</td>
                    <td className="strong">{i === 0 && <I.Trophy size={11} style={{ color: 'var(--trophy)', marginRight: 6, verticalAlign: '-1px' }} />}{s[0]}</td>
                    <td>{s[1] !== '—' ? <Flag code={s[1]} /> : <span className="subtle">—</span>}</td>
                    <td className="mono" style={{ textAlign: 'right', fontWeight: 600, color: 'var(--foreground)' }}>{s[2]}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <div className="strong" style={{ padding: '12px 0' }}>{H.topScorer}</div>
          )}

          <div className="divider" />

          <div className="eyebrow" style={{ marginBottom: 8 }}>3rd / 4th place</div>
          <div className="strong" style={{ fontSize: 14, fontWeight: 500 }}>{E?.third || '—'}</div>
        </section>
      </div>

      <section className="panel" style={{ marginTop: 16 }}>
        <div className="panel-head"><h3>The moment</h3><span className="subtle" style={{ fontSize: 11 }}>defining storyline · {year}</span></div>
        <p style={{
          margin: 0,
          fontSize: 18,
          fontWeight: 500,
          lineHeight: 1.55,
          color: 'var(--foreground)',
          letterSpacing: '-0.01em',
          maxWidth: 820,
          textWrap: 'pretty',
        }}>
          {E?.moment || H.host + ' staged the ' + (idx + 1) + 'th World Cup. ' + (window.WCL_TEAMS[H.winner]?.name || H.winner) + ' lifted the trophy.'}
        </p>
      </section>

      {/* HOST NATION + IMAGES + MAP */}
      {compHasRich && window.WCL_HOSTS && window.WCL_HOSTS[year] && (
        <TournamentHost year={year} />
      )}

      {/* Footer strip — ball / mascot / venues / final line */}
      <div className="col4" style={{ marginTop: 16 }}>
        <div className="kpi">
          <div className="kpi-label">Match ball</div>
          <div className="strong" style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }}>{E?.ball || '—'}</div>
          <div className="kpi-delta">Official ball</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Mascot</div>
          <div className="strong" style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }}>{E?.mascot && E.mascot !== '—' ? E.mascot : 'None'}</div>
          <div className="kpi-delta">{year < 1966 ? 'pre-mascot era' : '—'}</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Venues</div>
          <div className="strong" style={{ fontSize: 13, fontWeight: 600, marginTop: 4, lineHeight: 1.4 }}>{E?.venues?.slice(0, 2).join(' · ') || '—'}</div>
          <div className="kpi-delta">{E?.cities || ''}</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">How it ended</div>
          <div className="strong" style={{ fontSize: 13, fontWeight: 500, marginTop: 4, lineHeight: 1.4, textWrap: 'pretty' }}>{E?.finalLine || H.score}</div>
          <div className="kpi-delta">Final · {H.score}</div>
        </div>
      </div>

      {/* Compare to surrounding editions */}
      <section className="panel" style={{ marginTop: 16 }}>
        <div className="panel-head"><h3>Editions in context</h3><span className="subtle" style={{ fontSize: 11 }}>±3 around {year}</span></div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 10 }}>
          {window.WCL_HISTORY && editions.filter(h => Math.abs(h.y - year) <= 12).map(h => {
            const sel = h.y === year;
            return (
              <button key={h.y} onClick={() => onRoute('tournament', { year: h.y, competition })} style={{
                background: sel ? 'color-mix(in oklch, var(--trophy) 16%, var(--card))' : 'var(--surface)',
                border: '1px solid ' + (sel ? 'color-mix(in oklch, var(--trophy) 40%, transparent)' : 'var(--border)'),
                borderRadius: 'var(--radius-md)',
                padding: '10px 12px',
                cursor: 'pointer',
                textAlign: 'left',
                color: 'inherit',
                fontFamily: 'inherit',
              }}>
                <div className="mono" style={{ fontSize: 11, color: sel ? 'var(--trophy)' : 'var(--foreground-muted)', fontWeight: 600 }}>{h.y}</div>
                <div className="strong" style={{ fontSize: 11, marginTop: 2 }}>{h.host}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 6 }}>
                  <Flag code={h.winner} />
                  <span className="mono" style={{ fontSize: 10, color: 'var(--trophy)' }}>{h.winner}</span>
                </div>
              </button>
            );
          })}
        </div>
      </section>
    </div>
  );
}
Object.assign(window, { TournamentView });

// ---------- Host nation deep panel ----------
function TournamentHost({ year }) {
  const H = window.WCL_HOSTS[year];
  if (!H) return null;
  const flagshipCity = H.cities.find(c => c.host) || H.cities[0];

  return (
    <>
      {/* Host overview */}
      <section className="panel" style={{ marginTop: 16 }}>
        <div className="panel-head">
          <h3>Host nation · {H.countryNames.join(' & ')}</h3>
          <span className="subtle" style={{ fontSize: 11 }}>{H.cities.length} cities · flagship: {H.flagshipCity}</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 24, alignItems: 'flex-start' }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
              {H.countries.map(c => <Flag key={c} code={c} size="xl" />)}
              <div>
                <div className="strong" style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1.1 }}>
                  {H.countryNames.join(' & ')}
                </div>
                <div className="subtle" style={{ fontSize: 12, marginTop: 4 }}>{H.govType}</div>
              </div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 14 }}>
              <div style={{ padding: 12, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--radius-md)' }}>
                <div className="eyebrow">Population</div>
                <div className="strong" style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }}>{H.population}</div>
              </div>
              <div style={{ padding: 12, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--radius-md)' }}>
                <div className="eyebrow">Host cities</div>
                <div className="strong" style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }}>{H.cities.length}</div>
              </div>
            </div>

            <div className="eyebrow" style={{ marginBottom: 6 }}>Context</div>
            <p className="subtle" style={{ fontSize: 13, lineHeight: 1.55, margin: 0, textWrap: 'pretty' }}>
              {H.economyNote}
            </p>

            {H.hostingFirsts?.length > 0 && (
              <>
                <div className="eyebrow" style={{ marginTop: 16, marginBottom: 8 }}>Firsts & milestones</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {H.hostingFirsts.map((s, i) => (
                    <span key={i} style={{
                      padding: '5px 10px',
                      background: 'color-mix(in oklch, var(--trophy) 14%, transparent)',
                      border: '1px solid color-mix(in oklch, var(--trophy) 30%, transparent)',
                      color: 'var(--trophy)',
                      borderRadius: 999,
                      fontSize: 11,
                      fontWeight: 600,
                    }}>{s}</span>
                  ))}
                </div>
              </>
            )}
          </div>

          {/* Map */}
          <div>
            <div className="eyebrow" style={{ marginBottom: 8 }}>Host cities · map</div>
            <HostMap cities={H.cities} />
          </div>
        </div>
      </section>

      {/* Cities table */}
      <section className="panel" style={{ marginTop: 16 }}>
        <div className="panel-head"><h3>All host cities · {H.cities.length}</h3></div>
        <table className="table">
          <thead>
            <tr>
              <th>City</th>
              <th>Venues</th>
              <th>Coords</th>
              <th>Notes</th>
            </tr>
          </thead>
          <tbody>
            {H.cities.map((c, i) => (
              <tr key={i}>
                <td className="strong">
                  {c.host && <I.Trophy size={11} style={{ color: 'var(--trophy)', marginRight: 6, verticalAlign: '-1px' }} />}
                  {c.name}
                </td>
                <td className="subtle" style={{ fontSize: 12 }}>{c.venues?.join(' · ') || '—'}</td>
                <td className="mono subtle" style={{ fontSize: 11 }}>{c.lat.toFixed(2)}, {c.lon.toFixed(2)}</td>
                <td className="subtle" style={{ fontSize: 12, textWrap: 'pretty' }}>{c.note || ''}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </section>

      {/* Event images */}
      {H.images?.length > 0 && (
        <section className="panel" style={{ marginTop: 16 }}>
          <div className="panel-head"><h3>Defining moments · imagery</h3><span className="subtle" style={{ fontSize: 11 }}>via Wikipedia Commons</span></div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
            gap: 14,
          }}>
            {H.images.map((img, i) => (
              <figure key={i} style={{
                margin: 0,
                background: 'var(--surface)',
                border: '1px solid var(--border)',
                borderRadius: 'var(--radius-md)',
                overflow: 'hidden',
                display: 'flex',
                flexDirection: 'column',
              }}>
                <div style={{
                  aspectRatio: '4/3',
                  background: 'var(--muted)',
                  position: 'relative',
                  overflow: 'hidden',
                }}>
                  <img src={img.src} alt={img.caption} loading="lazy" style={{
                    width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center', display: 'block',
                  }} />
                </div>
                <figcaption style={{
                  padding: '12px 14px',
                  fontSize: 12,
                  color: 'var(--foreground-subtle)',
                  lineHeight: 1.5,
                  textWrap: 'pretty',
                }}>{img.caption}</figcaption>
              </figure>
            ))}
          </div>
        </section>
      )}
    </>
  );
}
Object.assign(window, { TournamentHost });
