import { emit } from '../lib/socket';

interface Props {
  cardsInRound: number;
  guesses: Record<string, number>;
  myOrder: number;
  activePlayer: number;
  activePlayerName: string;
}

export default function GuessControls({ cardsInRound, guesses, myOrder, activePlayer, activePlayerName }: Props) {
  const guessCount = Object.keys(guesses).length;
  const isMyTurn = activePlayer === myOrder;
  const isLastToGuess = guessCount === 3;
  const alreadySum = Object.values(guesses).reduce((a, b) => a + b, 0);
  const forbidden = isLastToGuess ? cardsInRound - alreadySum : -1;

  if (!isMyTurn) {
    return (
      <p className="text-gray-400 text-sm text-center py-2">
        Caka sa na tip: <span className="text-white font-semibold">{activePlayerName}</span>
      </p>
    );
  }

  const options = Array.from({ length: cardsInRound + 1 }, (_, i) => i);

  return (
    <div className="flex flex-col items-center gap-2 py-2">
      <p className="text-sm text-gray-300">Tvoj tip (pocet kopok):</p>
      <div className="flex flex-wrap gap-2 justify-center">
        {options.map((n) => {
          const isForbidden = n === forbidden;
          return (
            <button
              key={n}
              disabled={isForbidden}
              onClick={() => emit.addGuess(n)}
              title={isForbidden ? 'Zakázaná hodnota (suma = počet kopok)' : undefined}
              className={[
                'w-10 h-10 rounded-lg font-bold text-lg border-2 transition-colors',
                isForbidden
                  ? 'border-red-700 text-red-700 opacity-40 cursor-not-allowed'
                  : 'border-blue-400 text-blue-200 hover:bg-blue-600 hover:border-blue-600 active:scale-95',
              ].join(' ')}
            >
              {n}
            </button>
          );
        })}
      </div>
    </div>
  );
}
