'use client';

import { useEffect, useState } from 'react';

import { useBreakpointMd } from '@/hooks/useBreakpoint';

/**
 * Custom hook that provides dynamic viewport height that adapts to mobile browser UI changes.
 * Uses modern CSS viewport units (dvh) with JavaScript fallbacks for better mobile support.
 *
 * @param initialHeight - Initial height multiplier (default: 1 for 100% viewport height)
 * @param offset - Additional offset in pixels (can be positive or negative)
 * @returns Object with height value and CSS class name
 */
export const useDynamicViewportHeight = (
  initialHeight: number = 1,
  offset: number = 0
) => {
  const [viewportHeight, setViewportHeight] = useState<number | null>(null);
  const [supportsDvh, setSupportsDvh] = useState(false);

  useEffect(() => {
    // Check if browser supports dvh (dynamic viewport height)
    const checkDvhSupport = () => {
      const testEl = document.createElement('div');
      testEl.style.height = '100dvh';
      return testEl.style.height === '100dvh';
    };

    const dvhSupported = checkDvhSupport();
    setSupportsDvh(dvhSupported);

    if (!dvhSupported) {
      // Fallback to JavaScript calculation for older browsers
      const updateViewportHeight = () => {
        // Use visualViewport if available (better for mobile)
        const height = window.visualViewport?.height || window.innerHeight;
        setViewportHeight(height);
      };

      // Initial calculation
      updateViewportHeight();

      // Listen for viewport changes
      const handleResize = () => {
        updateViewportHeight();
      };

      const handleVisualViewportChange = () => {
        updateViewportHeight();
      };

      // Add event listeners
      window.addEventListener('resize', handleResize);
      window.addEventListener('orientationchange', handleResize);

      if (window.visualViewport) {
        window.visualViewport.addEventListener(
          'resize',
          handleVisualViewportChange
        );
        window.visualViewport.addEventListener(
          'scroll',
          handleVisualViewportChange
        );
      }

      // Cleanup
      return () => {
        window.removeEventListener('resize', handleResize);
        window.removeEventListener('orientationchange', handleResize);

        if (window.visualViewport) {
          window.visualViewport.removeEventListener(
            'resize',
            handleVisualViewportChange
          );
          window.visualViewport.removeEventListener(
            'scroll',
            handleVisualViewportChange
          );
        }
      };
    }
  }, []);

  // Generate the appropriate height value and CSS
  if (supportsDvh) {
    // Use modern CSS viewport units
    const heightValue = `calc(${initialHeight * 100}dvh ${offset >= 0 ? '+' : '-'} ${Math.abs(offset)}px)`;
    return {
      height: heightValue,
      style: { height: heightValue },
      className: '', // CSS handled via style prop
    };
  } else if (viewportHeight !== null) {
    // Use JavaScript calculated height
    const calculatedHeight = viewportHeight * initialHeight + offset;
    return {
      height: `${calculatedHeight}px`,
      style: { height: `${calculatedHeight}px` },
      className: '', // CSS handled via style prop
    };
  }

  // Fallback while calculating
  const fallbackHeight = `calc(${initialHeight * 100}vh ${offset >= 0 ? '+' : '-'} ${Math.abs(offset)}px)`;
  return {
    height: fallbackHeight,
    style: { height: fallbackHeight },
    className: '', // CSS handled via style prop
  };
};

/**
 * Hook specifically for mobile-aware viewport height with different desktop/mobile multipliers
 */
export const useMobileAwareViewportHeight = (
  desktopHeight: number = 1,
  mobileHeight: number = 1,
  desktopOffset: number = 0,
  mobileOffset: number = 0
) => {
  const isBreakpointMd = useBreakpointMd();
  const isMobile = !isBreakpointMd;

  const height = isMobile ? mobileHeight : desktopHeight;
  const offset = isMobile ? mobileOffset : desktopOffset;

  return useDynamicViewportHeight(height, offset);
};

/**
 * Hook for calculating viewport height minus mobile UI elements (topbar, banner)
 * Uses minHeight instead of height to allow content to expand beyond the calculated minimum
 * Must be used within a component that has access to MobileBannerContext
 */
export const useMobileLayoutAwareHeight = (
  isBannerVisible: boolean = false
) => {
  const isBreakpointMd = useBreakpointMd();
  const isMobile = !isBreakpointMd;

  // Mobile - subtract topbar and banner heights
  const MOBILE_TOP_BAR_HEIGHT = 60; // px
  const MOBILE_BANNER_HEIGHT = 56; // px - typical mobile banner height

  let totalOffset = 0;
  if (isMobile) {
    totalOffset = -MOBILE_TOP_BAR_HEIGHT;
    if (isBannerVisible) {
      totalOffset -= MOBILE_BANNER_HEIGHT;
    }
  }

  const { height } = useDynamicViewportHeight(1, totalOffset);

  // Return minHeight instead of height to prevent constraining parent containers
  return {
    height,
    style: { minHeight: height },
  };
};
