import React, { createContext, useContext, useEffect, useState } from 'react';

type InputMode = 'mouse' | 'gamepad' | 'keyboard';

interface InputModeContextType {
  mode: InputMode;
  setMode: (mode: InputMode) => void;
}

const InputModeContext = createContext<InputModeContextType | undefined>(undefined);

export const InputModeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [mode, setMode] = useState<InputMode>('mouse');

  useEffect(() => {
    // Spatial Engine Override
    document.body.classList.remove('gamepad-active', 'keyboard-active');
    if (mode === 'gamepad') {
      document.body.classList.add('gamepad-active');
    } else if (mode === 'keyboard') {
      document.body.classList.add('keyboard-active');
    }
  }, [mode]);

  useEffect(() => {
    const onMouseMove = () => setMode('mouse');
    const onMouseDown = () => setMode('mouse');
    
    const onKeyDown = (e: KeyboardEvent) => {
      // Common navigation keys
      const navKeys = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Enter', 'Escape', 'Tab', ' ', 'Backspace'];
      if (navKeys.includes(e.key)) {
        setMode('keyboard');
      }
    };

    window.addEventListener('mousemove', onMouseMove, { passive: true });
    window.addEventListener('mousedown', onMouseDown, { passive: true });
    window.addEventListener('keydown', onKeyDown, { passive: true });

    return () => {
      window.removeEventListener('mousemove', onMouseMove);
      window.removeEventListener('mousedown', onMouseDown);
      window.removeEventListener('keydown', onKeyDown);
    };
  }, []);

  return (
    <InputModeContext.Provider value={{ mode, setMode }}>
      {children}
    </InputModeContext.Provider>
  );
};

export const useInputMode = () => {
  const context = useContext(InputModeContext);
  if (context === undefined) {
    throw new Error('useInputMode must be used within an InputModeProvider');
  }
  return context;
};
