import React, { useState, useEffect } from 'react';
import { useLocation } from '@docusaurus/router';

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

  useEffect(() => {
    const isDocPage = location.pathname !== '/';
    if (!isDocPage) {
      setProgress(0);
      return;
    }

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

    window.addEventListener('scroll', updateProgress);
    updateProgress();
    return () => window.removeEventListener('scroll', updateProgress);
  }, [location.pathname]);

  if (progress === 0 && location.pathname === '/') return null;

  return (
    <div
      style={{
        position: 'fixed',
        top: 0,
        left: 0,
        height: '3px',
        width: `${progress}%`,
        background: 'linear-gradient(90deg, #466aff, #00d4ff)',
        zIndex: 9999,
        transition: 'width 0.1s ease-out',
        boxShadow: '0 0 8px rgba(70, 106, 255, 0.5)',
      }}
    />
  );
}
