'use client';

import { useEffect, useRef, useState } from 'react';
import { useAuthStore } from '../store/useAuthStore';
import { loginService } from '../services/login.service';
import { profileService } from '../../profile/services/profile.service';
import { mapToSafeProfile } from '../utils/mappers';

export function AuthInitializer({ children }: { children: React.ReactNode }) {
  const { setUser, logout } = useAuthStore();
  const initialized = useRef(false);
  const [isChecking, setIsChecking] = useState(true);

  useEffect(() => {
    if (initialized.current) return;
    initialized.current = true;

    const validateSession = async () => {
      try {
        await loginService.refreshToken();

        const profile = await profileService.getMe();
        setUser(mapToSafeProfile(profile));
      } catch (error) {
        console.warn('Sessão expirada ou inválida', error);
        logout();
      } finally {
        setIsChecking(false);
      }
    };

    validateSession();
  }, [setUser, logout]);

  if (isChecking) {
    return (
      <div className="flex h-screen w-screen items-center justify-center bg-background">
        <div className="animate-pulse flex flex-col items-center gap-4">
          <div className="h-12 w-12 rounded-full bg-primary/20" />
          <p className="text-sm text-muted-foreground">Validando acesso...</p>
        </div>
      </div>
    );
  }

  return <>{children}</>;
}
