/**
 * Reaction Game - Click after the cue appears
 */

import React, { useEffect, useRef, useState } from 'react';
import { motion } from 'framer-motion';
import { Button } from '../ui/Button';

interface ReactionGameProps {
  onSuccess: () => void;
  onFail: () => void;
}

export const REACTION_SUCCESS_THRESHOLD_MS = 500;

export const ReactionGame: React.FC<ReactionGameProps> = ({ onSuccess, onFail }) => {
  const [gameState, setGameState] = useState<'waiting' | 'go' | 'result' | 'tooEarly'>('waiting');
  const [reactionTime, setReactionTime] = useState<number | null>(null);
  const [wasSuccessful, setWasSuccessful] = useState<boolean | null>(null);
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);
  const cueTimeRef = useRef<number | null>(null);

  useEffect(() => {
    if (gameState !== 'waiting') {
      return () => undefined;
    }

    const delay = Math.random() * 2000 + 1000;
    timeoutRef.current = setTimeout(() => {
      cueTimeRef.current = Date.now();
      setGameState('go');
    }, delay);

    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, [gameState]);

  const finishGame = (success: boolean, time: number | null) => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }

    setReactionTime(time);
    setWasSuccessful(success);
    setGameState(time === null ? 'tooEarly' : 'result');

    window.setTimeout(() => {
      if (success) {
        onSuccess();
      } else {
        onFail();
      }
    }, 900);
  };

  const handleClick = () => {
    if (gameState === 'result' || gameState === 'tooEarly') {
      return;
    }

    if (gameState === 'waiting') {
      finishGame(false, null);
      return;
    }

    if (gameState === 'go' && cueTimeRef.current !== null) {
      const elapsed = Date.now() - cueTimeRef.current;
      finishGame(elapsed <= REACTION_SUCCESS_THRESHOLD_MS, elapsed);
    }
  };

  return (
    <div className="space-y-8 text-center">
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        className="space-y-2"
      >
        <h3 className="text-xl font-epic text-gold-dark">⚡ Reaction Test</h3>
        <p className="text-sm text-text-secondary">Click when you see &quot;GO!&quot; — 500ms or faster succeeds.</p>
      </motion.div>

      {gameState === 'waiting' && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="space-y-4"
        >
          <p className="text-parchment-light">Wait for the signal...</p>
          <motion.div
            animate={{ scale: [1, 1.15, 1] }}
            transition={{ duration: 0.7, repeat: Infinity }}
            className="text-4xl"
          >
            ⏳
          </motion.div>
        </motion.div>
      )}

      {gameState === 'go' && (
        <motion.div
          initial={{ scale: 0.7, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          transition={{ type: 'spring', stiffness: 220 }}
          className="text-6xl font-bold text-green-400"
        >
          GO!
        </motion.div>
      )}

      {gameState === 'tooEarly' && (
        <motion.div
          initial={{ opacity: 0, scale: 0.8 }}
          animate={{ opacity: 1, scale: 1 }}
          className="text-lg text-red-400 font-semibold"
        >
          ✗ Too early! Resetting challenge...
        </motion.div>
      )}

      {gameState === 'result' && (
        <motion.div
          initial={{ opacity: 0, scale: 0.8 }}
          animate={{ opacity: 1, scale: 1 }}
          className="space-y-3"
        >
          <p className="text-lg text-parchment-light">Your reaction time:</p>
          <p className={`text-3xl font-bold ${wasSuccessful ? 'text-green-400' : 'text-red-400'}`}>
            {reactionTime}ms
          </p>
          <p className="text-sm text-text-secondary">
            {wasSuccessful ? '⚡ Excellent!' : '⏱️ Too slow...'}
          </p>
        </motion.div>
      )}

      <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.15 }}>
        <Button onClick={handleClick} variant="epic" className="w-full py-6 text-lg">
          {gameState === 'go' ? 'CLICK!' : 'Wait for GO!'}
        </Button>
      </motion.div>
    </div>
  );
};

ReactionGame.displayName = 'ReactionGame';
