<template>
  <a-layout-header class="modern-header">
    <div class="header-container">
      <!-- LOGO -->
      <div 
        class="university-logo" 
        @click="handleLogoClick"
        style="cursor: pointer;"
      >
        <div class="logo-icon">
          <img src="/logotiny.png" alt="Logo UNA" />
        </div>
        <div class="logo-text">
          <h1>Universidad Nacional del Altiplano</h1>
          <span>Dirección de Admisión</span>
        </div>
      </div>

      <!-- DESKTOP NAV -->
      <nav class="modern-nav desktop-only">
        <a-menu
          v-model:selectedKeys="selectedKeys"
          mode="horizontal"
          class="nav-menu-modern"
          :items="navItems"
          @click="handleMenuClick"
          @openChange="handleDesktopOpenChange"
        />
      </nav>

      <!-- MOBILE MENU BUTTON -->
      <a-button
        class="mobile-menu-btn mobile-only"
        type="text"
        @click="drawerOpen = true"
      >
        ☰
      </a-button>
    </div>

    <!-- MOBILE DRAWER -->
    <a-drawer
      title="Menú"
      placement="right"
      :open="drawerOpen && isMobile"
      @close="handleDrawerClose"
      :width="280"
      :bodyStyle="{ padding: 0 }"
      :headerStyle="{ borderBottom: '1px solid #f0f0f0', fontFamily: 'Times New Roman' }"
      :closable="true"
      :maskClosable="true"
    >
      <div class="drawer-content">
        <div class="drawer-header">
          <div class="drawer-logo">
            <div class="logo-icon">
              <img src="/logotiny.png" alt="Logo UNA" />
            </div>
            <div class="drawer-logo-text">
              <h3>UNA</h3>
              <span>Dirección de Admisión</span>
            </div>
          </div>
        </div>

        <a-menu
          v-model:selectedKeys="selectedKeys"
          mode="inline"
          :items="mobileNavItems"
          class="drawer-menu"
          @click="handleDrawerMenuClick"
          @openChange="handleMobileOpenChange"
          :openKeys="mobileOpenKeys"
        />
      </div>

    <div class="auth-section">
    <router-link 
      v-if="!authStore.isAuthenticated" 
      to="/login-postulante"
      class="login-link"
    >
      <a-button type="primary">
        <template #icon><UserOutlined /></template>
        Portal del Postulante
      </a-button>
    </router-link>
    
    <router-link 
      v-else 
      to="/portal"
      class="portal-link"
    >
      <a-button type="primary" ghost>
        <template #icon><DashboardOutlined /></template>
        Mi Portal
      </a-button>
    </router-link>
  </div>
    </a-drawer>

    <div class="auth-section">
    <router-link 
      v-if="!authStore.isAuthenticated" 
      to="/login-postulante"
      class="login-link"
    >
      <a-button type="primary">
        <template #icon><UserOutlined /></template>
        Portal del Postulante
      </a-button>
    </router-link>
    
    <router-link 
      v-else 
      to="/portal-postulante"
      class="portal-link"
    >
      <a-button type="primary" ghost>
        <template #icon><DashboardOutlined /></template>
        Mi Portal
      </a-button>
    </router-link>
  </div>
  </a-layout-header>
  
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useAuthStore } from '../store/postulanteStore'
import { UserOutlined, DashboardOutlined } from '@ant-design/icons-vue'
const drawerOpen = ref(false)
const selectedKeys = ref(['inicio'])
const isMobile = ref(false)


const authStore = useAuthStore()

const desktopOpenKeys = ref([])
const mobileOpenKeys = ref([])

// Detectar tamaño de pantalla
const checkScreenSize = () => {
  isMobile.value = window.innerWidth < 768
  
  // Si cambia a desktop, cerrar el drawer
  if (!isMobile.value && drawerOpen.value) {
    drawerOpen.value = false
    mobileOpenKeys.value = [] // Limpiar openKeys del móvil
  }
}

// Items del menú para desktop
const navItems = computed(() => [
  { 
    key: 'inicio', 
    label: 'Inicio'
  },
  {
    key: 'programas',
    label: 'Programas',
    children: [
      { key: 'ingenierias', label: 'Ingenierías' },
      { key: 'biomedicas', label: 'Biomédicas' },
      { key: 'sociales', label: 'Sociales' }
    ]
  },
  { 
    key: 'procesos', 
    label: 'Procesos'
  },
  {
    key: 'modalidades',
    label: 'Modalidades',
    children: [
      { key: 'ordinario', label: 'Ordinario' },
      { key: 'extraordinario', label: 'Extraordinario' },
      { key: 'sedes', label: 'Sedes' }
    ]
  },
  { 
    key: 'resultados', 
    label: 'Resultados'
  }
])

