// Who am I? quiz — progressive player clues from the loaded squad data.
const { useEffect: useEffectWho, useMemo: useMemoWho, useRef: useRefWho, useState: useStateWho } = React;

const WHOAMI_POINTS = [10, 8, 5, 3, 2, 1];
const WHOAMI_HIGH_SCORE_KEY = 'wc26-whoami-high-score';
const WHOAMI_COUNTRY_KEY = 'wc26-whoami-country';

function whoPosLabel(pos) {
  const labels = {
    GK: 'goalkeeper',
    DF: 'defender',
    MF: 'midfielder',
    FW: 'forward',
  };
  return labels[pos] || (pos || 'footballer');
}

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

function whoNumber(value) {
  const n = parseInt(value, 10);
  return Number.isFinite(n) ? n : null;
}

function shuffleWho(list) {
  const arr = list.slice();
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}

function buildWhoPlayers(squads) {
  const { GROUPS, GROUP_LETTERS, FIFA_RANKINGS } = window.TEAMS_DATA;
  const aliases = (window.SQUAD_LOADER && window.SQUAD_LOADER.aliases) || {};
  const out = [];
  GROUP_LETTERS.forEach(group => {
    GROUPS[group].teams.forEach(country => {
      const src = aliases[country] || country;
      (squads[src] || []).forEach((p, index) => {
        const age = whoNumber(p.age);
        const caps = whoNumber(p.caps);
        const dob = whoDob(p.dob);
        if (!p.name || !country || !age || !p.club || !p.pos || caps == null || !dob) return;
        out.push({
          ...p,
          id: `${country}-${p.name}-${p.dob || index}`,
          country,
          group,
          rank: FIFA_RANKINGS[country] ?? 999,
          age,
          caps,
          dobText: dob,
          posLabel: whoPosLabel(p.pos),
        });
      });
    });
  });
  return out;
}

function highScoreKey(country) {
  return country === 'all' ? WHOAMI_HIGH_SCORE_KEY : `${WHOAMI_HIGH_SCORE_KEY}:${country}`;
}

function loadWhoHighScore(country) {
  try {
    return Math.max(0, parseInt(localStorage.getItem(highScoreKey(country)), 10) || 0);
  } catch (e) {
    return 0;
  }
}

function saveWhoHighScore(country, score) {
  try { localStorage.setItem(highScoreKey(country), String(score)); } catch (e) {}
}

function buildWhoRound(players, previousId) {
  const answers = players.filter(p => p.id !== previousId);
  const answer = answers[Math.floor(Math.random() * answers.length)] || players[Math.floor(Math.random() * players.length)];
  const distractors = shuffleWho(players.filter(p => p.id !== answer.id)).slice(0, 3);
  return {
    answer,
    options: shuffleWho([answer, ...distractors]),
    clueIndex: 0,
    status: 'playing',
    selectedId: null,
  };
}

function clueList(player, countryFilter) {
  const clues = [
    `My date of birth is ${player.dobText}`,
    `I play club football for ${player.club}`,
    `I am a ${player.posLabel}`,
  ];
  if (countryFilter === 'all') clues.push(`My country is ${player.country}`);
  clues.push(`I have ${player.caps} caps for my country`);
  return clues;
}

function clueText(player, index, countryFilter) {
  const clues = clueList(player, countryFilter);
  return clues[index] || clues[clues.length - 1];
}

