import { useEffect, useState } from "react";
import { useNavigation } from "react-router-dom";

function TopBarLoader() {
  const navigation = useNavigation();
  const active = navigation.state !== "idle";

  const [progress, setProgress] = useState(0);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    if (active) {
      setVisible(true);
      setProgress((p) => (p < 10 ? 10 : p));
      const interval = setInterval(() => {
        setProgress((p) => (p >= 90 ? p : p + (90 - p) * 0.18));
      }, 220);
      return () => clearInterval(interval);
    }

    if (!visible) return;
    setProgress(100);
    const hide = setTimeout(() => {
      setVisible(false);
      setProgress(0);
    }, 260);
    return () => clearTimeout(hide);
  }, [active, visible]);

  if (!visible) return null;

  return (
    <div
      className="fixed top-0 left-0 right-0 h-[2px] z-50 pointer-events-none"
      role="progressbar"
      aria-valuenow={Math.round(progress)}
      aria-valuemin={0}
      aria-valuemax={100}
      aria-label="Loading"
    >
      <div
        className="h-full bg-accent shadow-[0_0_8px_rgba(245,158,11,0.55)] transition-[width,opacity] duration-200 ease-out"
        style={{
          width: `${progress}%`,
          opacity: progress >= 100 ? 0 : 1,
        }}
      />
    </div>
  );
}

window.TopBarLoader = TopBarLoader;
