/**
 * Toggles an "is-scrolled" class on the sticky element when the user has scrolled.
 * Replaces bindStickyScrollShadow from webapp/js/main.js.
 */

"use client";

import { useEffect, useRef } from "react";

const IS_SCROLLED_CLASS = "is-scrolled";

/**
 * Listens to window scroll and toggles the class "is-scrolled" on the given element
 * when window.scrollY > 0. Uses passive scroll listener.
 */
export function useStickyScroll(
  elementRef: React.RefObject<HTMLElement | null>
): void {
  const rafRef = useRef<number | null>(null);

  useEffect(() => {
    const el = elementRef.current;
    if (!el) return;

    const update = () => {
      rafRef.current = null;
      const scrolled = typeof window !== "undefined" && window.scrollY > 0;
      el.classList.toggle(IS_SCROLLED_CLASS, scrolled);
    };

    const handleScroll = () => {
      if (rafRef.current == null) {
        rafRef.current = requestAnimationFrame(update);
      }
    };

    update();
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => {
      window.removeEventListener("scroll", handleScroll);
      if (rafRef.current != null) cancelAnimationFrame(rafRef.current);
    };
  }, [elementRef]);
}
