// Players view — full searchable/sortable table of every squad player.
const { useEffect: useEffectPl, useMemo: useMemoPl, useState: useStatePl } = React;

const POSITION_OPTIONS = [
  { id: 'all', label: 'All positions' },
  { id: 'GK', label: 'Goalkeepers' },
  { id: 'DF', label: 'Defenders' },
  { id: 'MF', label: 'Midfielders' },
  { id: 'FW', label: 'Forwards' },
];

function fmtDob(dob) {
  if (!dob) return '-';
  const iso = dob.match(/^(\d{4})-(\d{2})-(\d{2})$/);
  if (iso) {
    const d = new Date(+iso[1], +iso[2] - 1, +iso[3]);
    return d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
  }
  return dob; // already a readable fallback string
}

function PlayersView() {
  const { GROUPS, GROUP_LETTERS, FIFA_RANKINGS } = window.TEAMS_DATA;
  const [state, setState] = useStatePl({ status: 'loading', squads: {}, error: null });
  const [posFilter, setPosFilter] = useStatePl('all');
  const [countryFilter, setCountryFilter] = useStatePl('all');
  const [sort, setSort] = useStatePl({ key: 'caps', dir: 'desc' });

  useEffectPl(() => {
    let alive = true;
    if (!window.SQUAD_LOADER) {
      setState({ status: 'error', squads: {}, error: 'Squad loader unavailable' });
      return undefined;
    }
    window.SQUAD_LOADER.loadSquads()
      .then(squads => { if (alive) setState({ status: 'ready', squads, error: null }); })
      .catch(err => { if (alive) setState({ status: 'error', squads: {}, error: err.message || 'Unable to load' }); });
    return () => { alive = false; };
  }, []);

  const countries = useMemoPl(
    () => GROUP_LETTERS.flatMap(g => GROUPS[g].teams).slice().sort((a, b) => a.localeCompare(b)),
    []
  );

  const allPlayers = useMemoPl(() => {
    const aliases = (window.SQUAD_LOADER && window.SQUAD_LOADER.aliases) || {};
    const out = [];
    GROUP_LETTERS.forEach(g => {
      GROUPS[g].teams.forEach(name => {
        const src = aliases[name] || name;
        const squad = state.squads[src] || [];
        squad.forEach(p => {
          out.push({
            ...p,
            country: name,
            group: g,
            rank: FIFA_RANKINGS[name] ?? 999,
            ageN: p.age ?? null,
            capsN: Number.isFinite(parseInt(p.caps, 10)) ? parseInt(p.caps, 10) : null,
            goalsN: Number.isFinite(parseInt(p.goals, 10)) ? parseInt(p.goals, 10) : null,
            numberN: parseInt(p.number, 10) || 999,
          });
        });
      });
    });
    return out;
  }, [state.squads]);

  const rows = useMemoPl(() => {
    let r = allPlayers;
    if (posFilter !== 'all') r = r.filter(p => p.pos === posFilter);
    if (countryFilter !== 'all') r = r.filter(p => p.country === countryFilter);
    const dir = sort.dir === 'asc' ? 1 : -1;
    const keyMap = { number: 'numberN', age: 'ageN', caps: 'capsN', goals: 'goalsN' };
    const numKey = keyMap[sort.key];
    r = r.slice().sort((a, b) => {
      let av = a[numKey], bv = b[numKey];
      // Missing values always sort to the bottom regardless of direction.
      if (av == null && bv == null) return a.name.localeCompare(b.name);
      if (av == null) return 1;
      if (bv == null) return -1;
      if (av !== bv) return (av - bv) * dir;
      return a.name.localeCompare(b.name);
    });
    return r;
  }, [allPlayers, posFilter, countryFilter, sort]);

  const onSort = (key) => setSort(prev => ({
    key,
    dir: prev.key === key && prev.dir === 'desc' ? 'asc' : 'desc',
  }));

  const sortArrow = (key) => (sort.key === key ? (sort.dir === 'asc' ? '^' : 'v') : '');
  const flagUrl = (name) => window.TEAMS_DATA.flagUrl(name, 20);

  return (
    <div className="players-view">
      <div className="pv-toolbar">
        <div className="pv-filter">
          <label className="pv-field">
            <span>Position</span>
            <select value={posFilter} onChange={(e) => setPosFilter(e.target.value)}>
              {POSITION_OPTIONS.map(o => <option key={o.id} value={o.id}>{o.label}</option>)}
            </select>
          </label>
          <label className="pv-field">
            <span>Country</span>
            <select value={countryFilter} onChange={(e) => setCountryFilter(e.target.value)}>
              <option value="all">All countries</option>
              {countries.map(c => <option key={c} value={c}>{c}</option>)}
            </select>
          </label>
        </div>
        <div className="pv-count">
          {state.status === 'ready' ? `${rows.length} player${rows.length === 1 ? '' : 's'}` : ''}
        </div>
      </div>

      {state.status === 'loading' && <div className="pv-empty">Loading players…</div>}
      {state.status === 'error' && <div className="pv-empty">Unable to load player data.</div>}
      {state.status === 'ready' && rows.length === 0 && <div className="pv-empty">No players match these filters.</div>}

      {state.status === 'ready' && rows.length > 0 && (
        <div className="pv-table-wrap">
          <table className="pv-table">
            <thead>
              <tr>
                <th className="pv-country-col">Country</th>
                <th className="pv-num pv-sortable" onClick={() => onSort('number')}>No. <span>{sortArrow('number')}</span></th>
                <th className="pv-player">Player</th>
                <th className="pv-pos">Pos</th>
                <th className="pv-sortable" onClick={() => onSort('age')}>Age <span>{sortArrow('age')}</span></th>
                <th className="pv-sortable" onClick={() => onSort('caps')}>Caps <span>{sortArrow('caps')}</span></th>
                <th className="pv-sortable" onClick={() => onSort('goals')}>Goals <span>{sortArrow('goals')}</span></th>
                <th className="pv-club">Club</th>
                <th className="pv-dob">Birthday</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((p, i) => (
                <tr key={`${p.country}-${p.name}-${i}`}>
                  <td className="pv-country">
                    {flagUrl(p.country) && <img src={flagUrl(p.country)} alt="" className="team-flag" onError={(e) => { e.target.style.display = 'none'; }} />}
                    <span>{p.country}</span>
                  </td>
                  <td className="pv-num">{p.number || '-'}</td>
                  <td className="pv-player">
                    {p.wikiUrl ? (
                      <a className="pv-player-link" href={p.wikiUrl} target="_blank" rel="noopener noreferrer">
                        {p.name}
                      </a>
                    ) : p.name}
                  </td>
                  <td className="pv-pos">{p.pos || '-'}</td>
                  <td>{p.ageN ?? '-'}</td>
                  <td>{p.capsN ?? '-'}</td>
                  <td>{p.goalsN ?? '-'}</td>
                  <td className="pv-club">{p.club || '-'}</td>
                  <td className="pv-dob">{fmtDob(p.dob)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

window.PlayersView = PlayersView;
