import { evaluateGuess } from '../lib/wordUtils';
import type { GuessResult, LetterState } from '../types';

type BoardProps = {
  guesses: string[];
  currentGuess: string;
  target: string;
  maxGuesses: number;
  wordLength: number;
  hideFeedback: boolean;
  shake: boolean;
};

const stateClasses: Record<LetterState, string> = {
  correct: 'border-emerald-400 bg-emerald-500 text-slate-950',
  present: 'border-amber-300 bg-amber-400 text-slate-950',
  absent: 'border-slate-700 bg-slate-800 text-slate-300',
  empty: 'border-slate-700/80 bg-slate-950/80 text-slate-100',
};

const hiddenResult = (guess: string): GuessResult[] =>
  guess.split('').map((letter) => ({ letter, state: 'empty' }));

export function Board({ guesses, currentGuess, target, maxGuesses, wordLength, hideFeedback, shake }: BoardProps) {
  const rows = Array.from({ length: maxGuesses }, (_, rowIndex) => {
    const submitted = guesses[rowIndex];
    const active = rowIndex === guesses.length;
    const letters = submitted ?? (active ? currentGuess : '');
    const result = submitted
      ? hideFeedback
        ? hiddenResult(submitted)
        : evaluateGuess(submitted, target)
      : Array.from({ length: wordLength }, (_, index) => ({
          letter: letters[index] ?? '',
          state: 'empty' as const,
        }));

    return { result, active };
  });

  const tileSize = wordLength >= 10 ? 'clamp(1.45rem, 5vw, 2.6rem)' : 'clamp(2.35rem, 10vw, 3.7rem)';

  return (
    <div className="mx-auto grid w-full justify-center gap-2">
      {rows.map((row, rowIndex) => (
        <div
          className={`grid justify-center gap-1.5 ${shake && row.active ? 'animate-shake' : ''}`}
          style={{ gridTemplateColumns: `repeat(${wordLength}, ${tileSize})` }}
          key={`row-${rowIndex}`}
        >
          {Array.from({ length: wordLength }, (_, columnIndex) => {
            const tile = row.result[columnIndex] ?? { letter: '', state: 'empty' as const };
            const wasSubmitted = Boolean(guesses[rowIndex]);
            return (
              <div
                className={`grid aspect-square place-items-center rounded-md border text-center font-black uppercase leading-none shadow-inner transition-colors ${
                  stateClasses[tile.state]
                } ${wasSubmitted && !hideFeedback ? 'animate-flipTile' : ''}`}
                style={{ animationDelay: `${columnIndex * 70}ms` }}
                key={`${rowIndex}-${columnIndex}`}
              >
                <span className={wordLength >= 10 ? 'text-sm sm:text-lg' : 'text-xl sm:text-2xl'}>{tile.letter}</span>
              </div>
            );
          })}
        </div>
      ))}
    </div>
  );
}
