// views/History.jsx — All editions for the active competition
function HistoryView({ onRoute, competition }) {
  const comp = window.WCL_COMPETITIONS?.[competition] || window.WCL_COMPETITIONS?.wc_men || { editions: window.WCL_HISTORY, name: 'FIFA World Cup', since: 1930, short: 'World Cup' };
  const H = comp.editions;
  const [year, setYear] = React.useState(H[H.length - 1].y);
  const focus = H.find(h => h.y === year) || H[H.length - 1];

  // titles per nation
  const titles = {};
  H.forEach(h => { titles[h.winner] = (titles[h.winner] || 0) + 1; });
  const topNations = Object.entries(titles).sort((a, b) => b[1] - a[1]);

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="eyebrow">Archive · {H.length} editions · since {comp.since}</div>
          <h1 className="type-h1">{comp.name} history</h1>
          <div className="sub">{H.reduce((s, h) => s + (h.goals || 0), 0)} goals across {H.length} tournaments · pick any year</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <input className="input" placeholder="Search match, player, year…" style={{ width: 280, paddingLeft: 12 }} />
        </div>
      </div>

      <section className="panel" style={{ padding: '18px 20px', marginBottom: 16 }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>22 editions · click to focus</div>
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${H.length}, 1fr)`, gap: 4, alignItems: 'end' }}>
          {H.map(h => {
            const sel = h.y === year;
            const maxG = Math.max(...H.map(x => x.goals || 70));
            const minG = Math.min(...H.map(x => x.goals || 70));
            const h0 = ((h.goals || 70) - minG) / Math.max(1, maxG - minG);
            return (
              <button key={h.y} onClick={() => { setYear(h.y); onRoute('tournament', { year: h.y, competition }); }} style={{
                background: sel ? 'var(--trophy)' : 'var(--surface)',
                border: '1px solid ' + (sel ? 'var(--trophy)' : 'var(--border)'),
                borderRadius: 'var(--radius-sm)',
                padding: '20px 4px 6px',
                cursor: 'pointer',
                color: sel ? '#1a1505' : 'var(--foreground-muted)',
                fontFamily: 'var(--font-mono)',
                fontSize: 10,
                fontWeight: 600,
                writingMode: 'vertical-rl',
                transform: 'rotate(180deg)',
                height: 60 + h0 * 56,
                transition: 'all 120ms var(--ease-out)',
              }}>
                {h.y}
              </button>
            );
          })}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontSize: 11, color: 'var(--foreground-muted)' }}>
          <span>{H[0].y}</span>
          <span>bar height = total goals scored</span>
          <span>{H[H.length - 1].y}</span>
        </div>
      </section>

      {/* Focused edition */}
      <div className="col3" style={{ marginBottom: 16 }}>
        <section className="panel" style={{ gridColumn: 'span 2' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16, flexWrap: 'wrap', gap: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <div style={{ fontSize: 48, fontWeight: 700, letterSpacing: '-0.04em', color: 'var(--trophy)', lineHeight: 1, fontFamily: 'var(--font-sans)' }}>{focus.y}</div>
              <div>
                <div className="strong" style={{ fontSize: 18, fontWeight: 600 }}>{focus.host}</div>
                <div className="subtle" style={{ fontSize: 12 }}>{focus.teams} teams · {focus.goals} goals · {(focus.goals / (focus.teams * 4)).toFixed(2)} g/match</div>
              </div>
            </div>
            <button className="btn btn-secondary btn-sm" onClick={() => onRoute('tournament', { year, competition })}>Full tournament page <I.ArrowUR size={12} /></button>
          </div>

          <div className="match-hero" style={{ padding: '20px 24px' }}>
            <div className="meta-strip">
              <div className="stage-tag"><I.Trophy size={12} style={{ color: 'var(--trophy)' }} /> Final</div>
              <span>{focus.host} {focus.y}</span>
            </div>
            <div className="scoreline">
              <div className="team">
                <Flag code={focus.winner} size="xl" />
                <div className="crest">{window.WCL_TEAMS[focus.winner]?.name || focus.winner}<small style={{ color: 'var(--trophy)' }}>CHAMPION</small></div>
              </div>
              <div style={{ textAlign: 'center' }}>
                <div className="score">{focus.score.split(' ')[0].replace('-', '–')}</div>
                <div className="clock ft">{focus.score.includes('aet') ? 'After extra time' : focus.score.includes('pen') ? 'On penalties' : 'Full time'}</div>
              </div>
              <div className="team away">
                <Flag code={focus.runner} size="xl" />
                <div className="crest" style={{ textAlign: 'right' }}>{window.WCL_TEAMS[focus.runner]?.name || focus.runner}<small>Runner-up</small></div>
              </div>
            </div>
          </div>

          <div className="col3" style={{ marginTop: 16 }}>
            <div className="kpi" style={{ padding: 12 }}><div className="kpi-label">Top scorer</div><div className="strong" style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }}>{focus.topScorer}</div></div>
            <div className="kpi" style={{ padding: 12 }}><div className="kpi-label">Host nation</div><div className="strong" style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }}>{focus.host}</div></div>
            <div className="kpi" style={{ padding: 12 }}><div className="kpi-label">Teams · Goals</div><div className="strong" style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }}>{focus.teams} · {focus.goals}</div></div>
          </div>
        </section>

        <section className="panel">
          <div className="panel-head"><h3>Titles by nation</h3></div>
          <table className="table">
            <tbody>
              {topNations.map(([t, n], i) => (
                <tr key={t} onClick={() => onRoute('team', { code: t })} style={{ cursor: 'pointer' }}>
                  <td className="mono subtle" style={{ width: 22 }}>{i + 1}</td>
                  <td className="strong"><TeamRow code={t} /></td>
                  <td className="mono" style={{ textAlign: 'right', color: 'var(--trophy)' }}>{n}</td>
                  <td>
                    <div style={{ display: 'flex', gap: 2 }}>
                      {Array.from({ length: n }).map((_, k) => <I.Trophy key={k} size={11} style={{ color: 'var(--trophy)' }} />)}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>
      </div>

      <section className="panel">
        <div className="panel-head"><h3>Every edition · finals</h3>
          <div style={{ display: 'flex', gap: 4 }}>
            <button className="btn btn-ghost btn-sm"><I.Filter size={12} /></button>
            <button className="btn btn-ghost btn-sm">Export</button>
          </div>
        </div>
        <table className="table">
          <thead>
            <tr>
              <th>Year</th>
              <th>Host</th>
              <th>Winner</th>
              <th>Final score</th>
              <th>Runner-up</th>
              <th style={{ textAlign: 'right' }}>Teams</th>
              <th style={{ textAlign: 'right' }}>Goals</th>
              <th>Top scorer</th>
            </tr>
          </thead>
          <tbody>
            {H.slice().reverse().map(h => (
              <tr key={h.y} onClick={() => onRoute('tournament', { year: h.y, competition })} style={{ cursor: 'pointer', background: h.y === year ? 'var(--card-hover)' : undefined }}>
                <td className="mono strong">{h.y}</td>
                <td>{h.host}</td>
                <td><TeamRow code={h.winner} /></td>
                <td className="mono">{h.score}</td>
                <td><TeamRow code={h.runner} /></td>
                <td className="mono" style={{ textAlign: 'right' }}>{h.teams}</td>
                <td className="mono" style={{ textAlign: 'right' }}>{h.goals}</td>
                <td className="subtle" style={{ fontSize: 12 }}>{h.topScorer}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </section>
    </div>
  );
}
Object.assign(window, { HistoryView });
