import { useState, useEffect, useLayoutEffect } from "react"

import EditSidebar from "./partials/edit-sidebar"
import EditorCanvas from "./partials/editor-canvas"
import EditorHeader from "./partials/editor-header"
import EditorControls from "./partials/editor-controls"
import { calculateOptimalMaxWidth, calculateResponsiveWidth } from "./utils/layout-constants"

// Hook to detect if viewport is below minimum width
const useViewportDetection = (minWidth = 320) => {
  const [isBelowMinWidth, setIsBelowMinWidth] = useState(false);

  useLayoutEffect(() => {
    setIsBelowMinWidth(window.innerWidth < minWidth);
  }, [minWidth]);

  useEffect(() => {
    const checkViewport = () => {
      setIsBelowMinWidth(window.innerWidth < minWidth);
    };

    checkViewport();
    window.addEventListener('resize', checkViewport);
    window.addEventListener('orientationchange', checkViewport);

    let resizeObserver;
    if (window.ResizeObserver) {
      resizeObserver = new ResizeObserver(checkViewport);
      resizeObserver.observe(document.body);
    }

    return () => {
      window.removeEventListener('resize', checkViewport);
      window.removeEventListener('orientationchange', checkViewport);
      if (resizeObserver) resizeObserver.disconnect();
    };
  }, [minWidth]);

  return isBelowMinWidth;
};

// Hook for responsive dimensions
const useResponsiveDimensions = () => {
  const [dimensions, setDimensions] = useState(() => ({
    maxWidth: calculateOptimalMaxWidth(),
    responsiveWidth: calculateResponsiveWidth()
  }));

  useLayoutEffect(() => {
    const newMaxWidth = calculateOptimalMaxWidth();
    const newResponsiveWidth = calculateResponsiveWidth();
    setDimensions({
      maxWidth: newMaxWidth,
      responsiveWidth: newResponsiveWidth
    });
  }, []);

  useEffect(() => {
    const handleResize = () => {
      const newMaxWidth = calculateOptimalMaxWidth();
      const newResponsiveWidth = calculateResponsiveWidth();
      setDimensions({
        maxWidth: newMaxWidth,
        responsiveWidth: newResponsiveWidth
      });
    };

    window.addEventListener('resize', handleResize);
    window.addEventListener('orientationchange', handleResize);

    let resizeObserver;
    if (window.ResizeObserver) {
      resizeObserver = new ResizeObserver(handleResize);
      resizeObserver.observe(document.body);
    }

    let mutationObserver;
    if (window.MutationObserver) {
      mutationObserver = new MutationObserver(() => {
        setTimeout(handleResize, 50);
      });
      mutationObserver.observe(document.documentElement, {
        attributes: true,
        attributeFilter: ['style']
      });
    }

    return () => {
      window.removeEventListener('resize', handleResize);
      window.removeEventListener('orientationchange', handleResize);
      if (resizeObserver) resizeObserver.disconnect();
      if (mutationObserver) mutationObserver.disconnect();
    };
  }, []);

  return dimensions;
};

const Editor = () => {
  const [isEditSidebarOpen, setIsEditSidebarOpen] = useState(false)
  const { maxWidth, responsiveWidth } = useResponsiveDimensions();
  const isBelowMinWidth = useViewportDetection(320);

  const handleEditClick = () => {
    setIsEditSidebarOpen(!isEditSidebarOpen)
  }

  const handleCloseSidebar = () => {
    setIsEditSidebarOpen(false)
  }

  return (
    <div
      className="mx-auto min-h-screen flex flex-col relative space-y-2 py-4"
      style={{ width: `${responsiveWidth}px` }}
    >
      <EditSidebar isOpen={isEditSidebarOpen} onClose={handleCloseSidebar} />

      <EditorHeader className="mx-auto" style={{ width: `${responsiveWidth}px` }} />

      {isBelowMinWidth ? (
              <div className="flex-1 flex items-center justify-center px-4 bg-white h-full rounded-lg border shadow-lg">

                  <div>
                  <video className="mx-auto" width="100" height="100%" src="https://cdn.memeaigen.com/videos/cat%20asking%20for%20food.webm" autoPlay muted loop />
          <div className="text-center">
            <p className="text-gray-600 text-sm leading-relaxed">
              Please continue with desktop for a more refined experience!
            </p>
          </div>
                 </div>
        </div>
      ) : (
        <>
          <EditorCanvas maxWidth={maxWidth} />
          <EditorControls
            className="mx-auto"
            style={{ width: `${responsiveWidth}px` }}
            onEditClick={handleEditClick}
            isEditActive={isEditSidebarOpen}
          />
        </>
      )}
    </div>
  )
}

export default Editor;
