import React, { useRef, useEffect, useState } from "react";
import Box from "@mui/material/Box";
import "./DynamicLayout.styles.scss";

export const DynamicLayout = ({
  leftPanel,
  rightContent,
  leftPanelWidth,
  className,
  showStepper,
  ...props
}) => {
  const contentRef = useRef(null);
  const [hasScroll, setHasScroll] = useState(false);

  // Use layout effect so ref is attached before we measure.
  React.useLayoutEffect(() => {
    const el = contentRef.current;

    const checkScroll = () => {
      if (!el) return;
      const hasScrollbar = el.scrollHeight > el.clientHeight;
      setHasScroll(hasScrollbar);
    };

    // Initial measurement after DOM updates.
    checkScroll();

    // Recalculate on window resize.
    window.addEventListener("resize", checkScroll);

    // Observe element size changes.
    const resizeObserver =
      typeof ResizeObserver !== "undefined"
        ? new ResizeObserver(() => checkScroll())
        : null;
    resizeObserver?.observe(el);

    // Observe DOM mutations that might affect scroll height (content changes).
    const mutationObserver =
      typeof MutationObserver !== "undefined"
        ? new MutationObserver(() => checkScroll())
        : null;
    mutationObserver?.observe(el, {
      childList: true,
      subtree: true,
      characterData: true,
      attributes: true,
    });

    return () => {
      window.removeEventListener("resize", checkScroll);
      resizeObserver?.disconnect();
      mutationObserver?.disconnect();
    };
  }, [rightContent]);

  return (
    <Box className={`dynamic-layout-container ${className || ""}`} {...props}>
      <Box
        className="left-panel"
        style={{
          width: leftPanelWidth,
        }}
      >
        {leftPanel}
      </Box>
      <Box className={`right-content ${showStepper ? "with-stepper" : ""}`}>
        {React.cloneElement(rightContent, { contentRef, hasScroll })}
      </Box>
    </Box>
  );
};
