<?php
$branches = is_array($branches ?? null) ? $branches : [];
$countries = is_array($countries ?? null) ? $countries : [];
$cities = is_array($cities ?? null) ? $cities : [];
$users = is_array($users ?? null) ? $users : [];
$cashBoxes = is_array($cashBoxes ?? null) ? $cashBoxes : [];
$branchLimit = is_array($branch_limit ?? null) ? $branch_limit : null;
$branchCount = (int) ($branch_count ?? count($branches));
$branchCanCreate = (bool) ($branch_can_create ?? true);
$branchPlanName = trim((string) (($branchLimit['plan_nombre'] ?? '') ?: 'Plan actual'));
$branchMax = is_array($branchLimit) ? max(0, (int) ($branchLimit['max_sucursales'] ?? 0)) : null;
$branchLimitReached = $branchMax !== null && !$branchCanCreate;

$usersByBranch = [];
$totalAssignedUsers = 0;
foreach ($users as $user) {
    $branchKey = (int) ($user['sucursal_id'] ?? 0);
    if ($branchKey <= 0) {
        continue;
    }
    if (!isset($usersByBranch[$branchKey])) {
        $usersByBranch[$branchKey] = [];
    }
    $usersByBranch[$branchKey][] = $user;
    $totalAssignedUsers++;
}

$cashBoxesByBranch = [];
foreach ($cashBoxes as $cashBox) {
    $branchKey = (int) ($cashBox['sucursal_id'] ?? 0);
    if ($branchKey <= 0) {
        continue;
    }
    if (!isset($cashBoxesByBranch[$branchKey])) {
        $cashBoxesByBranch[$branchKey] = [];
    }
    $cashBoxesByBranch[$branchKey][] = $cashBox;
}

$activeBranches = 0;
foreach ($branches as $branch) {
    if ((int) ($branch['activa'] ?? 0) === 1) {
        $activeBranches++;
    }
}

$planUsage = null;
if ($branchMax !== null && $branchMax > 0) {
    $planUsage = min(100, (int) round(($branchCount / $branchMax) * 100));
}

$citiesById = [];
$cityOptions = [];
foreach ($cities as $city) {
    $cityId = (int) ($city['id'] ?? 0);
    if ($cityId <= 0) {
        continue;
    }

    $countryId = (int) ($city['pais_id'] ?? 0);
    $cityName = trim((string) ($city['nombre'] ?? ''));
    $countryName = trim((string) ($city['pais'] ?? ''));
    $departmentName = trim((string) ($city['departamento'] ?? ''));
    $label = $cityName;
    if ($departmentName !== '') {
        $label .= ' - ' . $departmentName;
    }

    $cityData = [
        'id' => $cityId,
        'country_id' => $countryId,
        'name' => $cityName,
        'country' => $countryName,
        'department' => $departmentName,
        'label' => $label,
    ];
    $citiesById[$cityId] = $cityData;
    $cityOptions[] = $cityData;
}

$createSelectedCityId = (int) old('ciudad_id', '0');
$createSelectedCountryId = (int) old('pais_id', (string) ($citiesById[$createSelectedCityId]['country_id'] ?? 0));
if ($createSelectedCountryId <= 0 && $createSelectedCityId > 0) {
    $createSelectedCountryId = (int) ($citiesById[$createSelectedCityId]['country_id'] ?? 0);
}
$createSelectedDepartment = trim((string) old('departamento', (string) ($citiesById[$createSelectedCityId]['department'] ?? '')));
?>

<div class="row g-3 mb-3">
    <div class="col-sm-6 col-xl-3">
        <div class="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"><?= e((string) $branchCount) ?></p>
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-xl-3">
        <div class="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"><?= e((string) $activeBranches) ?></p>
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-xl-3">
        <div class="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"><?= e((string) $totalAssignedUsers) ?></p>
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-xl-3">
        <div class="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"><?= e((string) count($cashBoxes)) ?></p>
            </div>
        </div>
    </div>
</div>

<?php if ($branchMax !== null): ?>
    <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>
                    <small class="text-muted"><?= e($branchPlanName) ?> · <?= e((string) $branchCount) ?>/<?= e((string) $branchMax) ?> sucursales usadas</small>
                </div>
                <span class="badge <?= $branchLimitReached ? 'text-bg-warning' : 'text-bg-info' ?>">
                    <?= $branchLimitReached ? 'Límite alcanzado' : 'Disponible' ?>
                </span>
            </div>
            <?php if ($branchMax > 0): ?>
                <div class="progress" role="progressbar" aria-label="Uso de sucursales" aria-valuenow="<?= e((string) ($planUsage ?? 0)) ?>" aria-valuemin="0" aria-valuemax="100">
                    <div class="progress-bar <?= $branchLimitReached ? 'bg-warning text-dark' : 'bg-info' ?>" style="width: <?= e((string) ($planUsage ?? 0)) ?>%">
                        <?= e((string) ($planUsage ?? 0)) ?>%
                    </div>
                </div>
            <?php else: ?>
                <div class="alert alert-warning py-2 mb-0">Este plan no permite crear sucursales.</div>
            <?php endif; ?>
        </div>
    </div>
