<template>
  <Teleport to="body">
    <Transition name="drawer">
      <div v-if="modelValue" class="drawer-overlay" @click.self="close">
        <nav class="drawer-menu" ref="drawerRef">
          <!-- Header with Logo -->
          <div class="drawer-header">
            <div class="drawer-logo">
              <i class="pi pi-building"></i>
              <span class="logo-text">ROA2WEB</span>
            </div>
          </div>

          <!-- Company & Period Selection (below header, above navigation) -->
          <!-- US-608: Direct dropdowns (no collapsible sections) -->
          <div v-if="companiesStore" class="drawer-selectors">
            <!-- Company Selector (Direct Dropdown) -->
            <div class="selector-group">
              <label class="selector-label">Firma</label>
              <button
                class="selector-trigger"
                @click="toggleCompanyDropdown"
                :aria-expanded="companyDropdownOpen"
              >
                <div class="selector-value">
                  <span class="selector-main">{{ selectedCompanyName }}</span>
                  <span v-if="selectedCompanyCode" class="selector-sub">{{ selectedCompanyCode }}</span>
                </div>
                <i class="pi pi-chevron-down" :class="{ 'rotate-180': companyDropdownOpen }"></i>
              </button>
              <!-- Company Dropdown Panel -->
              <div v-if="companyDropdownOpen" class="selector-panel">
                <div class="selector-search">
                  <i class="pi pi-search"></i>
                  <input
                    ref="companySearchInput"
                    type="text"
                    v-model="companySearchQuery"
                    placeholder="Caută firmă..."
                    class="selector-search-input"
                  />
                </div>
                <div class="selector-list">
                  <div
                    v-for="company in filteredCompanies"
                    :key="company.id_firma"
                    class="selector-item"
                    :class="{ active: company.id_firma === companiesStore.selectedCompany?.id_firma }"
                    @click="selectCompany(company)"
                  >
                    <div class="selector-item-content">
                      <span class="selector-item-name">{{ company.name }}</span>
                      <span v-if="company.fiscal_code" class="selector-item-sub">CUI: {{ company.fiscal_code }}</span>
                    </div>
                    <i v-if="company.id_firma === companiesStore.selectedCompany?.id_firma" class="pi pi-check"></i>
                  </div>
                  <div v-if="filteredCompanies.length === 0" class="selector-empty">
                    <i class="pi pi-info-circle"></i>
                    <span>Nu s-au găsit firme</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- Period Selector (Direct Dropdown) -->
            <div v-if="periodStore && companiesStore.selectedCompany" class="selector-group">
              <label class="selector-label">Perioada</label>
              <button
                class="selector-trigger"
                @click="togglePeriodDropdown"
                :aria-expanded="periodDropdownOpen"
              >
                <div class="selector-value">
                  <span class="selector-main">{{ selectedPeriodDisplay }}</span>
                </div>
                <i class="pi pi-chevron-down" :class="{ 'rotate-180': periodDropdownOpen }"></i>
              </button>
              <!-- Period Dropdown Panel -->
              <div v-if="periodDropdownOpen" class="selector-panel">
                <div class="selector-list">
                  <div
                    v-for="period in availablePeriods"
                    :key="`${period.an}-${period.luna}`"
                    class="selector-item"
                    :class="{ active: isPeriodSelected(period) }"
                    @click="selectPeriod(period)"
                  >
                    <span class="selector-item-name">{{ period.display_name }}</span>
                    <i v-if="isPeriodSelected(period)" class="pi pi-check"></i>
                  </div>
                  <div v-if="availablePeriods.length === 0" class="selector-empty">
                    <i class="pi pi-info-circle"></i>
                    <span>Nu sunt perioade disponibile</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- Server Selector (Direct Dropdown) - only show if multiple servers available -->
            <div v-if="availableServers && availableServers.length > 1" class="selector-group">
              <label class="selector-label">Server</label>
              <button
                class="selector-trigger"
                @click="toggleServerDropdown"
                :aria-expanded="serverDropdownOpen"
              >
                <div class="selector-value">
                  <span class="selector-main">{{ currentServerName }}</span>
                </div>
                <i class="pi pi-chevron-down" :class="{ 'rotate-180': serverDropdownOpen }"></i>
              </button>
              <!-- Server Dropdown Panel -->
              <div v-if="serverDropdownOpen" class="selector-panel">
                <div class="selector-list">
                  <div
                    v-for="server in availableServers"
                    :key="server.id"
                    class="selector-item"
                    :class="{ active: server.id === currentServerId }"
                    @click="selectServer(server)"
                  >
                    <span class="selector-item-name">{{ server.name }}</span>
                    <i v-if="server.id === currentServerId" class="pi pi-check"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Section Divider after selectors -->
          <div v-if="companiesStore" class="drawer-divider"></div>

          <!-- Navigation Sections (scrollable) -->
          <div class="drawer-sections">
            <!-- PRINCIPALE Section -->
            <div class="drawer-section">
              <div class="section-header">PRINCIPALE</div>
              <ul class="drawer-nav">
                <li v-for="item in principaleItems" :key="item.to">
                  <router-link
                    :to="item.to"
                    class="drawer-link"
                    :class="{ 'active': isActive(item.to, item.exactMatch) }"
                    @click="handleNavClick"
                  >
                    <i :class="['drawer-icon', item.icon]"></i>
                    <span class="drawer-label">{{ item.label }}</span>
                  </router-link>
                </li>
              </ul>
            </div>

            <!-- Section Divider -->
            <div class="drawer-divider"></div>

            <!-- RAPOARTE Section -->
            <div class="drawer-section">
              <div class="section-header">RAPOARTE</div>
              <ul class="drawer-nav">
                <li v-for="item in rapoarteItems" :key="item.to">
                  <router-link
                    :to="item.to"
                    class="drawer-link"
                    :class="{ 'active': isActive(item.to, item.exactMatch) }"
                    @click="handleNavClick"
                  >
                    <i :class="['drawer-icon', item.icon]"></i>
                    <span class="drawer-label">{{ item.label }}</span>
                  </router-link>
                </li>
              </ul>
            </div>

            <!-- Section Divider -->
            <div class="drawer-divider"></div>

            <!-- ANALIZE Section -->
            <div class="drawer-section">
              <div class="section-header">ANALIZE</div>
              <ul class="drawer-nav">
                <li v-for="item in analizeItems" :key="item.to">
                  <router-link
                    :to="item.to"
                    class="drawer-link"
                    :class="{ 'active': isActive(item.to, item.exactMatch) }"
                    @click="handleNavClick"
                  >
                    <i :class="['drawer-icon', item.icon]"></i>
                    <span class="drawer-label">{{ item.label }}</span>
                  </router-link>
                </li>
              </ul>
            </div>

            <!-- Section Divider -->
            <div class="drawer-divider"></div>

            <!-- ADMINISTRARE Section -->
            <div class="drawer-section">
              <div class="section-header">ADMINISTRARE</div>
              <ul class="drawer-nav">
                <li v-for="item in administrareItems" :key="item.to">
                  <router-link
                    :to="item.to"
                    class="drawer-link"
                    :class="{ 'active': isActive(item.to, item.exactMatch) }"
                    @click="handleNavClick"
                  >
                    <i :class="['drawer-icon', item.icon]"></i>
                    <span class="drawer-label">{{ item.label }}</span>
                  </router-link>
                </li>
              </ul>
            </div>
          </div>

          <!-- Profile Section (at bottom) - US-607: Compact layout -->
          <div class="drawer-profile drawer-profile--compact">
            <!-- US-607: User name + Logout on same line -->
            <div class="profile-row">
              <div class="profile-user">
                <i class="pi pi-user profile-icon"></i>
                <span class="profile-name">{{ displayName }}</span>
              </div>
              <button
                type="button"
                class="logout-btn"
                @click="handleLogout"
                aria-label="Deconectare"
              >
                <i class="pi pi-sign-out"></i>
                <span>Ieșire</span>
              </button>
            </div>

            <!-- Theme Toggle (compact cyclic button) - US-604 -->
            <button
              type="button"
              class="theme-toggle-compact"
              @click="cycleTheme"
              :aria-label="`Schimbă tema: ${currentThemeOption.label}`"
            >
              <i :class="currentThemeOption.icon"></i>
              <span>{{ currentThemeOption.label }}</span>
              <i class="pi pi-chevron-right"></i>
            </button>
          </div>
        </nav>
      </div>
    </Transition>

    <!-- Server Switch Password Modal -->
    <Dialog
      v-model:visible="showServerPasswordModal"
      :header="`Schimbare server: ${targetServerName}`"
      :modal="true"
      :closable="!isSwitchingServer"
      :style="{ width: '90vw', maxWidth: '320px' }"
      class="mobile-server-switch-modal"
    >
      <div class="server-switch-modal-content">
        <Password
          v-model="serverSwitchPassword"
          :feedback="false"
          toggleMask
          inputClass="w-full"
          class="w-full"
          :disabled="isSwitchingServer"
          @keyup.enter="confirmServerSwitch"
          autofocus
        />

        <div v-if="serverSwitchError" class="switch-error">
          <i class="pi pi-exclamation-circle"></i>
          <span>{{ serverSwitchError }}</span>
        </div>
      </div>

      <template #footer>
        <Button
          label="Anulează"
          severity="secondary"
          :disabled="isSwitchingServer"
          @click="cancelServerSwitch"
        />
        <Button
          label="Confirmă"
          :loading="isSwitchingServer"
          :disabled="!serverSwitchPassword"
          @click="confirmServerSwitch"
        />
      </template>
    </Dialog>
  </Teleport>
