'use client';

import { useRef, useState, useEffect } from 'react';
import { cn } from '@/lib/utils';

interface AnimatedSectionProps {
  children: React.ReactNode;
  className?: string;
  stagger?: number;
  delay?: number;
}

/**
 * Scroll-triggered section with CSS-only entrance animations.
 *
 * No Framer Motion for visibility — content is ALWAYS visible in the
 * server-rendered HTML. Animations are purely progressive enhancement
 * via CSS classes applied after IntersectionObserver fires.
 */
export function AnimatedSection({
  children,
  className,
  stagger = 0.1,
}: AnimatedSectionProps) {
  const ref = useRef<HTMLDivElement>(null);
  const [hasEntered, setHasEntered] = useState(false);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;

    // Reduced-motion handled purely by CSS (@media prefers-reduced-motion).
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setHasEntered(true);
          observer.disconnect();
        }
      },
      { rootMargin: '-20px' },
    );

    observer.observe(el);
    return () => observer.disconnect();
  }, []);

  return (
    <div
      ref={ref}
      className={cn(className)}
      style={
        {
          '--stagger': `${stagger}s`,
        } as React.CSSProperties
      }
      data-entered={hasEntered || undefined}
    >
      {children}
    </div>
  );
}

interface AnimatedItemProps {
  children: React.ReactNode;
  className?: string;
}

export function AnimatedItem({ children, className }: AnimatedItemProps) {
  return <div className={cn('animated-item', className)}>{children}</div>;
}
