<template>
  <!-- US-703: Mobile Top Bar with Hamburger Menu (not back button) -->
  <MobileTopBar
    v-if="isMobile"
    title="Scadențe"
    :show-menu="true"
    @menu-click="showDrawer = true"
  />

  <!-- US-703: Mobile Drawer Menu (replaces navigation via back button) -->
  <MobileDrawerMenu
    v-model="showDrawer"
    :user="authStore.user"
    :companies-store="companyStore"
    :period-store="periodStore"
    :available-servers="authStore.availableServers"
    :current-server-id="authStore.selectedServerId"
    :auth-store="authStore"
    @logout="handleLogout"
    @company-changed="handleCompanyChanged"
    @period-changed="handlePeriodChanged"
    @server-switched="handleServerSwitched"
  />

  <!-- US-608: Mobile Tabs (sticky below MobileTopBar) - like DetailedInvoicesView -->
  <div v-if="isMobile && companyStore.selectedCompany" class="mobile-tabs-container">
    <div class="mobile-tabs">
      <button
        class="mobile-tab"
        :class="{ active: activeTab === 'clients' }"
        @click="switchTab('clients')"
      >
        <span class="tab-label">Clienți</span>
      </button>
      <button
        class="mobile-tab"
        :class="{ active: activeTab === 'suppliers' }"
        @click="switchTab('suppliers')"
      >
        <span class="tab-label">Furnizori</span>
      </button>
    </div>
  </div>

  <main class="main-content" :class="{ 'mobile-layout': isMobile, 'has-tabs': isMobile && companyStore.selectedCompany }">
    <div class="app-container">
      <!-- Page Header - only on desktop -->
      <div v-if="!isMobile" class="page-header">
        <div class="header-top">
          <div>
            <h1 class="page-title">Analiză Scadențe</h1>
            <p class="page-subtitle">Analiza scadențelor clienți și furnizori</p>
          </div>
        </div>
        <!-- US-608: Desktop Tabs (in header) -->
        <div v-if="companyStore.selectedCompany" class="desktop-tabs">
          <button
            class="desktop-tab"
            :class="{ active: activeTab === 'clients' }"
            @click="switchTab('clients')"
          >
            <i class="pi pi-users"></i>
            <span>Clienți</span>
          </button>
          <button
            class="desktop-tab"
            :class="{ active: activeTab === 'suppliers' }"
            @click="switchTab('suppliers')"
          >
            <i class="pi pi-building"></i>
            <span>Furnizori</span>
          </button>
        </div>
      </div>

      <!-- Loading state when no company selected -->
      <div v-if="!companyStore.selectedCompany" class="empty-state">
        <i class="pi pi-building empty-icon"></i>
        <h2 class="empty-title">Selectați o companie</h2>
        <p class="empty-description">
          Pentru a vizualiza analiza scadențelor, vă rugăm să selectați o companie din Dashboard.
        </p>
        <Button
          label="Mergi la Dashboard"
          icon="pi pi-arrow-left"
          @click="goBack"
          class="empty-action"
        />
      </div>

      <!-- US-608: Flat content structure - no card wrapper -->
      <div v-else class="maturity-content">
        <MaturityAnalysisCard
          ref="maturityCardRef"
          :companyId="companyStore.selectedCompany?.id_firma"
          :activeTab="activeTab"
          @periodChanged="handlePeriodChange"
        />
      </div>
    </div>
  </main>

  <!-- Mobile Bottom Nav -->
  <MobileBottomNav v-if="isMobile" />
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import Button from 'primevue/button'
import MobileTopBar from '@shared/components/mobile/MobileTopBar.vue'
import MobileBottomNav from '@shared/components/mobile/MobileBottomNav.vue'
import MobileDrawerMenu from '@shared/components/mobile/MobileDrawerMenu.vue'
import MaturityAnalysisCard from '@reports/components/dashboard/cards/MaturityAnalysisCard.vue'
import { useCompanyStore, useAuthStore, useAccountingPeriodStore } from '@reports/stores/sharedStores'

const router = useRouter()
const route = useRoute()
const companyStore = useCompanyStore()
const authStore = useAuthStore()
const periodStore = useAccountingPeriodStore()

// US-703: Drawer state for hamburger menu
const showDrawer = ref(false)

// Detectare mobile - reactive with resize listener
const windowWidth = ref(window.innerWidth)
const isMobile = computed(() => windowWidth.value < 768)

// Ref to MaturityAnalysisCard
const maturityCardRef = ref(null)

// US-608: Tab state (persisted via URL query)
const TAB_STORAGE_KEY = 'maturity_analysis_active_tab'

const getInitialTab = () => {
  // Check URL query first
  if (route.query.tab === 'suppliers') return 'suppliers'
  // Then localStorage
  const stored = localStorage.getItem(TAB_STORAGE_KEY)
  if (stored === 'suppliers') return 'suppliers'
  return 'clients'
}

const activeTab = ref(getInitialTab())

// US-608: Switch tab and update URL
const switchTab = (tab) => {
  activeTab.value = tab
  localStorage.setItem(TAB_STORAGE_KEY, tab)
  // Update URL without full navigation
  router.replace({
    query: tab === 'suppliers' ? { tab: 'suppliers' } : {}
  })
}

// Handle window resize for mobile detection
const handleResize = () => {
  windowWidth.value = window.innerWidth
}

// Navigation
const goBack = () => {
  router.push('/reports/dashboard')
}

// US-703: Handlers for MobileDrawerMenu
const handleLogout = async () => {
  await authStore.logout()
  router.push('/login')
}

