(function () {
    function ready(fn) {
        if (document.readyState !== 'loading') {
            fn();
        } else {
            document.addEventListener('DOMContentLoaded', fn);
        }
    }



    function syncAllAcrChecklists(root) {
        (root || document).querySelectorAll('.tiaur-acr-value-checklist').forEach(function (checklist) {
            syncSelectFromChecklist(checklist);
        });
    }

    ready(function () {


    document.addEventListener('click', function (event) {
        var target = event.target && event.target.closest ? event.target.closest('[data-tiaur-confirm]') : null;
        if (!target) {
            return;
        }
        var message = target.getAttribute('data-tiaur-confirm') || 'Are you sure?';
        if (!window.confirm(message)) {
            event.preventDefault();
        }
    });
        var app = document.getElementById('tiaur-admin-app');
        if (app) {
            app.classList.remove('tiaur-loading');
            app.classList.add('tiaur-ready');
        }

        setTimeout(function () {
            if (app && app.classList.contains('tiaur-loading')) {
                app.classList.remove('tiaur-loading');
                app.classList.add('tiaur-ready');
            }
        }, 1500);


        var tiaurProfileRolesTemplate = document.querySelector('.tiaur-profile-roles-template');
        if (tiaurProfileRolesTemplate) {
            var defaultRoleSelect = document.querySelector('select#role');
            if (defaultRoleSelect) {
                var defaultRoleRow = defaultRoleSelect.closest('tr');
                if (defaultRoleRow) {
                    var cell = defaultRoleRow.querySelector('td');
                    if (cell) {
                        cell.innerHTML = '';
                        while (tiaurProfileRolesTemplate.firstChild) {
                            cell.appendChild(tiaurProfileRolesTemplate.firstChild);
                        }
                        defaultRoleRow.classList.add('tiaur-profile-roles-row');
                    }
                    tiaurProfileRolesTemplate.remove();
                }
            } else {
                tiaurProfileRolesTemplate.style.display = '';
            }
        }


        document.querySelectorAll('.tiaur-profile-role-line input[type="checkbox"][value="administrator"]').forEach(function (checkbox) {
            checkbox.addEventListener('change', function () {
                if (!checkbox.checked) {
                    return;
                }
                var ok = window.confirm('You are about to give this user the Administrator role. Are you sure?');
                if (!ok) {
                    checkbox.checked = false;
                }
            });
        });

        document.querySelectorAll('.tiaur-role-select-nav').forEach(function (select) {
            select.addEventListener('change', function () {
                if (select.value) {
                    var shell = select.closest('.tiaur-select-shell');
                    if (shell) {
                        shell.classList.add('tiaur-is-loading');
                    }
                    window.location.href = select.value;
                }
            });
        });


        document.querySelectorAll('.tiaur-role-nav-picker').forEach(function (picker) {
            function closeAll() {
                document.querySelectorAll('.tiaur-role-nav-picker.is-open').forEach(function (openPicker) {
                    openPicker.classList.remove('is-open');
                    openPicker.setAttribute('aria-expanded', 'false');
                    var openCard = openPicker.closest('.tiaur-role-tools-card');
                    if (openCard) {
                        openCard.classList.remove('tiaur-role-dropdown-open');
                    }
                    var openTool = openPicker.closest('.tiaur-role-tool');
                    if (openTool) {
                        openTool.classList.remove('tiaur-role-dropdown-open');
                    }
                });
            }
            function togglePicker() {
                var isOpen = picker.classList.contains('is-open');
                closeAll();
                if (!isOpen) {
                    picker.classList.add('is-open');
                    picker.setAttribute('aria-expanded', 'true');
                    var card = picker.closest('.tiaur-role-tools-card');
                    if (card) {
                        card.classList.add('tiaur-role-dropdown-open');
                    }
                    var tool = picker.closest('.tiaur-role-tool');
                    if (tool) {
                        tool.classList.add('tiaur-role-dropdown-open');
                    }
                }
            }
            picker.addEventListener('click', function (event) {
                var option = event.target.closest('.tiaur-role-nav-option');
                if (option) {
                    var url = option.getAttribute('data-url');
                    if (url) {
                        picker.classList.add('tiaur-is-loading');
                        window.location.href = url;
                    }
                    return;
                }
                togglePicker();
            });
            picker.addEventListener('keydown', function (event) {
                if (event.key === 'Enter' || event.key === ' ') {
                    event.preventDefault();
                    togglePicker();
                }
                if (event.key === 'Escape') {
                    closeAll();
                }
            });
            document.addEventListener('click', function (event) {
                if (!event.target.closest('.tiaur-role-nav-picker')) {
                    closeAll();
                }
            });
        });

        document.querySelectorAll('[data-tiaur-toggle="multi-role"]').forEach(function (button) {
            var status = button.parentElement ? button.parentElement.querySelector('.tiaur-switch-status') : null;
            var label = button.querySelector('.tiaur-switch-label');

            function setState(enabled, saved) {
                button.dataset.enabled = enabled ? '1' : '0';
                button.setAttribute('aria-pressed', enabled ? 'true' : 'false');
                button.classList.toggle('is-on', enabled);
                button.classList.toggle('is-saved', !!saved && enabled);
                if (label) {
                    label.textContent = enabled ? 'Enabled' : 'Disabled';
                }
            }

            button.addEventListener('click', function () {
                if (button.classList.contains('is-saving')) {
                    return;
                }

                var previous = button.dataset.enabled === '1' || button.classList.contains('is-on');
                var next = !previous;

                if (previous && !next) {
                    var ok = window.confirm('Are you sure you want to disable multiple roles? User profiles will return to the default single-role selector.');
                    if (!ok) {
                        setState(true, true);
                        return;
                    }
                }

                setState(next, false);
                button.classList.add('is-saving');
                if (status) {
                    status.textContent = (window.TIAURAdmin && TIAURAdmin.savingText) ? TIAURAdmin.savingText : 'Saving...';
                }

                var formData = new FormData();
                formData.append('action', 'tiaur_toggle_multi_role');
                formData.append('nonce', window.TIAURAdmin ? TIAURAdmin.toggleNonce : '');
                formData.append('enabled', next ? '1' : '0');

                fetch(window.TIAURAdmin ? TIAURAdmin.ajaxUrl : ajaxurl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: formData
                }).then(function (response) {
                    return response.json();
                }).then(function (data) {
                    if (!data || !data.success) {
                        throw new Error('Save failed');
                    }
                    setState(!!data.data.enabled, true);
                    if (status) {
                        status.textContent = (window.TIAURAdmin && TIAURAdmin.savedText) ? TIAURAdmin.savedText : 'Saved';
                    }
                }).catch(function () {
                    setState(previous, previous);
                    if (status) {
                        status.textContent = (window.TIAURAdmin && TIAURAdmin.failedText) ? TIAURAdmin.failedText : 'Could not save';
                    }
                }).finally(function () {
                    button.classList.remove('is-saving');
                });
            });
        });




        function tiaurGetModuleContent(wrap) {
            if (!wrap) {
                return null;
            }
            var content = wrap.querySelector('.tiaur-module-content');
            if (!content && wrap.classList.contains('tiaur-module-header-card')) {
                var next = wrap.nextElementSibling;
                if (next && next.classList && next.classList.contains('tiaur-module-content')) {
                    content = next;
                }
            }
            return content;
        }

        function tiaurSetModuleFieldsDisabled(content, disabled) {
            if (!content) {
                return;
            }
            content.classList.toggle('is-disabled', !!disabled);
            content.querySelectorAll('input, select, textarea, button').forEach(function (field) {
                if (!field.closest('.tiaur-toggle-wrap')) {
                    field.disabled = !!disabled;
                }
            });
            content.querySelectorAll('.tiaur-content-edit-link').forEach(function (link) {
                if (!link.dataset.tiaurHref && link.getAttribute('href')) {
                    link.dataset.tiaurHref = link.getAttribute('href');
                }
                link.classList.toggle('is-disabled', !!disabled);
                link.setAttribute('aria-disabled', disabled ? 'true' : 'false');
                if (disabled) {
                    link.removeAttribute('href');
                    link.setAttribute('tabindex', '-1');
                } else {
                    if (link.dataset.tiaurHref) {
                        link.setAttribute('href', link.dataset.tiaurHref);
                    }
                    link.removeAttribute('tabindex');
                }
            });
        }
        function tiaurSyncDisabledModules() {
            document.querySelectorAll('.tiaur-module-content').forEach(function (content) {
                tiaurSetModuleFieldsDisabled(content, content.classList.contains('is-disabled'));
            });
        }
        tiaurSyncDisabledModules();

        document.querySelectorAll('[data-tiaur-toggle="module"]').forEach(function (button) {
            var wrap = button.closest('.tiaur-module-toggle-card, .tiaur-module-header-card');
            var status = button.parentElement ? button.parentElement.querySelector('.tiaur-switch-status') : null;
            var label = button.querySelector('.tiaur-switch-label');

            button.addEventListener('click', function (event) {
                event.preventDefault();
                event.stopPropagation();
                if (button.classList.contains('is-saving')) {
                    return;
                }

                var previous = button.dataset.enabled === '1' || button.classList.contains('is-on');
                var next = !previous;

                if (previous && !next) {
                    var ok = window.confirm((window.TIAURAdmin && TIAURAdmin.moduleDisableConfirm) ? TIAURAdmin.moduleDisableConfirm : 'Disable this module? Existing settings will be kept, but this feature will stop running.');
                    if (!ok) {
                        return;
                    }
                }

                function setState(enabled, saved) {
                    button.dataset.enabled = enabled ? '1' : '0';
                    button.setAttribute('aria-pressed', enabled ? 'true' : 'false');
                    button.classList.toggle('is-on', enabled);
                    button.classList.toggle('is-saved', !!saved && enabled);
                    if (wrap) {
                        wrap.classList.toggle('is-module-disabled', !enabled);
                        tiaurSetModuleFieldsDisabled(tiaurGetModuleContent(wrap), !enabled);
                    }
                    if (label) {
                        label.textContent = enabled ? 'Enabled' : 'Disabled';
                    }
                }

                setState(next, false);
                button.classList.add('is-saving');
                if (status) {
                    status.textContent = (window.TIAURAdmin && TIAURAdmin.savingText) ? TIAURAdmin.savingText : 'Saving...';
                }

                var formData = new FormData();
                formData.append('action', 'tiaur_toggle_plugin_setting');
                formData.append('nonce', window.TIAURAdmin ? TIAURAdmin.moduleNonce : '');
                formData.append('setting', button.getAttribute('data-setting') || '');
                formData.append('enabled', next ? '1' : '0');

                fetch(window.TIAURAdmin ? TIAURAdmin.ajaxUrl : ajaxurl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: formData
                }).then(function (response) {
                    return response.json();
                }).then(function (data) {
                    if (!data || !data.success) {
                        throw new Error('Save failed');
                    }
                    setState(!!data.data.enabled, true);
                    if (status) {
                        status.textContent = (window.TIAURAdmin && TIAURAdmin.savedText) ? TIAURAdmin.savedText : 'Saved';
                    }
                }).catch(function () {
                    setState(previous, previous);
                    if (status) {
                        status.textContent = (window.TIAURAdmin && TIAURAdmin.failedText) ? TIAURAdmin.failedText : 'Could not save';
                    }
                }).finally(function () {
                    button.classList.remove('is-saving');
                });
            });
        });


        document.addEventListener('click', function (event) {
            var disabledLink = event.target.closest('.tiaur-content-edit-link.is-disabled');
            if (disabledLink) {
                event.preventDefault();
                event.stopPropagation();
            }
        });

        document.querySelectorAll('[data-tiaur-toggle="delete-data"]').forEach(function (button) {
            var status = button.parentElement ? button.parentElement.querySelector('.tiaur-switch-status') : null;
            var label = button.querySelector('.tiaur-switch-label');

            function setState(enabled, saved) {
                button.dataset.enabled = enabled ? '1' : '0';
                button.setAttribute('aria-pressed', enabled ? 'true' : 'false');
                button.classList.toggle('is-on', enabled);
                button.classList.toggle('is-saved', !!saved && enabled);
                if (label) {
                    label.textContent = enabled ? 'Enabled' : 'Disabled';
                }
            }

            button.addEventListener('click', function () {
                if (button.classList.contains('is-saving')) {
                    return;
                }

                var previous = button.dataset.enabled === '1' || button.classList.contains('is-on');
                var next = !previous;

                if (next) {
                    var okOn = window.confirm('Enable uninstall cleanup? This will delete Titanium User Roles saved plugin data when the plugin is uninstalled. Role/capability changes are not automatically reverted.');
                    if (!okOn) {
                        setState(false, false);
                        return;
                    }
                } else {
                    var okOff = window.confirm('Keep plugin data when uninstalling?');
                    if (!okOff) {
                        setState(true, true);
                        return;
                    }
                }

                setState(next, false);
                button.classList.add('is-saving');
                if (status) {
                    status.textContent = (window.TIAURAdmin && TIAURAdmin.savingText) ? TIAURAdmin.savingText : 'Saving...';
                }

                var formData = new FormData();
                formData.append('action', 'tiaur_toggle_delete_data_on_uninstall');
                formData.append('nonce', window.TIAURAdmin ? TIAURAdmin.deleteDataNonce : '');
                formData.append('enabled', next ? '1' : '0');

                fetch(window.TIAURAdmin ? TIAURAdmin.ajaxUrl : ajaxurl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: formData
                }).then(function (response) {
                    return response.json();
                }).then(function (data) {
                    if (!data || !data.success) {
                        throw new Error('Save failed');
                    }
                    setState(!!data.data.enabled, true);
                    if (status) {
                        status.textContent = (window.TIAURAdmin && TIAURAdmin.savedText) ? TIAURAdmin.savedText : 'Saved';
                    }
                }).catch(function () {
                    setState(previous, previous);
                    if (status) {
                        status.textContent = (window.TIAURAdmin && TIAURAdmin.failedText) ? TIAURAdmin.failedText : 'Could not save';
                    }
                }).finally(function () {
                    button.classList.remove('is-saving');
                });
            });
        });


        document.querySelectorAll('[data-tiaur-toggle="beta-updates"]').forEach(function (button) {
            var status = button.parentElement ? button.parentElement.querySelector('.tiaur-switch-status') : null;
            var label = button.querySelector('.tiaur-switch-label');

            function setState(enabled, saved) {
                button.dataset.enabled = enabled ? '1' : '0';
                button.setAttribute('aria-pressed', enabled ? 'true' : 'false');
                button.classList.toggle('is-on', enabled);
                button.classList.toggle('is-saved', !!saved && enabled);
                if (label) {
                    label.textContent = enabled ? 'Enabled' : 'Disabled';
                }
            }

            button.addEventListener('click', function () {
                if (button.classList.contains('is-saving')) {
                    return;
                }

                var previous = button.dataset.enabled === '1' || button.classList.contains('is-on');
                var next = !previous;

                if (next) {
                    var okOn = window.confirm('Join the beta updates program? Beta versions can contain unfinished fixes and should be tested carefully before production use.');
                    if (!okOn) {
                        setState(false, false);
                        return;
                    }
                }

                setState(next, false);
                button.classList.add('is-saving');
                if (status) {
                    status.textContent = (window.TIAURAdmin && TIAURAdmin.savingText) ? TIAURAdmin.savingText : 'Saving...';
                }

                var formData = new FormData();
                var betaMode = button.dataset.betaMode || 'local';

                if (betaMode === 'freemius' && button.dataset.freemiusAction && button.dataset.freemiusSecurity && button.dataset.freemiusModuleId) {
                    formData.append('action', button.dataset.freemiusAction);
                    formData.append('security', button.dataset.freemiusSecurity);
                    formData.append('is_beta', next ? 'true' : 'false');
                    formData.append('module_id', button.dataset.freemiusModuleId);
                } else {
                    formData.append('action', 'tiaur_toggle_beta_updates');
                    formData.append('nonce', window.TIAURAdmin ? TIAURAdmin.betaUpdatesNonce : '');
                    formData.append('enabled', next ? '1' : '0');
                }

                fetch(window.TIAURAdmin ? TIAURAdmin.ajaxUrl : ajaxurl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: formData
                }).then(function (response) {
                    return response.json();
                }).then(function (data) {
                    if (!data || data.success === false) {
                        throw new Error('Save failed');
                    }
                    setState(next, true);
                    if (status) {
                        status.textContent = (window.TIAURAdmin && TIAURAdmin.savedText) ? TIAURAdmin.savedText : 'Saved';
                    }
                }).catch(function () {
                    setState(previous, previous);
                    if (status) {
                        status.textContent = (window.TIAURAdmin && TIAURAdmin.failedText) ? TIAURAdmin.failedText : 'Could not save';
                    }
                }).finally(function () {
                    button.classList.remove('is-saving');
                });
            });
        });

        document.querySelectorAll('.tiaur-color-scheme-form input[name="color_scheme"]').forEach(function (radio) {
            radio.addEventListener('change', function () {
                var form = radio.closest('.tiaur-color-scheme-form');
                if (!form) {
                    return;
                }
                form.querySelectorAll('.tiaur-color-option').forEach(function (option) {
                    option.classList.remove('is-selected');
                });
                var selectedOption = radio.closest('.tiaur-color-option');
                if (selectedOption) {
                    selectedOption.classList.add('is-selected');
                }

                var app = document.getElementById('tiaur-admin-app');
                if (app) {
                    form.querySelectorAll('input[name="color_scheme"]').forEach(function (themeRadio) {
                        if (themeRadio.value) {
                            app.classList.remove('tiaur-theme-' + themeRadio.value);
                        }
                    });
                    if (radio.value) {
                        app.classList.add('tiaur-theme-' + radio.value);
                    }
                }
            });
        });

        document.querySelectorAll('.tiaur-role-search').forEach(function (input) {
            input.addEventListener('input', function () {
                var q = input.value.toLowerCase().trim();
                var browser = input.closest('.tiaur-role-browser');
                if (!browser) {
                    return;
                }
                browser.querySelectorAll('.tiaur-role-chip').forEach(function (chip) {
                    var haystack = chip.getAttribute('data-role-label') || chip.textContent || '';
                    chip.style.display = haystack.toLowerCase().indexOf(q) === -1 ? 'none' : '';
                });
            });
        });

        document.querySelectorAll('.tiaur-cap-search').forEach(function (input) {
            input.addEventListener('input', function () {
                var q = input.value.toLowerCase();
                document.querySelectorAll('.tiaur-cap-item').forEach(function (item) {
                    var cap = item.getAttribute('data-cap') || '';
                    item.style.display = cap.toLowerCase().indexOf(q) === -1 ? 'none' : '';
                });
            });
        });

        var addCondition = document.getElementById('tiaur-add-condition');
        var conditions = document.getElementById('tiaur-filter-conditions');
        var template = document.getElementById('tiaur-condition-template');

        if (addCondition && conditions && template) {
            addCondition.addEventListener('click', function () {
                var clone = template.content.cloneNode(true);
                conditions.appendChild(clone);
            });
        }



        document.querySelectorAll('.tiaur-role-picker').forEach(function (picker) {
            var control = picker.querySelector('.tiaur-role-picker-control');
            var tags = picker.querySelector('.tiaur-role-picker-tags');
            var menu = picker.querySelector('.tiaur-role-picker-menu');
            var inputName = picker.getAttribute('data-input-name');
            var placeholder = picker.querySelector('.tiaur-role-picker-placeholder');

            if (!control || !tags || !menu || !inputName) {
                return;
            }

            function roleAlreadyAdded(value) {
                return !!tags.querySelector('.tiaur-role-tag[data-role="' + CSS.escape(value) + '"]');
            }

            function syncPicker() {
                var hasTags = !!tags.querySelector('.tiaur-role-tag');
                if (placeholder) {
                    placeholder.style.display = hasTags ? 'none' : '';
                }
                picker.querySelectorAll('.tiaur-role-picker-option').forEach(function (option) {
                    var isAdded = roleAlreadyAdded(option.getAttribute('data-role'));
                    option.hidden = isAdded;
                    option.classList.toggle('tiaur-option-hidden', isAdded);
                });
            }

            function openMenu() {
                document.querySelectorAll('.tiaur-role-picker.tiaur-picker-open').forEach(function (openPicker) {
                    if (openPicker !== picker) {
                        openPicker.classList.remove('tiaur-picker-open');
                        var openControl = openPicker.querySelector('.tiaur-role-picker-control');
                        if (openControl) {
                            openControl.setAttribute('aria-expanded', 'false');
                        }
                    }
                });
                picker.classList.add('tiaur-picker-open');
                control.setAttribute('aria-expanded', 'true');
                syncPicker();
            }

            function closeMenu() {
                picker.classList.remove('tiaur-picker-open');
                control.setAttribute('aria-expanded', 'false');
            }

            function addRole(value, label) {
                if (!value || roleAlreadyAdded(value)) {
                    return;
                }

                var tag = document.createElement('span');
                tag.className = 'tiaur-role-tag';
                tag.setAttribute('data-role', value);

                var text = document.createElement('span');
                text.textContent = label;

                var remove = document.createElement('button');
                remove.type = 'button';
                remove.className = 'tiaur-role-tag-remove';
                remove.setAttribute('aria-label', 'Remove role');
                remove.textContent = '×';

                var input = document.createElement('input');
                input.type = 'hidden';
                input.name = inputName + '[]';
                input.value = value;

                tag.appendChild(text);
                tag.appendChild(remove);
                tag.appendChild(input);
                tags.appendChild(tag);
                syncPicker();
            }

            control.addEventListener('click', function (event) {
                if (event.target && event.target.classList.contains('tiaur-role-tag-remove')) {
                    return;
                }
                picker.classList.contains('tiaur-picker-open') ? closeMenu() : openMenu();
            });

            control.addEventListener('keydown', function (event) {
                if (event.key === 'Enter' || event.key === ' ') {
                    event.preventDefault();
                    picker.classList.contains('tiaur-picker-open') ? closeMenu() : openMenu();
                }
                if (event.key === 'Escape') {
                    closeMenu();
                }
            });

            menu.addEventListener('click', function (event) {
                var option = event.target.closest('.tiaur-role-picker-option');
                if (!option) {
                    return;
                }
                addRole(option.getAttribute('data-role'), option.getAttribute('data-label') || option.textContent.trim());
                if (!event.ctrlKey && !event.metaKey) {
                    closeMenu();
                }
            });

            syncPicker();
        });

        document.addEventListener('click', function (event) {
            if (!event.target.closest('.tiaur-role-picker')) {
                document.querySelectorAll('.tiaur-role-picker.tiaur-picker-open').forEach(function (picker) {
                    picker.classList.remove('tiaur-picker-open');
                    var control = picker.querySelector('.tiaur-role-picker-control');
                    if (control) {
                        control.setAttribute('aria-expanded', 'false');
                    }
                });
            }
        });

        document.addEventListener('click', function (event) {
            if (event.target && event.target.classList.contains('tiaur-remove-condition')) {
                var row = event.target.closest('.tiaur-condition-row');
                if (row && document.querySelectorAll('.tiaur-condition-row').length > 1) {
                    row.remove();
                }
            }

            if (event.target && event.target.classList.contains('tiaur-role-tag-remove')) {
                var tag = event.target.closest('.tiaur-role-tag');
                var picker = event.target.closest('.tiaur-role-picker');
                if (tag) {
                    tag.remove();
                }
                if (picker) {
                    var hasTags = !!picker.querySelector('.tiaur-role-tag');
                    var placeholder = picker.querySelector('.tiaur-role-picker-placeholder');
                    if (placeholder) {
                        placeholder.style.display = hasTags ? 'none' : '';
                    }
                    picker.querySelectorAll('.tiaur-role-picker-option').forEach(function (option) {
                        var value = option.getAttribute('data-role');
                        var isAdded = !!picker.querySelector('.tiaur-role-tag[data-role="' + CSS.escape(value) + '"]');
                        option.hidden = isAdded;
                        option.classList.toggle('tiaur-option-hidden', isAdded);
                    });
                }
            }

            if (event.target && event.target.classList.contains('tiaur-check-all')) {
                var table = event.target.closest('table');
                if (table) {
                    table.querySelectorAll('tbody input[type="checkbox"]').forEach(function (checkbox) {
                        checkbox.checked = event.target.checked;
                    });
                }
            }
        });
    });
})();

