"use client";

import { useEffect, useState, useRef } from "react";
import { usePathname } from "@/i18n/navigation";

export default function LoadingScreen() {
  const [isLoading, setIsLoading] = useState(true);
  const pathname = usePathname();
  const pathnameRef = useRef(pathname);
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }

    if (pathnameRef.current !== pathname) {
      pathnameRef.current = pathname;
      timerRef.current = setTimeout(() => {
        setIsLoading(true);
        timerRef.current = setTimeout(() => {
          setIsLoading(false);
        }, 500);
      }, 0);
    } else {
      timerRef.current = setTimeout(() => {
        setIsLoading(false);
      }, 500);
    }

    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    };
  }, [pathname]);

  if (!isLoading) return null;

  return (
    <div className="fixed inset-0 z-9999 flex items-center justify-center bg-primary-darker">
      <div className="flex flex-col items-center gap-4">
        <div className="relative">
          <div className="w-16 h-16 border-4 border-primary-main/30 border-t-primary-main rounded-full animate-spin"></div>
        </div>
      </div>
    </div>
  );
}