// Handle server switch completed - reload data for new server
const handleServerSwitched = async (newServerId) => {
  // Server switch already completed in MobileDrawerMenu modal
  // Reload data for the new server
  await companyStore.loadCompanies()
  if (companyStore.selectedCompany?.id_firma) {
    await periodStore.loadPeriods(companyStore.selectedCompany.id_firma)
  }
}

const handleCompanyChanged = (company) => {
  // Company store watcher handles the refresh
  console.log('Company changed:', company?.id_firma)
}

const handlePeriodChanged = () => {
  // Period store watcher handles the refresh
  console.log('Period changed')
}

// Handle period change from MaturityAnalysisCard
const handlePeriodChange = (period) => {
  console.log('Maturity period changed:', period)
}

// Lifecycle
onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
/* Mobile Layout - Padding for fixed top/bottom bars */
/* US-706: Override margin-top from containers.css to eliminate gap between tabs and content */
.main-content.mobile-layout {
  margin-top: 0 !important;
  padding-top: 56px;
  padding-bottom: 56px;
}

/* US-608: Extra padding when tabs are visible on mobile */
.main-content.mobile-layout.has-tabs {
  padding-top: calc(56px + 48px);
}

/* App container */
/* US-705: Reduced padding for less top spacing - sm (8px) instead of lg (24px) */
.app-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: var(--space-sm) var(--space-lg);
}

@media (max-width: 768px) {
  .app-container {
    /* US-706: Minimal vertical padding on mobile - content starts immediately after tabs */
    padding: var(--space-xs) var(--space-md);
  }
}

/* Page Header - Desktop only */
/* US-705: Reduced from var(--space-md) to var(--space-sm) for less excessive top spacing */
.page-header {
  margin-bottom: var(--space-sm);
}

.header-top {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  /* US-705: Reduced from var(--space-md) to var(--space-xs) - title/subtitle need minimal gap */
  margin-bottom: var(--space-xs);
}

.page-title {
  font-size: var(--text-3xl);
  font-weight: var(--font-bold);
  color: var(--text-color);
  margin: 0 0 var(--space-xs) 0;
}

.page-subtitle {
  font-size: var(--text-base);
  color: var(--text-color-secondary);
  margin: 0;
}

/* ================================================
   US-608: Mobile Tabs (sticky below MobileTopBar)
   Copied from DetailedInvoicesView for consistency
   ================================================ */

.mobile-tabs-container {
  position: fixed;
  top: 56px;
  left: 0;
  right: 0;
  z-index: var(--z-sticky, 100);
  background: var(--surface-card);
  border-bottom: 1px solid var(--surface-border);
}

.mobile-tabs {
  display: flex;
  width: 100%;
}

.mobile-tab {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--space-md);
  min-height: 48px;
  background: transparent;
  border: none;
  border-bottom: 2px solid transparent;
  cursor: pointer;
  transition: all var(--transition-fast);
  color: var(--text-color-secondary);
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
}

.mobile-tab.active {
  color: var(--color-primary);
  border-bottom-color: var(--color-primary);
  font-weight: var(--font-semibold);
}

.mobile-tab:hover:not(.active) {
  background: var(--surface-hover);
}

.tab-label {
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

/* ================================================
   US-608: Desktop Tabs (in page-header)
   ================================================ */

.desktop-tabs {
  display: flex;
  gap: var(--space-sm);
}

.desktop-tab {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  padding: var(--space-sm) var(--space-lg);
  background: var(--surface-hover);
  border: 1px solid var(--surface-border);
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: all var(--transition-fast);
  color: var(--text-color-secondary);
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
}

.desktop-tab:hover:not(.active) {
  border-color: var(--color-primary);
  color: var(--color-primary);
}

.desktop-tab.active {
  background: var(--color-primary);
  border-color: var(--color-primary);
  color: var(--color-text-inverse, white);
}

.desktop-tab i {
  font-size: var(--text-base);
}

/* ================================================
   US-608: Flat content (no card wrapper)
   ================================================ */

.maturity-content {
  display: flex;
  flex-direction: column;
  gap: var(--space-lg);
}

@media (max-width: 768px) {
  .maturity-content {
    gap: var(--space-sm);
  }
}

/* Empty state styles */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  text-align: center;
  padding: var(--space-xl);
  background: var(--surface-card);
  border-radius: var(--radius-lg);
  border: 1px solid var(--surface-border);
}

.empty-icon {
  font-size: 64px;
  color: var(--text-color-secondary);
  margin-bottom: var(--space-lg);
  opacity: 0.5;
}

.empty-title {
  font-size: var(--text-xl);
  font-weight: var(--font-semibold);
  color: var(--text-color);
  margin: 0 0 var(--space-sm) 0;
}

.empty-description {
  font-size: var(--text-base);
  color: var(--text-color-secondary);
  margin: 0 0 var(--space-lg) 0;
  max-width: 400px;
}

.empty-action {
  margin-top: var(--space-md);
}

/* ================================================
   Dark Mode Support
   ================================================ */

[data-theme="dark"] .mobile-tabs-container {
  background: var(--surface-card);
  border-bottom-color: var(--surface-border);
}

[data-theme="dark"] .mobile-tab.active {
  color: var(--blue-400);
  border-bottom-color: var(--blue-400);
}

[data-theme="dark"] .desktop-tab.active {
  background: var(--blue-600);
  border-color: var(--blue-600);
}

@media (prefers-color-scheme: dark) {
  :root:not([data-theme]) .mobile-tabs-container {
    background: var(--surface-card);
    border-bottom-color: var(--surface-border);
  }

  :root:not([data-theme]) .mobile-tab.active {
    color: var(--blue-400);
    border-bottom-color: var(--blue-400);
  }

  :root:not([data-theme]) .desktop-tab.active {
    background: var(--blue-600);
    border-color: var(--blue-600);
  }
}
</style>
