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);
};

// 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 = 390;
  const responsiveWidth = useResponsiveWidth(maxWidth);

  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` }} />
      <EditorCanvas maxWidth={maxWidth} />
      <EditorControls
        className="mx-auto"
        style={{ width: `${responsiveWidth}px` }}
        onEditClick={handleEditClick}
        isEditActive={isEditSidebarOpen}
      />
    </div>
  )
}

export default Editor;