// Items del menú para móvil con submenús contraídos
const mobileNavItems = computed(() => {
  return navItems.value.map(item => {
    const baseItem = {
      key: item.key,
      label: item.label
    }

    if (item.children) {
      // Submenú plegable en móvil
      return {
        ...baseItem,
        children: item.children.map(child => ({
          key: child.key,
          label: child.label
        }))
      }
    }
    
    return baseItem
  })
})

// Observar cambios en el drawer para limpiar openKeys cuando se cierra
watch(drawerOpen, (newVal) => {
  if (!newVal) {
    // Limpiar openKeys cuando se cierra el drawer
    mobileOpenKeys.value = []
  }
})

// Observar cambios en isMobile para cerrar drawer si cambia a desktop
watch(isMobile, (newVal) => {
  if (!newVal && drawerOpen.value) {
    drawerOpen.value = false
  }
})

const handleMenuClick = ({ key }) => {
  selectedKeys.value = [key]
  
  console.log('Navegando a:', key)
  
  // Si es un item de submenú, cerrar el drawer en móvil
  const isSubmenuItem = navItems.value.some(item => 
    item.children && item.children.some(child => child.key === key)
  )
  
  if (isSubmenuItem && isMobile.value) {
    drawerOpen.value = false
  }
}

const handleDrawerMenuClick = ({ key }) => {
  handleMenuClick({ key })
  
  // Si NO es un submenú padre, cerrar el drawer
  const isParentItem = navItems.value.some(item => 
    item.key === key && item.children
  )
  
  if (!isParentItem && isMobile.value) {
    drawerOpen.value = false
  }
}

const handleLogoClick = () => {
  selectedKeys.value = ['inicio']
  // router.push('/')
}

const handleDesktopOpenChange = (keys) => {
  desktopOpenKeys.value = keys
}

const handleMobileOpenChange = (keys) => {
  // En móvil, solo permitir un submenú abierto a la vez
  const latestOpenKey = keys.find(key => !mobileOpenKeys.value.includes(key))
  
  if (latestOpenKey) {
    mobileOpenKeys.value = [latestOpenKey]
  } else {
    mobileOpenKeys.value = []
  }
}

const handleDrawerClose = () => {
  // Limpiar openKeys y cerrar drawer
  mobileOpenKeys.value = []
  drawerOpen.value = false
}

// Configurar event listeners para responsive
onMounted(() => {
  checkScreenSize()
  window.addEventListener('resize', checkScreenSize)
})

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

<style scoped>
/* VARIABLES */
:root {
  --primary-color: #1e3a8a;
  --secondary-color: #374151;
  --border-color: #d1d5db;
  --bg-color: #ffffff;
}

/* FUENTE INSTITUCIONAL */
.modern-header,
.nav-menu-modern,
.logo-text h1,
.logo-text span,
.drawer-logo-text h3,
.drawer-logo-text span {
  font-family: "Times New Roman", Times, serif;
}

