"use client";
import { useEffect } from "react";

// Initialises the gentle fade-in-on-scroll behaviour for the About letter.
// Default: all .tia-reveal elements are VISIBLE on first paint.
// Only elements below the fold get .tia-pre (opacity 0 + translateY) applied
// on mount, then removed as they scroll into view. This guarantees content is
// never stuck invisible if JS/IntersectionObserver misbehaves.
export function AboutScrollReveal() {
  useEffect(() => {
    const mq = window.matchMedia("(prefers-reduced-motion: reduce)");

    const vh0 = window.innerHeight;
    const all = Array.from(document.querySelectorAll<HTMLElement>(".tia-reveal"));

    // If reduced motion: don't hide anything at all
    if (!mq.matches) {
      all.forEach((el) => {
        if (el.getBoundingClientRect().top > vh0 * 0.9) {
          el.classList.add("tia-pre");
        }
      });
    }

    let ticking = false;
    function revealVisible() {
      const vh = window.innerHeight;
      document.querySelectorAll<HTMLElement>(".tia-reveal.tia-pre").forEach((el) => {
        if (el.getBoundingClientRect().top < vh * 0.92) {
          el.classList.remove("tia-pre");
        }
      });
    }
    function onTick() {
      if (!ticking) {
        ticking = true;
        requestAnimationFrame(() => {
          revealVisible();
          ticking = false;
        });
      }
    }

    window.addEventListener("scroll", onTick, { passive: true });
    window.addEventListener("resize", onTick);
    window.addEventListener("load", revealVisible);
    setTimeout(revealVisible, 300);

    return () => {
      window.removeEventListener("scroll", onTick);
      window.removeEventListener("resize", onTick);
    };
  }, []);

  return null;
}
