"use client";

import { useEffect, useRef, useState } from "react";

/** Returns true when user scrolls down past threshold (Safari-style compact header) */
export function useScrollDirection(threshold = 16) {
  const [compact, setCompact] = useState(false);
  const lastY = useRef(0);
  const ticking = useRef(false);

  useEffect(() => {
    lastY.current = window.scrollY;

    const update = () => {
      const y = window.scrollY;
      if (y <= threshold) {
        setCompact(false);
      } else if (y > lastY.current + 4) {
        setCompact(true);
      } else if (y < lastY.current - 4) {
        setCompact(false);
      }
      lastY.current = y;
      ticking.current = false;
    };

    const onScroll = () => {
      if (!ticking.current) {
        ticking.current = true;
        requestAnimationFrame(update);
      }
    };

    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [threshold]);

  return compact;
}
