<!doctype html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>{{ trim($__env->yieldContent('title')) ?: config('app.name') }}</title>

    <link rel="icon" type="image/png" href="{{ asset('assets/img/veltrix-favicon.png') }}">
    <link rel="apple-touch-icon" href="{{ asset('assets/img/veltrix-favicon.png') }}">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css" rel="stylesheet">

    @vite(['resources/scss/app.scss', 'resources/js/app.js'])
    @livewireStyles
    @stack('styles')
</head>
<body
    class="vx-body"
    data-flash-status="{{ (string) session('status', '') }}"
    data-flash-error="{{ (string) session('error', '') }}"
>
@php
    $user = auth_user();
    $rawDocumentTitle = trim((string) $__env->yieldContent('title'));
    $pageTitleOverride = trim((string) $__env->yieldContent('page_title'));
    $pageSubtitleOverride = trim((string) $__env->yieldContent('page_subtitle'));
    $pageIconOverride = trim((string) $__env->yieldContent('page_icon'));
    $requestPath = '/'.ltrim(request()->path(), '/');
    if ($requestPath === '//') {
        $requestPath = '/';
    }

    $tenantEmpresaNombre = $tenantSwitcher['current_empresa_nombre'] ?? 'N/A';
    $tenantSucursalNombre = $tenantSwitcher['current_sucursal_nombre'] ?? 'N/A';
    $showCompanySwitcher = (bool) ($tenantSwitcher['can_switch'] ?? false);
    $isSuperadminPanel = has_permission('superadmin.acceso');
    $validSuperadminSections = [
        'resumen',
        'wompi',
        'correo',
        'whatsapp_meta',
        'whatsapp_meta_templates',
        'whatsapp_manychat',
        'notificaciones',
        'ai',
        'reporte_openia',
        'checkout',
        'cobranza',
        'planes',
        'empresas',
        'suscripciones',
        'sla',
        'soporte',
        'pagos',
    ];
    $currentSuperadminSection = strtolower(trim((string) request()->query('seccion', 'resumen')));
    if (! in_array($currentSuperadminSection, $validSuperadminSections, true)) {
        $currentSuperadminSection = 'resumen';
    }
    $profileHomeRoute = route('perfil.index');

    if ($isSuperadminPanel) {
        $superadminHref = static function (string $section): string {
            if ($section === 'resumen') {
                return route('superadmin.index');
            }

            return route('superadmin.index', ['seccion' => $section]);
        };

        $navGroups = [
            [
                'title' => 'General',
                'icon' => 'bx bxs-home',
                'items' => [
                    ['label' => 'Resumen', 'href' => $superadminHref('resumen'), 'section' => 'resumen', 'icon' => 'bx bxs-dashboard', 'visible' => true],
                ],
            ],
            [
                'title' => 'Comercial',
                'icon' => 'bx bxs-briefcase-alt-2',
                'items' => [
                    ['label' => 'Planes', 'href' => $superadminHref('planes'), 'section' => 'planes', 'icon' => 'bx bxs-package', 'visible' => true],
                    ['label' => 'Empresas', 'href' => $superadminHref('empresas'), 'section' => 'empresas', 'icon' => 'bx bxs-buildings', 'visible' => true],
                    ['label' => 'Suscripciones', 'href' => $superadminHref('suscripciones'), 'section' => 'suscripciones', 'icon' => 'bx bx-time-five', 'visible' => true],
                    ['label' => 'Pagos', 'href' => $superadminHref('pagos'), 'section' => 'pagos', 'icon' => 'bx bxs-wallet-alt', 'visible' => true],
                    ['label' => 'Checkout fallidos', 'href' => $superadminHref('checkout'), 'section' => 'checkout', 'icon' => 'bx bx-cart-download', 'visible' => true],
                    ['label' => 'Cobranza', 'href' => $superadminHref('cobranza'), 'section' => 'cobranza', 'icon' => 'bx bx-credit-card-front', 'visible' => true],
                ],
            ],
            [
                'title' => 'Api e Integraciones',
                'icon' => 'bx bx-link-alt',
                'items' => [
                    ['label' => 'Wompi', 'href' => $superadminHref('wompi'), 'section' => 'wompi', 'icon' => 'bx bx-credit-card', 'visible' => true],
                    ['label' => 'Correo', 'href' => $superadminHref('correo'), 'section' => 'correo', 'icon' => 'bx bx-envelope', 'visible' => true],
                    ['label' => 'WhatsApp Meta', 'href' => $superadminHref('whatsapp_meta'), 'section' => 'whatsapp_meta', 'icon' => 'bx bxl-whatsapp', 'visible' => true],
                    ['label' => 'Templates Meta', 'href' => $superadminHref('whatsapp_meta_templates'), 'section' => 'whatsapp_meta_templates', 'icon' => 'bx bx-message-square-dots', 'visible' => true],
                    ['label' => 'ManyChat', 'href' => $superadminHref('whatsapp_manychat'), 'section' => 'whatsapp_manychat', 'icon' => 'bx bx-chat', 'visible' => true],
                    ['label' => 'Notificaciones', 'href' => $superadminHref('notificaciones'), 'section' => 'notificaciones', 'icon' => 'bx bx-bell', 'visible' => true],
                ],
            ],
            [
                'title' => 'Reporte',
                'icon' => 'bx bxs-report',
                'items' => [
                    ['label' => 'SLA', 'href' => $superadminHref('sla'), 'section' => 'sla', 'icon' => 'bx bx-timer', 'visible' => true],
                    ['label' => 'Reporte IA', 'href' => $superadminHref('reporte_openia'), 'section' => 'reporte_openia', 'icon' => 'bx bx-line-chart', 'visible' => true],
                ],
            ],
            [
                'title' => 'Soporte',
                'icon' => 'bx bx-support',
                'items' => [
                    ['label' => 'Tickets', 'href' => $superadminHref('soporte'), 'section' => 'soporte', 'icon' => 'bx bx-support', 'visible' => true],
                    ['label' => 'Ayuda IA', 'href' => $superadminHref('ai'), 'section' => 'ai', 'icon' => 'bx bx-bot', 'visible' => true],
                ],
            ],
        ];
    } else {
        $navGroups = [
            [
                'title' => 'Operacion',
                'icon' => 'bx bxs-grid-alt',
                'items' => [
                    ['label' => 'Dashboard', 'href' => route('dashboard'), 'match' => '/dashboard', 'icon' => 'bx bxs-grid-alt', 'visible' => has_permission('dashboard.ver')],
                    ['label' => 'POS', 'href' => route('pos.index'), 'match' => '/pos', 'icon' => 'bx bxs-cart-add', 'visible' => has_permission('pos.vender')],
                    ['label' => 'Ventas', 'href' => route('ventas.index'), 'match' => '/ventas', 'icon' => 'bx bxs-receipt', 'visible' => has_permission('ventas.ver')],
                    ['label' => 'Caja', 'href' => route('caja.index'), 'match' => '/caja', 'icon' => 'bx bxs-wallet', 'visible' => has_permission('caja.ver')],
                    ['label' => 'C. Cobrar', 'href' => route('cuentas-cobrar.index'), 'match' => '/cuentas-cobrar', 'icon' => 'bx bx-wallet-alt', 'visible' => has_permission('cuentas_cobrar.ver')],
                ],
            ],
            [
                'title' => 'Inventario',
                'icon' => 'bx bxs-package',
                'items' => [
                    ['label' => 'Inventario', 'href' => route('inventario.index'), 'match' => '/inventario', 'icon' => 'bx bxs-package', 'visible' => has_permission('inventario.ver')],
                    ['label' => 'Productos', 'href' => route('productos.index'), 'match' => '/productos', 'icon' => 'bx bxs-box', 'visible' => has_permission('productos.ver')],
                    ['label' => 'Categorias', 'href' => route('categorias.index'), 'match' => '/categorias', 'icon' => 'bx bxs-category', 'visible' => has_permission('categorias.ver')],
                    ['label' => 'Compras', 'href' => route('compras.index'), 'match' => '/compras', 'icon' => 'bx bxs-cart-download', 'visible' => has_permission('compras.ver')],
                    ['label' => 'Envíos', 'href' => route('envios.index'), 'match' => '/envios', 'icon' => 'bx bxs-truck', 'visible' => has_permission('envios.ver')],
                    ['label' => 'Proveedores', 'href' => route('proveedores.index'), 'match' => '/proveedores', 'icon' => 'bx bxs-store-alt', 'visible' => has_permission('proveedores.ver')],
                ],
            ],
            [
                'title' => 'Comercial',
                'icon' => 'bx bxs-briefcase-alt-2',
                'items' => [
                    ['label' => 'Clientes', 'href' => route('clientes.index'), 'match' => '/clientes', 'icon' => 'bx bxs-user-detail', 'visible' => has_permission('clientes.ver')],
                    ['label' => 'Reportes', 'href' => route('reportes.index'), 'match' => '/reportes', 'icon' => 'bx bxs-bar-chart-alt-2', 'visible' => has_permission('reportes.ver')],
                ],
            ],
            [
                'title' => 'Soporte',
                'icon' => 'bx bx-support',
                'items' => [
                    ['label' => 'Ticket', 'href' => route('soporte.index'), 'match' => '/soporte', 'icon' => 'bx bx-support', 'visible' => has_permission('dashboard.ver')],
                    ['label' => 'Ayuda IA', 'href' => route('ayuda-ia.index'), 'match' => '/ayuda-ia', 'icon' => 'bx bx-bot', 'visible' => has_permission('dashboard.ver')],
                ],
            ],
            [
                'title' => 'Administracion',
                'icon' => 'bx bxs-cog',
                'items' => [
                    ['label' => 'Superadmin', 'href' => route('superadmin.index'), 'match' => '/superadmin', 'icon' => 'bx bxs-crown', 'visible' => has_permission('superadmin.acceso')],
                    ['label' => 'Empresas', 'href' => route('empresas.index'), 'match' => '/empresas', 'icon' => 'bx bxs-buildings', 'visible' => has_permission('superadmin.acceso')],
                    ['label' => 'Sucursales', 'href' => route('sucursales.index'), 'match' => '/sucursales', 'icon' => 'bx bxs-store', 'visible' => has_permission('sucursales.ver')],
                    ['label' => 'Usuarios', 'href' => route('usuarios.index'), 'match' => '/usuarios', 'icon' => 'bx bxs-group', 'visible' => has_permission('usuarios.ver')],
                    ['label' => 'Configuracion', 'href' => route('configuracion.index'), 'match' => '/configuracion', 'icon' => 'bx bxs-cog', 'visible' => has_permission('configuracion.ver')],
                ],
            ],
        ];
    }

    $preparedGroups = [];
    foreach ($navGroups as $group) {
        $items = [];
        $groupHasActive = false;

        foreach ((array) ($group['items'] ?? []) as $item) {
            if (array_key_exists('visible', $item) && ! $item['visible']) {
                continue;
            }

            $match = (string) ($item['match'] ?? '');
            $section = strtolower(trim((string) ($item['section'] ?? '')));
            if ($section !== '') {
                $active = $requestPath === '/superadmin' && $currentSuperadminSection === $section;
            } else {
                $active = $match !== '' && ($requestPath === $match || str_starts_with($requestPath, $match.'/'));
            }
            $item['_active'] = $active;

            if ($active) {
                $groupHasActive = true;
            }

            $items[] = $item;
        }

        if ($items === []) {
            continue;
        }

        $preparedGroups[] = [
            'title' => (string) ($group['title'] ?? 'Modulo'),
            'icon' => (string) ($group['icon'] ?? 'bx bxs-layer'),
            'items' => $items,
            'has_active' => $groupHasActive,
        ];
    }

    $defaultOpenGroupIndex = 0;
    foreach ($preparedGroups as $idx => $group) {
        if ((bool) ($group['has_active'] ?? false)) {
            $defaultOpenGroupIndex = $idx;
            break;
        }
    }

    $activeNavItem = null;
    foreach ($preparedGroups as $group) {
        foreach ((array) ($group['items'] ?? []) as $item) {
            if ((bool) ($item['_active'] ?? false)) {
                $activeNavItem = $item;
                break 2;
            }
        }
    }

    $defaultPageTitle = $rawDocumentTitle !== ''
        ? trim((string) preg_replace('/\s*\|.*$/', '', $rawDocumentTitle))
        : 'Dashboard';
    $currentPageTitle = $pageTitleOverride !== '' ? $pageTitleOverride : $defaultPageTitle;
    $currentPageSubtitle = $pageSubtitleOverride !== '' ? $pageSubtitleOverride : 'Gestion operativa en tiempo real';
    $defaultPageIcon = trim((string) ($activeNavItem['icon'] ?? 'bx bxs-grid-alt'));
    $currentPageIcon = $pageIconOverride !== '' ? $pageIconOverride : $defaultPageIcon;
    $profileName = trim((string) ($user->nombre ?? 'Usuario'));
    $profileRole = trim((string) ($user->rol?->nombre ?? 'Cuenta'));
    $profileInitial = strtoupper((string) mb_substr($profileName !== '' ? $profileName : 'U', 0, 1));
    $notificationScope = $isSuperadminPanel ? 'superadmin' : 'tenant';
    $notificationInventoryUrl = route('inventario.index');
    $notificationSupportUrl = $isSuperadminPanel
        ? route('superadmin.index', ['seccion' => 'soporte'])
        : route('soporte.index');
    $notificationPayload = [
        'count' => 0,
        'count_stock' => 0,
        'count_tickets' => 0,
        'items' => [],
    ];
    try {
        $notificationPayload = app(\App\Services\Notifications\NotificationCenterService::class)
            ->payload($notificationScope, 10);
    } catch (\Throwable) {
        // Evita romper la UI si ocurre un error temporal de lectura de notificaciones.
    }
