'use client';

import Image from 'next/image';
import { useEffect, useRef, useState } from 'react';

interface ParallaxSectionProps {
  imageSrc: string;
  imageAlt: string;
  children?: React.ReactNode;
  className?: string;
  overlayOpacity?: number;
  speed?: number; // Parallax speed factor (0.1 - 0.5 recommended)
}

export function ParallaxSection({
  imageSrc,
  imageAlt,
  children,
  className = '',
  overlayOpacity = 0.3,
  speed = 0.3,
}: ParallaxSectionProps) {
  const sectionRef = useRef<HTMLDivElement>(null);
  const [offset, setOffset] = useState(0);

  useEffect(() => {
    const handleScroll = () => {
      if (!sectionRef.current) return;

      const rect = sectionRef.current.getBoundingClientRect();
      const windowHeight = window.innerHeight;

      // Calculate how far into the viewport the section is
      if (rect.top < windowHeight && rect.bottom > 0) {
        const scrollProgress = (windowHeight - rect.top) / (windowHeight + rect.height);
        setOffset(scrollProgress * 100 * speed);
      }
    };

    window.addEventListener('scroll', handleScroll, { passive: true });
    handleScroll(); // Initial calculation

    return () => window.removeEventListener('scroll', handleScroll);
  }, [speed]);

  return (
    <div
      ref={sectionRef}
      className={`relative overflow-hidden ${className}`}
    >
      {/* Parallax background image */}
      <div
        className="absolute inset-0 scale-110"
        style={{ transform: `translateY(${offset}%)` }}
      >
        <Image
          src={imageSrc}
          alt={imageAlt}
          fill
          className="object-cover"
          sizes="100vw"
        />
        {/* Overlay */}
        <div
          className="absolute inset-0 bg-black"
          style={{ opacity: overlayOpacity }}
        />
      </div>

      {/* Content */}
      <div className="relative z-10">
        {children}
      </div>
    </div>
  );
}
