import type { GameStats, SolverReplay } from '@wordle/shared';
import { getMessages } from '../messages/index.js';
import { LangSwitch } from '../components/LangSwitch.js';

interface Screen3ResultsProps {
  won: boolean;
  attemptCount: number;
  revealedWord: string | null;
  stats: GameStats;
  replays?: SolverReplay[];
  onPlayAgain?: () => void;
}

const MINI_COLORS: Record<string, string> = { g: '#6aaa64', y: '#c9b458', x: '#787c7e' };

/** Compute Wordle feedback colors for a guess against the target word (same algorithm as server). */
function computeFeedback(target: string, guess: string): string[] {
  const targetUpper = target.toLowerCase();
  const guessUpper = guess.toLowerCase();

  const targetCounts: Record<string, number> = {};
  for (const ch of targetUpper) {
    targetCounts[ch] = (targetCounts[ch] ?? 0) + 1;
  }

  const result: string[] = Array(5).fill('x');

  // Pass 1: greens
  for (let i = 0; i < 5; i++) {
    if (guessUpper[i] === targetUpper[i]) {
      result[i] = 'g';
      targetCounts[guessUpper[i]]--;
    }
  }

  // Pass 2: yellows
  for (let i = 0; i < 5; i++) {
    if (result[i] === 'g') continue;
    const ch = guessUpper[i];
    if ((targetCounts[ch] ?? 0) > 0) {
      result[i] = 'y';
      targetCounts[ch]--;
    }
  }

  return result;
}

function MiniBoard({ replay, targetWord }: { replay: SolverReplay; targetWord: string }) {
  return (
    <div style={{ marginBottom: '12px' }}>
      <div style={{ fontSize: '0.7rem', fontWeight: 'bold', color: '#555', marginBottom: '4px', textAlign: 'center' }}>
        {replay.solver}
      </div>
      {replay.steps.map((guess, rowIdx) => {
        const colors = computeFeedback(targetWord, guess);
        return (
          <div key={rowIdx} style={{ display: 'flex', gap: '2px', justifyContent: 'center', marginBottom: '2px' }}>
            {guess.split('').map((letter, colIdx) => {
              const c = colors[colIdx];
              return (
                <div key={colIdx} style={{
                  width: '20px', height: '20px',
                  backgroundColor: MINI_COLORS[c] ?? '#d3d6da',
                  color: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: '0.55rem', fontWeight: 'bold',
                  textTransform: 'uppercase', fontFamily: 'monospace',
                  borderRadius: '2px',
                }}>
                  {letter}
                </div>
              );
            })}
          </div>
        );
      })}
    </div>
  );
}

function Histogram({ stats }: { stats: GameStats }) {
  if (stats.gamesPlayed === 0) return <p style={{ color: '#787c7e' }}>{getMessages().results.noGames}</p>;

  const maxCount = Math.max(...stats.histogram, 1);

  return (
    <div style={{ maxWidth: '300px', margin: '0 auto' }}>
      {stats.histogram.map((count, idx) => {
        const label = idx < 6 ? `${idx + 1}` : 'X';
        const pct = (count / maxCount) * 100;
        return (
          <div key={idx} style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
            <span style={{ width: '20px', textAlign: 'right', fontWeight: 'bold', color: '#555' }}>{label}</span>
            <div style={{ flex: 1, height: '20px', backgroundColor: count > 0 ? '#6aaa64' : '#d3d6da', width: `${Math.max(pct, count > 0 ? 5 : 0)}%`, minWidth: count > 0 ? '12px' : '4px', borderRadius: '2px' }} />
            <span style={{ width: '24px', fontSize: '0.8rem', color: '#555' }}>{count}</span>
          </div>
        );
      })}
    </div>
  );
}

export function Screen3Results({ won, attemptCount, revealedWord, stats, replays, onPlayAgain }: Screen3ResultsProps) {
  const r = getMessages().results;

  return (
    <div style={{ maxWidth: '400px', margin: '24px auto', padding: '16px', fontFamily: 'sans-serif', textAlign: 'center', position: 'relative' }}>
      <LangSwitch />
      <h1 style={{ fontSize: '1.6rem', marginBottom: '12px' }}>
        {won ? r.congratulations : r.betterLuck}
      </h1>

      {won ? (
        <p style={{ fontSize: '1.1rem', marginBottom: '8px' }}>{r.solvedIn(attemptCount)}</p>
      ) : (
        revealedWord && <p style={{ fontSize: '1.1rem', marginBottom: '8px' }}>{r.theWordWas(revealedWord)}</p>
      )}

      <div style={{ margin: '24px 0' }}>
        <h2 style={{ fontSize: '1.1rem', marginBottom: '12px' }}>{r.statistics}</h2>
        <div style={{ display: 'flex', justifyContent: 'center', gap: '24px', marginBottom: '16px' }}>
          <div><div style={{ fontSize: '1.4rem', fontWeight: 'bold' }}>{stats.gamesPlayed}</div><div style={{ fontSize: '0.75rem', color: '#787c7e' }}>{r.played}</div></div>
          <div><div style={{ fontSize: '1.4rem', fontWeight: 'bold' }}>{stats.gamesPlayed > 0 ? Math.round((stats.wins / stats.gamesPlayed) * 100) : 0}%</div><div style={{ fontSize: '0.75rem', color: '#787c7e' }}>{r.winRate}</div></div>
          <div><div style={{ fontSize: '1.4rem', fontWeight: 'bold' }}>{stats.currentStreak}</div><div style={{ fontSize: '0.75rem', color: '#787c7e' }}>{r.streak}</div></div>
          <div><div style={{ fontSize: '1.4rem', fontWeight: 'bold' }}>{stats.maxStreak}</div><div style={{ fontSize: '0.75rem', color: '#787c7e' }}>{r.maxStreak}</div></div>
        </div>
        <Histogram stats={stats} />
      </div>

      {replays && replays.length > 0 && revealedWord && (
        <div style={{ margin: '24px 0' }}>
          <p style={{ fontSize: '0.85rem', color: '#787c7e', marginBottom: '12px' }}>
            {r.solverCaption}
          </p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '16px', justifyContent: 'center', maxWidth: '320px', margin: '0 auto' }}>
            {replays.map((rp) => (
              <div key={rp.solver} style={{ flex: '0 0 calc(50% - 8px)' }}>
                <MiniBoard replay={rp} targetWord={revealedWord} />
              </div>
            ))}
          </div>
        </div>
      )}

      {onPlayAgain && (
        <button
          onClick={onPlayAgain}
          style={{
            padding: '12px 48px',
            fontSize: '1.1rem',
            fontWeight: 'bold',
            backgroundColor: '#6aaa64',
            color: '#fff',
            border: 'none',
            borderRadius: '8px',
            cursor: 'pointer',
          }}
        >
          {r.playAgain}
        </button>
      )}
    </div>
  );
}