/* HEADER */
.modern-header {
  background: rgba(255, 255, 255, 0.92) !important;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border-bottom: 1px solid var(--border-color);
  padding: 0 24px !important;
  height: 82px !important;
  line-height: 82px !important;
  position: sticky;
  top: 0;
  z-index: 1000;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

/* CONTAINER */
.header-container {
  max-width: 1320px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  width: 100%;
}

/* LOGO */
.university-logo {
  display: flex;
  align-items: center;
  gap: 14px;
  min-width: 250px;
  transition: opacity 0.3s;
}

.university-logo:hover {
  opacity: 0.9;
}

.logo-icon {
  width: 46px;
  height: 46px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background: var(--bg-color);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.logo-icon img {
  width: 90%;
  height: 90%;
  object-fit: contain;
}

.logo-text {
  display: flex;
  flex-direction: column;
  line-height: 1.4;
}

.logo-text h1 {
  margin: 0;
  font-size: 1.05rem;
  font-weight: 700;
  color: var(--primary-color);
}

.logo-text span {
  font-size: 0.8rem;
  color: var(--secondary-color);
}

/* NAV DESKTOP */
.modern-nav {
  flex: 1;
  display: flex;
  justify-content: center;
  min-width: 0;
}

.nav-menu-modern {
  flex: 1;
  background: transparent !important;
  border-bottom: none !important;
  justify-content: center;
}

.nav-menu-modern :deep(.ant-menu-item),
.nav-menu-modern :deep(.ant-menu-submenu) {
  height: 82px;
  line-height: 82px;
  padding: 0 16px;
  font-size: 0.95rem;
  color: var(--secondary-color);
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.nav-menu-modern :deep(.ant-menu-item:hover),
.nav-menu-modern :deep(.ant-menu-submenu:hover) {
  color: var(--primary-color);
}

.nav-menu-modern :deep(.ant-menu-item-selected),
.nav-menu-modern :deep(.ant-menu-submenu-selected) {
  color: var(--primary-color);
  font-weight: 600;
}

.nav-menu-modern :deep(.ant-menu-item-selected::after),
.nav-menu-modern :deep(.ant-menu-submenu-selected::after) {
  border-bottom: 3px solid var(--primary-color) !important;
}

.nav-menu-modern :deep(.ant-menu-submenu-arrow) {
  color: var(--secondary-color);
}

.nav-menu-modern :deep(.ant-menu-submenu:hover .ant-menu-submenu-arrow) {
  color: var(--primary-color);
}

/* BOTÓN MÓVIL */
.mobile-menu-btn {
  font-size: 24px;
  color: #111827;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.mobile-menu-btn:hover {
  background: rgba(0, 0, 0, 0.04);
}

/* DRAWER MÓVIL */
.drawer-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.drawer-header {
  padding: 20px 24px;
  border-bottom: 1px solid var(--border-color);
  background: #fafafa;
}

.drawer-logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.drawer-logo-text {
  display: flex;
  flex-direction: column;
  line-height: 1.4;
}

.drawer-logo-text h3 {
  margin: 0;
  color: var(--primary-color);
  font-size: 1rem;
}

.drawer-logo-text span {
  font-size: 12px;
  color: var(--secondary-color);
}

.drawer-menu {
  border-right: none !important;
}

.drawer-menu :deep(.ant-menu-item) {
  font-size: 15px;
  padding-left: 24px !important;
  height: 48px;
  line-height: 48px;
  margin: 4px 0;
  border-radius: 0;
  transition: background-color 0.3s;
}

.drawer-menu :deep(.ant-menu-item:hover) {
  background-color: #f0f7ff;
}

.drawer-menu :deep(.ant-menu-item-selected) {
  background-color: #f0f7ff;
  color: var(--primary-color);
  font-weight: 500;
}

.drawer-menu :deep(.ant-menu-item-selected::after) {
  border-right: 3px solid var(--primary-color);
}

.drawer-menu :deep(.ant-menu-submenu-title) {
  font-size: 15px;
  padding-left: 24px !important;
  height: 48px;
  line-height: 48px;
  margin: 4px 0;
  border-radius: 0;
  transition: background-color 0.3s;
}

.drawer-menu :deep(.ant-menu-submenu-title:hover) {
  background-color: #f0f7ff;
}

.drawer-menu :deep(.ant-menu-submenu-selected > .ant-menu-submenu-title) {
  color: var(--primary-color);
  font-weight: 500;
}

.drawer-menu :deep(.ant-menu-submenu-arrow) {
  font-size: 12px !important;
}

.drawer-menu :deep(.ant-menu-submenu .ant-menu-item) {
  padding-left: 48px !important;
  font-size: 14px;
}

/* RESPONSIVE */
.desktop-only {
  display: flex;
}

.mobile-only {
  display: none;
}

/* TABLET (768px - 992px) */
@media (max-width: 992px) {
  .modern-header {
    padding: 0 16px !important;
  }
  
  .header-container {
    padding: 0 8px;
  }
  
  .logo-text h1 {
    font-size: 14px !important;
  }
  
  .logo-text span {
    font-size: 12px !important;
  }
  
  .nav-menu-modern :deep(.ant-menu-item),
  .nav-menu-modern :deep(.ant-menu-submenu) {
    padding: 0 12px;
    font-size: 0.9rem;
  }
}

/* MOBILE (< 768px) */
@media (max-width: 768px) {
  .desktop-only {
    display: none;
  }
  
  .mobile-only {
    display: inline-flex;
  }
  
  .modern-header {
    height: 72px !important;
    line-height: 72px !important;
  }
  
  .header-container {
    padding: 0;
  }
  
  .university-logo {
    min-width: auto;
    gap: 10px;
  }
  
  .logo-icon {
    width: 40px;
    height: 40px;
  }
  
  .logo-text h1 {
    font-size: 13px !important;
    line-height: 1.2;
  }
  
  .logo-text span {
    font-size: 11px !important;
  }
}

/* SMALL MOBILE (< 480px) */
@media (max-width: 480px) {
  .modern-header {
    padding: 0 12px !important;
  }
  
  .logo-text h1 {
    font-size: 12px !important;
  }
  
  .logo-text span {
    display: none;
  }
  
  .mobile-menu-btn {
    font-size: 20px;
    padding: 4px;
  }
  
  .drawer-menu :deep(.ant-menu-submenu-title),
  .drawer-menu :deep(.ant-menu-item) {
    height: 44px;
    line-height: 44px;
    font-size: 14px;
  }
  
  .drawer-menu :deep(.ant-menu-submenu .ant-menu-item) {
    height: 40px;
    line-height: 40px;
    font-size: 13px;
  }
}

/* IMPRESIÓN */
@media print {
  .modern-header {
    position: static;
    box-shadow: none;
    border-bottom: 2px solid #000;
  }
  
  .mobile-menu-btn {
    display: none !important;
  }
}
</style>