<template>
  <div id="app">
    <!-- Desktop Header - hidden on mobile (viewport < 768px) -->
    <AppHeader
      v-if="authStore.isAuthenticated && !isMobile"
      title="ROA2WEB"
      brand-link="/reports/dashboard"
      :menu-open="menuOpen"
      :companies-store="companyStore"
      :period-store="periodStore"
      :current-user="authStore.currentUser"
      :server-name="authStore.serverName"
      :available-servers="authStore.availableServers"
      :current-server-id-prop="authStore.selectedServerId"
      :auth-store="authStore"
      :show-user="false"
      @menu-toggle="menuOpen = !menuOpen"
      @company-changed="handleCompanyChanged"
      @period-changed="handlePeriodChanged"
      @server-switched="handleServerSwitched"
    />

    <!-- Desktop Slide Menu - hidden on mobile (viewport < 768px) -->
    <SlideMenu
      v-if="authStore.isAuthenticated && !isMobile"
      :is-open="menuOpen"
      :menu-items="enabledMenuItems"
      :current-user="authStore.currentUser"
      @close="menuOpen = false"
      @logout="handleLogout"
    />

    <!-- Main Content - with-navbar only on desktop when authenticated -->
    <main class="main-content" :class="{ 'with-navbar': authStore.isAuthenticated && !isMobile }">
      <router-view />
    </main>

    <!-- Global Toast Messages -->
    <Toast position="top-right" />
    <ConfirmDialog />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import AppHeader from '@shared/components/layout/AppHeader.vue'
import SlideMenu from '@shared/components/layout/SlideMenu.vue'
import Toast from 'primevue/toast'
import ConfirmDialog from 'primevue/confirmdialog'
import { createAuthStore } from '@shared/stores/auth.js'
import { createCompaniesStore } from '@shared/stores/companies.js'
import { createAccountingPeriodStore } from '@shared/stores/accountingPeriod.js'
import { menuSections } from '@/config/menu.js'
import { getEnabledMenuSections } from '@/config/features.js'
import { handleUnauthorized, isAuthRedirectInProgress } from '@/shared/utils/authRedirect'
import axios from 'axios'

const router = useRouter()

// Mobile detection - reactive with resize listener
const windowWidth = ref(typeof window !== 'undefined' ? window.innerWidth : 1024)
const isMobile = computed(() => windowWidth.value <= 768)

const handleResize = () => {
  windowWidth.value = window.innerWidth
}

// API service for auth and shared endpoints (unified backend)
const authApi = axios.create({
  baseURL: import.meta.env.BASE_URL + 'api',
  headers: { 'Content-Type': 'application/json' }
})

// Store definitions (factories return store definitions)
// IMPORTANT: Trebuie create ÎNAINTE de interceptori pentru a fi disponibile în closure-uri
const useAuthStore = createAuthStore(authApi)
const useCompanyStore = createCompaniesStore(authApi, useAuthStore)
const useAccountingPeriodStore = createAccountingPeriodStore(authApi)

// Store instances (invoke the definitions to get instances)
const authStore = useAuthStore()
const companyStore = useCompanyStore()
const periodStore = useAccountingPeriodStore()

