import { createApp } from 'vue'
import { createPinia } from 'pinia'
import router from './router'
import App from './App.vue'
import './style.css'

const app = createApp(App)
const pinia = createPinia()

app.use(pinia)
app.use(router)

// Initialize stores after pinia is set up
import { useAuthStore } from '@/stores/auth'
import { useThemeStore } from '@/stores/theme'
import { useProjectsStore } from '@/stores/projects'

const authStore = useAuthStore()
const themeStore = useThemeStore()
const projectsStore = useProjectsStore()

// Initialize theme first (affects UI immediately)
themeStore.initializeTheme()

// Initialize auth and projects, wait for completion before mounting
async function initializeApp() {
  try {
    // Validate tokens first (clear if expired)
    authStore.validateTokens()
    
    // Then try to initialize auth
    await authStore.initializeAuth()
    
    // If user is authenticated, fetch projects
    if (authStore.isAuthenticated) {
      try {
        await projectsStore.fetchProjects()
      } catch (error) {
        console.warn('Projects initialization failed:', error)
        // Don't block app mounting if projects fail to load
      }
    }
  } catch (error) {
    console.warn('Auth initialization failed:', error)
  }
  
  app.mount('#app')
}

initializeApp()