"use client";

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

type HeroSize = "sm" | "md" | "lg" | "full";

const sizeClasses: Record<HeroSize, string> = {
  sm: "min-h-[42vh] md:min-h-[48vh]",
  md: "min-h-[52vh] md:min-h-[58vh]",
  lg: "min-h-[70vh] md:min-h-[78vh]",
  full: "min-h-[88vh] md:min-h-[92vh]",
};

export function ParallaxHero({
  image,
  alt,
  children,
  size = "md",
  priority = false,
  overlayClassName = "bg-gradient-to-b from-black/55 via-black/45 to-black/70",
  contentClassName = "",
  align = "center",
}: {
  image: string;
  alt: string;
  children: ReactNode;
  size?: HeroSize;
  priority?: boolean;
  overlayClassName?: string;
  contentClassName?: string;
  align?: "center" | "start" | "end";
}) {
  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;
        // Only transform while near the viewport
        if (rect.bottom < 0 || rect.top > viewH) return;
        const offset = rect.top * -0.35;
        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]);

  const alignClass =
    align === "start"
      ? "items-start text-left"
      : align === "end"
        ? "items-end text-right"
        : "items-center text-center";

  return (
    <section
      ref={sectionRef}
      className={`relative isolate flex overflow-hidden ${sizeClasses[size]}`}
    >
      <div
        ref={bgRef}
        className="pointer-events-none absolute inset-x-0 -top-[18%] h-[136%] w-full will-change-transform"
        aria-hidden
      >
        <Image
          src={image}
          alt={alt}
          fill
          priority={priority}
          sizes="100vw"
          className="object-cover object-center"
        />
      </div>

      <div className={`absolute inset-0 ${overlayClassName}`} aria-hidden />

      {/* Soft vignette for readability */}
      <div
        className="absolute inset-0 bg-[radial-gradient(ellipse_at_center,transparent_0%,rgba(0,0,0,0.35)_100%)]"
        aria-hidden
      />

      <div
        className={`container-xl relative z-10 flex w-full flex-col justify-center py-16 md:py-24 ${alignClass} ${contentClassName}`}
      >
        {children}
      </div>
    </section>
  );
}