</template>

<script setup>
import { computed, ref, watch, nextTick, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Dialog from 'primevue/dialog'
import Password from 'primevue/password'
import Button from 'primevue/button'

/**
 * MobileDrawerMenu - Material Design 3 inspired navigation drawer for mobile (v4)
 * US-608: Direct dropdown selectors (removed collapsible sections)
 *
 * Props:
 * - modelValue (v-model): Controls visibility of the drawer
 * - user: Optional user object with { username } for profile display
 * - onLogout: Optional callback function for logout action
 * - companiesStore: Optional Pinia store instance for company selection
 * - periodStore: Optional Pinia store instance for accounting period selection
 * - availableServers: Optional array of { id, name } objects for multi-server selection
 * - currentServerId: Currently selected server ID for multi-server feature
 *
 * Events:
 * - update:modelValue: Emitted when visibility changes (for v-model support)
 * - logout: Emitted when logout is clicked (if no onLogout prop)
 * - company-changed: Emitted when company selection changes
 * - period-changed: Emitted when period selection changes
 * - server-switch: Emitted when server selection changes (with new server ID)
 *
 * Features:
 * - Slide-in animation from left
 * - Header with ROA2WEB logo
 * - Company, Period & Server selectors as direct dropdowns (1-tap interaction)
 * - Server selector only visible when multiple servers available
 * - Navigation organized into 4 category sections:
 *   - PRINCIPALE: Dashboard, Bonuri
 *   - RAPOARTE: Facturi, Balanță, Casă, Bancă
 *   - ANALIZE: Scadențe, Facturi Detaliate
 *   - ADMINISTRARE: Setări
 * - Visual separators between sections
 * - Active state highlighting based on current route
 * - Profile section with user name, logout button, and theme toggle
 * - Theme toggle cycles through: Auto → Light → Dark
 * - Close on tap outside or on link click
 * - Full dark mode support
 * - Teleported to body to avoid z-index issues
 */

const props = defineProps({
  /**
   * Controls visibility of the drawer (v-model support)
   */
  modelValue: {
    type: Boolean,
    default: false
  },
  /**
   * User object for profile display
   * Expected shape: { username: string }
   */
  user: {
    type: Object,
    default: () => null
  },
  /**
   * Optional callback for logout action
   * If not provided, 'logout' event is emitted
   */
  onLogout: {
    type: Function,
    default: null
  },
  /**
   * Companies store instance for company selection
   * Expected: Pinia store with companies, selectedCompany, setSelectedCompany
   */
  companiesStore: {
    type: Object,
    default: null
  },
  /**
   * Accounting period store instance for period selection
   * Expected: Pinia store with periods, selectedPeriod, setSelectedPeriod
   */
  periodStore: {
    type: Object,
    default: null
  },
  /**
   * Available servers for multi-server selection
   * Expected: Array of { id: string, name: string } objects
   */
  availableServers: {
    type: Array,
    default: () => []
  },
  /**
   * Currently selected server ID
   */
  currentServerId: {
    type: String,
    default: ''
  },
  /**
   * Auth store instance for server switching
   * Required for password-protected server switch
   */
  authStore: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'logout', 'company-changed', 'period-changed', 'server-switch', 'server-switched'])

const route = useRoute()
const router = useRouter()
const drawerRef = ref(null)

// Company selector state
const companyDropdownOpen = ref(false)
const companySearchQuery = ref('')
const companySearchInput = ref(null)

// Period selector state
const periodDropdownOpen = ref(false)

// Server selector state
const serverDropdownOpen = ref(false)

// Server switch password modal state
const showServerPasswordModal = ref(false)
const serverSwitchPassword = ref('')
const targetServerId = ref('')
const targetServerName = ref('')
const isSwitchingServer = ref(false)
const serverSwitchError = ref('')

// US-608: Removed collapsible state management - using direct dropdowns now

// Computed properties for company selector
const selectedCompanyName = computed(() => {
  return props.companiesStore?.selectedCompany?.name || 'Selectare firmă'
})

const selectedCompanyCode = computed(() => {
  const code = props.companiesStore?.selectedCompany?.fiscal_code
  return code ? `CUI: ${code}` : ''
})

const filteredCompanies = computed(() => {
  const companies = props.companiesStore?.companies || []
  if (!companySearchQuery.value?.trim()) {
    return companies
  }
  const query = companySearchQuery.value.toLowerCase().trim()
  return companies.filter(
    (company) =>
      company.name?.toLowerCase().includes(query) ||
      company.fiscal_code?.toLowerCase().includes(query)
  )
})

// Computed properties for period selector
const selectedPeriodDisplay = computed(() => {
  return props.periodStore?.selectedPeriod?.display_name || 'Selectare perioadă'
})

const availablePeriods = computed(() => {
  return props.periodStore?.periods || []
})

// Company selector methods
const toggleCompanyDropdown = async () => {
  companyDropdownOpen.value = !companyDropdownOpen.value
  // Close other dropdowns
  periodDropdownOpen.value = false
  serverDropdownOpen.value = false
  if (companyDropdownOpen.value) {
    companySearchQuery.value = ''
    await nextTick()
    companySearchInput.value?.focus()
  }
}

const selectCompany = (company) => {
  if (props.companiesStore) {
    props.companiesStore.setSelectedCompany(company)
    emit('company-changed', company)
  }
  companyDropdownOpen.value = false
  companySearchQuery.value = ''
}

// Period selector methods
const togglePeriodDropdown = () => {
  periodDropdownOpen.value = !periodDropdownOpen.value
  // Close other dropdowns
  companyDropdownOpen.value = false
  serverDropdownOpen.value = false
}

const isPeriodSelected = (period) => {
  const selected = props.periodStore?.selectedPeriod
  if (!selected) return false
  return period.an === selected.an && period.luna === selected.luna
}

const selectPeriod = (period) => {
  if (props.periodStore) {
    props.periodStore.setSelectedPeriod(period)
    emit('period-changed', period)
  }
  periodDropdownOpen.value = false
}

// Computed property for current server name
const currentServerName = computed(() => {
  const server = props.availableServers?.find(s => s.id === props.currentServerId)
  return server?.name || 'Selectare server'
})

// Server selector methods
const toggleServerDropdown = () => {
  serverDropdownOpen.value = !serverDropdownOpen.value
  // Close other dropdowns
  companyDropdownOpen.value = false
  periodDropdownOpen.value = false
}

const selectServer = (server) => {
  if (server.id !== props.currentServerId) {
    // Open password modal instead of switching directly
    targetServerId.value = server.id
    targetServerName.value = server.name
    serverSwitchPassword.value = ''
    serverSwitchError.value = ''
    isSwitchingServer.value = false
    showServerPasswordModal.value = true
  }
  serverDropdownOpen.value = false
}

// Server switch password modal methods
const cancelServerSwitch = () => {
  showServerPasswordModal.value = false
  serverSwitchPassword.value = ''
  serverSwitchError.value = ''
}

const confirmServerSwitch = async () => {
  if (!serverSwitchPassword.value || !targetServerId.value) {
    serverSwitchError.value = 'Introduceți parola'
    return
  }

  if (!props.authStore?.switchServer) {
    serverSwitchError.value = 'Eroare: authStore nu este disponibil'
    return
  }

  isSwitchingServer.value = true
  serverSwitchError.value = ''

  try {
    const result = await props.authStore.switchServer(targetServerId.value, serverSwitchPassword.value)

    if (result.success) {
      // Close modal and drawer
      showServerPasswordModal.value = false
      serverSwitchPassword.value = ''

      // Emit event for parent to reload data
      emit('server-switched', targetServerId.value)

      // Close the drawer after successful switch
      close()
    } else {
      serverSwitchError.value = result.error || 'Autentificare eșuată'
    }
  } catch (error) {
    serverSwitchError.value = error.message || 'Eroare la schimbarea serverului'
  } finally {
    isSwitchingServer.value = false
  }
}

// Close dropdowns when drawer closes
watch(() => props.modelValue, (isOpen) => {
  if (!isOpen) {
    companyDropdownOpen.value = false
    periodDropdownOpen.value = false
    serverDropdownOpen.value = false
    companySearchQuery.value = ''
  }
})

/**
 * Navigation items organized by category
 * Based on US-308 acceptance criteria
 */

// PRINCIPALE: Dashboard, Bonuri
const principaleItems = [
  { to: '/dashboard', icon: 'pi pi-home', label: 'Dashboard', exactMatch: true },
  { to: '/data-entry', icon: 'pi pi-shopping-bag', label: 'Bonuri', exactMatch: false }
]

// RAPOARTE: Facturi, Balanță, Casă, Bancă (US-519: separate pages)
const rapoarteItems = [
  { to: '/reports/invoices', icon: 'pi pi-file', label: 'Facturi', exactMatch: true },
  { to: '/reports/trial-balance', icon: 'pi pi-calculator', label: 'Balanță', exactMatch: true },
  { to: '/reports/cash', icon: 'pi pi-wallet', label: 'Casă', exactMatch: true },
  { to: '/reports/bank', icon: 'pi pi-building', label: 'Bancă', exactMatch: true }
]

// ANALIZE: Scadențe, Facturi Detaliate
const analizeItems = [
  { to: '/reports/maturity-analysis', icon: 'pi pi-clock', label: 'Scadențe', exactMatch: true },
  { to: '/reports/detailed-invoices', icon: 'pi pi-list', label: 'Facturi Detaliate', exactMatch: true }
]

// ADMINISTRARE: Setări
const administrareItems = [
  { to: '/settings', icon: 'pi pi-cog', label: 'Setări', exactMatch: false }
]

/**
 * Display name for profile section
 * Falls back to 'Utilizator' if no user provided
 */
const displayName = computed(() => {
  return props.user?.username || 'Utilizator'
})

/**
 * Check if a navigation item is active based on current route
 */
const isActive = (to, exactMatch) => {
  if (exactMatch) {
    return route.path === to
  }
  // For non-exact match, check if current path starts with the route
  return route.path.startsWith(to)
}

/**
 * Close the drawer menu
 */
const close = () => {
  emit('update:modelValue', false)
}

/**
 * Handle navigation link click - close drawer after navigation
 */
const handleNavClick = () => {
  close()
}

/**
 * Handle logout action
 * Calls onLogout prop if provided, otherwise emits 'logout' event
 */
const handleLogout = async () => {
  if (props.onLogout) {
    await props.onLogout()
  } else {
    emit('logout')
  }
  close()
}

/**
 * Theme Toggle Logic
 * Supports three modes: auto (system), light, dark
 * Persists preference in localStorage['user-theme']
 */
const currentTheme = ref('auto')

// Theme options with icons and labels
const themeOptions = [
  { value: 'auto', icon: 'pi pi-desktop', label: 'Auto (sistem)' },
  { value: 'light', icon: 'pi pi-sun', label: 'Light' },
  { value: 'dark', icon: 'pi pi-moon', label: 'Dark' }
]

// Get current theme option for display
const currentThemeOption = computed(() => {
  return themeOptions.find(opt => opt.value === currentTheme.value) || themeOptions[0]
})

/**
 * Apply theme to document
 */
const applyTheme = (theme) => {
  if (theme === 'auto') {
    document.documentElement.removeAttribute('data-theme')
    localStorage.removeItem('user-theme')
  } else {
    document.documentElement.setAttribute('data-theme', theme)
    localStorage.setItem('user-theme', theme)
  }
}

/**
 * Cycle through themes: auto → light → dark → auto
 */
const cycleTheme = () => {
  const themes = ['auto', 'light', 'dark']
  const currentIndex = themes.indexOf(currentTheme.value)
  const nextTheme = themes[(currentIndex + 1) % themes.length]
  currentTheme.value = nextTheme
  applyTheme(nextTheme)
}

// Initialize theme from localStorage on mount
onMounted(() => {
  const savedTheme = localStorage.getItem('user-theme')
  if (savedTheme === 'light' || savedTheme === 'dark') {
    currentTheme.value = savedTheme
  } else {
    currentTheme.value = 'auto'
  }
})
</script>

<style scoped>
/* ================================================
   MobileDrawerMenu Component Styles
   Material Design 3 inspired navigation drawer
   ================================================ */

/* Overlay background */
.drawer-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: var(--z-modal-backdrop);
  display: flex;
  align-items: stretch;
  justify-content: flex-start;
}

