"use client";

import { useEffect, useState } from "react";

export function ReadingProgress() {
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    if (window.CSS?.supports("animation-timeline", "scroll()")) {
      return;
    }

    const update = () => {
      const article = document.querySelector("article");
      if (!article) return;
      const rect = article.getBoundingClientRect();
      const total = article.scrollHeight;
      const scrolled = Math.max(0, -rect.top + window.innerHeight * 0.3);
      setProgress(total > 0 ? Math.min(100, (scrolled / total) * 100) : 0);
    };

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

  return (
    <div className="reading-progress hidden lg:block">
      <div
        className="reading-progress-fill"
        style={{ height: `${progress}%` }}
      />
    </div>
  );
}
