<style>
    /* Alineación vertical perfecta de checkboxes */
    .checkbox-center-aligned {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        margin: 0;
        padding: 0;
        min-height: 1.5rem; /* Altura mínima consistente */
    }

    .checkbox-center-aligned .form-check-input {
        margin: 0;
        float: none;
        position: static; /* Evita desplazamientos por position relative */
        vertical-align: middle;
        flex-shrink: 0; /* Evita que el checkbox se encoja */
    }

    .checkbox-center-aligned .form-check-label {
        margin-left: 0.25rem;
        padding: 0;
        display: inline-flex;
        align-items: center;
        line-height: 1; /* Normaliza la altura de línea */
    }

    /* Asegurar que las celdas tengan la misma altura y alineación */
    .table td.text-center,
    .table td.table-warning {
        vertical-align: middle;
        padding-top: 0.5rem;
        padding-bottom: 0.5rem;
    }

    /* Resaltado de coincidencias de búsqueda */
    .search-highlight {
        background-color: #ffeb3b;
        padding: 2px 4px;
        border-radius: 3px;
        transition: background-color 0.3s ease;
    }
</style>

<form action="" method="post" onsubmit="animateSpinner('add')">
    {{ formToken() }}
    <input type="hidden" name="action" value="edit-rules"/>
    <input type="hidden" name="activetab" value="{{ fsc.getCurrentView().getViewName() }}"/>
    <div class="card shadow">
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col">
                    <h5 class="mb-0">
                        <i class="fa-solid fa-user-lock me-2"></i>
                        {{ trans('permissions-by-page') }}
                    </h5>
                </div>
                <div class="col-auto">
                    <button type="submit" class="btn btn-sm btn-outline-primary btn-spin-action">
                        <i class="fa-solid fa-save fa-fw"></i> {{ trans('save') }}
                    </button>
                </div>
            </div>
        </div>
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead>
                <tr class="align-middle">
                    <th>
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="fa-solid fa-search"></i>
                            </span>
                            <input type="text" class="form-control" id="search-menu"
                                   placeholder="{{ trans('search') }}"/>
                        </div>
                    </th>
                    <th class="text-center">{{ trans('show') }}</th>
                    <th class="table-warning text-center">{{ trans('only-owner-data') }}</th>
                    <th class="text-center">{{ trans('allow-update') }}</th>
                    <th class="text-center">{{ trans('allow-import') }}</th>
                    <th class="text-center">{{ trans('allow-export') }}</th>
                    <th class="text-center">{{ trans('allow-delete') }}</th>
                </tr>
                </thead>
                <tbody>
                {% set menu = 'TodosMenus' %}
                <tr id="tr{{ menu }}">
                    <td>
                        <b>{{ trans('all') }}</b>
                    </td>
                    <td class="text-center">
                        <div class="form-check checkbox-center-aligned">
                            <input class="all-permission form-check-input" id="checkbox-all-show" value="show"
                                   type="checkbox" data-menu="{{ menu }}" data-type="show"
                                   aria-label="{{ trans('show') }} - {{ trans('all') }}"/>
                        </div>
                    </td>
                    <td class="table-warning text-center">
                        <div class="form-check checkbox-center-aligned">
                            <input class="all-permission form-check-input" id="checkbox-all-onlyOwner"
                                   value="only-owner" type="checkbox" data-menu="{{ menu }}" data-type="only-owner"
                                   aria-label="{{ trans('only-owner-data') }} - {{ trans('all') }}"/>
                        </div>
                    </td>
                    <td class="text-center">
                        <div class="form-check checkbox-center-aligned">
                            <input class="all-permission form-check-input" id="checkbox-all-update" value="update"
                                   type="checkbox" data-menu="{{ menu }}" data-type="update"
                                   aria-label="{{ trans('allow-update') }} - {{ trans('all') }}"/>
                        </div>
                    </td>
                    <td class="text-center">
                        <div class="form-check checkbox-center-aligned">
                            <input class="all-permission form-check-input" id="checkbox-all-import" value="import"
                                   type="checkbox" data-menu="{{ menu }}" data-type="import"
                                   aria-label="{{ trans('allow-import') }} - {{ trans('all') }}"/>
                        </div>
                    </td>
                    <td class="text-center">
                        <div class="form-check checkbox-center-aligned">
                            <input class="all-permission form-check-input" id="checkbox-all-export" value="export"
                                   type="checkbox" data-menu="{{ menu }}" data-type="export"
                                   aria-label="{{ trans('allow-export') }} - {{ trans('all') }}"/>
                        </div>
                    </td>
                    <td class="text-center">
                        <div class="form-check checkbox-center-aligned">
                            <input class="all-permission form-check-input" id="checkbox-all-delete" value="delete"
                                   type="checkbox" data-menu="{{ menu }}" data-type="delete"
                                   aria-label="{{ trans('allow-delete') }} - {{ trans('all') }}"/>
                        </div>
                    </td>
                </tr>
                {% for pageName, rule in fsc.getAccessRules() %}
                    {% if rule.menu|replace({' ': ''}) != menu %}
                        {% set menu = rule.menu|replace({' ': ''}) %}
                        <tr class="table-secondary" id="tr{{ menu }}">
                            <td>
                                <span style="cursor:pointer" onclick="toggleMenu('{{ menu }}')">
                                    <i id="plus{{ menu }}" class="fa-regular fa-plus-square"></i>
                                    <i id="minus{{ menu }}" class="fa-regular fa-minus-square d-none"></i>
                                    <b>{{ trans('menu') }} {{ menu }}</b>
                                </span>
                            </td>
                            <td class="text-center">
                                <div class="form-check checkbox-center-aligned">
                                    <input class="all-menu-permission show-menu-permission form-check-input"
                                           id="checkbox-all-menu-show-{{ menu }}" value="show-{{ menu }}"
                                           type="checkbox" data-menu="{{ menu }}" data-type="show"
                                           aria-label="{{ trans('show') }} - {{ menu }}"/>
                                    <label class="form-check-label label-contador"
                                           for="checkbox-all-menu-show-{{ menu }}" data-menu="{{ menu }}"
                                           data-type="show" aria-hidden="true">&nbsp;</label>
                                </div>
                            </td>
                            <td class="table-warning text-center">
                                <div class="form-check checkbox-center-aligned">
                                    <input class="all-menu-permission only-owner-menu-permission form-check-input"
                                           id="checkbox-all-menu-only-owner-{{ menu }}" value="only-owner-{{ menu }}"
                                           type="checkbox" data-menu="{{ menu }}" data-type="only-owner"
                                           aria-label="{{ trans('only-owner-data') }} - {{ menu }}"/>
                                    <label class="form-check-label label-contador"
                                           for="checkbox-all-menu-only-owner-{{ menu }}" data-menu="{{ menu }}"
                                           data-type="only-owner" aria-hidden="true">&nbsp;</label>
                                </div>
                            </td>
                            <td class="text-center">
                                <div class="form-check checkbox-center-aligned">
                                    <input class="all-menu-permission update-menu-permission form-check-input"
                                           id="checkbox-all-menu-update-{{ menu }}" value="update-{{ menu }}"
                                           type="checkbox" data-menu="{{ menu }}" data-type="update"
                                           aria-label="{{ trans('allow-update') }} - {{ menu }}"/>
                                    <label class="form-check-label label-contador"
                                           for="checkbox-all-menu-update-{{ menu }}" data-menu="{{ menu }}"
                                           data-type="update" aria-hidden="true">&nbsp;</label>
                                </div>
                            </td>
                            <td class="text-center">
                                <div class="form-check checkbox-center-aligned">
                                    <input class="all-menu-permission import-menu-permission form-check-input"
                                           id="checkbox-all-menu-import-{{ menu }}" value="import-{{ menu }}"
                                           type="checkbox" data-menu="{{ menu }}" data-type="import"
                                           aria-label="{{ trans('allow-import') }} - {{ menu }}"/>
                                    <label class="form-check-label label-contador"
                                           for="checkbox-all-menu-import-{{ menu }}" data-menu="{{ menu }}"
                                           data-type="import" aria-hidden="true">&nbsp;</label>
                                </div>
                            </td>
                            <td class="text-center">
                                <div class="form-check checkbox-center-aligned">
                                    <input class="all-menu-permission export-menu-permission form-check-input"
                                           id="checkbox-all-menu-export-{{ menu }}" value="export-{{ menu }}"
                                           type="checkbox" data-menu="{{ menu }}" data-type="export"
                                           aria-label="{{ trans('allow-export') }} - {{ menu }}"/>
                                    <label class="form-check-label label-contador"
                                           for="checkbox-all-menu-export-{{ menu }}" data-menu="{{ menu }}"
                                           data-type="export" aria-hidden="true">&nbsp;</label>
                                </div>
                            </td>
                            <td class="text-center">
                                <div class="form-check checkbox-center-aligned">
                                    <input class="all-menu-permission delete-menu-permission form-check-input"
                                           id="checkbox-all-menu-delete-{{ menu }}" value="delete-{{ menu }}"
                                           type="checkbox" data-menu="{{ menu }}" data-type="delete"
                                           aria-label="{{ trans('allow-delete') }} - {{ menu }}"/>
                                    <label class="form-check-label label-contador"
                                           for="checkbox-all-menu-delete-{{ menu }}" data-menu="{{ menu }}"
                                           data-type="delete" aria-hidden="true">&nbsp;</label>
                                </div>
                            </td>
                        </tr>
                    {% endif %}
                    <tr class="d-none tr{{ menu }}">
                        <td>
                            {{ ((rule.submenu is not empty) ? ' » ' ~ rule.submenu : '') ~ ' » ' ~ rule.page }}
                            {% if 'List' in pageName %}
                                <span class="badge bg-info ms-1">{{ trans('list') }}</span>
                            {% endif %}
                            <div class="small text-secondary">
                                {{ trans('controller') }}: <span class="controller-name">{{ pageName }}</span>
                            </div>
                        </td>
                        <td class="text-center">
                            <div class="form-check checkbox-center-aligned">
                                <input class="permission show-permission show-menu-permission show-{{ menu }}-permission form-check-input"
                                       id="checkbox-large-show-{{ pageName }}" type="checkbox" name="show[]"
                                       data-menu="{{ menu }}" data-type="show" value="{{ pageName }}"
                                       {% if rule.show %}checked{% endif %}
                                       aria-label="{{ trans('show') }} - {{ pageName }}"/>
                            </div>
                        </td>
                        <td class="table-warning text-center">
                            <div class="form-check checkbox-center-aligned">
                                <input class="permission only-owner-permission only-owner-menu-permission only-owner-{{ menu }}-permission form-check-input"
                                       id="checkbox-large-onlyOwner-{{ pageName }}" type="checkbox" name="onlyOwner[]"
                                       data-menu="{{ menu }}" data-type="only-owner" value="{{ pageName }}"
                                       {% if rule.onlyOwner %}checked{% endif %}
                                       aria-label="{{ trans('only-owner-data') }} - {{ pageName }}"/>
                                <label class="form-check-label"
                                       for="checkbox-large-onlyOwner-{{ pageName }}" aria-hidden="true">
                                    <i class="fa-solid fa-lock text-secondary"></i>
                                </label>
                            </div>
                        </td>
                        <td class="text-center">
                            <div class="form-check checkbox-center-aligned">
                                <input class="permission update-permission update-menu-permission update-{{ menu }}-permission form-check-input"
                                       id="checkbox-large-update-{{ pageName }}" type="checkbox" name="update[]"
                                       data-menu="{{ menu }}" data-type="update"
                                       value="{{ pageName }}" {% if rule.update %} checked{% endif %}
                                       aria-label="{{ trans('allow-update') }} - {{ pageName }}"/>
                            </div>
                        </td>
                        <td class="text-center">
                            <div class="form-check checkbox-center-aligned">
                                <input class="permission import-permission import-menu-permission import-{{ menu }}-permission form-check-input"
                                       id="checkbox-large-import-{{ pageName }}" type="checkbox" name="import[]"
                                       data-menu="{{ menu }}" data-type="import"
                                       value="{{ pageName }}" {% if rule.import %} checked{% endif %}
                                       aria-label="{{ trans('allow-import') }} - {{ pageName }}"/>
                            </div>
                        </td>
                        <td class="text-center">
                            <div class="form-check checkbox-center-aligned">
                                <input class="permission export-permission export-menu-permission export-{{ menu }}-permission form-check-input"
                                       id="checkbox-large-export-{{ pageName }}" type="checkbox" name="export[]"
                                       data-menu="{{ menu }}" data-type="export"
                                       value="{{ pageName }}" {% if rule.export %} checked{% endif %}
                                       aria-label="{{ trans('allow-export') }} - {{ pageName }}"/>
                            </div>
                        </td>
                        <td class="text-center">
                            <div class="form-check checkbox-center-aligned">
                                <input class="permission delete-permission delete-menu-permission delete-{{ menu }}-permission form-check-input"
                                       id="checkbox-large-delete-{{ pageName }}" type="checkbox" name="delete[]"
                                       data-menu="{{ menu }}" data-type="delete"
                                       value="{{ pageName }}" {% if rule.delete %} checked{% endif %}
                                       aria-label="{{ trans('allow-delete') }} - {{ pageName }}"/>
                            </div>
                        </td>
                    </tr>
                {% else %}
                    <tr class="table-warning">
                        <td colspan="7">
                            {{ trans('no-data') }}
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
        <div class="card-footer">
            <div class="row align-items-center">
                <div class="col">
                    <p class="mb-0">
                        <i class="fa-solid fa-lock me-1"></i> {{ trans('only-owner-data-p') }}
                    </p>
                </div>
                <div class="col-auto">
                    <button type="submit" class="btn btn-primary btn-spin-action">
                        <i class="fa-solid fa-save fa-fw"></i> {{ trans('save') }}
                    </button>
                </div>
            </div>
        </div>
    </div>
