"use client";

import { useEffect, useRef, type ReactNode } from 'react';
import { cn } from '@/lib/utils';
import { smoothScrollIntoView } from '@/lib/smoothScroll';

type Props = {
  active: boolean;
  /** When true, scrolls the item into view on first activation. */
  autoScroll?: boolean;
  children: ReactNode;
};

export const RevealItem = ({ active, autoScroll = true, children }: Props) => {
  const ref = useRef<HTMLDivElement>(null);
  const hasRevealed = useRef(false);

  useEffect(() => {
    if (!active) return;
    if (hasRevealed.current) return;
    hasRevealed.current = true;
    if (!autoScroll) return;
    // wait for the reveal transition to begin before scrolling
    const timer = setTimeout(() => {
      smoothScrollIntoView(ref.current, { offset: 128, duration: 900 });
    }, 120);
    return () => clearTimeout(timer);
  }, [active, autoScroll]);

  return (
    <div
      ref={ref}
      aria-hidden={!active}
      className={cn(
        'scroll-mt-32 transition-all duration-500 ease-out',
        // Spacing applied INSIDE the item so that collapsed items leave no ghost gap.
        active
          ? 'opacity-100 max-h-[2000px] mt-8 first:mt-0'
          : 'opacity-0 max-h-0 mt-0 overflow-hidden pointer-events-none',
      )}
    >
      <div
        className={cn(
          'transition-transform duration-500 ease-out',
          active ? 'translate-y-0' : 'translate-y-2',
        )}
      >
        {children}
      </div>
    </div>
  );
};
