/* Shared hooks for Petdent site */

function useScrollReveal() {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const root = ref.current;
    if (!root) return;
    const els = Array.from(root.querySelectorAll(".scroll-rise"));
    if (!els.length) return;

    const reveal = (el) => el.classList.add("in");
    const supportsIO = typeof IntersectionObserver === "function";
    let io = null;

    if (supportsIO) {
      io = new IntersectionObserver((entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) { reveal(e.target); io.unobserve(e.target); }
        });
      }, { threshold: 0.12, rootMargin: "0px 0px -40px 0px" });
      els.forEach((el) => io.observe(el));
    } else {
      // IntersectionObserver yoksa hepsini hemen göster.
      els.forEach(reveal);
    }

    // Çift RAF: layout settle olduktan sonra viewport içindekileri SENKRON aç.
    // (iOS WebKit'in geç/kaçan "initial-dispatch" IO callback'ini bekleme —
    //  görünürlüğü IO'nun ateşlemesinden tamamen bağımsız kıl.)
    let raf1 = 0, raf2 = 0, safety = 0;
    raf1 = requestAnimationFrame(() => {
      raf2 = requestAnimationFrame(() => {
        const vp = window.innerHeight || document.documentElement.clientHeight;
        root.querySelectorAll(".scroll-rise:not(.in)").forEach((el) => {
          const r = el.getBoundingClientRect();
          if (r.top < vp * 0.95 && r.bottom > 0) { reveal(el); io && io.unobserve(el); }
        });
      });
    });

    // Güvenlik ağı: motor ne olursa olsun ~900ms sonra viewport+marj içinde
    // kalan herkesi aç. Salt .in EKLER, hiçbir kartı gizlemez.
    safety = window.setTimeout(() => {
      const vp = window.innerHeight || document.documentElement.clientHeight;
      root.querySelectorAll(".scroll-rise:not(.in)").forEach((el) => {
        if (el.getBoundingClientRect().top < vp + 120) reveal(el);
      });
    }, 900);

    return () => {
      cancelAnimationFrame(raf1); cancelAnimationFrame(raf2);
      window.clearTimeout(safety); io && io.disconnect();
    };
  }, []);
  return ref;
}

window.useScrollReveal = useScrollReveal;