</form>

<script>
    $(document).ready(function () {
        let searchTimeout;

        // Búsqueda de controladores (optimizada)
        $('#search-menu').on('input', function () {
            clearTimeout(searchTimeout);

            searchTimeout = setTimeout(function () {
                const searchValue = $('#search-menu').val().toLowerCase().trim();
                const $controllerNames = $('.controller-name');

                // Eliminar resaltado anterior
                $controllerNames.removeClass('search-highlight');

                // Si el input está vacío, colapsar todos los menús
                if (searchValue === '') {
                    $('tr[class^="tr"]').addClass('d-none');
                    $('i[id^="plus"]').removeClass('d-none');
                    $('i[id^="minus"]').addClass('d-none');
                    return;
                }

                // Buscar coincidencias usando filter (más eficiente)
                const foundMenus = new Set();
                const $matches = $controllerNames.filter(function () {
                    return $(this).text().toLowerCase().includes(searchValue);
                }).addClass('search-highlight');

                // Extraer menús de las coincidencias
                $matches.each(function () {
                    const classes = $(this).closest('tr').attr('class');
                    if (classes) {
                        const menuMatch = classes.match(/tr([^\s]+)/);
                        if (menuMatch && menuMatch[1]) {
                            foundMenus.add(menuMatch[1]);
                        }
                    }
                });

                // Primero colapsar todos los menús
                $('tr[class^="tr"]').addClass('d-none');
                $('i[id^="plus"]').removeClass('d-none');
                $('i[id^="minus"]').addClass('d-none');

                // Expandir solo los menús que tienen coincidencias
                foundMenus.forEach(function (menu) {
                    $('tr.tr' + menu).removeClass('d-none');
                    $('#plus' + menu).addClass('d-none');
                    $('#minus' + menu).removeClass('d-none');
                });

                // Hacer scroll suave al primer resultado
                if ($matches.length > 0) {
                    const firstElement = $matches.first().closest('tr')[0];
                    if (firstElement && firstElement.scrollIntoView) {
                        firstElement.scrollIntoView({
                            behavior: 'smooth',
                            block: 'center'
                        });
                    }
                }
            }, 300); // 300 milisegundos de debounce
        });

        // Individuales
        $('input[type="checkbox"].permission').change(function () {
            if (this.checked && 'show' !== $(this).data('type')) {
                $(this).parent().parent().parent().find('input.show-permission').prop('checked', true).change();
            }
            if (!this.checked && $(this).data('type') === 'show') {
                $("#tr" + $(this).data("menu")).find('input').prop('checked', false);
                $(this).parent().parent().parent().find('input.only-owner-permission, input.update-permission, input.import-permission, input.export-permission, input.delete-permission').prop('checked', false).change();
            }
            if (!this.checked && 'show' !== $(this).data('type')) {
                $("#trTodosMenus").find('input[data-type=' + $(this).data('type') + ']').prop('checked', false);
                $("#tr" + $(this).data("menu")).find('input[data-type=' + $(this).data('type') + ']').prop('checked', false);
            }
            let cuenta = countChecked($(this).data('type'), $(this).data('menu'));
            let selector = "label[for='checkbox-all-menu-" + $(this).data('type') + "-" + $(this).data('menu') + "']";
            if ('' !== cuenta) {
                $(selector).html('<span class="badge bg-info">' + cuenta + '</span>');
                if (cuenta === '{{ trans('all') }}') {
                    $(selector).parent().parent().parent().find('input.' + $(this).data('type') + '-menu-permission').prop('checked', true);
                }
            } else {
                $(selector).html('&nbsp;');
            }

            if ($("#tr" + $(this).data("menu")).find('input:not(:checked)').length === 0) {
                $("#tr" + $(this).data("menu")).removeClass('table-secondary').addClass('table-success');
            } else {
                $("#tr" + $(this).data("menu")).removeClass('table-success').addClass('table-secondary');
            }
        });

        // Todo el menú
        $('input[type="checkbox"].all-menu-permission').change(function () {
            $('input.' + this.value + '-permission').prop('checked', this.checked).change();
        });

        // Todos
        $('input[type="checkbox"].all-permission').change(function () {
            $('input.' + this.value + '-menu-permission').prop('checked', this.checked).change();
        });

        $('label.label-contador').each(function () {
            let cuenta = countChecked($(this).data('type'), $(this).data('menu'));
            if ('' !== cuenta) {
                $(this).html('<span class="badge bg-info">' + cuenta + '</span>');
                if (cuenta === '{{ trans('all') }}') {
                    $(this).parent().parent().parent().find('input.' + $(this).data('type') + '-menu-permission').prop('checked', true);
                }
            } else {
                $(this).html('&nbsp;');
            }
        });
    });

    function countChecked(type, menu) {
        let numchecked = $("input[data-type='" + type + "'][data-menu='" + menu + "'].permission:checked").length;
        let numunchecked = $("input[data-type='" + type + "'][data-menu='" + menu + "'].permission").length;
        if (numchecked === 0) {
            return '';
        }
        if (numchecked === numunchecked) {
            return '{{ trans('all') }}';
        }
        return numchecked + '/' + numunchecked;
    }

    function toggleMenu(menu) {
        $('#plus' + menu + ', #minus' + menu + ', tr.tr' + menu).toggleClass('d-none');
    }
</script>