import { useEffect, useRef } from "react";

type ParallaxImageProps = {
  src: string;
  alt: string;
  className?: string;
  imageClassName?: string;
  loading?: "eager" | "lazy";
};

export function ParallaxImage({ src, alt, className = "", imageClassName = "", loading = "lazy" }: ParallaxImageProps) {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;
    const preference = window.matchMedia("(prefers-reduced-motion: reduce)");
    let frame = 0;
    const update = () => {
      frame = 0;
      if (preference.matches) {
        container.style.setProperty("--photo-offset", "0px");
        return;
      }
      const rect = container.getBoundingClientRect();
      const progress = (window.innerHeight / 2 - rect.top - rect.height / 2) / ((window.innerHeight + rect.height) / 2);
      const offset = Math.max(-1, Math.min(1, progress)) * rect.height * 0.09;
      container.style.setProperty("--photo-offset", `${offset}px`);
    };
    const schedule = () => {
      if (!frame) frame = window.requestAnimationFrame(update);
    };
    const observer = new ResizeObserver(schedule);
    observer.observe(container);
    window.addEventListener("scroll", schedule, { passive: true });
    window.addEventListener("resize", schedule);
    preference.addEventListener("change", schedule);
    update();
    return () => {
      window.cancelAnimationFrame(frame);
      observer.disconnect();
      window.removeEventListener("scroll", schedule);
      window.removeEventListener("resize", schedule);
      preference.removeEventListener("change", schedule);
    };
  }, []);

  return (
    <div ref={containerRef} className={`parallax-photo relative overflow-hidden ${className}`}>
      <img src={src} alt={alt} width={1280} height={832} loading={loading} className={`parallax-photo-image absolute w-full object-cover ${imageClassName}`} />
    </div>
  );
}