// Add interceptor to inject auth token from localStorage
authApi.interceptors.request.use(config => {
  // Skip requests if we're already redirecting to login
  if (isAuthRedirectInProgress()) {
    const controller = new AbortController()
    controller.abort()
    config.signal = controller.signal
    return config
  }

  const token = localStorage.getItem('access_token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// Response interceptor to handle 401 errors
authApi.interceptors.response.use(
  response => response,
  error => {
    if (error.response?.status === 401) {
      // NU redirecta dacă suntem în proces de autentificare
      // (login sau server switch - eroarea va fi gestionată de formular)
      if (!authStore.isAuthenticating) {
        // Use shared handler to prevent race conditions
        handleUnauthorized()
      }
    }
    return Promise.reject(error)
  }
)

// Menu state
const menuOpen = ref(false)

// Get enabled menu items based on feature flags
const enabledMenuItems = computed(() => {
  return getEnabledMenuSections(menuSections)
})

// Watch for company selection changes and auto-load periods
watch(
  () => companyStore.selectedCompany,
  async (newCompany, oldCompany) => {
    // Only load periods if company actually changed and is valid
    // FIX: Use value-based comparison instead of reference comparison
    // Reference comparison (newCompany !== oldCompany) fails when same company
    // exists on different servers because objects are different instances
    if (newCompany && newCompany.id_firma &&
        (newCompany.id_firma !== oldCompany?.id_firma ||
         newCompany._server_id !== oldCompany?._server_id)) {
      console.log('[App] Company changed via watch, loading periods for:', newCompany.id_firma, 'server:', newCompany._server_id)
      await periodStore.loadPeriods(newCompany.id_firma)
      console.log('[App] Periods auto-loaded successfully')
    }
  },
  { immediate: true } // Run immediately with current value
)

// Initialize auth and load companies on mount
onMounted(async () => {
  // Add resize listener for mobile detection
  window.addEventListener('resize', handleResize)
  // Also call handleResize immediately to ensure correct initial value
  // (important when viewport is set before Vue mounts, e.g., in Playwright tests)
  handleResize()

  console.log('[App] Mounted - initializing auth...')
  await authStore.initializeAuth()
  console.log('[App] Auth initialized, isAuthenticated:', authStore.isAuthenticated)

  // If authenticated, load companies and available servers immediately
  if (authStore.isAuthenticated) {
    console.log('[App] Loading companies and available servers...')
    // Fetch available servers for dropdown (US-010)
    // This is needed after page reload since availableServers is only set during login flow
    await fetchAvailableServers()
    await companyStore.loadCompanies()
    console.log('[App] Companies loaded, selectedCompany:', companyStore.selectedCompany)
    // Period loading will be triggered by the watcher above
  } else {
    console.log('[App] Not authenticated, skipping company/period/server loading')
  }
})

// Cleanup resize listener
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// Event handlers
const handleCompanyChanged = async (company) => {
  console.log('[App] Company changed:', company)

  // Load periods for the selected company
  if (company && company.id_firma) {
    console.log('[App] Loading periods for company:', company.id_firma)
    await periodStore.loadPeriods(company.id_firma)
  }
}

const handlePeriodChanged = (period) => {
  console.log('[App] Period changed:', period)
}

const handleLogout = async () => {
  await authStore.logout()
  router.push('/login')
}

/**
 * Fetch available servers for current user (US-010)
 * Called after authentication to populate server dropdown
 * This is needed because availableServers is only set during login flow (checkIdentity),
 * but after page reload we need to fetch it separately.
 */
const fetchAvailableServers = async () => {
  try {
    const response = await authApi.get('/auth/my-servers')
    const servers = response.data?.servers || []
    // Update auth store's availableServers ref directly
    authStore.availableServers = servers
    console.log('[App] Fetched available servers:', servers.length)
  } catch (err) {
    // Don't fail silently but also don't block the app
    console.warn('[App] Could not fetch available servers:', err.message)
    // Keep availableServers as empty array - dropdown won't show
  }
}

// Server switched handler (US-009, US-010)
// Called after successful server switch to reload data
const handleServerSwitched = async (newServerId) => {
  console.log('[App] Server switched to:', newServerId)

  // Clear selected company FIRST to prevent stale data from old server
  companyStore.clearSelectedCompany()
  console.log('[App] Company selection cleared after server switch')

  // Reset period store for the new server context (US-010)
  periodStore.reset()
  console.log('[App] Period store reset after server switch')

  // Reload companies for the new server
  await companyStore.loadCompanies()
  console.log('[App] Companies reloaded after server switch')

  // FIX: Explicitly load periods for the selected company
  // The company watcher may not trigger if the same company exists on both servers
  // with identical id_firma and _server_id values after loadCompanies
  if (companyStore.selectedCompany?.id_firma) {
    console.log('[App] Loading periods after server switch for company:', companyStore.selectedCompany.id_firma)
    await periodStore.loadPeriods(companyStore.selectedCompany.id_firma)
    console.log('[App] Periods loaded after server switch')
  }
}
</script>

<style>
/* Import shared styles */
@import '@shared/styles/layout/header.css';
@import '@shared/styles/layout/navigation.css';

/* Import global CSS system */
@import './assets/css/main.css';
</style>
