document.addEventListener('DOMContentLoaded', function () {
    var root = document.querySelector('[data-diar4a]');
    if (!root) { return; }

    var groups = Array.prototype.slice.call(root.querySelectorAll('[data-rule-group]'));
    var search = root.querySelector('[data-rule-search]');
    var clear = root.querySelector('[data-rule-search-clear]');
    var summary = root.querySelector('[data-rule-search-summary]');
    var empty = root.querySelector('[data-rule-search-empty]');
    var isRtl = document.documentElement.dir === 'rtl';

    function normalize(value) {
        return String(value || '').toLocaleLowerCase().replace(/\s+/g, ' ').trim();
    }

    function applySearch() {
        var query = normalize(search ? search.value : '');
        var visibleFields = 0;
        var visibleGroups = 0;
        groups.forEach(function (group) {
            var fields = Array.prototype.slice.call(group.querySelectorAll('[data-rule-field]'));
            var groupMatch = normalize(group.getAttribute('data-group-code')).indexOf(query) !== -1;
            var groupVisibleFields = 0;
            fields.forEach(function (field) {
                var match = query === '' || groupMatch || normalize(field.getAttribute('data-search-text')).indexOf(query) !== -1;
                field.hidden = !match;
                if (match) { groupVisibleFields += 1; visibleFields += 1; }
            });
            group.hidden = query !== '' && groupVisibleFields === 0;
            if (!group.hidden) { visibleGroups += 1; }
            if (query !== '' && groupVisibleFields > 0) { group.open = true; }
        });
        if (summary) {
            summary.hidden = query === '';
            summary.textContent = isRtl
                ? 'تم العثور على ' + visibleFields + ' عنصرًا ضمن ' + visibleGroups + ' أقسام.'
                : visibleFields + ' matching items across ' + visibleGroups + ' sections.';
        }
        if (empty) { empty.hidden = query === '' || visibleFields > 0; }
    }

    if (search) { search.addEventListener('input', applySearch); }
    if (clear) {
        clear.addEventListener('click', function () {
            if (!search) { return; }
            search.value = '';
            applySearch();
            search.focus();
        });
    }

    var expand = root.querySelector('[data-groups-expand]');
    var collapse = root.querySelector('[data-groups-collapse]');
    if (expand) { expand.addEventListener('click', function () { groups.forEach(function (group) { if (!group.hidden) { group.open = true; } }); }); }
    if (collapse) { collapse.addEventListener('click', function () { groups.forEach(function (group) { group.open = false; }); }); }

    root.querySelectorAll('form').forEach(function (form) {
        form.addEventListener('submit', function (event) {
            var button = event.submitter;
            if (!button) { return; }
            var action = button.value || '';
            if (action === 'activate' && !window.confirm(isRtl
                ? 'سيتم إحالة الإصدار النشط الحالي للتقاعد وتفعيل الإصدار المحدد. هل تريد المتابعة؟'
                : 'The current active version will be retired and the selected version activated. Continue?')) {
                event.preventDefault(); return;
            }
            button.disabled = true;
            button.dataset.originalText = button.textContent;
            button.textContent = isRtl ? 'جارٍ التنفيذ…' : 'Working…';
        });
    });

    applySearch();
    var hasJckh = root.textContent.indexOf('JCKH') !== -1;
    var hasSearch = !!search;
    var hasAccordions = groups.length > 0;
    var hasMode = !!root.querySelector('.edit-state');
    root.setAttribute('data-ui3-r1-contract', (!hasJckh && hasSearch && hasAccordions && hasMode) ? 'PASS' : 'FAIL');
});
