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"

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

  const calculateWidth = () => {
    const viewportWidth = window.innerWidth;
    const padding = 32;
    const availableWidth = viewportWidth - padding;
    const constrainedWidth = Math.min(availableWidth, maxWidth);
    setWidth(constrainedWidth);
  };

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

  useEffect(() => {
    calculateWidth();

    const handleResize = () => calculateWidth();

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

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

    // MutationObserver for dev tools
    let mutationObserver;
    if (window.MutationObserver) {
      mutationObserver = new MutationObserver(() => {
        setTimeout(calculateWidth, 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 = 325;
    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;
