// views/Teams.jsx — All 48 teams in the 2026 field
function TeamsView({ onRoute }) {
  const field = window.WCL_FIELD_2026;
  const odds = Object.fromEntries(window.WCL_TROPHY_ODDS.map(o => [o.team, o]));
  const [grouping, setGrouping] = React.useState('confed'); // confed | fifa | model
  const [filter, setFilter] = React.useState('');

  // Synthesize a small model probability for every team if not in trophy odds
  function modelProb(code) {
    if (odds[code]) return odds[code].model;
    const fifa = window.WCL_TEAMS[code]?.fifa || 80;
    return Math.max(0.001, 0.18 / Math.pow(fifa / 5, 1.4));
  }

  const teams = field
    .filter(code => {
      if (!filter) return true;
      const t = window.WCL_TEAMS[code];
      const q = filter.toLowerCase();
      return code.toLowerCase().includes(q) || t.name.toLowerCase().includes(q) || t.confed.toLowerCase().includes(q);
    });

  const confedOrder = ['UEFA', 'CONMEBOL', 'CONCACAF', 'AFC', 'CAF', 'OFC'];
  const confedTitle = {
    UEFA: 'Europe · UEFA',
    CONMEBOL: 'South America · CONMEBOL',
    CONCACAF: 'N. America · CONCACAF',
    AFC: 'Asia · AFC',
    CAF: 'Africa · CAF',
    OFC: 'Oceania · OFC',
  };
  const confedCount = { UEFA: 16, CONMEBOL: 6, CONCACAF: 6, AFC: 8, CAF: 9, OFC: 1 };

  let groups;
  if (grouping === 'confed') {
    groups = confedOrder.map(cf => ({
      title: confedTitle[cf],
      count: confedCount[cf],
      items: teams.filter(code => window.WCL_TEAMS[code].confed === cf)
                  .sort((a, b) => window.WCL_TEAMS[a].fifa - window.WCL_TEAMS[b].fifa),
    })).filter(g => g.items.length > 0);
  } else if (grouping === 'fifa') {
    groups = [{ title: 'By FIFA ranking', count: teams.length,
      items: teams.slice().sort((a, b) => window.WCL_TEAMS[a].fifa - window.WCL_TEAMS[b].fifa) }];
  } else {
    groups = [{ title: 'By model probability', count: teams.length,
      items: teams.slice().sort((a, b) => modelProb(b) - modelProb(a)) }];
  }

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="eyebrow">2026 field · 48 nations · 6 confederations</div>
          <h1 className="type-h1">All teams</h1>
          <div className="sub">First expanded World Cup · 12 groups of 4 · top 2 + 8 best 3rds advance</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <div className="seg">
            <button className={grouping === 'confed' ? 'active' : ''} onClick={() => setGrouping('confed')}>Confederation</button>
            <button className={grouping === 'fifa' ? 'active' : ''} onClick={() => setGrouping('fifa')}>FIFA</button>
            <button className={grouping === 'model' ? 'active' : ''} onClick={() => setGrouping('model')}>Model</button>
          </div>
          <input className="input" placeholder="Filter team, confed…" value={filter} onChange={(e) => setFilter(e.target.value)} style={{ width: 220 }} />
        </div>
      </div>

      <div className="col4" style={{ marginBottom: 16 }}>
        <div className="kpi">
          <div className="kpi-label">Confederations</div>
          <div className="kpi-value">6</div>
          <div className="kpi-delta">UEFA 16 · CAF 9 · AFC 8 · CONMEBOL/CONCACAF 6 · OFC 1 + 2 PO</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Debutants</div>
          <div className="kpi-value">3</div>
          <div className="kpi-delta">UZB · CIV · CMR-return</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Top-10 FIFA</div>
          <div className="kpi-value">10/10</div>
          <div className="kpi-delta up">all qualified</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Combined squad value</div>
          <div className="kpi-value">€14.8B</div>
          <div className="kpi-delta">FRA €1.12B leads · NZL €18M trails</div>
        </div>
      </div>

      {groups.map(group => (
        <section key={group.title} className="panel" style={{ marginBottom: 16 }}>
          <div className="panel-head">
            <h3>{group.title}</h3>
            <span className="subtle" style={{ fontSize: 11 }}>{group.items.length} of {group.count}</span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',
            gap: 10,
          }}>
            {group.items.map(code => {
              const t = window.WCL_TEAMS[code];
              const o = odds[code];
              const mp = modelProb(code);
              return (
                <button key={code}
                        onClick={() => onRoute('team', { code })}
                        style={{
                          textAlign: 'left',
                          background: 'var(--surface)',
                          border: '1px solid var(--border)',
                          borderRadius: 'var(--radius-md)',
                          padding: '12px 14px',
                          cursor: 'pointer',
                          color: 'inherit',
                          fontFamily: 'inherit',
                          transition: 'border-color var(--dur-fast) var(--ease-out), background var(--dur-fast) var(--ease-out)',
                        }}
                        onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--border-hover)'; e.currentTarget.style.background = 'var(--card-hover)'; }}
                        onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.background = 'var(--surface)'; }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                    <Flag code={code} size="lg" />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div className="strong" style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.2 }}>{t.name}</div>
                      <div className="subtle" style={{ fontSize: 11, marginTop: 2, fontFamily: 'var(--font-mono)' }}>#{t.fifa} · {t.confed}</div>
                    </div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div className="probbar model" style={{ flex: 1 }}>
                      <span style={{ width: Math.min(100, (mp / 0.15) * 100) + '%' }} />
                    </div>
                    <span className="mono" style={{ fontSize: 11, color: mp > 0.05 ? 'var(--pitch)' : 'var(--foreground-muted)', minWidth: 42, textAlign: 'right' }}>
                      {(mp * 100).toFixed(mp >= 0.01 ? 1 : 2)}%
                    </span>
                  </div>
                </button>
              );
            })}
          </div>
        </section>
      ))}
    </div>
  );
}
Object.assign(window, { TeamsView });