<?php endif; ?>

<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="<?= e(url('sucursales')) ?>" method="post">
                    <?= csrf_field() ?>
                    <div class="row g-2">
                        <div class="col-12">
                            <label class="form-label">Nombre</label>
                            <input class="form-control" name="nombre" value="<?= e((string) 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="<?= e((string) old('codigo', '')) ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Teléfono</label>
                            <input class="form-control" name="telefono" value="<?= e((string) old('telefono', '')) ?>">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Dirección</label>
                            <input class="form-control" name="direccion" value="<?= e((string) 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 foreach ($countries as $country): ?>
                                    <option value="<?= e((string) ($country['id'] ?? 0)) ?>" <?= $createSelectedCountryId === (int) ($country['id'] ?? 0) ? 'selected' : '' ?>>
                                        <?= e((string) ($country['nombre'] ?? '')) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Departamento</label>
                            <select class="form-select" name="departamento" id="vxCreateBranchDepartment" data-selected="<?= 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="<?= e((string) $createSelectedCityId) ?>">
                                <option value="0">Sin definir</option>
                            </select>
                            <?php if ($cityOptions === []): ?>
                                <small class="text-muted d-block mt-1">No hay ciudades cargadas. Importa el catálogo DANE.</small>
                            <?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" <?= (string) old('activa', '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" <?= $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 ($branches === []): ?>
                    <div class="alert alert-light border mb-0">No hay sucursales creadas.</div>
                <?php else: ?>
                    <div class="accordion vx-branch-accordion" id="vxBranchManageAccordion">
                        <?php foreach ($branches as $index => $branch): ?>
                            <?php
                            $branchId = (int) ($branch['id'] ?? 0);
                            $branchName = trim((string) ($branch['nombre'] ?? 'Sucursal'));
                            $branchCode = trim((string) ($branch['codigo'] ?? ''));
                            $branchCity = trim((string) ($branch['ciudad'] ?? 'Sin ciudad'));
                            $branchPhone = trim((string) ($branch['telefono'] ?? ''));
                            $branchAddress = trim((string) ($branch['direccion'] ?? ''));
                            $branchActive = (int) ($branch['activa'] ?? 0) === 1;
                            $branchSelectedCityId = (int) ($branch['ciudad_id'] ?? 0);
                            $branchSelectedCountryId = (int) ($citiesById[$branchSelectedCityId]['country_id'] ?? 0);
                            $branchSelectedDepartment = trim((string) ($citiesById[$branchSelectedCityId]['department'] ?? ''));
                            $assignedUsers = $usersByBranch[$branchId] ?? [];
                            $boxes = $cashBoxesByBranch[$branchId] ?? [];
                            $collapseId = 'vxBranchManage' . $branchId;
                            $headerId = 'vxBranchManageHeading' . $branchId;
                            $isFirst = $index === 0;
                            $searchIndex = strtolower(trim($branchName . ' ' . $branchCode . ' ' . $branchCity));
                            ?>
                            <div class="accordion-item vx-branch-manage-item" data-search="<?= e($searchIndex) ?>">
                                <h2 class="accordion-header" id="<?= e($headerId) ?>">
                                    <button class="accordion-button <?= $isFirst ? '' : 'collapsed' ?>" type="button" data-bs-toggle="collapse" data-bs-target="#<?= e($collapseId) ?>" aria-expanded="<?= $isFirst ? 'true' : 'false' ?>" aria-controls="<?= e($collapseId) ?>">
                                        <div class="vx-branch-head">
                                            <div>
                                                <strong><?= e($branchName) ?></strong>
                                                <small><?= e($branchCity) ?><?= $branchCode !== '' ? ' · ' . e($branchCode) : '' ?></small>
                                            </div>
                                            <div class="vx-branch-head-meta">
                                                <span class="badge <?= $branchActive ? 'text-bg-success' : 'text-bg-secondary' ?>">
                                                    <?= $branchActive ? 'Activa' : 'Inactiva' ?>
                                                </span>
                                                <span class="badge text-bg-light border"><?= e((string) count($assignedUsers)) ?> usuarios</span>
                                                <span class="badge text-bg-light border"><?= e((string) count($boxes)) ?> cajas</span>
                                            </div>
                                        </div>
                                    </button>
                                </h2>
                                <div id="<?= e($collapseId) ?>" class="accordion-collapse collapse <?= $isFirst ? 'show' : '' ?>" aria-labelledby="<?= e($headerId) ?>" data-bs-parent="#vxBranchManageAccordion">
                                    <div class="accordion-body">
                                        <form action="<?= e(url('sucursales/' . $branchId . '/actualizar')) ?>" method="post" class="row g-2">
                                            <?= csrf_field() ?>
                                            <div class="col-md-6">
                                                <label class="form-label">Nombre</label>
                                                <input class="form-control form-control-sm" name="nombre" value="<?= e($branchName) ?>" required>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Código</label>
                                                <input class="form-control form-control-sm" name="codigo" value="<?= e($branchCode) ?>">
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Teléfono</label>
                                                <input class="form-control form-control-sm" name="telefono" value="<?= e($branchPhone) ?>">
                                            </div>
                                            <div class="col-md-4">
                                                <label class="form-label">Pais</label>
                                                <select class="form-select form-select-sm" name="pais_id" id="vxBranchCountry<?= e((string) $branchId) ?>">
                                                    <option value="0">Sin definir</option>
                                                    <?php foreach ($countries as $country): ?>
                                                        <option value="<?= e((string) ($country['id'] ?? 0)) ?>" <?= $branchSelectedCountryId === (int) ($country['id'] ?? 0) ? 'selected' : '' ?>>
                                                            <?= e((string) ($country['nombre'] ?? '')) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-4">
                                                <label class="form-label">Departamento</label>
                                                <select
                                                    class="form-select form-select-sm"
                                                    name="departamento"
                                                    id="vxBranchDepartment<?= e((string) $branchId) ?>"
                                                    data-selected="<?= e($branchSelectedDepartment) ?>"
                                                >
                                                    <option value="">Sin definir</option>
                                                </select>
                                            </div>
                                            <div class="col-md-4">
                                                <label class="form-label">Municipio</label>
                                                <select
                                                    class="form-select form-select-sm"
                                                    name="ciudad_id"
                                                    id="vxBranchCitySelect<?= e((string) $branchId) ?>"
                                                    data-selected="<?= e((string) $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="<?= e($branchAddress) ?>">
                                            </div>
                                            <div class="col-12 d-flex flex-wrap align-items-center justify-content-between gap-2 mt-2">
                                                <small class="text-muted">Creada: <?= e((string) ($branch['created_at'] ?? '-')) ?></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="<?= e(url('sucursales/' . $branchId . '/estado')) ?>" method="post" class="mt-2">
                                            <?= csrf_field() ?>
                                            <input type="hidden" name="activa" value="<?= $branchActive ? '0' : '1' ?>">
                                            <button class="btn btn-sm <?= $branchActive ? 'btn-outline-secondary' : 'btn-outline-success' ?>" type="submit">
                                                <i class="bx <?= $branchActive ? 'bx-pause-circle' : 'bx-play-circle' ?> me-1"></i>
                                                <?= $branchActive ? 'Desactivar sucursal' : 'Activar sucursal' ?>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?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 ($branches === []): ?>
                    <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 foreach ($branches as $index => $branch): ?>
                            <?php
                            $branchId = (int) ($branch['id'] ?? 0);
                            $branchName = trim((string) ($branch['nombre'] ?? 'Sucursal'));
                            $assignedUsers = $usersByBranch[$branchId] ?? [];
                            $collapseId = 'vxUsersBranch' . $branchId;
                            $headerId = 'vxUsersBranchHeading' . $branchId;
                            $isFirst = $index === 0;
                            ?>
                            <div class="accordion-item">
                                <h2 class="accordion-header" id="<?= e($headerId) ?>">
                                    <button class="accordion-button <?= $isFirst ? '' : 'collapsed' ?>" type="button" data-bs-toggle="collapse" data-bs-target="#<?= e($collapseId) ?>" aria-expanded="<?= $isFirst ? 'true' : 'false' ?>" aria-controls="<?= e($collapseId) ?>">
                                        <div class="d-flex align-items-center justify-content-between w-100 pe-3">
                                            <strong><?= e($branchName) ?></strong>
                                            <span class="badge text-bg-light border"><?= e((string) count($assignedUsers)) ?> asignados</span>
                                        </div>
                                    </button>
                                </h2>
                                <div id="<?= e($collapseId) ?>" class="accordion-collapse collapse <?= $isFirst ? 'show' : '' ?>" aria-labelledby="<?= e($headerId) ?>" data-bs-parent="#vxUsersByBranchAccordion">
                                    <div class="accordion-body">
                                        <form action="<?= e(url('sucursales/' . $branchId . '/usuarios')) ?>" method="post" class="row g-2 mb-3">
                                            <?= csrf_field() ?>
                                            <div class="col-8">
                                                <select class="form-select form-select-sm" name="usuario_id" required>
                                                    <option value="">Selecciona usuario</option>
                                                    <?php foreach ($users as $user): ?>
                                                        <option value="<?= e((string) $user['id']) ?>">
                                                            <?= e((string) ($user['nombre'] ?? '')) ?> (<?= e((string) ($user['email'] ?? '')) ?>)
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-4">
                                                <button class="btn btn-sm btn-primary w-100" type="submit">Asignar</button>
                                            </div>
                                        </form>

                                        <?php if ($assignedUsers === []): ?>
                                            <div class="alert alert-light border mb-0 py-2">Sin usuarios asignados.</div>
                                        <?php else: ?>
                                            <div class="list-group list-group-flush">
                                                <?php foreach ($assignedUsers as $assigned): ?>
                                                    <div class="list-group-item px-0 d-flex flex-wrap align-items-center justify-content-between gap-2">
                                                        <div>
                                                            <strong class="d-block"><?= e((string) ($assigned['nombre'] ?? '')) ?></strong>
                                                            <small class="text-muted"><?= e((string) ($assigned['email'] ?? '')) ?></small>
                                                        </div>
                                                        <form action="<?= e(url('sucursales/' . $branchId . '/usuarios/' . (int) ($assigned['id'] ?? 0) . '/quitar')) ?>" method="post">
                                                            <?= csrf_field() ?>
                                                            <button class="btn btn-sm btn-outline-danger" type="submit">Quitar</button>
                                                        </form>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?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 ($branches === []): ?>
                    <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 foreach ($branches as $index => $branch): ?>
                            <?php
                            $branchId = (int) ($branch['id'] ?? 0);
                            $branchName = trim((string) ($branch['nombre'] ?? 'Sucursal'));
                            $branchBoxes = $cashBoxesByBranch[$branchId] ?? [];
                            $collapseId = 'vxCashBranch' . $branchId;
                            $headerId = 'vxCashBranchHeading' . $branchId;
                            $isFirst = $index === 0;
                            ?>
                            <div class="accordion-item">
                                <h2 class="accordion-header" id="<?= e($headerId) ?>">
                                    <button class="accordion-button <?= $isFirst ? '' : 'collapsed' ?>" type="button" data-bs-toggle="collapse" data-bs-target="#<?= e($collapseId) ?>" aria-expanded="<?= $isFirst ? 'true' : 'false' ?>" aria-controls="<?= e($collapseId) ?>">
                                        <div class="d-flex align-items-center justify-content-between w-100 pe-3">
                                            <strong><?= e($branchName) ?></strong>
                                            <span class="badge text-bg-light border"><?= e((string) count($branchBoxes)) ?> cajas</span>
                                        </div>
                                    </button>
                                </h2>
                                <div id="<?= e($collapseId) ?>" class="accordion-collapse collapse <?= $isFirst ? 'show' : '' ?>" aria-labelledby="<?= e($headerId) ?>" data-bs-parent="#vxCashByBranchAccordion">
                                    <div class="accordion-body">
                                        <form action="<?= e(url('sucursales/' . $branchId . '/cajas')) ?>" method="post" class="row g-2 mb-3">
                                            <?= 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 ($branchBoxes === []): ?>
                                            <div class="alert alert-light border mb-0 py-2">Sin cajas registradas.</div>
                                        <?php else: ?>
                                            <div class="list-group list-group-flush">
                                                <?php foreach ($branchBoxes as $cashBox): ?>
                                                    <?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"><?= e((string) ($cashBox['nombre'] ?? '')) ?></strong>
                                                            <small class="text-muted"><?= $activeBox ? 'Activa' : 'Inactiva' ?></small>
                                                        </div>
                                                        <form action="<?= e(url('sucursales/cajas/' . (int) ($cashBox['id'] ?? 0) . '/estado')) ?>" method="post">
                                                            <?= csrf_field() ?>
                                                            <input type="hidden" name="activa" value="<?= $activeBox ? '0' : '1' ?>">
                                                            <button class="btn btn-sm <?= $activeBox ? 'btn-outline-secondary' : 'btn-outline-success' ?>" type="submit">
                                                                <?= $activeBox ? 'Desactivar' : 'Activar' ?>
                                                            </button>
                                                        </form>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
    window.addEventListener('DOMContentLoaded', () => {
        const searchInput = document.getElementById('vxBranchSearchInput');
        const cityOptions = <?= json_encode(
            $cityOptions,
            JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT
        ) ?>;
        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: department,
                citySelect: 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>