(function () {
    function initAurContentControlBox() {
        var box = document.querySelector('.tiaur-content-metabox');
        if (!box) {
            return;
        }
        var toggle = box.querySelector('input[name="tiaur_content_enabled"]');
        var fields = box.querySelector('.tiaur-content-fields');
        if (!toggle || !fields) {
            return;
        }
        function sync() {
            fields.disabled = !toggle.checked;
        }
        toggle.addEventListener('change', sync);
        sync();
    }

    if (document.readyState !== 'loading') {
        initAurContentControlBox();
    } else {
        document.addEventListener('DOMContentLoaded', initAurContentControlBox);
    }
})();

(function () {
    function onReady(fn) {
        if (document.readyState !== 'loading') {
            fn();
        } else {
            document.addEventListener('DOMContentLoaded', fn);
        }
    }

    onReady(function () {
        document.querySelectorAll('.tiaur-export-picker').forEach(function (picker) {
            var input = picker.parentElement ? picker.parentElement.querySelector('.tiaur-export-scope-input') : null;
            var current = picker.querySelector('.tiaur-export-current');
            var options = picker.querySelectorAll('.tiaur-export-option');

            function closeOtherPickers() {
                document.querySelectorAll('.tiaur-export-picker.is-open').forEach(function (openPicker) {
                    if (openPicker !== picker) {
                        openPicker.classList.remove('is-open');
                        openPicker.setAttribute('aria-expanded', 'false');
                    }
                });
            }

            picker.addEventListener('click', function (event) {
                var option = event.target.closest('.tiaur-export-option');
                if (option) {
                    event.preventDefault();
                    if (input) {
                        input.value = option.getAttribute('data-value') || 'everything';
                    }
                    if (current) {
                        current.textContent = option.textContent;
                    }
                    options.forEach(function (item) {
                        item.classList.toggle('is-selected', item === option);
                    });
                    picker.classList.remove('is-open');
                    picker.setAttribute('aria-expanded', 'false');
                    return;
                }

                closeOtherPickers();
                var isOpen = picker.classList.toggle('is-open');
                picker.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
            });

            picker.addEventListener('keydown', function (event) {
                if (event.key === 'Enter' || event.key === ' ') {
                    event.preventDefault();
                    picker.click();
                }
                if (event.key === 'Escape') {
                    picker.classList.remove('is-open');
                    picker.setAttribute('aria-expanded', 'false');
                }
            });
        });

        document.addEventListener('click', function (event) {
            if (!event.target.closest('.tiaur-export-picker')) {
                document.querySelectorAll('.tiaur-export-picker.is-open').forEach(function (picker) {
                    picker.classList.remove('is-open');
                    picker.setAttribute('aria-expanded', 'false');
                });
            }
        });
    });

})();

