import { useState, useEffect, useRef, useCallback } from "@wordpress/element";

export function useStickyInSidebar(options = {}) {
  const { offset = 0, zIndex = 1000 } = options;
  const elementRef = useRef(null);
  const placeholderRef = useRef(null);
  const [isSticky, setIsSticky] = useState(false);
  const [stickyStyles, setStickyStyles] = useState({});
  const initialTopRef = useRef(null);

  const updateStickyState = useCallback(() => {
    if (!elementRef.current || !placeholderRef.current) return;

    const scrollContainer = elementRef.current.closest(
      ".interface-interface-skeleton__sidebar, .edit-post-sidebar, .block-editor-block-inspector"
    );
    if (!scrollContainer) return;

    if (initialTopRef.current === null) {
      const containerRect = scrollContainer.getBoundingClientRect();
      const elementRect = placeholderRef.current.getBoundingClientRect();
      initialTopRef.current = elementRect.top - containerRect.top + scrollContainer.scrollTop;
    }

    const scrollTop = scrollContainer.scrollTop;
    const shouldBeSticky = scrollTop > initialTopRef.current - offset;

    if (shouldBeSticky !== isSticky) {
      setIsSticky(shouldBeSticky);

      if (shouldBeSticky) {
        const containerRect = scrollContainer.getBoundingClientRect();
        const elementRect = elementRef.current.getBoundingClientRect();
        setStickyStyles({
          position: "fixed",
          top: `${containerRect.top + offset}px`,
          left: `${containerRect.left}px`,
          width: `${containerRect.width}px`,
          zIndex: zIndex,
          boxSizing: "border-box",
        });
      } else {
        setStickyStyles({});
      }
    } else if (shouldBeSticky) {
      const containerRect = scrollContainer.getBoundingClientRect();
      setStickyStyles((prev) => ({
        ...prev,
        top: `${containerRect.top + offset}px`,
        left: `${containerRect.left}px`,
        width: `${containerRect.width}px`,
      }));
    }
  }, [isSticky, offset, zIndex]);

  useEffect(() => {
    if (!elementRef.current) return;

    const scrollContainer = elementRef.current.closest(
      ".interface-interface-skeleton__sidebar, .edit-post-sidebar, .block-editor-block-inspector"
    );
    if (!scrollContainer) return;

    const handleScroll = () => {
      requestAnimationFrame(updateStickyState);
    };

    const handleResize = () => {
      initialTopRef.current = null;
      requestAnimationFrame(updateStickyState);
    };

    scrollContainer.addEventListener("scroll", handleScroll, { passive: true });
    window.addEventListener("resize", handleResize);

    updateStickyState();

    return () => {
      scrollContainer.removeEventListener("scroll", handleScroll);
      window.removeEventListener("resize", handleResize);
    };
  }, [updateStickyState]);

  return {
    elementRef,
    placeholderRef,
    isSticky,
    stickyStyles,
  };
}

export default useStickyInSidebar;
