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

interface GameDimensions {
  cellSize: number;
  canvasWidth: number;
  canvasHeight: number;
  isMobile: boolean;
}

interface UseGameDimensionsOptions {
  gridWidth: number;
  gridHeight: number;
  minCellSize?: number;
  maxCellSize?: number;
  padding?: number;
}

export const useGameDimensions = ({
  gridWidth,
  gridHeight,
  minCellSize = 12,
  maxCellSize = 40,
  padding = 120, // Space for controls and UI
}: UseGameDimensionsOptions): GameDimensions => {
  const calculateDimensions = useCallback((): GameDimensions => {
    const isMobile = window.innerWidth < 768;
    const availableWidth = window.innerWidth - (isMobile ? 32 : padding);
    const availableHeight = window.innerHeight - (isMobile ? 200 : padding);
    
    // Calculate cell size based on available space
    const cellFromWidth = Math.floor(availableWidth / gridWidth);
    const cellFromHeight = Math.floor(availableHeight / gridHeight);
    
    // Use the smaller of the two to ensure it fits
    let cellSize = Math.min(cellFromWidth, cellFromHeight);
    
    // Clamp to min/max
    cellSize = Math.max(minCellSize, Math.min(maxCellSize, cellSize));
    
    return {
      cellSize,
      canvasWidth: cellSize * gridWidth,
      canvasHeight: cellSize * gridHeight,
      isMobile,
    };
  }, [gridWidth, gridHeight, minCellSize, maxCellSize, padding]);

  const [dimensions, setDimensions] = useState<GameDimensions>(calculateDimensions);

  useEffect(() => {
    const handleResize = () => {
      setDimensions(calculateDimensions());
    };

    window.addEventListener('resize', handleResize);
    // Also handle orientation change on mobile
    window.addEventListener('orientationchange', handleResize);
    
    return () => {
      window.removeEventListener('resize', handleResize);
      window.removeEventListener('orientationchange', handleResize);
    };
  }, [calculateDimensions]);

  return dimensions;
};

// Hook to handle browser fullscreen API
export const useBrowserFullscreen = () => {
  const [isBrowserFullscreen, setIsBrowserFullscreen] = useState(false);

  const enterFullscreen = useCallback(async (element?: HTMLElement) => {
    const target = element || document.documentElement;
    try {
      if (target.requestFullscreen) {
        await target.requestFullscreen();
      } else if ((target as any).webkitRequestFullscreen) {
        await (target as any).webkitRequestFullscreen();
      } else if ((target as any).msRequestFullscreen) {
        await (target as any).msRequestFullscreen();
      }
      setIsBrowserFullscreen(true);
    } catch (err) {
      console.log('Fullscreen not supported or denied');
    }
  }, []);

  const exitFullscreen = useCallback(async () => {
    try {
      if (document.exitFullscreen) {
        await document.exitFullscreen();
      } else if ((document as any).webkitExitFullscreen) {
        await (document as any).webkitExitFullscreen();
      } else if ((document as any).msExitFullscreen) {
        await (document as any).msExitFullscreen();
      }
      setIsBrowserFullscreen(false);
    } catch (err) {
      console.log('Exit fullscreen failed');
    }
  }, []);

  useEffect(() => {
    const handleChange = () => {
      setIsBrowserFullscreen(!!document.fullscreenElement);
    };
    
    document.addEventListener('fullscreenchange', handleChange);
    document.addEventListener('webkitfullscreenchange', handleChange);
    
    return () => {
      document.removeEventListener('fullscreenchange', handleChange);
      document.removeEventListener('webkitfullscreenchange', handleChange);
    };
  }, []);

  return { isBrowserFullscreen, enterFullscreen, exitFullscreen };
};
