<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="$store.commit('toggleSideBar', !$store.state.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">{{ $t('layout.header.welcome') }}</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">
                                        {{ $t('layout.header.role') }} {{ 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>
                                    {{ $t('layout.header.profile') }}
                                </router-link>
                            </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>
                                    {{ $t('layout.header.logout') }}
                                </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="$store.commit('toggleSideBar', !$store.state.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">
                    <!-- 1. Inicio -->
                    <li class="menu single-menu" v-if="can('dashboard.ver') || can('lavanderia.dashboard')">
                        <a href="javascript:;" class="dropdown-toggle autodroprown">
                            <div class="">
                                <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-home">
                                    <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
                                    <polyline points="9 22 9 12 15 12 15 22"></polyline>
                                </svg>
                                <span>{{ $t('layout.sidebar.home') }}</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"></polyline>
                            </svg>
                        </a>
                        <ul class="collapse submenu list-unstyled">
                            <li><router-link to="/lavanderia/dashboard">{{ $t('layout.sidebar.dashboard_semaforo') }}</router-link></li>
                        </ul>
                    </li>

                    <!-- 2. Punto de Venta -->
                    <li class="menu single-menu" v-if="can('pos.vender') || can('caja.administrar')">
                        <a href="javascript:;" class="dropdown-toggle">
                            <div class="">
                                <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-shopping-cart">
                                    <circle cx="9" cy="21" r="1"></circle>
                                    <circle cx="20" cy="21" r="1"></circle>
                                    <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
                                </svg>
                                <span>{{ $t('layout.sidebar.sales_pos') }}</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"></polyline>
                            </svg>
                        </a>
                        <ul class="collapse submenu list-unstyled">
                            <li v-if="can('pos.vender')"><router-link to="/ventas/pos">{{ $t('layout.sidebar.new_sale') }}</router-link></li>
                            <li v-if="can('caja.administrar')"><router-link to="/ventas/caja">{{ $t('layout.sidebar.cash_register') }}</router-link></li>
                            <li v-if="can('pos.vender') || can('lavanderia.recepcion') || can('lavanderia.consultar')"><router-link to="/ventas/tickets">{{ $t('layout.sidebar.ticket_history') }}</router-link></li>
                        </ul>
                    </li>

                    <!-- 2b. Catálogo -->
                    <li class="menu single-menu" v-if="can('administracion.areas') || can('pos.vender') || can('caja.administrar')">
                        <a href="javascript:;" class="dropdown-toggle">
                            <div class="">
                                <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-layers">
                                    <polygon points="12 2 2 7 12 12 22 7 12 2"></polygon>
                                    <polyline points="2 17 12 22 22 17"></polyline>
                                    <polyline points="2 12 12 17 22 12"></polyline>
                                </svg>
                                <span>{{ $t('layout.sidebar.catalog') }}</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"></polyline>
                            </svg>
                        </a>
                        <ul class="collapse submenu list-unstyled">
                            <li v-if="can('administracion.areas')"><router-link to="/admin/catalogo-categorias">{{ $t('layout.sidebar.catalog_categories') }}</router-link></li>
                            <li v-if="can('administracion.areas')"><router-link to="/admin/catalogo-servicios">{{ $t('layout.sidebar.catalog_sale_services') }}</router-link></li>
                            <li v-if="can('administracion.areas')"><router-link to="/admin/catalogo-productos">{{ $t('layout.sidebar.catalog_sale_products') }}</router-link></li>
                            <li v-if="canAny(CATALOG_AUX_PERMISSIONS)"><router-link to="/catalogos/etapas">{{ $t('layout.sidebar.catalog_etapas') }}</router-link></li>
                            <li v-if="canAny(CATALOG_AUX_PERMISSIONS)"><router-link to="/catalogos/tipos-servicio">{{ $t('layout.sidebar.catalog_tipos_servicio') }}</router-link></li>
                            <li v-if="can('administracion.areas')"><router-link to="/admin/garment-types">{{ $t('layout.sidebar.catalog_garment_types') }}</router-link></li>
                            <li v-if="canAny(CATALOG_CLIENTES_PERMISSIONS)"><router-link to="/catalogos/clientes">{{ $t('layout.sidebar.catalog_clients') }}</router-link></li>
                        </ul>
                    </li>

                    <!-- 3. Lavandería -->
                    <li class="menu single-menu" v-if="can('lavanderia.recepcion') || can('lavanderia.operador') || can('lavanderia.consultar')">
                        <a href="javascript:;" class="dropdown-toggle">
                            <div class="">
                                <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-wind">
                                    <path d="M17.7 7.7a2.5 2.5 0 1 1 1.8 4.3H2"></path>
                                    <path d="M9.6 4.6A2 2 0 1 1 11 8H2"></path>
                                    <path d="M12.6 19.4A2 2 0 1 0 14 16H2"></path>
                                </svg>
                                <span>{{ $t('layout.sidebar.laundry_ops') }}</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"></polyline>
                            </svg>
                        </a>
                        <ul class="collapse submenu list-unstyled">
                            <li v-if="can('lavanderia.consultar') || can('lavanderia.recepcion')"><router-link to="/lavanderia/lista">{{ $t('layout.sidebar.order_list') }}</router-link></li>
                            <li v-if="can('lavanderia.operador')"><router-link to="/lavanderia/escanear">{{ $t('layout.sidebar.scan_qr') }}</router-link></li>
                        </ul>
                    </li>

                    <!-- 4. Inventario -->
                    <li class="menu single-menu" v-if="canAny(['inventory.view', 'inventory.manage'])">
                        <a href="javascript:;" class="dropdown-toggle">
                            <div class="">
                                <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-archive">
                                    <polyline points="21 8 21 21 3 21 3 8"></polyline>
                                    <rect x="1" y="3" width="22" height="5"></rect>
                                    <line x1="10" y1="12" x2="14" y2="12"></line>
                                </svg>
                                <span>{{ $t('layout.sidebar.inventory') }}</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"></polyline>
                            </svg>
                        </a>
                        <ul class="collapse submenu list-unstyled">
                            <li><router-link to="/inventario/productos">{{ $t('layout.sidebar.warehouse_products') }}</router-link></li>
                            <li><router-link :to="{ name: 'inventory-transfer-documents-router' }">{{ $t('inventory.transfer_documents.menu') }}</router-link></li>
                        </ul>
                    </li>

                    <!-- 5. Reportes -->
                    <li class="menu single-menu" v-if="can('reportes.ver')">
                        <a href="javascript:;" class="dropdown-toggle">
                            <div class="">
                                <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-bar-chart-2">
                                    <line x1="18" y1="20" x2="18" y2="10"></line>
                                    <line x1="12" y1="20" x2="12" y2="4"></line>
                                    <line x1="6" y1="20" x2="6" y2="14"></line>
                                </svg>
                                <span>{{ $t('layout.sidebar.reports') }}</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"></polyline>
                            </svg>
                        </a>
                        <ul class="collapse submenu list-unstyled">
                            <li><router-link to="/reportes/cierre-dia">{{ $t('layout.sidebar.day_close') }}</router-link></li>
                            <li><router-link to="/reportes/ventas-producto">{{ $t('layout.sidebar.sales_by_product') }}</router-link></li>
                            <li><router-link to="/ventas/mensual">{{ $t('layout.sidebar.monthly_sales') }}</router-link></li>
                        </ul>
                    </li>

                    <!-- 6. Administración -->
                    <li class="menu single-menu" v-if="can('administracion.usuarios') || can('administracion.roles') || can('administracion.areas') || can('caja.administrar')">
                        <a href="javascript:;" class="dropdown-toggle">
                            <div class="">
                                <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-settings"
                                >
                                    <circle cx="12" cy="12" r="3"></circle>
                                    <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
                                </svg>
                                <span>{{ $t('layout.sidebar.system_admin') }}</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"
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                class="feather feather-chevron-down"
                            >
                                <polyline points="6 9 12 15 18 9"></polyline>
                            </svg>
                        </a>
                        <ul class="collapse submenu list-unstyled">
                            <li v-if="canAny(CONFIG_EMPRESA_PERMISSIONS)"><router-link to="/admin/configuracion-empresa">{{ $t('admin.config_empresa.nav') }}</router-link></li>
                            <li v-if="can('administracion.usuarios')"><router-link to="/users/lista">{{ $t('layout.sidebar.users') }}</router-link></li>
                            <li v-if="can('administracion.roles')"><router-link to="/roles/lista">{{ $t('layout.sidebar.roles') }}</router-link></li>
                            <li v-if="can('administracion.areas')"><router-link to="/admin/impresoras">{{ $t('admin.impresoras.nav') }}</router-link></li>
                            <li v-if="can('administracion.areas')"><router-link to="/admin/areas">{{ $t('layout.sidebar.tibu_areas') }}</router-link></li>
                            <li v-if="can('administracion.areas')"><router-link to="/catalogos/productos">{{ $t('layout.sidebar.legacy_products_archive') }}</router-link></li>
                        </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 { useStore } from 'vuex';
    import { useConfiguracionEmpresaStore } from '@/store/ConfiguracionEmpresaStore';
    import * as AuthRepository from "@/repositories/AuthRepository";
    import * as UserRepository from "@/repositories/UserRepository";
    import { usePermissions } from '@/composables/use-permissions';
    import { TIBU_AREA_CODES } from '@/constants/tibuAreas';
    import { CONFIG_EMPRESA_PERMISSIONS, CATALOG_AUX_PERMISSIONS, CATALOG_CLIENTES_PERMISSIONS } from '@/constants/routePermissions';
    import Loading from "vue-loading-overlay";
    import "vue-loading-overlay/dist/css/index.css";
    // Logo por defecto como asset importado: Vite lo sirve con URL válida y evita que Laravel devuelva HTML
    import defaultLogoAsset from '@/assets/images/logo.png';
    import defaultUsers from '@/assets/images/user-avtar.svg';

    const store = useStore();
    // 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 } = usePermissions();
    const permissionsLoaded = ref(false);

    const selectedLang = ref(null);
    const countryList = ref(store.state.countryList);

    const i18n = reactive(useI18n());

    // Funciones helper para verificar permisos
    const can = (permission) => {
        if (!permissionsLoaded.value) return false;
        return hasPermission(permission);
    };
    
    const canAny = (permissions) => {
        if (!permissionsLoaded.value) return false;
        return hasAnyPermission(permissions);
    };

    const canAnyAreaOperate = () => {
        if (!permissionsLoaded.value) return false;
        return TIBU_AREA_CODES.some((code) => hasPermission(`area.${code}.operate`));
    };

    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();
        await loadPermissions();
        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>
