<template>
  <div class="sidebar-wrapper sidebar-theme">
    <nav ref="menu" id="sidebar">
      <div class="ranch-sidebar-brand">
        <div class="ranch-sidebar-brand-icon" aria-hidden="true">
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M12 2L4 7v10l8 5 8-5V7z" />
            <path d="M12 22V12" />
            <path d="M4 7l8 5 8-5" />
          </svg>
        </div>
        <div class="ranch-sidebar-brand-text">
          <strong>Control Ganadero</strong>
          <small>Gestión del rancho</small>
        </div>
      </div>
      <div class="shadow-bottom"></div>
      <perfect-scrollbar
        v-if="permissionsReady"
        class="list-unstyled menu-categories"
        tag="ul"
        :options="{ wheelSpeed: 0.5, swipeEasing: !0, minScrollbarLength: 40, maxScrollbarLength: 300, suppressScrollX: true }"
      >
        <li v-if="!visibleMenu.length && permissionsLoaded" class="menu sidebar-empty-hint">
          <span class="sidebar-empty-text">
            Sin permisos en el menú. Cierra sesión e inicia con
            <strong>admin@gmail.com</strong> o contacta al administrador.
          </span>
        </li>
        <li
          v-for="group in visibleMenu"
          :key="group.id"
          class="menu"
          :class="{ active: isBranchActive(group) }"
        >
          <a
            href="javascript:;"
            class="dropdown-toggle"
            :aria-expanded="isOpen(group.id) ? 'true' : 'false'"
            :data-active="isBranchActive(group) ? 'true' : 'false'"
            @click.prevent="toggle(group.id)"
          >
            <div>
              <MenuIcon :name="group.icon" />
              <span>{{ group.label }}</span>
            </div>
            <div>
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                class="feather feather-chevron-right"
              >
                <polyline points="9 18 15 12 9 6" />
              </svg>
            </div>
          </a>

          <ul class="collapse submenu list-unstyled" :class="{ show: isOpen(group.id) }">
            <template v-for="child in group.children" :key="child.id">
              <!-- Segundo nivel (ej. Reportes) -->
              <li v-if="child.children?.length" :class="{ active: isBranchActive(child) }">
                <a
                  href="javascript:;"
                  class="dropdown-toggle"
                  :aria-expanded="isOpen(child.id) ? 'true' : 'false'"
                  :data-active="isBranchActive(child) ? 'true' : 'false'"
                  @click.prevent="toggle(child.id, group.id)"
                >
                  <div>
                    <span>{{ child.label }}</span>
                  </div>
                  <div>
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="24"
                      height="24"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      class="feather feather-chevron-right"
                    >
                      <polyline points="9 18 15 12 9 6" />
                    </svg>
                  </div>
                </a>
                <ul class="collapse sub-submenu list-unstyled" :class="{ show: isOpen(child.id) }">
                  <li v-for="leaf in child.children" :key="leaf.id" :class="{ active: isLeafActive(leaf.route) }">
                    <router-link
                      :to="leaf.route"
                      :class="{ active: isLeafActive(leaf.route) }"
                      @click="closeMobileMenu"
                    >
                      {{ leafLabel(leaf) }}
                    </router-link>
                  </li>
                </ul>
              </li>

              <!-- Hoja de primer subnivel -->
              <li v-else :class="{ active: isLeafActive(child.route) }">
                <router-link
                  :to="child.route"
                  :class="{ active: isLeafActive(child.route) }"
                  @click="closeMobileMenu"
                >
                  {{ leafLabel(child) }}
                </router-link>
              </li>
            </template>
          </ul>
        </li>
      </perfect-scrollbar>
      <p v-else class="sidebar-loading">Cargando menú…</p>
    </nav>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
import { usePermissions } from '@/composables/use-permissions'
import { useLayoutStore } from '@/store/layoutStore'
import { collectRoutes, pathMatchesRoute, ranchMenu } from '@/config/ranch-menu'
import MenuIcon from '@/components/layout/MenuIcon.vue'

