'use client';

import { initializeAuthenticatedApp } from '@/services/initializer.service';
import { useAppStore } from '@/store/app.store';
import { useAuthStore } from '@/store/auth.store';
import type { ReactNode } from 'react';
import { useEffect } from 'react';

export default function AppInitializer({ children }: { children: ReactNode }) {
  const accessToken = useAuthStore((state) => state.accessToken);
  const logout = useAuthStore((state) => state.logout);
  const user = useAppStore((state) => state.user);
  const setLoading = useAppStore((state) => state.setLoading);
  const setLoaded = useAppStore((state) => state.setLoaded);
  const setLoadError = useAppStore((state) => state.setLoadError);
  const clearApp = useAppStore((state) => state.clear);

  useEffect(() => {
    let isActive = true;

    const initialize = async () => {
      if (!accessToken || user) {
        setLoaded();
        return;
      }

      setLoading();

      try {
        await initializeAuthenticatedApp();
      } catch {
        if (isActive) {
          logout();
          clearApp();
          setLoadError();
        }
      }
    };

    initialize();

    return () => {
      isActive = false;
    };
  }, [accessToken, clearApp, logout, setLoaded, setLoadError, setLoading, user]);

  return children;
}
