"use client";

import { useEffect, useRef, useState } from "react";
import { usePathname, useSearchParams } from "next/navigation";

export function NavigationProgressBar() {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [progress, setProgress] = useState(0);
  const [visible, setVisible] = useState(false);
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
  const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const startProgress = () => {
    setProgress(0);
    setVisible(true);

    // Simula avanço rápido inicial até ~80%, depois desacelera
    let current = 0;
    timerRef.current = setInterval(() => {
      current += current < 40 ? 15 : current < 70 ? 6 : current < 85 ? 2 : 0.5;
      if (current >= 90) current = 90;
      setProgress(current);
    }, 80);
  };

  const completeProgress = () => {
    if (timerRef.current) clearInterval(timerRef.current);
    setProgress(100);
    timeoutRef.current = setTimeout(() => {
      setVisible(false);
      setProgress(0);
    }, 400);
  };

  useEffect(() => {
    startProgress();
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
      if (timeoutRef.current) clearTimeout(timeoutRef.current);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pathname, searchParams]);

  // Completar quando o conteúdo montar
  useEffect(() => {
    const raf = requestAnimationFrame(() => {
      completeProgress();
    });
    return () => cancelAnimationFrame(raf);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pathname, searchParams]);

  if (!visible && progress === 0) return null;

  return (
    <div
      className="pointer-events-none fixed left-0 top-0 z-[9999] h-[3px] transition-all"
      style={{
        width: `${progress}%`,
        opacity: visible ? 1 : 0,
        background: "linear-gradient(90deg, hsl(var(--primary)), hsl(var(--primary) / 0.8), hsl(221 83% 60%))",
        boxShadow: "0 0 10px hsl(var(--primary) / 0.6), 0 0 5px hsl(var(--primary) / 0.4)",
        transition: progress === 100 ? "width 200ms ease, opacity 400ms ease 300ms" : "width 80ms linear",
      }}
    />
  );
}