@endphp

<div id="sileo-root" style="position: fixed; inset: 0; pointer-events: none; z-index: 2147483647;"></div>
<style>
    [data-sileo-viewport][data-position="top-center"] {
        top: 50% !important;
        transform: translate(-50%, -50%) !important;
    }
</style>
<script>
    window.__veltrixStockNotifications = @json($notificationPayload);
</script>

@if ($user)
    <div class="vx-shell">
        <aside class="vx-sidebar" id="vxSidebar">
            <div class="vx-brand">
                <span class="vx-brand-dot">
                    <img src="{{ asset('assets/img/veltrix-icon-white.png') }}" alt="Veltrix" class="vx-brand-icon">
                </span>
                <div>
                    <strong>Veltrix</strong>
                    <small>HunoLabs</small>
                </div>
                <button class="vx-sidebar-close d-lg-none" id="vxSidebarClose" type="button">
                    <i class="bx bx-x"></i>
                </button>
            </div>

            <nav class="vx-nav">
                @foreach ($preparedGroups as $groupIndex => $group)
                    @php
                        $groupItems = (array) ($group['items'] ?? []);
                        $isGroupOpen = (bool) ($group['has_active'] ?? false) || $groupIndex === $defaultOpenGroupIndex;
                        $groupPanelId = 'vxNavGroupPanel'.$groupIndex;
                    @endphp

                    <div class="vx-nav-group" data-vx-nav-group>
                        <button
                            class="vx-nav-group-toggle {{ $isGroupOpen ? 'is-open' : '' }}"
                            type="button"
                            data-vx-nav-toggle
                            aria-expanded="{{ $isGroupOpen ? 'true' : 'false' }}"
                            aria-controls="{{ $groupPanelId }}"
                        >
                            <i class="vx-nav-group-icon {{ $group['icon'] }}"></i>
                            <span class="vx-nav-group-title">{{ $group['title'] }}</span>
                            <i class="bx bx-chevron-down vx-nav-group-arrow"></i>
                        </button>

                        <div id="{{ $groupPanelId }}" class="vx-nav-group-body {{ $isGroupOpen ? 'is-open' : '' }}" data-vx-nav-panel>
                            @foreach ($groupItems as $item)
                                <a
                                    class="vx-nav-link {{ ($item['_active'] ?? false) ? 'is-active' : '' }}"
                                    href="{{ $item['href'] }}"
                                    title="{{ $item['label'] }}"
                                    aria-label="{{ $item['label'] }}"
                                >
                                    <i class="{{ $item['icon'] }}"></i>
                                    <span class="vx-nav-label">{{ $item['label'] }}</span>
                                </a>
                            @endforeach
                        </div>
                    </div>
                @endforeach
            </nav>

            <div class="vx-sidebar-user">
                <p class="mb-0">Sesion activa</p>
                <strong>{{ $user->nombre ?? 'Usuario' }}</strong>
                <small class="d-block text-uppercase mt-1">{{ $user->rol?->nombre ?? 'Sin rol' }}</small>
                <a class="vx-sidebar-profile-link" href="{{ $profileHomeRoute }}">
                    <i class="bx bx-user-circle"></i>Mi perfil
                </a>
            </div>
        </aside>

        <div class="vx-main">
            <header class="vx-topbar">
                <div class="d-flex align-items-center gap-2 vx-topbar-heading">
                    <button class="vx-icon-btn" id="vxSidebarToggle" type="button" aria-label="Abrir menu">
                        <i class="bx bx-menu-alt-left"></i>
                    </button>
                    <div>
                        <h1 class="vx-page-title">{{ $currentPageTitle }}</h1>
                        <small class="vx-page-subtitle">{{ $currentPageSubtitle }}</small>
                    </div>
                </div>

                <div class="d-flex align-items-center gap-2 vx-topbar-actions">
                    <div class="dropdown vx-topbar-notifications">
                        <button
                            class="btn btn-light btn-sm vx-topbar-action vx-notify-btn dropdown-toggle"
                            type="button"
                            id="vxNotificationToggle"
                            data-notifications-url="{{ route('notificaciones.index', ['scope' => $notificationScope]) }}"
                            data-mark-read-url="{{ route('notificaciones.mark-read') }}"
                            data-notification-scope="{{ $notificationScope }}"
                            data-inventory-url="{{ $notificationInventoryUrl }}"
                            data-support-url="{{ $notificationSupportUrl }}"
                            data-bs-toggle="dropdown"
                            aria-expanded="false"
                            aria-label="Notificaciones"
                        >
                            <i class="bx bxs-bell"></i>
                            @php
                                $notificationCount = max(0, (int) ($notificationPayload['count'] ?? 0));
                            @endphp
                            <span
                                id="vxNotificationBadge"
                                class="vx-notify-badge {{ $notificationCount > 0 ? '' : 'd-none' }}"
                            >
                                {{ $notificationCount > 99 ? '99+' : $notificationCount }}
                            </span>
                        </button>
                        <div class="dropdown-menu dropdown-menu-end shadow-sm vx-notify-menu" aria-labelledby="vxNotificationToggle">
                            <div class="vx-notify-menu-header">
                                <div class="vx-notify-menu-title">
                                    <strong>Notificaciones</strong>
                                    <small id="vxNotificationCountLabel">{{ $notificationCount }} notificación(es)</small>
                                </div>
                                <button
                                    type="button"
                                    id="vxNotificationMarkRead"
                                    class="btn btn-outline-primary btn-sm vx-notify-mark-read"
                                    @disabled($notificationCount <= 0)
                                >
                                    Marcar como leído
                                </button>
                            </div>
                            <ul id="vxNotificationList" class="vx-notify-list">
                                <li class="vx-notify-empty">No hay notificaciones por ahora.</li>
                            </ul>
                            <div class="vx-notify-menu-footer">
                                <a href="{{ $notificationSupportUrl }}">Ver soporte</a>
                            </div>
                        </div>
                    </div>

                    @yield('topbar_actions')

                    <div class="dropdown vx-topbar-dropdown vx-profile-dropdown">
                        <button
                            class="vx-profile-menu-btn dropdown-toggle"
                            type="button"
                            data-bs-toggle="dropdown"
                            aria-expanded="false"
                            aria-label="Menú de perfil"
                        >
                            <span class="vx-profile-avatar">{{ $profileInitial }}</span>
                            <span class="vx-profile-meta">
                                <strong>{{ $profileName !== '' ? $profileName : 'Usuario' }}</strong>
                                <small>{{ $profileRole !== '' ? $profileRole : 'Cuenta' }}</small>
                            </span>
                            <i class="bx bx-chevron-down vx-profile-chevron"></i>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end shadow-sm vx-profile-menu">
                            <li class="vx-profile-menu-header">
                                <div class="vx-profile-menu-title">
                                    <strong>{{ $profileName !== '' ? $profileName : 'Usuario' }}</strong>
                                    <small>{{ $profileRole !== '' ? $profileRole : 'Cuenta' }}</small>
                                </div>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center gap-2" href="{{ $profileHomeRoute }}">
                                    <i class="bx bx-user-circle"></i>
                                    <span>Mi perfil</span>
                                </a>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            <li>
                                <form method="POST" action="{{ route('logout') }}" class="m-0">
                                    @csrf
                                    <button class="dropdown-item d-flex align-items-center gap-2 text-danger" type="submit">
                                        <i class="bx bx-log-out-circle"></i>
                                        <span>Cerrar sesión</span>
                                    </button>
                                </form>
                            </li>
                        </ul>
                    </div>
                </div>
            </header>

            <main class="vx-content">
                {{ $slot ?? '' }}
                @yield('content')
            </main>
        </div>
    </div>

    <div class="vx-sidebar-backdrop" id="vxSidebarBackdrop"></div>
@else
    {{ $slot ?? '' }}
    @yield('content')
@endif

<script src="{{ asset('assets/js/app.js') }}"></script>

@livewireScripts
@stack('scripts')
</body>
</html>