const layoutStore = useLayoutStore()
const { can, hasAnyPermission, loadPermissions, userPermissions, isLoading } = usePermissions()
const permissionsReady = ref(false)
const permissionsLoaded = computed(() => permissionsReady.value && !isLoading.value)
const { t } = useI18n()
const route = useRoute()
const openIds = reactive({})

function allowed(item) {
  if (!item.anyOf?.length) return true
  return hasAnyPermission(item.anyOf) || item.anyOf.some((p) => can(p))
}

function filterTree(nodes) {
  return (nodes || [])
    .map((node) => {
      if (!allowed(node)) return null
      if (node.children?.length) {
        const children = filterTree(node.children)
        if (!children.length) return null
        return { ...node, children }
      }
      return node
    })
    .filter(Boolean)
}

const visibleMenu = computed(() => {
  void userPermissions.value
  if (!permissionsReady.value) return []
  return filterTree(ranchMenu)
})

onMounted(async () => {
  if (window.localStorage.getItem('token')) {
    try {
      await loadPermissions()
    } catch {
      // ApiService / router ya redirigen a login si el token es inválido
    }
  }
  permissionsReady.value = true
})

function isOpen(id) {
  return Boolean(openIds[id])
}

function closeAllExcept(keepId = null, nestedParentId = null) {
  if (nestedParentId == null) {
    visibleMenu.value.forEach((group) => {
      if (group.id !== keepId) openIds[group.id] = false
      ;(group.children || []).forEach((child) => {
        if (child.children?.length) openIds[child.id] = false
      })
    })
    return
  }

  const parent = visibleMenu.value.find((g) => g.id === nestedParentId)
  ;(parent?.children || []).forEach((child) => {
    if (child.children?.length && child.id !== keepId) openIds[child.id] = false
  })
}

/** Acordeón: solo un submenú abierto a la vez. */
function toggle(id, nestedParentId = null) {
  const willOpen = !openIds[id]
  if (willOpen) {
    closeAllExcept(id, nestedParentId)
  }
  openIds[id] = willOpen
}

function isLeafActive(path) {
  return pathMatchesRoute(route.path, path)
}

function isBranchActive(node) {
  return collectRoutes(node).some((r) => pathMatchesRoute(route.path, r))
}

function leafLabel(leaf) {
  if (leaf.labelKey) {
    try {
      return t(leaf.labelKey)
    } catch {
      return leaf.label
    }
  }
  return leaf.label
}

function openAncestorsForPath() {
  // Cierra todo y abre solo la rama de la ruta actual
  visibleMenu.value.forEach((group) => {
    openIds[group.id] = false
    ;(group.children || []).forEach((child) => {
      if (child.children?.length) openIds[child.id] = false
    })
  })

  visibleMenu.value.forEach((group) => {
    if (!isBranchActive(group)) return
    openIds[group.id] = true
    ;(group.children || []).forEach((child) => {
      if (child.children?.length && isBranchActive(child)) {
        openIds[child.id] = true
      }
    })
  })
}

watch(
  () => route.path,
  () => openAncestorsForPath(),
  { immediate: true },
)

watch(visibleMenu, () => openAncestorsForPath(), { deep: true })

function closeMobileMenu() {
  if (window.innerWidth < 991) {
    // En móvil, is_show_sidebar=true oculta el drawer
    layoutStore.toggleSideBar(true)
  }
}
</script>

<style scoped>
.collapse:not(.show) {
  display: none;
}
.collapse.show {
  display: block;
}

.sidebar-loading {
  padding: 12px 16px;
  font-size: 0.85rem;
  color: #888ea8;
}

.sidebar-empty-hint {
  padding: 8px 14px;
}

.sidebar-empty-text {
  font-size: 0.82rem;
  color: #888ea8;
  line-height: 1.35;
}
</style>
