import { useEffect, useRef, useState } from 'react';

interface ScrollAnimationOptions {
  /** IntersectionObserver threshold (0-1). Default: 0.15 */
  threshold?: number;
  /** Root margin for earlier/later triggering. Default: '0px 0px -60px 0px' */
  rootMargin?: string;
  /** Only trigger once. Default: true */
  once?: boolean;
}

/**
 * Hook that returns a ref and a boolean indicating if the element is visible.
 * Attaches an IntersectionObserver to trigger scroll-based animations.
 */
export function useScrollAnimation<T extends HTMLElement = HTMLDivElement>(
  options: ScrollAnimationOptions = {}
) {
  const { threshold = 0.15, rootMargin = '0px 0px -60px 0px', once = true } = options;
  const ref = useRef<T>(null);
  const [isVisible, setIsVisible] = useState(false);

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

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);
          if (once) observer.unobserve(element);
        } else if (!once) {
          setIsVisible(false);
        }
      },
      { threshold, rootMargin }
    );

    observer.observe(element);
    return () => observer.disconnect();
  }, [threshold, rootMargin, once]);

  return { ref, isVisible };
}

/**
 * CSS class helper for scroll animations.
 * Returns the appropriate CSS class string based on visibility.
 */
export function scrollAnimClass(isVisible: boolean, variant: 'fade-up' | 'fade-left' | 'fade-right' | 'fade-in' = 'fade-up', delay: number = 0): React.CSSProperties {
  const baseTransition = `opacity 0.7s cubic-bezier(0.16, 1, 0.3, 1) ${delay}ms, transform 0.7s cubic-bezier(0.16, 1, 0.3, 1) ${delay}ms`;

  const transforms: Record<string, string> = {
    'fade-up': 'translateY(32px)',
    'fade-left': 'translateX(40px)',
    'fade-right': 'translateX(-40px)',
    'fade-in': 'none',
  };

  return {
    opacity: isVisible ? 1 : 0,
    transform: isVisible ? 'none' : transforms[variant],
    transition: baseTransition,
    willChange: 'opacity, transform',
  };
}
