"use client";

import { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";

interface FakeProgressBarProps {
  active: boolean;
  durationMs?: number;
  label?: string;
  className?: string;
}

export function FakeProgressBar({ active, durationMs = 12000, label, className }: FakeProgressBarProps) {
  const [progress, setProgress] = useState(0);
  const [visible, setVisible] = useState(false);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
  const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    if (active) {
      setVisible(true);
      setProgress(0);
      const start = Date.now();
      intervalRef.current = setInterval(() => {
        const elapsed = Date.now() - start;
        const t = Math.min(elapsed / durationMs, 1);
        // exponential ease: approaches ~88% asymptotically
        const p = 88 * (1 - Math.exp(-3.5 * t));
        setProgress(p);
      }, 40);
    } else {
      if (intervalRef.current) clearInterval(intervalRef.current);
      if (visible) {
        setProgress(100);
        timeoutRef.current = setTimeout(() => {
          setVisible(false);
          setProgress(0);
        }, 600);
      }
    }
    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
      if (timeoutRef.current) clearTimeout(timeoutRef.current);
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [active]);

  if (!visible) return null;

  return (
    <div className={cn("space-y-1.5", className)}>
      <div className="w-full h-1.5 bg-muted rounded-full overflow-hidden">
        <div
          className="h-full bg-primary rounded-full"
          style={{
            width: `${progress}%`,
            transition: progress >= 100 ? "width 0.3s ease-out" : "width 0.04s linear",
          }}
        />
      </div>
      {label && (
        <p className="text-xs text-muted-foreground text-center animate-pulse">{label}</p>
      )}
    </div>
  );
}
