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"

// Move calculation outside the hook for best performance
const calculateResponsiveWidth = (maxWidth) => {
  const viewportWidth = window.innerWidth;
  const padding = 32;
  const availableWidth = viewportWidth - padding;
  return Math.min(availableWidth, maxWidth);
};

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

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

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

    // Update immediately
    checkViewport();

    // Event listeners
    window.addEventListener('resize', checkViewport);
    window.addEventListener('orientationchange', checkViewport);

    // ResizeObserver for more reliable detection
    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;
};

// Shared responsive hook
const useResponsiveWidth = (maxWidth = 350) => {
  const [width, setWidth] = useState(350);

  useLayoutEffect(() => {
    setWidth(calculateResponsiveWidth(maxWidth));
  }, [maxWidth]);

  useEffect(() => {
    // Update immediately
    setWidth(calculateResponsiveWidth(maxWidth));

    // Create event handlers inside effect to avoid dependency issues
    const handleResize = () => {
      setWidth(calculateResponsiveWidth(maxWidth));
    };

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

    // ResizeObserver for more reliable detection
    let resizeObserver;
    if (window.ResizeObserver) {
      resizeObserver = new ResizeObserver(() => {
        setWidth(calculateResponsiveWidth(maxWidth));
      });
      resizeObserver.observe(document.body);
    }

    // MutationObserver for dev tools
    let mutationObserver;
    if (window.MutationObserver) {
      mutationObserver = new MutationObserver(() => {
        setTimeout(() => {
          setWidth(calculateResponsiveWidth(maxWidth));
        }, 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();
    };
  }, [maxWidth]);

  return width;
};

const Editor = () => {
  const [isEditSidebarOpen, setIsEditSidebarOpen] = useState(false)
  const maxWidth = 340;
  const responsiveWidth = useResponsiveWidth(maxWidth);
  const isBelowMinWidth = useViewportDetection(340);

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

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

  return (
    <div
      className="mx-auto min-h-screen flex flex-col relative space-y-4 py-6"
      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;
