'use client';

import React, { useEffect, useState } from 'react';
import { usePathname } from 'next/navigation';
import Preloader from '@/app/loading';
import ScrollToTop from 'react-scroll-to-top';

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}

          {/* Scroll to Top Button */}
          <ScrollToTop
            smooth
            color="#ffffffff"
            style={{
              background: '#ce2029',
              borderRadius: '50%',
              boxShadow: '0 4px 6px rgba(0,0,0,0.2)',
              padding: '8px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
            svgPath="M222.138,91.475l-89.6-89.6c-2.5-2.5-6.551-2.5-9.051,0l-89.6,89.6c-2.5,2.5-2.5,6.551,0,9.051
                      s6.744,2.5,9.244,0L122,21.85V249.6c0,3.535,2.466,6.4,6,6.4s6-2.865,6-6.4V21.85l78.881,78.676
                      c1.25,1.25,2.992,1.875,4.629,1.875s3.326-0.625,4.576-1.875
                      C224.586,98.025,224.638,93.975,222.138,91.475z"
          />
        </>
      )}
    </>
  );
}
