<template>
    <div>
        <!--  BEGIN NAVBAR  -->
        <div class="header-container fixed-top">
            <header class="header navbar navbar-expand-sm">
                <ul class="navbar-item theme-brand flex-row text-center">
                    <li class="nav-item theme-logo">
                        <router-link to="/">
                            <img
                                :src="logoUrl"
                                class="navbar-logo"
                                :alt="$t('brand.logo_alt')"
                                @error="onLogoError"
                            />
                        </router-link>
                    </li>
                    <li class="nav-item theme-text">
                        <router-link to="/" class="nav-link">{{ $t("brand.nav_title") }}</router-link>
                    </li>
                </ul>
                <div class="d-none horizontal-menu">
                    <a href="javascript:void(0);" class="sidebarCollapse" data-placement="bottom" @click="layoutStore.toggleSideBar(!layoutStore.is_show_sidebar)">
                        <svg
                            xmlns="http://www.w3.org/2000/svg"
                            width="24"
                            height="24"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="2"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            class="feather feather-menu"
                        >
                            <line x1="3" y1="12" x2="21" y2="12"></line>
                            <line x1="3" y1="6" x2="21" y2="6"></line>
                            <line x1="3" y1="18" x2="21" y2="18"></line>
                        </svg>
                    </a>
                </div>

                <div class="navbar-item flex-row ms-md-auto">
                    <div class="nav-item user-name me-3 d-flex align-items-center text-white" v-if="currentUser">
                        <span class="me-2">Bienvenido,</span>
                        <strong>{{ currentUser.name }}</strong>
                    </div>
                    <div class="dropdown nav-item user-profile-dropdown btn-group">
                        <a href="javascript:;" id="ddluser" data-bs-toggle="dropdown" aria-expanded="false" class="btn dropdown-toggle btn-icon-only user nav-link header-avatar-link">
                            <img :src="defaultUsers" alt="avatar" class="header-avatar-img" />
                        </a>
                        <ul class="dropdown-menu dropdown-menu-right m-0" aria-labelledby="ddluser">
                            <li role="presentation" class="dropdown-header" v-if="currentUser">
                                <div class="d-flex flex-column">
                                    <span class="fw-bold">{{ currentUser.name }}</span>
                                    <small class="text-muted">{{ currentUser.email }}</small>
                                    <small class="text-muted" v-if="currentUser.roles && currentUser.roles.length > 0">
                                        Rol: {{ currentUser.roles[0].name }}
                                    </small>
                                </div>
                            </li>
                            <li role="presentation"><hr class="dropdown-divider" /></li>
                            <li role="presentation">
                                <router-link to="/users/profile" class="dropdown-item">
                                    <svg
                                        xmlns="http://www.w3.org/2000/svg"
                                        width="24"
                                        height="24"
                                        viewBox="0 0 24 24"
                                        fill="none"
                                        stroke="currentColor"
                                        stroke-width="2"
                                        stroke-linecap="round"
                                        stroke-linejoin="round"
                                        class="feather feather-user"
                                    >
                                        <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                                        <circle cx="12" cy="7" r="4"></circle>
                                    </svg>
                                    Perfil
                                </router-link>
                            </li>
                            <li role="presentation"><hr class="dropdown-divider" /></li>
                            <li role="presentation" class="px-3 py-2">
                                <div class="small text-muted mb-2">Color del tema</div>
                                <div class="theme-swatches">
                                    <button
                                        v-for="preset in layoutStore.themeColorPresets"
                                        :key="preset.id"
                                        type="button"
                                        class="theme-swatch"
                                        :class="{ 'is-active': layoutStore.theme_color === preset.id }"
                                        :style="{ backgroundColor: preset.hex }"
                                        :title="preset.label"
                                        @click.stop="layoutStore.setThemeColor(preset.id)"
                                    />
                                </div>
                            </li>
                            <li role="presentation"><hr class="dropdown-divider" /></li>
                            <li role="presentation">
                                <a
                                    v-on:click.stop="logout"
                                    class="dropdown-item center-login"
                                >
                                    <svg
                                        xmlns="http://www.w3.org/2000/svg"
                                        width="24"
                                        height="24"
                                        viewBox="0 0 24 24"
                                        fill="none"
                                        stroke="currentColor"
                                        stroke-width="2"
                                        stroke-linecap="round"
                                        stroke-linejoin="round"
                                        class="feather feather-log-out"
                                    >
                                        <path
                                            d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"
                                        ></path>
                                        <polyline
                                            points="16 17 21 12 16 7"
                                        ></polyline>
                                        <line
                                            x1="21"
                                            y1="12"
                                            x2="9"
                                            y2="12"
                                        ></line>
                                    </svg>
                                    Cerrar
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>
            </header>
        </div>
        <!--  END NAVBAR  -->
        <!--  BEGIN NAVBAR  -->
        <div class="sub-header-container">
            <header class="header navbar navbar-expand-sm">
                <a href="javascript:void(0);" class="sidebarCollapse" data-placement="bottom" @click="layoutStore.toggleSideBar(!layoutStore.is_show_sidebar)">
                    <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width="24"
                        height="24"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        class="feather feather-menu"
                    >
                        <line x1="3" y1="12" x2="21" y2="12"></line>
                        <line x1="3" y1="6" x2="21" y2="6"></line>
                        <line x1="3" y1="18" x2="21" y2="18"></line>
                    </svg>
                </a>

                <div id="breadcrumb" class="vue-portal-target"></div>
            </header>
        </div>
        <!--  END NAVBAR  -->
        <!--  BEGIN TOPBAR  -->
        <div class="topbar-nav header navbar" role="banner">
            <nav class="topbar">
                <ul class="list-unstyled menu-categories" id="topAccordion">
                    <li
                        v-for="group in visibleTopMenu"
                        :key="group.id"
                        class="menu"
                        :class="{ active: isTopBranchActive(group) }"
                    >
                        <a href="javascript:;" class="dropdown-toggle">
                            <div>
                                <MenuIcon :name="group.icon" />
                                <span>{{ group.label }}</span>
                            </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-down"
                            >
                                <polyline points="6 9 12 15 18 9" />
                            </svg>
                        </a>
                        <ul class="submenu list-unstyled">
                            <template v-for="child in group.children" :key="child.id">
                                <li v-if="child.children?.length" class="sub-sub-submenu-list">
                                    <a href="javascript:;">
                                        {{ child.label }}
                                        <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>
                                    </a>
                                    <ul class="sub-submenu list-unstyled">
                                        <li v-for="leaf in child.children" :key="leaf.id">
                                            <router-link :to="leaf.route" :class="{ active: isTopLeafActive(leaf.route) }">
                                                {{ leafLabel(leaf) }}
                                            </router-link>
                                        </li>
                                    </ul>
                                </li>
                                <li v-else>
                                    <router-link :to="child.route" :class="{ active: isTopLeafActive(child.route) }">
                                        {{ leafLabel(child) }}
                                    </router-link>
                                </li>
                            </template>
                        </ul>
                    </li>
                </ul>
            </nav>
        </div>
        <loading
            v-model:active="isLoading"
            :can-cancel="false"
            :is-full-page="true"
        />
        <!--  END TOPBAR  -->
    </div>
