/**
 * useLayoutState - Custom hook for managing editor layout state
 *
 * Handles split panel sizes, view modes, and fullscreen state
 */

import { useState, useCallback, useEffect, useMemo } from 'react';
import { PREVIEW_MODES, LAYOUT } from '../constants';

/**
 * Custom hook for layout state management
 *
 * @param {Object} initialLayout - Initial layout configuration
 * @returns {Object} Layout state and methods
 */
export const useLayoutState = (initialLayout = {}) => {
  // Memoize defaultLayout to prevent unnecessary re-renders of callbacks that depend on it
  const defaultLayout = useMemo(() => ({
    splitSizes: LAYOUT.DEFAULT_SPLIT_SIZES,
    splitSize: LAYOUT.DEFAULT_SPLIT_SIZES[0], // Single value for new SplitContainer
    viewMode: PREVIEW_MODES.DESKTOP,
    mobileWidth: LAYOUT.MOBILE_WIDTH_DEFAULT,
    isFullscreen: false,
    ...initialLayout
  }), [initialLayout]);

  const [layout, setLayout] = useState(defaultLayout);
  const [isResizing, setIsResizing] = useState(false);

  // Update split panel sizes
  const updateSplitSizes = useCallback((sizes) => {
    // Validate sizes
    const [leftSize, rightSize] = sizes;

    if (leftSize < LAYOUT.MIN_PANE_SIZE || leftSize > LAYOUT.MAX_PANE_SIZE) {
      return;
    }

    if (rightSize < LAYOUT.MIN_PANE_SIZE || rightSize > LAYOUT.MAX_PANE_SIZE) {
      return;
    }

    // Ensure sizes add up to 100%
    const total = leftSize + rightSize;
    if (Math.abs(total - 100) > 1) {
      return;
    }

    setLayout(prev => ({
      ...prev,
      splitSizes: [leftSize, rightSize],
      splitSize: leftSize // Update single value too
    }));
  }, []);

  // Update single split size (for new SplitContainer)
  const setSplitSize = useCallback((size) => {
    if (size < 10 || size > 90) return; // Basic validation

    const rightSize = 100 - size;
    setLayout(prev => ({
      ...prev,
      splitSize: size,
      splitSizes: [size, rightSize]
    }));
  }, []);

  // Set preview mode
  const setViewMode = useCallback((mode) => {
    if (Object.values(PREVIEW_MODES).includes(mode)) {
      setLayout(prev => ({
        ...prev,
        viewMode: mode
      }));
    }
  }, []);

  // Toggle between desktop and mobile view
  const toggleViewMode = useCallback(() => {
    setLayout(prev => ({
      ...prev,
      viewMode: prev.viewMode === PREVIEW_MODES.DESKTOP
        ? PREVIEW_MODES.MOBILE
        : PREVIEW_MODES.DESKTOP
    }));
  }, []);

  // Set mobile preview width
  const setMobileWidth = useCallback((width) => {
    const constrainedWidth = Math.max(320, Math.min(768, width));

    setLayout(prev => ({
      ...prev,
      mobileWidth: constrainedWidth
    }));
  }, []);

  // Toggle fullscreen mode
  const toggleFullscreen = useCallback(() => {
    setLayout(prev => ({
      ...prev,
      isFullscreen: !prev.isFullscreen
    }));
  }, []);

  // Reset layout to defaults
  const resetLayout = useCallback(() => {
    setLayout(defaultLayout);
  }, [defaultLayout]);

  // Set resizing state
  const setResizingState = useCallback((resizing) => {
    setIsResizing(resizing);
  }, []);

  // Handle responsive behavior
  const handleResize = useCallback((delta, containerSize) => {
    if (containerSize === 0) return;

    const percentDelta = (delta / containerSize) * 100;
    const currentSizes = layout.splitSizes;

    const newSizes = [
      Math.max(
        LAYOUT.MIN_PANE_SIZE,
        Math.min(LAYOUT.MAX_PANE_SIZE, currentSizes[0] + percentDelta)
      ),
      Math.max(
        LAYOUT.MIN_PANE_SIZE,
        Math.min(LAYOUT.MAX_PANE_SIZE, currentSizes[1] - percentDelta)
      )
    ];

    updateSplitSizes(newSizes);
  }, [layout.splitSizes, updateSplitSizes]);

  // Keyboard shortcuts for layout
  const handleKeyboardShortcut = useCallback((event) => {
    // F11 for fullscreen
    if (event.key === 'F11') {
      event.preventDefault();
      toggleFullscreen();
      return true;
    }

    // Ctrl/Cmd + P for preview toggle
    if ((event.ctrlKey || event.metaKey) && event.key === 'p') {
      event.preventDefault();
      toggleViewMode();
      return true;
    }

    return false;
  }, [toggleFullscreen, toggleViewMode]);

  // Handle window resize for responsive behavior
  useEffect(() => {
    const handleWindowResize = () => {
      const isMobile = window.innerWidth <= LAYOUT.MOBILE_BREAKPOINT;

      if (isMobile && layout.viewMode === PREVIEW_MODES.DESKTOP) {
        // Automatically switch to mobile view on small screens
        setViewMode(PREVIEW_MODES.MOBILE);
      }
    };

    window.addEventListener('resize', handleWindowResize);
    handleWindowResize(); // Check initial size

    return () => {
      window.removeEventListener('resize', handleWindowResize);
    };
  }, [layout.viewMode, setViewMode]);

  // Handle fullscreen changes
  useEffect(() => {
    const handleFullscreenChange = () => {
      const isCurrentlyFullscreen =
        document.fullscreenElement ||
        document.webkitFullscreenElement ||
        document.mozFullScreenElement ||
        document.msFullscreenElement;

      if (!isCurrentlyFullscreen && layout.isFullscreen) {
        // Fullscreen was exited externally (e.g., ESC key)
        setLayout(prev => ({
          ...prev,
          isFullscreen: false
        }));
      }
    };

    document.addEventListener('fullscreenchange', handleFullscreenChange);
    document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
    document.addEventListener('mozfullscreenchange', handleFullscreenChange);
    document.addEventListener('MSFullscreenChange', handleFullscreenChange);

    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
      document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
      document.removeEventListener('mozfullscreenchange', handleFullscreenChange);
      document.removeEventListener('MSFullscreenChange', handleFullscreenChange);
    };
  }, [layout.isFullscreen]);

  // Keyboard shortcuts effect
  useEffect(() => {
    const handleKeyDown = (event) => {
      handleKeyboardShortcut(event);
    };

    document.addEventListener('keydown', handleKeyDown);

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [handleKeyboardShortcut]);

  return {
    // Layout state
    ...layout,
    isResizing,

    // Layout methods
    updateSplitSizes,
    setSplitSize,
    setViewMode,
    toggleViewMode,
    setMobileWidth,
    toggleFullscreen,
    resetLayout,
    setResizingState,
    handleResize,

    // Utility methods
    handleKeyboardShortcut,

    // Computed properties
    isMobileView: layout.viewMode !== PREVIEW_MODES.DESKTOP,
    isDesktopView: layout.viewMode === PREVIEW_MODES.DESKTOP,

    // Layout constraints
    minPaneSize: LAYOUT.MIN_PANE_SIZE,
    maxPaneSize: LAYOUT.MAX_PANE_SIZE,
    gutterSize: LAYOUT.GUTTER_SIZE
  };
};
