"use client";

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

export default function ReadingProgress() {
  const [progress, setProgress] = useState(0);
  const rafRef = useRef<number | null>(null);

  useEffect(() => {
    const updateProgress = () => {
      const scrollTop = window.scrollY;
      const docHeight =
        document.documentElement.scrollHeight - window.innerHeight;
      const scrollPercent = (scrollTop / docHeight) * 100;
      setProgress(Math.min(100, Math.max(0, scrollPercent)));
    };

    const handleScroll = () => {
      // Cancel previous animation frame if it exists
      if (rafRef.current !== null) {
        cancelAnimationFrame(rafRef.current);
      }

      // Schedule update for next animation frame (throttling)
      rafRef.current = requestAnimationFrame(updateProgress);
    };

    window.addEventListener("scroll", handleScroll, { passive: true });
    updateProgress(); // Initialize

    return () => {
      window.removeEventListener("scroll", handleScroll);
      if (rafRef.current !== null) {
        cancelAnimationFrame(rafRef.current);
      }
    };
  }, []);

  // Determine language from document direction or default to English
  const isRTL =
    typeof document !== "undefined" && document.documentElement.dir === "rtl";
  const ariaLabel = isRTL ? "تقدم القراءة" : "Reading progress";

  return (
    <div className="fixed top-0 left-0 right-0 z-50 h-1 bg-gray-200 dark:bg-slate-800">
      <div
        className="h-full bg-gradient-to-r from-brand-green via-emerald-500 to-teal-500 transition-all duration-150 ease-out shadow-lg"
        style={{ width: `${progress}%` }}
        role="progressbar"
        aria-valuenow={Math.round(progress)}
        aria-valuemin={0}
        aria-valuemax={100}
        aria-label={ariaLabel}
      >
        <div className="absolute right-0 top-0 h-full w-2 bg-white/40 blur-sm" />
      </div>
    </div>
  );
}