</template>

<script setup>
    import { onMounted, ref, reactive, computed } from 'vue';
    import { useI18n } from 'vue-i18n';
    import { useRoute } from 'vue-router';
    import { useLayoutStore } from '@/store/layoutStore';
    import { useConfiguracionEmpresaStore } from '@/store/ConfiguracionEmpresaStore';
    import * as AuthRepository from "@/repositories/AuthRepository";
    import * as UserRepository from "@/repositories/UserRepository";
    import { usePermissions } from '@/composables/use-permissions';
    import { collectRoutes, pathMatchesRoute, ranchMenu } from '@/config/ranch-menu';
    import MenuIcon from '@/components/layout/MenuIcon.vue';
    import Loading from "vue-loading-overlay";
    import "vue-loading-overlay/dist/css/index.css";
    const defaultLogoAsset = '/logo-rancho.svg';
    import defaultUsers from '@/assets/images/user-avtar.svg';

    const layoutStore = useLayoutStore();
    const route = useRoute();
    // Logo: siempre nuestro ref (nunca refs de Pinia) para evitar error _s si el store no está listo
    const storeLogoUrlRef = ref(defaultLogoAsset);
    let configuracionEmpresaStore = null;
    try {
        configuracionEmpresaStore = useConfiguracionEmpresaStore();
    } catch (e) {
        console.warn('Header: ConfiguracionEmpresa store no disponible, usando logo por defecto.', e);
    }

    // Logo: solo leemos nuestro ref; cache-bust si la URL viene del backend
    const logoUrl = computed(() => {
        const url = storeLogoUrlRef.value;
        if (!url || typeof url !== 'string') return defaultLogoAsset;
        if ((url.startsWith('/storage/') || url.startsWith('http')) && configuracionEmpresaStore?.configuracion) {
            const sep = url.indexOf('?') >= 0 ? '&' : '?';
            const v = configuracionEmpresaStore.configuracion.updated_at;
            return url + sep + 'v=' + (v ? String(v).replace(/\D/g, '').slice(0, 14) : Date.now());
        }
        return url;
    });

    const logoErrorCount = ref(0);
    const onLogoError = (e) => {
        if (!e?.target) return;
        // Evitar bucle: no volver a asignar la misma URL que ya falló
        if (e.target.src && e.target.src === defaultLogoAsset) {
            logoErrorCount.value += 1;
            if (logoErrorCount.value > 1) return;
        }
        e.target.src = defaultLogoAsset;
    };

    const isLoading = ref(false);
    const currentUser = ref(null);
    const { loadPermissions, hasPermission, hasAnyPermission, userPermissions } = usePermissions();
    const permissionsLoaded = ref(false);

    const selectedLang = ref(null);
    const countryList = ref(layoutStore.countryList);

    const i18n = reactive(useI18n());

    function allowed(item) {
        if (!item.anyOf?.length) return true;
        if (!permissionsLoaded.value) return false;
        return hasAnyPermission(item.anyOf) || item.anyOf.some((p) => hasPermission(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 visibleTopMenu = computed(() => {
        void userPermissions.value;
        void permissionsLoaded.value;
        if (!permissionsLoaded.value) return [];
        return filterTree(ranchMenu);
    });

    function isTopLeafActive(path) {
        return pathMatchesRoute(route.path, path);
    }

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

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

    const loadCurrentUser = async () => {
        try {
            const token = window.localStorage.getItem("token");
            if (token) {
                const userData = await UserRepository.getuser();
                currentUser.value = userData;
            }
        } catch (error) {
            console.error('Error loading current user:', error);
        }
    };

    onMounted(async () => {
        selectedLang.value = window.$appSetting.toggleLanguage();
        toggleMode();
        await loadCurrentUser();
        try {
            await loadPermissions();
        } catch {
            /* sesión inválida: interceptor redirige */
        }
        permissionsLoaded.value = true;
        // Cargar configuración de empresa (logo, etc.) y actualizar nuestro ref con el valor, no con refs de Pinia
        if (configuracionEmpresaStore) {
            try {
                await configuracionEmpresaStore.cargarConfiguracion();
            } catch (e) {
                await configuracionEmpresaStore.cargarConfiguracionPublica().catch(() => {});
            }
            try {
                const url = configuracionEmpresaStore.getLogoUrl;
                if (url && typeof url === 'string') storeLogoUrlRef.value = url;
            } catch (_) {}
        }
    });

    const toggleMode = (mode) => {
        window.$appSetting.toggleMode(mode);
    };

    const changeLanguage = (item) => {
        selectedLang.value = item;
        i18n.locale = item.code;
        window.$appSetting.toggleLanguage(item);
    };
    const logout = async () => {
        try {
            isLoading.value = true;
            if (window.localStorage.getItem("token")) {
                try {
                    await AuthRepository.logoutCurrentToken();
                } catch (_) {
                    /* red aun si la API falla */
                }
            }
            localStorage.removeItem("token");
            location.reload("/");
        } catch (error) {
            console.log(error);
        } finally {
            isLoading.value = false;
        }
    };
</script>

<style scoped>
.header-container .header-avatar-link .header-avatar-img {
    filter: brightness(0) invert(1);
}
</style>