/* Main drawer container - US-606: Unified scrollable layout (updated) */
.drawer-menu {
  width: 280px;
  max-width: 85vw;
  height: 100%;
  min-height: 60vh; /* US-606: Ensure min 60% of screen height for menu visibility */
  background: var(--surface-card);
  box-shadow: var(--shadow-xl);
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  overflow-x: hidden;
  -webkit-overflow-scrolling: touch;
  z-index: var(--z-modal);
}

/* ================================================
   Header with Logo
   ================================================ */

.drawer-header {
  padding: var(--space-lg) var(--space-md);
  border-bottom: 1px solid var(--surface-border);
  background: var(--surface-ground);
}

.drawer-logo {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
}

.drawer-logo i {
  font-size: var(--text-2xl);
  color: var(--color-primary);
}

.logo-text {
  font-size: var(--text-xl);
  font-weight: var(--font-bold);
  color: var(--text-color);
}

/* ================================================
   Company & Period Selectors
   ================================================ */

.drawer-selectors {
  padding: var(--space-md);
  display: flex;
  flex-direction: column;
  gap: var(--space-sm);
  background: var(--surface-ground);
}

.selector-group {
  position: relative;
}

.selector-label {
  display: block;
  font-size: var(--text-xs);
  font-weight: var(--font-medium);
  color: var(--text-color-secondary);
  margin-bottom: var(--space-xs);
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.selector-trigger {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: var(--space-sm) var(--space-md);
  background: var(--surface-card);
  border: 1px solid var(--surface-border);
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: border-color var(--transition-fast), background var(--transition-fast);
  min-height: 48px;
  text-align: left;
}

.selector-trigger:hover {
  border-color: var(--color-primary);
  background: var(--surface-hover);
}

.selector-value {
  display: flex;
  flex-direction: column;
  min-width: 0;
  flex: 1;
}

.selector-main {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: var(--text-color);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.selector-sub {
  font-size: var(--text-xs);
  color: var(--text-color-secondary);
  margin-top: 2px;
}

.selector-trigger .pi-chevron-down {
  font-size: var(--text-xs);
  color: var(--text-color-secondary);
  transition: transform var(--transition-fast);
  flex-shrink: 0;
}

.selector-trigger .rotate-180 {
  transform: rotate(180deg);
}

/* Selector Dropdown Panel */
.selector-panel {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  margin-top: var(--space-xs);
  background: var(--surface-card);
  border: 1px solid var(--surface-border);
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-lg);
  z-index: 10;
  max-height: 250px;
  overflow: hidden;
}

.selector-search {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  padding: var(--space-sm);
  border-bottom: 1px solid var(--surface-border);
}

.selector-search .pi-search {
  color: var(--text-color-secondary);
  font-size: var(--text-sm);
}

.selector-search-input {
  flex: 1;
  border: none;
  background: transparent;
  font-size: var(--text-sm);
  color: var(--text-color);
  outline: none;
}

.selector-search-input::placeholder {
  color: var(--text-color-secondary);
}

.selector-list {
  max-height: 200px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.selector-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--space-sm) var(--space-md);
  cursor: pointer;
  transition: background var(--transition-fast);
  min-height: 48px;
  border-bottom: 1px solid var(--surface-border);
}

