"use client";

import { useEffect, useRef, useState } from "react";
import { CollapsibleProps } from "./types";

// Collapsible with smooth height/opacity transition
export const Collapse = (props: CollapsibleProps) => {
  const { open, children } = props;
  const contentRef = useRef<HTMLDivElement | null>(null);
  const [maxHeight, setMaxHeight] = useState<number>(0);

  useEffect(() => {
    const el = contentRef.current;
    /* istanbul ignore next -- defensive guard for ref not yet attached */
    if (!el) return;

    const updateHeight = () => {
      setMaxHeight(open ? el.scrollHeight : 0);
    };

    updateHeight();

    let resizeObserver: ResizeObserver | undefined;
    if (open) {
      resizeObserver = new ResizeObserver(() => updateHeight());
      resizeObserver.observe(el);
    }

    return () => {
      if (resizeObserver) resizeObserver.disconnect();
    };
  }, [open, children]);

  return (
    <div
      className="overflow-hidden transition-all duration-300 ease-in-out"
      style={{ maxHeight: maxHeight, opacity: open ? 1 : 0 }}
      aria-hidden={!open}
    >
      <div ref={contentRef}>{children}</div>
    </div>
  );
};

Collapse.displayName = "Collapse";

export type { CollapsibleProps };
