'use client';

import { useEffect } from 'react';
import { useAuthStore } from '@/lib/store';
import { authApi } from '@/lib/api';

export default function AuthProvider({ children }: { children: React.ReactNode }) {
  const { token, setUser } = useAuthStore();

  useEffect(() => {
    const loadUser = async () => {
      if (!token) {
        console.log('AuthProvider: No token, setting user to null');
        setUser(null);
        return;
      }

      try {
        console.log('AuthProvider: Loading user...');
        const user = await authApi.getMe();
        console.log('AuthProvider: User loaded:', user);
        setUser(user);
      } catch (error) {
        console.error('AuthProvider: Failed to load user:', error);
        setUser(null);
      }
    };

    loadUser();
  }, [token, setUser]);

  return <>{children}</>;
}
