import { useState, useEffect, useCallback } from 'react';

const KONAMI_CODE = [
  'ArrowUp', 'ArrowUp', 
  'ArrowDown', 'ArrowDown', 
  'ArrowLeft', 'ArrowRight', 
  'ArrowLeft', 'ArrowRight', 
  'KeyB', 'KeyA'
];

interface UseKonamiCodeReturn {
  activated: boolean;
  reset: () => void;
}

export const useKonamiCode = (): UseKonamiCodeReturn => {
  const [keysPressed, setKeysPressed] = useState<string[]>([]);
  const [activated, setActivated] = useState(false);
  const [lastKeyTime, setLastKeyTime] = useState(0);

  const reset = useCallback(() => {
    setActivated(false);
    setKeysPressed([]);
  }, []);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      const now = Date.now();
      
      // Reset if more than 2 seconds between keys
      if (now - lastKeyTime > 2000) {
        setKeysPressed([]);
      }
      
      setLastKeyTime(now);
      
      const key = e.code;
      
      setKeysPressed(prev => {
        const newKeys = [...prev, key];
        
        // Check if the sequence matches so far
        const expectedKey = KONAMI_CODE[newKeys.length - 1];
        if (key !== expectedKey) {
          // Wrong key, reset
          return [];
        }
        
        // Check if complete
        if (newKeys.length === KONAMI_CODE.length) {
          setActivated(true);
          return [];
        }
        
        return newKeys;
      });
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [lastKeyTime]);

  return { activated, reset };
};
