'use client';

import { useState, useEffect } from 'react';

/**
 * Hook to detect browser zoom level
 * Returns the zoom factor (1.0 = 100%, 1.5 = 150%, etc.)
 */
export function useZoomLevel(): number {
  const [zoomLevel, setZoomLevel] = useState(1);

  useEffect(() => {
    const updateZoomLevel = () => {
      // Method 1: Compare window.devicePixelRatio (most reliable)
      const deviceZoom = window.devicePixelRatio || 1;
      
      // Method 2: Compare outerWidth to innerWidth (fallback)
      const visualZoom = window.outerWidth / window.innerWidth;
      
      // Method 3: Use screen dimensions vs viewport (most accurate for zoom)
      const screenZoom = window.screen.width / window.innerWidth;
      
      // Use the most reliable method
      // devicePixelRatio works well for display scaling, but for browser zoom
      // we need to compare actual dimensions
      const zoom = Math.round(screenZoom * 100) / 100;
      
      setZoomLevel(zoom);
      
      // Set CSS custom property for use in CSS
      document.documentElement.style.setProperty('--zoom-factor', zoom.toString());
    };

    // Initial calculation
    updateZoomLevel();

    // Update on resize (zoom changes trigger resize)
    window.addEventListener('resize', updateZoomLevel);
    
    // Also listen for zoom-specific events if available
    window.addEventListener('orientationchange', updateZoomLevel);

    return () => {
      window.removeEventListener('resize', updateZoomLevel);
      window.removeEventListener('orientationchange', updateZoomLevel);
    };
  }, []);

  return zoomLevel;
}

/**
 * Hook to get zoom-aware breakpoint status
 * Returns an object with boolean flags for different breakpoints
 * that account for zoom level
 */
export function useZoomAwareBreakpoints() {
  const zoomLevel = useZoomLevel();
  const [breakpoints, setBreakpoints] = useState({
    isMobile: false,
    isTablet: false,
    isDesktop: false,
    isLargeDesktop: false,
    effectiveWidth: 0,
  });

  useEffect(() => {
    const updateBreakpoints = () => {
      const width = window.innerWidth;
      const effectiveWidth = width * zoomLevel;
      
      setBreakpoints({
        isMobile: width < 640,
        isTablet: width >= 640 && width < 1024,
        isDesktop: width >= 1024 && width < 1280,
        isLargeDesktop: width >= 1280,
        effectiveWidth,
      });
    };

    updateBreakpoints();
    window.addEventListener('resize', updateBreakpoints);

    return () => {
      window.removeEventListener('resize', updateBreakpoints);
    };
  }, [zoomLevel]);

  return breakpoints;
}

