'use client';

import React, { useEffect, useState } from 'react';
import { usePathname } from 'next/navigation';
import Preloader from '@/app/loading';

export default function ClientLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const [isLoading, setIsLoading] = useState(true);
  const [fadeOut, setFadeOut] = useState(false);

  useEffect(() => {
    setIsLoading(true);
    setFadeOut(false);

    const start = Date.now();
    const minDuration = 1200;
    const loadDelay = () => {
      const duration = Date.now() - start;
      const remaining = Math.max(0, minDuration - duration);

      setTimeout(() => {
        setFadeOut(true);
        setTimeout(() => setIsLoading(false), 600);
      }, remaining);
    };

    loadDelay();
  }, [pathname]);

  return (
    <>
      {isLoading && <Preloader fadeOut={fadeOut} />}
      {!isLoading && children}
    </>
  );
}