(function () {
    'use strict';

    function syncFilterValueSelect(row) {
        if (!row) {
            return;
        }
        var fieldSelect = row.querySelector('.tiaur-filter-field-select');
        var valueSelect = row.querySelector('.tiaur-filter-value-select');
        if (!fieldSelect || !valueSelect) {
            return;
        }
        var field = fieldSelect.value || 'role';
        var selectedOption = valueSelect.options[valueSelect.selectedIndex];
        var selectedField = selectedOption ? selectedOption.getAttribute('data-field') : '';

        Array.prototype.forEach.call(valueSelect.options, function (option) {
            var optionField = option.getAttribute('data-field') || '';
            option.hidden = optionField !== '' && optionField !== field;
            option.disabled = optionField !== '' && optionField !== field;
        });

        Array.prototype.forEach.call(valueSelect.querySelectorAll('optgroup'), function (group) {
            var groupField = group.getAttribute('data-field') || '';
            group.hidden = groupField !== field;
            group.disabled = groupField !== field;
        });

        if (selectedField && selectedField !== field) {
            valueSelect.value = '';
        }
    }

    function syncAllFilterRows() {
        document.querySelectorAll('.tiaur-condition-row').forEach(syncFilterValueSelect);
    }

    document.addEventListener('change', function (event) {
        if (event.target && event.target.classList.contains('tiaur-filter-field-select')) {
            syncFilterValueSelect(event.target.closest('.tiaur-condition-row'));
        }
    });

    document.addEventListener('click', function (event) {
        var row = event.target.closest('.tiaur-clickable-user-row');
        if (!row || event.target.closest('a, button, input, select, textarea, label')) {
            return;
        }
        var url = row.getAttribute('data-user-url');
        if (url) {
            window.location.href = url;
        }
    });

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', syncAllFilterRows);
    } else {
        syncAllFilterRows();
    }

    var addCondition = document.getElementById('tiaur-add-condition');
    if (addCondition) {
        addCondition.addEventListener('click', function () {
            window.setTimeout(syncAllFilterRows, 0);
        });
    }
}());