function WhoAmIView() {
  const [state, setState] = useStateWho({ status: 'loading', squads: {}, error: null });
  const [countryFilter, setCountryFilter] = useStateWho(() => {
    try { return localStorage.getItem(WHOAMI_COUNTRY_KEY) || 'all'; } catch (e) { return 'all'; }
  });
  const [round, setRound] = useStateWho(null);
  const [score, setScore] = useStateWho(0);
  const [highScore, setHighScore] = useStateWho(() => loadWhoHighScore(countryFilter));
  const [answered, setAnswered] = useStateWho(0);
  const [totalAnswerMs, setTotalAnswerMs] = useStateWho(0);
  const [attempts, setAttempts] = useStateWho(0);
  const [summary, setSummary] = useStateWho(null);
  const roundStartedAt = useRefWho(Date.now());

  useEffectWho(() => {
    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 allPlayers = useMemoWho(() => buildWhoPlayers(state.squads), [state.squads]);
  const countries = useMemoWho(() => {
    const { GROUPS, GROUP_LETTERS } = window.TEAMS_DATA;
    return GROUP_LETTERS.flatMap(g => GROUPS[g].teams).slice().sort((a, b) => a.localeCompare(b));
  }, []);
  const players = useMemoWho(() => (
    countryFilter === 'all' ? allPlayers : allPlayers.filter(p => p.country === countryFilter)
  ), [allPlayers, countryFilter]);
  const maxClueIndex = round ? clueList(round.answer, countryFilter).length - 1 : 0;

  const startRound = (previousId = null) => {
    if (players.length < 4) return;
    const next = buildWhoRound(players, previousId);
    setRound(next);
    setSummary(null);
    roundStartedAt.current = Date.now();
  };

  useEffectWho(() => {
    if (state.status === 'ready' && players.length >= 4 && !round && !summary) startRound();
  }, [state.status, players.length, countryFilter, round, summary]);

  const changeCountry = (value) => {
    setCountryFilter(value);
    try { localStorage.setItem(WHOAMI_COUNTRY_KEY, value); } catch (e) {}
    setHighScore(loadWhoHighScore(value));
    setScore(0);
    setAnswered(0);
    setTotalAnswerMs(0);
    setAttempts(0);
    setSummary(null);
    setRound(null);
  };

  const resetGame = () => {
    setScore(0);
    setAnswered(0);
    setTotalAnswerMs(0);
    setAttempts(0);
    setSummary(null);
    setRound(null);
    window.setTimeout(() => startRound(), 0);
  };

  const choosePlayer = (player) => {
    if (!round || round.status !== 'playing') return;
    const elapsed = Date.now() - roundStartedAt.current;
    const nextAttempts = attempts + 1;
    const nextTotalMs = totalAnswerMs + elapsed;
    setAttempts(nextAttempts);
    setTotalAnswerMs(nextTotalMs);

    if (player.id === round.answer.id) {
      const points = WHOAMI_POINTS[round.clueIndex] || 1;
      setScore(prev => {
        const nextScore = prev + points;
        if (nextScore > highScore) {
          setHighScore(nextScore);
          saveWhoHighScore(countryFilter, nextScore);
        }
        return nextScore;
      });
      setAnswered(prev => prev + 1);
      setRound(prev => ({ ...prev, status: 'correct', points, selectedId: player.id }));
      return;
    }

    setSummary({
      answered,
      score,
      avgMs: nextAttempts ? nextTotalMs / nextAttempts : 0,
      correct: round.answer,
    });
    setRound(prev => ({ ...prev, status: 'wrong', selectedId: player.id }));
  };

  const revealClue = () => {
    setRound(prev => {
      if (!prev || prev.status !== 'playing' || prev.clueIndex >= maxClueIndex) return prev;
      return { ...prev, clueIndex: prev.clueIndex + 1 };
    });
  };

  if (state.status === 'loading') return <div className="who-empty">Loading player quiz...</div>;
  if (state.status === 'error') return <div className="who-empty">Unable to load player data.</div>;
  const filterLabel = countryFilter === 'all' ? 'All countries' : countryFilter;

  const activeClues = round ? Array.from({ length: round.clueIndex + 1 }, (_, i) => clueText(round.answer, i, countryFilter)) : [];
  const avg = summary?.avgMs ? `${(summary.avgMs / 1000).toFixed(1)}s` : '-';

  return (
    <div className="who-view">
      <div className="who-shell">
        <div className="who-top">
          <div className="who-title-block">
            <div className="who-kicker">Who am I?</div>
            <h1>Guess the player</h1>
          </div>
          <div className="who-mobile-actions">
            <div className="who-high-score">
              <span>Highest score</span>
              <b>{highScore}</b>
            </div>
            {!summary && round && (
              <button className="who-secondary who-mobile-reveal" onClick={revealClue} disabled={round.status !== 'playing' || round.clueIndex >= maxClueIndex}>
                Reveal another clue
              </button>
            )}
            <div className="who-score">
              <span>Score</span>
              <b>{score}</b>
            </div>
          </div>
        </div>

        <div className="who-filter-row">
          <label className="who-field">
            <span>Country</span>
            <select value={countryFilter} onChange={(e) => changeCountry(e.target.value)}>
              <option value="all">All countries</option>
              {countries.map(country => <option key={country} value={country}>{country}</option>)}
            </select>
          </label>
          <span className="who-filter-count">{players.length} players · {filterLabel}</span>
        </div>

        {players.length < 4 && (
          <div className="who-empty">Not enough complete player records for this country.</div>
        )}

        {players.length >= 4 && round && (
          <>
            <div className="who-clues">
              {activeClues.map((clue, index) => (
                <div key={index} className={index === round.clueIndex ? 'active' : ''}>
                  <span>{index + 1}</span>
                  <p>{clue}</p>
                  {index === round.clueIndex && <b>{WHOAMI_POINTS[round.clueIndex]} pts</b>}
                </div>
              ))}
            </div>

            <div className="who-reveal-row">
              <button className="who-secondary" onClick={revealClue} disabled={round.status !== 'playing' || round.clueIndex >= maxClueIndex}>
                Reveal another clue
              </button>
            </div>

            <div className="who-options">
              {round.options.map((player, index) => {
                const isCorrect = round.status !== 'playing' && player.id === round.answer.id;
                const isWrongSelection = round.status === 'wrong' && player.id === round.selectedId;
                return (
                <button
                  key={player.id}
                  className={`who-option ${isCorrect ? 'correct' : ''} ${isWrongSelection ? 'wrong' : ''}`}
                  onClick={() => choosePlayer(player)}
                  disabled={round.status !== 'playing'}
                >
                  <span className="who-option-letter">{String.fromCharCode(65 + index)}</span>
                  <span className="who-option-name">{player.name}</span>
                </button>
                );
              })}
            </div>

            <div className="who-footer">
              <span>{answered} answered</span>
            </div>

            {round.status === 'correct' && (
              <div className="who-correct">
                <span>Correct: +{round.points}</span>
                <button className="who-primary" onClick={() => startRound(round.answer.id)}>Next question</button>
              </div>
            )}

            {summary && (
              <div className="who-summary">
                <div>
                  <span>Game over</span>
                  <h2>
                    {summary.correct.wikiUrl ? (
                      <a className="who-summary-link" href={summary.correct.wikiUrl} target="_blank" rel="noopener noreferrer">
                        {summary.correct.name}
                      </a>
                    ) : summary.correct.name}
                  </h2>
                  <p>The correct answer was {summary.correct.name} of {summary.correct.country}.</p>
                </div>
                <div className="who-summary-grid">
                  <div><span>Answered</span><b>{summary.answered}</b></div>
                  <div><span>Avg time</span><b>{avg}</b></div>
                  <div><span>Final score</span><b>{summary.score}</b></div>
                </div>
                <button className="who-primary" onClick={resetGame}>Play again</button>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}

window.WhoAmIView = WhoAmIView;