.selector-item:last-child {
  border-bottom: none;
}

.selector-item:hover {
  background: var(--surface-hover);
}

.selector-item.active {
  background: var(--blue-50);
  color: var(--color-primary);
}

.selector-item.active .pi-check {
  color: var(--color-primary);
}

.selector-item-content {
  display: flex;
  flex-direction: column;
  min-width: 0;
  flex: 1;
}

.selector-item-name {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: inherit;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.selector-item-sub {
  font-size: var(--text-xs);
  color: var(--text-color-secondary);
  margin-top: 2px;
}

.selector-item .pi-check {
  font-size: var(--text-sm);
  flex-shrink: 0;
}

.selector-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--space-sm);
  padding: var(--space-lg);
  color: var(--text-color-secondary);
  font-size: var(--text-sm);
}

/* ================================================
   US-608: Collapsible styles removed - using direct dropdowns
   ================================================ */

/* ================================================
   Navigation Sections Container
   US-606: No longer independently scrollable, part of unified scroll
   ================================================ */

.drawer-sections {
  padding: var(--space-sm) 0;
}

/* ================================================
   Individual Section
   ================================================ */

.drawer-section {
  padding: var(--space-xs) 0;
}

/* Section header label (PRINCIPALE, RAPOARTE, etc.) */
.section-header {
  padding: var(--space-sm) var(--space-lg);
  font-size: var(--text-xs);
  font-weight: var(--font-semibold);
  color: var(--text-color-secondary);
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.drawer-nav {
  list-style: none;
  margin: 0;
  padding: 0;
}

.drawer-link {
  display: flex;
  align-items: center;
  gap: var(--space-md);
  padding: var(--space-md) var(--space-lg);
  color: var(--text-color);
  text-decoration: none;
  font-size: var(--text-base);
  font-weight: var(--font-medium);
  min-height: 48px;
  transition: background var(--transition-fast), color var(--transition-fast);
  cursor: pointer;
  border: none;
  background: none;
  width: 100%;
  text-align: left;
}

.drawer-link:hover {
  background: var(--surface-hover);
}

.drawer-link:active {
  background: var(--surface-hover);
}

/* Active state */
.drawer-link.active {
  background: var(--blue-50);
  color: var(--color-primary);
}

.drawer-link.active .drawer-icon {
  color: var(--color-primary);
}

.drawer-icon {
  font-size: var(--text-xl);
  width: 24px;
  text-align: center;
  color: var(--text-color-secondary);
  flex-shrink: 0;
}

.drawer-label {
  flex: 1;
}

/* ================================================
   Divider
   ================================================ */

.drawer-divider {
  height: 1px;
  background: var(--surface-border);
  margin: var(--space-xs) var(--space-md);
}

/* ================================================
   Profile Section - US-607: Compact layout
   US-606: No longer fixed at bottom, scrolls with content
   ================================================ */

.drawer-profile {
  padding: var(--space-sm) var(--space-md);
  border-top: 1px solid var(--surface-border);
  /* Extra padding at bottom for MobileBottomNav clearance (56px) */
  padding-bottom: calc(var(--header-height) + var(--space-sm));
  display: flex;
  flex-direction: column;
  gap: var(--space-xs);
}

/* US-607/US-608: Compact variant - reduced spacing but with MobileBottomNav clearance */
.drawer-profile--compact {
  padding: var(--space-sm) var(--space-md);
  /* US-608: Ensure theme toggle is visible above MobileBottomNav (56px) */
  padding-bottom: calc(56px + var(--space-md));
  gap: var(--space-xs);
}

/* US-607: User name + Logout on same row */
.profile-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-sm);
  min-height: 44px;
}

