import { useEffect, useRef } from "react";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import { PRIMARY_COLOR } from "@/lib/common";

gsap.registerPlugin(ScrollTrigger);

const TRACK_HEIGHT = "h-1";
const SCRUB_DURATION = 0.3;

export default function ScrollProgress() {
  const progressRef = useRef<HTMLDivElement>(null);
  const triggerRef = useRef<ScrollTrigger | null>(null);

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

    triggerRef.current = ScrollTrigger.create({
      trigger: "body",
      start: "top top",
      end: "bottom bottom",
      scrub: SCRUB_DURATION,
      onUpdate: (self) => {
        el.style.width = `${self.progress * 100}%`;
      },
    });

    return () => {
      triggerRef.current?.kill();
      triggerRef.current = null;
    };
  }, []);

  return (
    <div
      className={`fixed top-0 left-0 right-0 ${TRACK_HEIGHT} bg-gray-200 dark:bg-white/10 z-50`}
      role="progressbar"
      aria-hidden
    >
      <div
        ref={progressRef}
        className="h-full bg-gradient-to-r from-orange via-orange to-orange shadow-lg transition-none"
        style={{
          width: "0%",
          boxShadow: `0 0 10px ${PRIMARY_COLOR}80`,
        }}
      />
    </div>
  );
}
