'use client';

import { useEffect, useRef, useState } from 'react';
import { usePathname } from 'next/navigation';

export default function DashboardPageTransition({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const transitionMs = 180;
  const [displayedChildren, setDisplayedChildren] = useState(children);
  const [displayedPathname, setDisplayedPathname] = useState(pathname);
  const [phase, setPhase] = useState<'in' | 'out'>('in');
  const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    if (pathname === displayedPathname) {
      setDisplayedChildren(children);
      return;
    }

    setPhase('out');

    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }

    timeoutRef.current = setTimeout(() => {
      setDisplayedPathname(pathname);
      setDisplayedChildren(children);
      setPhase('in');
    }, transitionMs);

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

  return <div className={`dashboard-page-transition dashboard-page-transition-${phase}`}>{displayedChildren}</div>;
}
