import { __ } from "@wordpress/i18n";
import { Button, Icon } from "@wordpress/components";
import { useState, useEffect, useRef } from "@wordpress/element";

export function StickyCollapsiblePanel({ title, isOpen, onToggle, children, className = "" }) {
  const wrapperRef = useRef(null);
  const headerRef = useRef(null);
  const contentRef = useRef(null);
  const [stickyTop, setStickyTop] = useState(47);

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

    const scrollContainer = wrapperRef.current.closest(".interface-complementary-area.editor-sidebar");
    if (!scrollContainer) return;

    const updateStickyTop = () => {
      let topOffset = 0;

      const sidebarHeader = scrollContainer.querySelector(".interface-complementary-area-header");
      if (sidebarHeader) {
        topOffset += sidebarHeader.offsetHeight;
      }

      const previewDeviceControl = scrollContainer.querySelector(".zenblocks-preview-device-control");
      if (previewDeviceControl) {
        topOffset += previewDeviceControl.offsetHeight;
      }

      setStickyTop(topOffset);
    };

    updateStickyTop();
    window.addEventListener("resize", updateStickyTop);

    return () => {
      window.removeEventListener("resize", updateStickyTop);
    };
  }, []);

  return (
    <div ref={wrapperRef} className={`custom-collapsible-panel ${isOpen ? "is-opened" : ""} ${className}`}>
      <Button
        ref={headerRef}
        className="custom-panel-toggle"
        onClick={onToggle}
        style={{
          position: isOpen ? "sticky" : "relative",
          top: isOpen ? stickyTop : undefined,
          zIndex: isOpen ? 500 : undefined,
          width: "100%",
          justifyContent: "space-between",
          textAlign: "left",
          borderBottom: isOpen ? "1px solid #e0e0e0" : "none",
          background: "#fff",
        }}
      >
        <span style={{ fontWeight: "500", fontSize: "13px" }}>{title}</span>
        <Icon style={{ margin: "0 5px 0 0" }} icon={isOpen ? "arrow-up-alt2" : "arrow-down-alt2"} size={15} />
      </Button>
      {isOpen && <div ref={contentRef} className="custom-collapsible-panel-content">{children}</div>}
    </div>
  );
}

export default StickyCollapsiblePanel;
