import { useEffect, useState } from 'react';
import { Navigate } from 'react-router-dom';
import { ProgressSpinner } from 'primereact/progressspinner';
import { authService } from '@/core/auth/auth.service';
import { useAuthStore } from '@/modules/auth/auth.store';

export default function AuthGuard({ children }: { children: React.ReactNode }) {
  const currentUser = useAuthStore((s) => s.currentUser);
  const fetchMe = useAuthStore((s) => s.fetchMe);
  const [checking, setChecking] = useState(true);

  useEffect(() => {
    if (!authService.isAuthenticated()) {
      setChecking(false);
      return;
    }
    if (!currentUser) {
      fetchMe().finally(() => setChecking(false));
    } else {
      setChecking(false);
    }
  }, [currentUser, fetchMe]);

  if (checking) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <ProgressSpinner />
      </div>
    );
  }

  if (!authService.isAuthenticated()) {
    return <Navigate to="/login" replace />;
  }

  return <>{children}</>;
}
