/* global React, useT */

function ScrollProgress() {
  const [p, setP] = React.useState(0);
  React.useEffect(() => {
    const onScroll = () => {
      const h = document.documentElement;
      const max = h.scrollHeight - h.clientHeight;
      setP(max > 0 ? Math.min(1, Math.max(0, h.scrollTop / max)) : 0);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <div className="scroll-progress" aria-hidden="true">
      <div className="scroll-progress-bar" style={{ transform: `scaleX(${p})` }}></div>
    </div>
  );
}

function useReveal() {
  React.useEffect(() => {
    if (typeof IntersectionObserver === "undefined") {
      document.querySelectorAll("[data-reveal]").forEach((el) => el.classList.add("is-in"));
      return;
    }
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("is-in");
            obs.unobserve(e.target);
          }
        });
      },
      { threshold: 0.08, rootMargin: "0px 0px -40px 0px" }
    );
    const scan = () => {
      document.querySelectorAll("[data-reveal]:not(.is-in)").forEach((el) => obs.observe(el));
    };
    scan();
    // re-scan when language switches (DOM updates)
    const mo = new MutationObserver(scan);
    mo.observe(document.body, { childList: true, subtree: true });
    return () => { obs.disconnect(); mo.disconnect(); };
  }, []);
}

function Marquee() {
  const { t, lang } = useT();
  const loop = [...t.marquee, ...t.marquee, ...t.marquee, ...t.marquee];
  return (
    <div className="marquee-strip" aria-hidden="true">
      <span className="marquee-strip-tag">
        <span>{lang === "fi" ? "SIGNAALI" : "SIGNALS"}</span>
        <span>· 08</span>
      </span>
      <div className="marquee">
        <div className="marquee-track">
          {loop.map((it, i) => (
            <span key={i} className="marquee-item">
              <span className="marquee-dot"></span>{it}
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}

window.ScrollProgress = ScrollProgress;
window.useReveal = useReveal;
window.Marquee = Marquee;
