"use client";

import { useEffect, useRef } from "react";

const ANIMATED = [
  ".animate-on-scroll",
  ".animate-from-left",
  ".animate-from-right",
  ".animate-scale-in",
  ".animate-fade-in",
].join(", ");

export function useScrollAnimation() {
  const ref = useRef<HTMLElement>(null);

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

    const els = section.querySelectorAll(ANIMATED);
    if (!els.length) return;

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            (entry.target as HTMLElement).classList.add("visible");
            observer.unobserve(entry.target);
          }
        });
      },
      { threshold: 0.08, rootMargin: "0px 0px -40px 0px" }
    );

    els.forEach((el, i) => {
      const existing = (el as HTMLElement).style.transitionDelay;
      if (!existing) {
        (el as HTMLElement).style.transitionDelay = `${i * 65}ms`;
      }
      observer.observe(el);
    });

    return () => observer.disconnect();
  }, []);

  return ref as React.RefObject<HTMLElement>;
}
