"use client";

import { useEffect, useState } from "react";

/**
 * Thin gold bar under the fixed header showing how far the reader has scrolled
 * through the article body (element `#article-body`). Width-only, so
 * prefers-reduced-motion needs no special handling.
 */
export default function ReadingProgress({ targetId = "article-body" }: { targetId?: string }) {
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    const el = document.getElementById(targetId);
    if (!el) {
      return;
    }
    const update = () => {
      const rect = el.getBoundingClientRect();
      const total = el.offsetHeight - window.innerHeight;
      const scrolled = -rect.top;
      setProgress(total > 0 ? Math.min(Math.max(scrolled / total, 0), 1) : 0);
    };
    update();
    window.addEventListener("scroll", update, { passive: true });
    window.addEventListener("resize", update, { passive: true });
    return () => {
      window.removeEventListener("scroll", update);
      window.removeEventListener("resize", update);
    };
  }, [targetId]);

  return (
    <div
      aria-hidden="true"
      className="fixed left-0 top-[var(--header-h,75px)] z-40 h-[2px] bg-burnished-gold"
      style={{ width: `${progress * 100}%` }}
    />
  );
}
