"use client";

import { useEffect } from "react";
import { usePathname } from "next/navigation";

/**
 * Aktiviert Scroll-Entrance-Animationen: blendet Elemente mit [data-reveal]
 * ein, sobald sie im Viewport sind. Ein MutationObserver rüstet auch später
 * eingefügte Elemente nach (Tab-Wechsel, Filter, Drawer …), damit dynamische
 * Inhalte nicht unsichtbar bleiben.
 */
export function ScrollReveal() {
  const pathname = usePathname();

  useEffect(() => {
    if (!("IntersectionObserver" in window)) {
      document.querySelectorAll<HTMLElement>("[data-reveal]").forEach((el) => el.classList.add("is-visible"));
      return;
    }

    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const el = entry.target as HTMLElement;
            if (el.dataset.revealDelay) el.style.transitionDelay = `${el.dataset.revealDelay}ms`;
            el.classList.add("is-visible");
            io.unobserve(el);
          }
        });
      },
      { threshold: 0.06, rootMargin: "0px 0px -6% 0px" },
    );

    const observe = (root: ParentNode) => {
      root.querySelectorAll?.<HTMLElement>("[data-reveal]").forEach((el) => {
        if (!el.classList.contains("is-visible")) io.observe(el);
      });
    };
    observe(document);

    const mo = new MutationObserver((muts) => {
      for (const m of muts) {
        m.addedNodes.forEach((n) => {
          if (n.nodeType !== 1) return;
          const el = n as HTMLElement;
          if (el.matches?.("[data-reveal]") && !el.classList.contains("is-visible")) io.observe(el);
          observe(el);
        });
      }
    });
    mo.observe(document.body, { childList: true, subtree: true });

    return () => {
      io.disconnect();
      mo.disconnect();
    };
  }, [pathname]);

  return null;
}
