"use client";

import { useEffect, useRef } from "react";

/* Site-wide reading-progress bar — sits at the very top edge and fills with the
   brand gradient as you scroll. Driven by a rAF lerp so it glides smoothly and
   works with Lenis smooth-scroll (reads native window.scrollY). */
export default function ScrollProgress() {
  const barRef = useRef<HTMLDivElement>(null);
  const target = useRef(0);
  const current = useRef(0);

  useEffect(() => {
    let raf = 0;
    const tick = () => {
      // Read scroll position every frame so it tracks regardless of how the
      // smooth-scroll library emits events.
      const max = document.documentElement.scrollHeight - window.innerHeight;
      target.current = max > 0 ? Math.min(1, Math.max(0, window.scrollY / max)) : 0;
      current.current += (target.current - current.current) * 0.12;
      if (barRef.current) {
        barRef.current.style.transform = `scaleX(${current.current.toFixed(4)})`;
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <div
      aria-hidden
      ref={barRef}
      className="fixed left-0 top-0 z-[100000000] h-1.5 w-full origin-left bg-gradient-to-r from-[#FFC72C] via-[#FF2E88] to-[#8B3DFF]"
      style={{ transform: "scaleX(0)" }}
    />
  );
}