.profile-user {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  min-width: 0;
  flex: 1;
}

.profile-icon {
  font-size: var(--text-base);
  color: var(--color-primary);
  flex-shrink: 0;
}

.profile-name {
  font-size: var(--text-sm);
  font-weight: var(--font-semibold);
  color: var(--text-color);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* US-607: Compact logout button */
.logout-btn {
  display: flex;
  align-items: center;
  gap: var(--space-xs);
  padding: var(--space-xs) var(--space-sm);
  background: transparent;
  border: 1px solid var(--color-error);
  border-radius: var(--radius-md);
  color: var(--color-error);
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  cursor: pointer;
  transition: background var(--transition-fast), color var(--transition-fast);
  min-height: 36px;
  flex-shrink: 0;
}

.logout-btn:hover {
  background: var(--red-50);
}

.logout-btn:active {
  background: var(--red-100);
}

.logout-btn i {
  font-size: var(--text-sm);
}

/* ================================================
   Theme Toggle (compact cyclic button) - US-604/US-607
   ================================================ */

.theme-toggle-compact {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  width: 100%;
  padding: var(--space-xs) var(--space-sm);
  background: var(--surface-hover);
  border: none;
  border-radius: var(--radius-md);
  color: var(--text-color);
  font-size: var(--text-sm);
  cursor: pointer;
  transition: background var(--transition-fast);
  min-height: 36px;
}

.theme-toggle-compact:hover {
  background: var(--surface-border);
}

.theme-toggle-compact i:first-child {
  color: var(--color-primary);
  font-size: var(--text-sm);
}

.theme-toggle-compact span {
  flex: 1;
  text-align: left;
}

.theme-toggle-compact i:last-child {
  font-size: var(--text-xs);
  color: var(--text-color-secondary);
  opacity: 0.6;
}

/* ================================================
   Slide Animation (Vue Transition)
   ================================================ */

.drawer-enter-active,
.drawer-leave-active {
  transition: opacity var(--transition-normal);
}

.drawer-enter-active .drawer-menu,
.drawer-leave-active .drawer-menu {
  transition: transform var(--transition-normal);
}

/* Initial state: invisible + drawer off-screen to left */
.drawer-enter-from,
.drawer-leave-to {
  opacity: 0;
}

.drawer-enter-from .drawer-menu,
.drawer-leave-to .drawer-menu {
  transform: translateX(-100%);
}

/* Final state: visible + drawer in place */
.drawer-enter-to,
.drawer-leave-from {
  opacity: 1;
}

.drawer-enter-to .drawer-menu,
.drawer-leave-from .drawer-menu {
  transform: translateX(0);
}

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

/* Manual dark mode via data-theme attribute */
[data-theme="dark"] .drawer-overlay {
  background: rgba(0, 0, 0, 0.7);
}

[data-theme="dark"] .drawer-menu {
  background: var(--surface-card);
  box-shadow: 4px 0 24px rgba(0, 0, 0, 0.4);
}

[data-theme="dark"] .drawer-header {
  background: var(--surface-ground);
  border-bottom-color: var(--surface-border);
}

[data-theme="dark"] .drawer-logo i {
  color: var(--blue-400);
}

[data-theme="dark"] .logo-text {
  color: var(--text-color);
}

/* Dark mode: Selectors */
[data-theme="dark"] .drawer-selectors {
  background: var(--surface-ground);
}

[data-theme="dark"] .selector-label {
  color: var(--text-color-secondary);
}

[data-theme="dark"] .selector-trigger {
  background: var(--surface-card);
  border-color: var(--surface-border);
}

[data-theme="dark"] .selector-trigger:hover {
  background: var(--surface-hover);
  border-color: var(--blue-400);
}

[data-theme="dark"] .selector-main {
  color: var(--text-color);
}

[data-theme="dark"] .selector-sub {
  color: var(--text-color-secondary);
}

[data-theme="dark"] .selector-trigger .pi-chevron-down {
  color: var(--text-color-secondary);
}

[data-theme="dark"] .selector-panel {
  background: var(--surface-card);
  border-color: var(--surface-border);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
}

[data-theme="dark"] .selector-search {
  border-bottom-color: var(--surface-border);
}

[data-theme="dark"] .selector-search .pi-search {
  color: var(--text-color-secondary);
}

[data-theme="dark"] .selector-search-input {
  color: var(--text-color);
}

[data-theme="dark"] .selector-search-input::placeholder {
  color: var(--text-color-secondary);
}

[data-theme="dark"] .selector-item {
  border-bottom-color: var(--surface-border);
}

[data-theme="dark"] .selector-item:hover {
  background: var(--surface-hover);
}

[data-theme="dark"] .selector-item.active {
  background: var(--blue-900);
  color: var(--blue-400);
}

[data-theme="dark"] .selector-item.active .pi-check {
  color: var(--blue-400);
}

[data-theme="dark"] .selector-item-name {
  color: var(--text-color);
}

[data-theme="dark"] .selector-item.active .selector-item-name {
  color: var(--blue-400);
}

[data-theme="dark"] .selector-item-sub {
  color: var(--text-color-secondary);
}

[data-theme="dark"] .selector-empty {
  color: var(--text-color-secondary);
}

[data-theme="dark"] .drawer-link {
  color: var(--text-color);
}

[data-theme="dark"] .drawer-link:hover {
  background: var(--surface-hover);
}

[data-theme="dark"] .drawer-link.active {
  background: var(--blue-900);
  color: var(--blue-400);
}

[data-theme="dark"] .drawer-link.active .drawer-icon {
  color: var(--blue-400);
}

[data-theme="dark"] .drawer-icon {
  color: var(--text-color-secondary);
}

[data-theme="dark"] .drawer-divider {
  background: var(--surface-border);
}

[data-theme="dark"] .section-header {
  color: var(--text-color-secondary);
}

/* Dark mode: Profile Section (US-607) */
[data-theme="dark"] .drawer-profile {
  border-top-color: var(--surface-border);
}

[data-theme="dark"] .profile-icon {
  color: var(--blue-400);
}

[data-theme="dark"] .profile-name {
  color: var(--text-color);
}

[data-theme="dark"] .logout-btn {
  border-color: var(--red-400);
  color: var(--red-400);
}

[data-theme="dark"] .logout-btn:hover {
  background: var(--red-900);
}

[data-theme="dark"] .logout-btn:active {
  background: var(--red-800);
}

/* Dark mode: Theme Toggle (US-607) */
[data-theme="dark"] .theme-toggle-compact {
  background: var(--surface-hover);
  color: var(--text-color);
}

[data-theme="dark"] .theme-toggle-compact:hover {
  background: var(--surface-border);
}

[data-theme="dark"] .theme-toggle-compact i:first-child {
  color: var(--blue-400);
}

[data-theme="dark"] .theme-toggle-compact i:last-child {
  color: var(--text-color-secondary);
}

/* Auto dark mode (when no manual theme is set) */
@media (prefers-color-scheme: dark) {
  :root:not([data-theme]) .drawer-overlay {
    background: rgba(0, 0, 0, 0.7);
  }

  :root:not([data-theme]) .drawer-menu {
    background: var(--surface-card);
    box-shadow: 4px 0 24px rgba(0, 0, 0, 0.4);
  }

  :root:not([data-theme]) .drawer-header {
    background: var(--surface-ground);
    border-bottom-color: var(--surface-border);
  }

  :root:not([data-theme]) .drawer-logo i {
    color: var(--blue-400);
  }

  :root:not([data-theme]) .logo-text {
    color: var(--text-color);
  }

  /* Auto dark mode: Selectors */
  :root:not([data-theme]) .drawer-selectors {
    background: var(--surface-ground);
  }

  :root:not([data-theme]) .selector-label {
    color: var(--text-color-secondary);
  }

  :root:not([data-theme]) .selector-trigger {
    background: var(--surface-card);
    border-color: var(--surface-border);
  }

  :root:not([data-theme]) .selector-trigger:hover {
    background: var(--surface-hover);
    border-color: var(--blue-400);
  }

  :root:not([data-theme]) .selector-main {
    color: var(--text-color);
  }

  :root:not([data-theme]) .selector-sub {
    color: var(--text-color-secondary);
  }

  :root:not([data-theme]) .selector-trigger .pi-chevron-down {
    color: var(--text-color-secondary);
  }

  :root:not([data-theme]) .selector-panel {
    background: var(--surface-card);
    border-color: var(--surface-border);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
  }

  :root:not([data-theme]) .selector-search {
    border-bottom-color: var(--surface-border);
  }

  :root:not([data-theme]) .selector-search .pi-search {
    color: var(--text-color-secondary);
  }

  :root:not([data-theme]) .selector-search-input {
    color: var(--text-color);
  }

  :root:not([data-theme]) .selector-search-input::placeholder {
    color: var(--text-color-secondary);
  }

  :root:not([data-theme]) .selector-item {
    border-bottom-color: var(--surface-border);
  }

  :root:not([data-theme]) .selector-item:hover {
    background: var(--surface-hover);
  }

  :root:not([data-theme]) .selector-item.active {
    background: var(--blue-900);
    color: var(--blue-400);
  }

  :root:not([data-theme]) .selector-item.active .pi-check {
    color: var(--blue-400);
  }

  :root:not([data-theme]) .selector-item-name {
    color: var(--text-color);
  }

  :root:not([data-theme]) .selector-item.active .selector-item-name {
    color: var(--blue-400);
  }

  :root:not([data-theme]) .selector-item-sub {
    color: var(--text-color-secondary);
  }

  :root:not([data-theme]) .selector-empty {
    color: var(--text-color-secondary);
  }

  :root:not([data-theme]) .drawer-link {
    color: var(--text-color);
  }

  :root:not([data-theme]) .drawer-link:hover {
    background: var(--surface-hover);
  }

  :root:not([data-theme]) .drawer-link.active {
    background: var(--blue-900);
    color: var(--blue-400);
  }

  :root:not([data-theme]) .drawer-link.active .drawer-icon {
    color: var(--blue-400);
  }

  :root:not([data-theme]) .drawer-icon {
    color: var(--text-color-secondary);
  }

  :root:not([data-theme]) .drawer-divider {
    background: var(--surface-border);
  }

  :root:not([data-theme]) .section-header {
    color: var(--text-color-secondary);
  }

  /* Auto dark mode: Profile Section (US-607) */
  :root:not([data-theme]) .drawer-profile {
    border-top-color: var(--surface-border);
  }

  :root:not([data-theme]) .profile-icon {
    color: var(--blue-400);
  }

  :root:not([data-theme]) .profile-name {
    color: var(--text-color);
  }

  :root:not([data-theme]) .logout-btn {
    border-color: var(--red-400);
    color: var(--red-400);
  }

  :root:not([data-theme]) .logout-btn:hover {
    background: var(--red-900);
  }

  :root:not([data-theme]) .logout-btn:active {
    background: var(--red-800);
  }

  /* Auto dark mode: Theme Toggle (US-607) */
  :root:not([data-theme]) .theme-toggle-compact {
    background: var(--surface-hover);
    color: var(--text-color);
  }

  :root:not([data-theme]) .theme-toggle-compact:hover {
    background: var(--surface-border);
  }

  :root:not([data-theme]) .theme-toggle-compact i:first-child {
    color: var(--blue-400);
  }

  :root:not([data-theme]) .theme-toggle-compact i:last-child {
    color: var(--text-color-secondary);
  }
}

/* ===== Server Switch Password Modal ===== */
.mobile-server-switch-modal :deep(.p-dialog) {
  border-radius: var(--radius-lg);
  background: var(--surface-card);
}

.mobile-server-switch-modal :deep(.p-dialog-header) {
  padding: var(--space-md) var(--space-lg);
  border-bottom: 1px solid var(--surface-border);
}

.mobile-server-switch-modal :deep(.p-dialog-content) {
  padding: var(--space-lg);
}

.mobile-server-switch-modal :deep(.p-dialog-footer) {
  padding: var(--space-md) var(--space-lg);
  border-top: 1px solid var(--surface-border);
  display: flex;
  gap: var(--space-sm);
  justify-content: flex-end;
}

.server-switch-modal-content {
  display: flex;
  flex-direction: column;
  gap: var(--space-md);
}

.server-switch-modal-content :deep(.p-password) {
  width: 100%;
}

.server-switch-modal-content :deep(.p-password input) {
  width: 100%;
}

.switch-error {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  padding: var(--space-sm) var(--space-md);
  background: var(--red-50);
  color: var(--red-600);
  border-radius: var(--radius-md);
  font-size: var(--text-sm);
}

.switch-error i {
  font-size: 1rem;
}

[data-theme="dark"] .switch-error {
  background: rgba(239, 68, 68, 0.15);
  color: var(--red-400);
}

/* Note: Dark mode styles for .mobile-server-switch-modal Dialog are in
   primevue-overrides.css because Dialog is teleported to body */
</style>
