// components/PageTransition.jsx
"use client";

import React, { useState, useEffect, useRef } from "react";
import { usePathname } from "next/navigation";
import Loader from "@/components/common/RouteLoader";

export default function PageTransition({
  children,
}: {
  children: React.ReactNode;
}) {
  const pathname = usePathname();
  const [loading, setLoading] = useState(false);
  const [prevPath, setPrevPath] = useState(pathname);
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (pathname !== prevPath) {
      setLoading(true);

      if (timerRef.current) clearTimeout(timerRef.current);

      timerRef.current = setTimeout(() => {
        setLoading(false);
        setPrevPath(pathname);
      }, 2000);
    }
  }, [pathname]);

  return (
    <>
      {loading && <Loader />}
      <div
        className={
          loading
            ? "pointer-events-none opacity-50 transition-opacity duration-300"
            : "transition-opacity duration-300"
        }
      >
        {children}
      </div>
    </>
  );
}
