import React, { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import PageLoader from './PageLoader';

const RouteTransition: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const location = useLocation();
    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
        // Trigger loading on route change
        setIsLoading(true);
        const timer = setTimeout(() => {
            setIsLoading(false);
        }, 2000); // 2 seconds loader on every page transition

        return () => clearTimeout(timer);
    }, [location.pathname]);

    return (
        <>
            <AnimatePresence mode="wait">
                {isLoading && (
                    <motion.div
                        key="loader"
                        exit={{ opacity: 0, transition: { duration: 0.5 } }}
                        className="fixed inset-0 z-[60]" // Higher z-index to cover everything
                    >
                        <PageLoader />
                    </motion.div>
                )}
            </AnimatePresence>
            <div className={isLoading ? 'opacity-0' : 'opacity-100 transition-opacity duration-500'}>
                {children}
            </div>
        </>
    );
};

export default RouteTransition;
