"use client";

import Image from "next/image";
import { useEffect, useRef, useState, type ReactNode } from "react";

/** Mid-page parallax strip — shorter than a full hero, great for quotes / CTAs */
export function ParallaxBand({
  image,
  alt,
  children,
  className = "",
}: {
  image: string;
  alt: string;
  children: ReactNode;
  className?: string;
}) {
  const sectionRef = useRef<HTMLElement>(null);
  const bgRef = useRef<HTMLDivElement>(null);
  const [reduceMotion, setReduceMotion] = useState(false);

  useEffect(() => {
    const media = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduceMotion(media.matches);
    update();
    media.addEventListener("change", update);
    return () => media.removeEventListener("change", update);
  }, []);

  useEffect(() => {
    if (reduceMotion) return;

    let frame = 0;
    const bg = bgRef.current;
    const section = sectionRef.current;
    if (!bg || !section) return;

    const onScroll = () => {
      cancelAnimationFrame(frame);
      frame = requestAnimationFrame(() => {
        const rect = section.getBoundingClientRect();
        const viewH = window.innerHeight || 1;
        if (rect.bottom < 0 || rect.top > viewH) return;
        const offset = rect.top * -0.28;
        bg.style.transform = `translate3d(0, ${offset}px, 0)`;
      });
    };

    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll, { passive: true });
    return () => {
      cancelAnimationFrame(frame);
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, [reduceMotion]);

  return (
    <section
      ref={sectionRef}
      className={`relative isolate overflow-hidden py-24 md:py-32 ${className}`}
    >
      <div
        ref={bgRef}
        className="pointer-events-none absolute inset-x-0 -top-[20%] h-[140%] w-full will-change-transform"
        aria-hidden
      >
        <Image
          src={image}
          alt={alt}
          fill
          sizes="100vw"
          className="object-cover object-center"
        />
      </div>
      <div className="absolute inset-0 bg-black/60" aria-hidden />
      <div className="container-xl relative z-10 text-center text-white">
        {children}
      </div>
    </section>
  );
}
