<?php $__env->startSection('title', 'Sucursales | Veltrix v2'); ?>
<?php $__env->startSection('page_title', 'Sucursales'); ?>
<?php $__env->startSection('page_subtitle', 'Gestion operativa en tiempo real'); ?>
<?php $__env->startSection('page_icon', 'bx bxs-store'); ?>

<?php $__env->startSection('content'); ?>
    <?php
        $sucursalesRows = $sucursales instanceof \Illuminate\Support\Collection ? $sucursales : collect($sucursales ?? []);
        $usuariosRows = $usuarios instanceof \Illuminate\Support\Collection ? $usuarios : collect($usuarios ?? []);
        $cajasRows = $cajas instanceof \Illuminate\Support\Collection ? $cajas : collect($cajas ?? []);
        $paisesRows = $paises instanceof \Illuminate\Support\Collection ? $paises : collect($paises ?? []);
        $ciudadesRows = $ciudades instanceof \Illuminate\Support\Collection ? $ciudades : collect($ciudades ?? []);

        $branchLimitData = is_array($branchLimit ?? null) ? $branchLimit : null;
        $branchCountValue = (int) ($branchCount ?? $sucursalesRows->count());
        $activeBranchesValue = (int) ($activeBranches ?? $sucursalesRows->where('activa', true)->count());
        $totalUsersAssigned = (int) ($totalAssignedUsers ?? $usuariosRows->filter(static fn ($user): bool => (int) ($user->sucursal_id ?? 0) > 0)->count());
        $totalCashBoxesValue = (int) ($totalCashBoxes ?? $cajasRows->count());

        $branchCanCreateValue = (bool) ($branchCanCreate ?? true);
        $branchPlanName = trim((string) (($branchLimitData['plan_nombre'] ?? '') ?: 'Plan actual'));
        $branchMax = is_array($branchLimitData) ? max(0, (int) ($branchLimitData['max_sucursales'] ?? 0)) : null;
        $branchLimitReached = $branchMax !== null && ! $branchCanCreateValue;
        $planUsage = null;
        if ($branchMax !== null && $branchMax > 0) {
            $planUsage = min(100, (int) round(($branchCountValue / $branchMax) * 100));
        }

        $usersByBranch = $usuariosRows
            ->filter(static fn ($user): bool => (int) ($user->sucursal_id ?? 0) > 0)
            ->groupBy(static fn ($user): int => (int) ($user->sucursal_id ?? 0));

        $cashBoxesByBranch = $cajasRows
            ->filter(static fn ($caja): bool => (int) ($caja->sucursal_id ?? 0) > 0)
            ->groupBy(static fn ($caja): int => (int) ($caja->sucursal_id ?? 0));

        $cityOptions = $ciudadesRows->map(static function ($city): array {
            $cityId = (int) ($city->id ?? 0);
            $countryId = (int) ($city->pais_id ?? 0);
            $cityName = trim((string) ($city->nombre ?? ''));
            $countryName = trim((string) ($city->pais->nombre ?? ''));
            $departmentName = trim((string) ($city->departamento ?? ''));
            $label = $cityName;

            if ($departmentName !== '') {
                $label .= ' - '.$departmentName;
            }

            return [
                'id' => $cityId,
                'country_id' => $countryId,
                'name' => $cityName,
                'country' => $countryName,
                'department' => $departmentName,
                'label' => $label,
            ];
        })->filter(static fn (array $city): bool => $city['id'] > 0)->values()->all();

        $citiesById = [];
        foreach ($cityOptions as $city) {
            $citiesById[(int) $city['id']] = $city;
        }

        $oldFormContext = trim((string) old('_form_context', ''));

        $createSelectedCityId = $oldFormContext === 'create' ? (int) old('ciudad_id', 0) : 0;
        $createSelectedCountryId = $oldFormContext === 'create'
            ? (int) old('pais_id', $citiesById[$createSelectedCityId]['country_id'] ?? 0)
            : 0;
        $createSelectedDepartment = $oldFormContext === 'create'
            ? trim((string) old('departamento', $citiesById[$createSelectedCityId]['department'] ?? ''))
            : '';

        if ($createSelectedCountryId <= 0 && $createSelectedCityId > 0) {
            $createSelectedCountryId = (int) ($citiesById[$createSelectedCityId]['country_id'] ?? 0);
        }

        $editingBranchFormId = $oldFormContext === 'update' ? (int) old('_branch_form_id', 0) : 0;
    ?>

    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($errors->any()): ?>
        <div class="alert alert-danger mb-3">
            <?php echo e($errors->first()); ?>

        </div>
    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

    <div class="row g-3 mb-3">
        <div class="col-sm-6 col-xl-3">
            <div class="card metric-card border-0 shadow-sm vx-branch-metric-card">
                <div class="card-body">
                    <small class="vx-branch-metric-label">Sucursales</small>
                    <p class="vx-branch-metric-value mb-0"><?php echo e($branchCountValue); ?></p>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="card metric-card border-0 shadow-sm vx-branch-metric-card">
                <div class="card-body">
                    <small class="vx-branch-metric-label">Activas</small>
                    <p class="vx-branch-metric-value mb-0"><?php echo e($activeBranchesValue); ?></p>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="card metric-card border-0 shadow-sm vx-branch-metric-card">
                <div class="card-body">
                    <small class="vx-branch-metric-label">Usuarios asignados</small>
                    <p class="vx-branch-metric-value mb-0"><?php echo e($totalUsersAssigned); ?></p>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="card metric-card border-0 shadow-sm vx-branch-metric-card">
                <div class="card-body">
                    <small class="vx-branch-metric-label">Cajas</small>
                    <p class="vx-branch-metric-value mb-0"><?php echo e($totalCashBoxesValue); ?></p>
                </div>
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm mb-3 vx-branch-plan-card">
        <div class="card-body">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-2">
                <div>
                    <h2 class="h6 mb-1">Límite por plan</h2>
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($branchMax !== null): ?>
                        <small class="text-muted"><?php echo e($branchPlanName); ?> · <?php echo e($branchCountValue); ?>/<?php echo e($branchMax); ?> sucursales usadas</small>
                    <?php else: ?>
                        <small class="text-muted">Sin plan activo · <?php echo e($branchCountValue); ?> sucursales usadas</small>
                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </div>
                <span class="badge <?php echo e($branchLimitReached ? 'text-bg-warning' : 'text-bg-info'); ?>">
                    <?php echo e($branchLimitReached ? 'Límite alcanzado' : 'Disponible'); ?>

                </span>
            </div>

            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($branchMax !== null && $branchMax > 0): ?>
                <div class="progress" role="progressbar" aria-label="Uso de sucursales" aria-valuenow="<?php echo e($planUsage ?? 0); ?>" aria-valuemin="0" aria-valuemax="100">
                    <div class="progress-bar <?php echo e($branchLimitReached ? 'bg-warning text-dark' : 'bg-info'); ?>" style="width: <?php echo e($planUsage ?? 0); ?>%">
                        <?php echo e($planUsage ?? 0); ?>%
                    </div>
                </div>
            <?php elseif($branchMax === 0): ?>
                <div class="alert alert-warning py-2 mb-0">Este plan no permite crear sucursales.</div>
            <?php else: ?>
                <div class="alert alert-light border py-2 mb-0">No se encontró una suscripción activa para calcular límite de sucursales.</div>
            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
        </div>
    </div>

    <div class="row g-3 mb-3">
        <div class="col-xl-6">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <h2 class="h6 mb-3">Nueva sucursal</h2>

                    <form action="<?php echo e(route('sucursales.store')); ?>" method="post">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="_form_context" value="create">
                        <div class="row g-2">
                            <div class="col-12">
                                <label class="form-label">Nombre</label>
                                <input class="form-control" name="nombre" value="<?php echo e($oldFormContext === 'create' ? old('nombre') : ''); ?>" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Código</label>
                                <input class="form-control" name="codigo" maxlength="50" value="<?php echo e($oldFormContext === 'create' ? old('codigo') : ''); ?>">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Teléfono</label>
                                <input class="form-control" name="telefono" value="<?php echo e($oldFormContext === 'create' ? old('telefono') : ''); ?>">
                            </div>
                            <div class="col-12">
                                <label class="form-label">Dirección</label>
                                <input class="form-control" name="direccion" value="<?php echo e($oldFormContext === 'create' ? old('direccion') : ''); ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Pais</label>
                                <select class="form-select" name="pais_id" id="vxCreateBranchCountry">
                                    <option value="0">Sin definir</option>
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $paisesRows; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $pais): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                        <?php $paisId = (int) ($pais->id ?? 0); ?>
                                        <option value="<?php echo e($paisId); ?>" <?php echo e($createSelectedCountryId === $paisId ? 'selected' : ''); ?>>
                                            <?php echo e((string) ($pais->nombre ?? '')); ?>

                                        </option>
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Departamento</label>
                                <select class="form-select" name="departamento" id="vxCreateBranchDepartment" data-selected="<?php echo e($createSelectedDepartment); ?>">
                                    <option value="">Sin definir</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Municipio</label>
                                <select class="form-select" name="ciudad_id" id="vxCreateBranchCitySelect" data-selected="<?php echo e($createSelectedCityId); ?>">
                                    <option value="0">Sin definir</option>
                                </select>
                                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($cityOptions === []): ?>
                                    <small class="text-muted d-block mt-1">No hay ciudades cargadas. Importa el catálogo DANE.</small>
                                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                            </div>
                            <div class="col-12">
                                <div class="form-check">
                                    <input type="hidden" name="activa" value="0">
                                    <input
                                        class="form-check-input"
                                        type="checkbox"
                                        name="activa"
                                        value="1"
                                        id="branchActive"
                                        <?php echo e(($oldFormContext === 'create' ? old('activa', '1') : '1') === '1' ? 'checked' : ''); ?>

                                    >
                                    <label class="form-check-label" for="branchActive">Sucursal activa</label>
                                </div>
                            </div>
                        </div>
                        <button class="btn btn-primary w-100 mt-3" type="submit" <?php echo e($branchLimitReached ? 'disabled' : ''); ?>>
                            <i class="bx bx-plus-circle me-1"></i>Crear sucursal
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-xl-6">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
                        <h1 class="h5 mb-0">Gestión de sucursales</h1>
                        <div class="input-group input-group-sm vx-branch-search">
                            <span class="input-group-text"><i class="bx bx-search"></i></span>
                            <input type="search" class="form-control" id="vxBranchSearchInput" placeholder="Buscar sucursal por nombre, ciudad o código...">
                        </div>
                    </div>

                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($sucursalesRows->isEmpty()): ?>
                        <div class="alert alert-light border mb-0">No hay sucursales creadas.</div>
                    <?php else: ?>
                        <div class="accordion vx-branch-accordion" id="vxBranchManageAccordion">
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $sucursalesRows; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $sucursal): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                <?php
                                    $branchId = (int) ($sucursal->id ?? 0);
                                    $branchCity = trim((string) ($sucursal->ciudad->nombre ?? 'Sin ciudad'));
                                    $branchCode = trim((string) ($sucursal->codigo ?? ''));
                                    $branchActiveState = (bool) ($sucursal->activa ?? false);
                                    $assignedUsers = $usersByBranch->get($branchId, collect());
                                    $boxes = $cashBoxesByBranch->get($branchId, collect());
                                    $collapseId = 'vxBranchManage'.$branchId;
                                    $headerId = 'vxBranchManageHeading'.$branchId;
                                    $isFirst = $index === 0;
                                    $searchIndex = strtolower(trim((string) ($sucursal->nombre ?? '').' '.$branchCode.' '.$branchCity));

                                    $branchCurrentCityId = (int) ($sucursal->ciudad_id ?? 0);
                                    $branchSelectedCityId = $editingBranchFormId === $branchId
                                        ? (int) old('ciudad_id', $branchCurrentCityId)
                                        : $branchCurrentCityId;

                                    $branchSelectedCountryId = $editingBranchFormId === $branchId
                                        ? (int) old('pais_id', $citiesById[$branchSelectedCityId]['country_id'] ?? ($sucursal->ciudad->pais_id ?? 0))
                                        : (int) ($sucursal->ciudad->pais_id ?? 0);

                                    if ($branchSelectedCountryId <= 0 && $branchSelectedCityId > 0) {
                                        $branchSelectedCountryId = (int) ($citiesById[$branchSelectedCityId]['country_id'] ?? 0);
                                    }

                                    $branchSelectedDepartment = $editingBranchFormId === $branchId
                                        ? trim((string) old('departamento', $citiesById[$branchSelectedCityId]['department'] ?? ($sucursal->ciudad->departamento ?? '')))
                                        : trim((string) ($sucursal->ciudad->departamento ?? ''));

                                    $branchNameInput = $editingBranchFormId === $branchId
                                        ? trim((string) old('nombre', (string) ($sucursal->nombre ?? '')))
                                        : trim((string) ($sucursal->nombre ?? ''));

                                    $branchCodeInput = $editingBranchFormId === $branchId
                                        ? trim((string) old('codigo', $branchCode))
                                        : $branchCode;

                                    $branchPhoneInput = $editingBranchFormId === $branchId
                                        ? trim((string) old('telefono', (string) ($sucursal->telefono ?? '')))
                                        : trim((string) ($sucursal->telefono ?? ''));

                                    $branchAddressInput = $editingBranchFormId === $branchId
                                        ? trim((string) old('direccion', (string) ($sucursal->direccion ?? '')))
                                        : trim((string) ($sucursal->direccion ?? ''));
                                ?>

                                <div class="accordion-item vx-branch-manage-item" data-search="<?php echo e($searchIndex); ?>">
                                    <h2 class="accordion-header" id="<?php echo e($headerId); ?>">
                                        <button
                                            class="accordion-button <?php echo e($isFirst ? '' : 'collapsed'); ?>"
                                            type="button"
                                            data-vx-collapse-target="#<?php echo e($collapseId); ?>"
                                            aria-expanded="<?php echo e($isFirst ? 'true' : 'false'); ?>"
                                            aria-controls="<?php echo e($collapseId); ?>"
                                        >
                                            <div class="vx-branch-head">
                                                <div>
                                                    <strong><?php echo e($sucursal->nombre); ?></strong>
                                                    <small>
                                                        <?php echo e($branchCity); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($branchCode !== ''): ?> · <?php echo e($branchCode); ?><?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                                    </small>
                                                </div>
                                                <div class="vx-branch-head-meta">
                                                    <span class="badge <?php echo e($branchActiveState ? 'text-bg-success' : 'text-bg-secondary'); ?>">
                                                        <?php echo e($branchActiveState ? 'Activa' : 'Inactiva'); ?>

                                                    </span>
                                                    <span class="badge text-bg-light border"><?php echo e($assignedUsers->count()); ?> usuarios</span>
                                                    <span class="badge text-bg-light border"><?php echo e($boxes->count()); ?> cajas</span>
                                                </div>
                                            </div>
                                        </button>
                                    </h2>

                                    <div
                                        id="<?php echo e($collapseId); ?>"
                                        class="accordion-collapse collapse <?php echo e($isFirst ? 'show' : ''); ?>"
                                        aria-labelledby="<?php echo e($headerId); ?>"
                                        data-vx-parent="#vxBranchManageAccordion"
                                    >
                                        <div class="accordion-body">
                                            <form action="<?php echo e(route('sucursales.update-inline', $sucursal)); ?>" method="post" class="row g-2">
                                                <?php echo csrf_field(); ?>
                                                <input type="hidden" name="_form_context" value="update">
                                                <input type="hidden" name="_branch_form_id" value="<?php echo e($branchId); ?>">
                                                <input type="hidden" name="activa" value="<?php echo e($branchActiveState ? '1' : '0'); ?>">

                                                <div class="col-md-6">
                                                    <label class="form-label">Nombre</label>
                                                    <input class="form-control form-control-sm" name="nombre" value="<?php echo e($branchNameInput); ?>" required>
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Código</label>
                                                    <input class="form-control form-control-sm" name="codigo" value="<?php echo e($branchCodeInput); ?>">
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Teléfono</label>
                                                    <input class="form-control form-control-sm" name="telefono" value="<?php echo e($branchPhoneInput); ?>">
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Pais</label>
                                                    <select class="form-select form-select-sm" name="pais_id" id="vxBranchCountry<?php echo e($branchId); ?>">
                                                        <option value="0">Sin definir</option>
                                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $paisesRows; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $pais): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                                            <?php $paisId = (int) ($pais->id ?? 0); ?>
                                                            <option value="<?php echo e($paisId); ?>" <?php echo e($branchSelectedCountryId === $paisId ? 'selected' : ''); ?>>
                                                                <?php echo e((string) ($pais->nombre ?? '')); ?>

                                                            </option>
                                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                                    </select>
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Departamento</label>
                                                    <select
                                                        class="form-select form-select-sm"
                                                        name="departamento"
                                                        id="vxBranchDepartment<?php echo e($branchId); ?>"
                                                        data-selected="<?php echo e($branchSelectedDepartment); ?>"
                                                    >
                                                        <option value="">Sin definir</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Municipio</label>
                                                    <select
                                                        class="form-select form-select-sm"
                                                        name="ciudad_id"
                                                        id="vxBranchCitySelect<?php echo e($branchId); ?>"
                                                        data-selected="<?php echo e($branchSelectedCityId); ?>"
                                                    >
                                                        <option value="0">Sin definir</option>
                                                    </select>
                                                </div>
                                                <div class="col-12">
                                                    <label class="form-label">Dirección</label>
                                                    <input class="form-control form-control-sm" name="direccion" value="<?php echo e($branchAddressInput); ?>">
                                                </div>
                                                <div class="col-12 d-flex flex-wrap align-items-center justify-content-between gap-2 mt-2">
                                                    <small class="text-muted">Creada: <?php echo e(optional($sucursal->created_at)->format('Y-m-d H:i:s') ?? '-'); ?></small>
                                                    <button class="btn btn-sm btn-primary" type="submit">
                                                        <i class="bx bx-save me-1"></i>Guardar cambios
                                                    </button>
                                                </div>
                                            </form>

                                            <form action="<?php echo e(route('sucursales.toggle', $sucursal)); ?>" method="post" class="mt-2">
                                                <?php echo csrf_field(); ?>
                                                <input type="hidden" name="activa" value="<?php echo e($branchActiveState ? '0' : '1'); ?>">
                                                <button class="btn btn-sm <?php echo e($branchActiveState ? 'btn-outline-secondary' : 'btn-outline-success'); ?>" type="submit">
                                                    <i class="bx <?php echo e($branchActiveState ? 'bx-pause-circle' : 'bx-play-circle'); ?> me-1"></i>
                                                    <?php echo e($branchActiveState ? 'Desactivar sucursal' : 'Activar sucursal'); ?>

                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                        </div>
                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-3">
        <div class="col-xl-6">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <h2 class="h6 mb-3">Usuarios por sucursal</h2>
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($sucursalesRows->isEmpty()): ?>
                        <p class="text-muted mb-0">Primero crea una sucursal para asignar usuarios.</p>
                    <?php else: ?>
                        <div class="accordion vx-branch-accordion" id="vxUsersByBranchAccordion">
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $sucursalesRows; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $sucursal): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                <?php
                                    $branchId = (int) ($sucursal->id ?? 0);
                                    $assignedUsers = $usersByBranch->get($branchId, collect());
                                    $collapseId = 'vxUsersBranch'.$branchId;
                                    $headerId = 'vxUsersBranchHeading'.$branchId;
                                    $isFirst = $index === 0;
                                ?>

                                <div class="accordion-item">
                                    <h2 class="accordion-header" id="<?php echo e($headerId); ?>">
                                        <button
                                            class="accordion-button <?php echo e($isFirst ? '' : 'collapsed'); ?>"
                                            type="button"
                                            data-vx-collapse-target="#<?php echo e($collapseId); ?>"
                                            aria-expanded="<?php echo e($isFirst ? 'true' : 'false'); ?>"
                                            aria-controls="<?php echo e($collapseId); ?>"
                                        >
                                            <div class="d-flex align-items-center justify-content-between w-100 pe-3">
                                                <strong><?php echo e((string) ($sucursal->nombre ?? 'Sucursal')); ?></strong>
                                                <span class="badge text-bg-light border"><?php echo e($assignedUsers->count()); ?> asignados</span>
                                            </div>
                                        </button>
                                    </h2>

                                    <div
                                        id="<?php echo e($collapseId); ?>"
                                        class="accordion-collapse collapse <?php echo e($isFirst ? 'show' : ''); ?>"
                                        aria-labelledby="<?php echo e($headerId); ?>"
                                        data-vx-parent="#vxUsersByBranchAccordion"
                                    >
                                        <div class="accordion-body">
                                            <form action="<?php echo e(route('sucursales.users.assign', $sucursal)); ?>" method="post" class="row g-2 mb-3">
                                                <?php echo csrf_field(); ?>
                                                <div class="col-8">
                                                    <select class="form-select form-select-sm" name="usuario_id" required>
                                                        <option value="">Selecciona usuario</option>
                                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $usuariosRows; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $usuario): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                                            <?php $userId = (int) ($usuario->id ?? 0); ?>
                                                            <option value="<?php echo e($userId); ?>">
                                                                <?php echo e((string) ($usuario->nombre ?? '')); ?> (<?php echo e((string) ($usuario->email ?? '')); ?>)
                                                            </option>
                                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                                    </select>
                                                </div>
                                                <div class="col-4">
                                                    <button class="btn btn-sm btn-primary w-100" type="submit">Asignar</button>
                                                </div>
                                            </form>

                                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($assignedUsers->isEmpty()): ?>
                                                <div class="alert alert-light border mb-0 py-2">Sin usuarios asignados.</div>
                                            <?php else: ?>
                                                <div class="list-group list-group-flush">
                                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $assignedUsers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $assigned): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                                        <div class="list-group-item px-0 d-flex flex-wrap align-items-center justify-content-between gap-2">
                                                            <div>
                                                                <strong class="d-block"><?php echo e((string) ($assigned->nombre ?? '')); ?></strong>
                                                                <small class="text-muted"><?php echo e((string) ($assigned->email ?? '')); ?></small>
                                                            </div>
                                                            <form action="<?php echo e(route('sucursales.users.unassign', [$sucursal, $assigned])); ?>" method="post">
                                                                <?php echo csrf_field(); ?>
                                                                <button class="btn btn-sm btn-outline-danger" type="submit">Quitar</button>
                                                            </form>
                                                        </div>
                                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                                </div>
                                            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                        </div>
                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </div>
            </div>
        </div>

        <div class="col-xl-6">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <h2 class="h6 mb-3">Cajas por sucursal</h2>
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($sucursalesRows->isEmpty()): ?>
                        <p class="text-muted mb-0">Primero crea una sucursal para crear cajas.</p>
                    <?php else: ?>
                        <div class="accordion vx-branch-accordion" id="vxCashByBranchAccordion">
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $sucursalesRows; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $sucursal): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                <?php
                                    $branchId = (int) ($sucursal->id ?? 0);
                                    $branchBoxes = $cashBoxesByBranch->get($branchId, collect());
                                    $collapseId = 'vxCashBranch'.$branchId;
                                    $headerId = 'vxCashBranchHeading'.$branchId;
                                    $isFirst = $index === 0;
                                ?>

                                <div class="accordion-item">
                                    <h2 class="accordion-header" id="<?php echo e($headerId); ?>">
                                        <button
                                            class="accordion-button <?php echo e($isFirst ? '' : 'collapsed'); ?>"
                                            type="button"
                                            data-vx-collapse-target="#<?php echo e($collapseId); ?>"
                                            aria-expanded="<?php echo e($isFirst ? 'true' : 'false'); ?>"
                                            aria-controls="<?php echo e($collapseId); ?>"
                                        >
                                            <div class="d-flex align-items-center justify-content-between w-100 pe-3">
                                                <strong><?php echo e((string) ($sucursal->nombre ?? 'Sucursal')); ?></strong>
                                                <span class="badge text-bg-light border"><?php echo e($branchBoxes->count()); ?> cajas</span>
                                            </div>
                                        </button>
                                    </h2>

                                    <div
                                        id="<?php echo e($collapseId); ?>"
                                        class="accordion-collapse collapse <?php echo e($isFirst ? 'show' : ''); ?>"
                                        aria-labelledby="<?php echo e($headerId); ?>"
                                        data-vx-parent="#vxCashByBranchAccordion"
                                    >
                                        <div class="accordion-body">
                                            <form action="<?php echo e(route('sucursales.cash-boxes.store', $sucursal)); ?>" method="post" class="row g-2 mb-3">
                                                <?php echo csrf_field(); ?>
                                                <div class="col-8">
                                                    <input class="form-control form-control-sm" name="nombre" placeholder="Nombre de caja" required>
                                                </div>
                                                <div class="col-2 d-flex align-items-center">
                                                    <div class="form-check">
                                                        <input type="hidden" name="activa" value="0">
                                                        <input class="form-check-input" type="checkbox" name="activa" value="1" checked>
                                                    </div>
                                                </div>
                                                <div class="col-2">
                                                    <button class="btn btn-sm btn-primary w-100" type="submit">Crear</button>
                                                </div>
                                            </form>

                                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($branchBoxes->isEmpty()): ?>
                                                <div class="alert alert-light border mb-0 py-2">Sin cajas registradas.</div>
                                            <?php else: ?>
                                                <div class="list-group list-group-flush">
                                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $branchBoxes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $cashBox): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                                        <?php $activeBox = (string) ($cashBox->estado ?? '') === 'activa'; ?>
                                                        <div class="list-group-item px-0 d-flex flex-wrap align-items-center justify-content-between gap-2">
                                                            <div>
                                                                <strong class="d-block"><?php echo e((string) ($cashBox->nombre ?? '')); ?></strong>
                                                                <small class="text-muted"><?php echo e($activeBox ? 'Activa' : 'Inactiva'); ?></small>
                                                            </div>
                                                            <form action="<?php echo e(route('sucursales.cash-boxes.toggle', $cashBox)); ?>" method="post">
                                                                <?php echo csrf_field(); ?>
                                                                <input type="hidden" name="activa" value="<?php echo e($activeBox ? '0' : '1'); ?>">
                                                                <button class="btn btn-sm <?php echo e($activeBox ? 'btn-outline-secondary' : 'btn-outline-success'); ?>" type="submit">
                                                                    <?php echo e($activeBox ? 'Desactivar' : 'Activar'); ?>

                                                                </button>
                                                            </form>
                                                        </div>
                                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                                </div>
                                            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                        </div>
                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <script>
        window.addEventListener('DOMContentLoaded', () => {
            const bindLocalAccordions = () => {
                const buttons = Array.from(document.querySelectorAll('[data-vx-collapse-target]'));
                if (buttons.length === 0) {
                    return;
                }

                const closeCollapse = (button, collapse) => {
                    button.classList.add('collapsed');
                    button.setAttribute('aria-expanded', 'false');
                    collapse.classList.remove('show');
                };

                const openCollapse = (button, collapse) => {
                    button.classList.remove('collapsed');
                    button.setAttribute('aria-expanded', 'true');
                    collapse.classList.add('show');
                };

                buttons.forEach((button) => {
                    if (!(button instanceof HTMLButtonElement)) {
                        return;
                    }

                    button.addEventListener('click', () => {
                        const targetSelector = String(button.dataset.vxCollapseTarget || '').trim();
                        if (!targetSelector.startsWith('#')) {
                            return;
                        }

                        const collapse = document.querySelector(targetSelector);
                        if (!(collapse instanceof HTMLElement)) {
                            return;
                        }

                        const isOpen = collapse.classList.contains('show');
                        const parentSelector = String(collapse.dataset.vxParent || '').trim();

                        if (parentSelector !== '' && !isOpen) {
                            const parent = document.querySelector(parentSelector);
                            if (parent instanceof HTMLElement) {
                                const siblings = Array.from(parent.querySelectorAll('.accordion-collapse.show'));
                                siblings.forEach((sibling) => {
                                    if (!(sibling instanceof HTMLElement) || sibling === collapse) {
                                        return;
                                    }

                                    sibling.classList.remove('show');

                                    const siblingId = sibling.getAttribute('id');
                                    if (!siblingId) {
                                        return;
                                    }

                                    const siblingButton = parent.querySelector('[data-vx-collapse-target="#' + siblingId + '"]');
                                    if (siblingButton instanceof HTMLButtonElement) {
                                        siblingButton.classList.add('collapsed');
                                        siblingButton.setAttribute('aria-expanded', 'false');
                                    }
                                });
                            }
                        }

                        if (isOpen) {
                            closeCollapse(button, collapse);
                            return;
                        }

                        openCollapse(button, collapse);
                    });
                });
            };

            bindLocalAccordions();

            const searchInput = document.getElementById('vxBranchSearchInput');
            const cityOptions = <?php echo json_encode($cityOptions, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES, 512) ?>;
            const cityPickers = [];

            cityPickers.push({
                country: document.getElementById('vxCreateBranchCountry'),
                department: document.getElementById('vxCreateBranchDepartment'),
                citySelect: document.getElementById('vxCreateBranchCitySelect'),
            });

            document.querySelectorAll('[id^="vxBranchCountry"]').forEach((countrySelect) => {
                if (!(countrySelect instanceof HTMLSelectElement)) {
                    return;
                }

                const branchId = countrySelect.id.replace('vxBranchCountry', '');
                const department = document.getElementById('vxBranchDepartment' + branchId);
                const citySelect = document.getElementById('vxBranchCitySelect' + branchId);
                cityPickers.push({ country: countrySelect, department, citySelect });
            });

            const normalize = (value) => String(value || '')
                .normalize('NFD')
                .replace(/[\u0300-\u036f]/g, '')
                .toLowerCase()
                .trim();

            const cityById = new Map();
            cityOptions.forEach((city) => {
                cityById.set(Number(city.id), city);
            });

            const buildPicker = (picker) => {
                const { country, department, citySelect } = picker;
                if (
                    !(country instanceof HTMLSelectElement)
                    || !(department instanceof HTMLSelectElement)
                    || !(citySelect instanceof HTMLSelectElement)
                ) {
                    return;
                }

                const getSelectedCountryId = () => Number(country.value || 0);
                const getSelectedDepartment = () => String(department.value || '').trim();
                const getSelectedCityId = () => Number(citySelect.value || 0);
                const getInitialCityId = () => Number(citySelect.dataset.selected || citySelect.value || 0);
                const getInitialDepartment = () => String(department.dataset.selected || '').trim();

                const renderDepartmentOptions = (preferredDepartment = '') => {
                    const countryId = getSelectedCountryId();
                    department.innerHTML = '';

                    const emptyOption = document.createElement('option');
                    emptyOption.value = '';
                    emptyOption.textContent = 'Sin definir';
                    department.appendChild(emptyOption);

                    const departments = new Set();
                    cityOptions.forEach((city) => {
                        const cityCountryId = Number(city.country_id || 0);
                        if (countryId > 0 && cityCountryId !== countryId) {
                            return;
                        }

                        const departmentName = String(city.department || '').trim();
                        if (departmentName !== '') {
                            departments.add(departmentName);
                        }
                    });

                    const sortedDepartments = Array.from(departments)
                        .sort((a, b) => a.localeCompare(b, 'es', { sensitivity: 'base' }));

                    let hasPreferred = false;
                    sortedDepartments.forEach((departmentName) => {
                        const option = document.createElement('option');
                        option.value = departmentName;
                        option.textContent = departmentName;
                        if (departmentName === preferredDepartment) {
                            option.selected = true;
                            hasPreferred = true;
                        }
                        department.appendChild(option);
                    });

                    if (!hasPreferred) {
                        department.value = '';
                    }

                    department.disabled = sortedDepartments.length === 0;
                };

                const cityMatchesFilters = (city) => {
                    const countryId = getSelectedCountryId();
                    const cityCountryId = Number(city.country_id || 0);
                    if (countryId > 0 && cityCountryId !== countryId) {
                        return false;
                    }

                    const departmentName = getSelectedDepartment();
                    if (departmentName === '') {
                        return true;
                    }

                    return String(city.department || '').trim() === departmentName;
                };

                const renderCityOptions = (preferredCityId = 0) => {
                    citySelect.innerHTML = '';

                    const emptyOption = document.createElement('option');
                    emptyOption.value = '0';
                    emptyOption.textContent = 'Sin definir';
                    citySelect.appendChild(emptyOption);

                    let optionsCount = 0;
                    let hasPreferred = false;

                    cityOptions.forEach((city) => {
                        if (!cityMatchesFilters(city)) {
                            return;
                        }

                        const option = document.createElement('option');
                        option.value = String(Number(city.id) || 0);
                        option.textContent = String(city.name || '').trim();

                        if (Number(city.id) === Number(preferredCityId)) {
                            option.selected = true;
                            hasPreferred = true;
                        }

                        citySelect.appendChild(option);
                        optionsCount++;
                    });

                    if (!hasPreferred) {
                        citySelect.value = '0';
                    }

                    citySelect.disabled = optionsCount === 0;
                };

                const syncInitialState = () => {
                    const initialCityId = getInitialCityId();
                    const initialCity = cityById.get(initialCityId) || null;

                    if (initialCity && getSelectedCountryId() <= 0) {
                        country.value = String(initialCity.country_id || 0);
                    }

                    const preferredDepartment = getInitialDepartment() !== ''
                        ? getInitialDepartment()
                        : String(initialCity ? (initialCity.department || '') : '').trim();

                    renderDepartmentOptions(preferredDepartment);

                    const preferredCity = initialCity && cityMatchesFilters(initialCity)
                        ? initialCityId
                        : 0;

                    renderCityOptions(preferredCity);
                    department.dataset.selected = '';
                    citySelect.dataset.selected = '';
                };

                country.addEventListener('change', () => {
                    const selectedCity = cityById.get(getSelectedCityId()) || null;
                    const preferredDepartment = selectedCity && Number(selectedCity.country_id || 0) === getSelectedCountryId()
                        ? String(selectedCity.department || '').trim()
                        : '';

                    renderDepartmentOptions(preferredDepartment);

                    const preferred = selectedCity && cityMatchesFilters(selectedCity)
                        ? getSelectedCityId()
                        : 0;
                    renderCityOptions(preferred);
                });

                department.addEventListener('change', () => {
                    const selectedCity = cityById.get(getSelectedCityId()) || null;
                    const preferred = selectedCity && cityMatchesFilters(selectedCity)
                        ? getSelectedCityId()
                        : 0;
                    renderCityOptions(preferred);
                });

                syncInitialState();
            };

            cityPickers.forEach(buildPicker);

            if (!(searchInput instanceof HTMLInputElement)) {
                return;
            }

            const items = Array.from(document.querySelectorAll('.vx-branch-manage-item'));
            if (items.length === 0) {
                return;
            }

            searchInput.addEventListener('input', () => {
                const term = normalize(searchInput.value);
                items.forEach((item) => {
                    const haystack = normalize(item.getAttribute('data-search'));
                    const visible = term === '' || haystack.includes(term);
                    item.classList.toggle('d-none', !visible);
                });
            });
        });
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /Applications/XAMPP/xamppfiles/htdocs/veltrix-v2/resources/views/modules/sucursales/index.blade.php ENDPATH**/ ?>