/**
 * AIEO Tools — Brand metabox enhancements.
 *
 * Runs on the WP product edit screen when the "Searchable + alphabetised
 * Brands metabox" tool is enabled. Two effects:
 *
 *   1. Sort the All Brands <ul> children alphabetically by visible label
 *      (case-insensitive locale compare so "ALAMA" / "Andreia" / "BRAHMA"
 *      sort the way a human reads them).
 *   2. Inject a search input above the list that hides non-matching <li>s
 *      as the operator types. Pure DOM filtering — no AJAX needed.
 *
 * Re-runs on the AJAX "Add new brand" hook (`wp_lists_add` → child added)
 * so a freshly-added brand sorts into place automatically.
 */

(function () {
    'use strict';

    var __ = ( window.wp && window.wp.i18n && window.wp.i18n.__ ) ? window.wp.i18n.__ : function (s) { return s; };
    var _x = ( window.wp && window.wp.i18n && window.wp.i18n._x ) ? window.wp.i18n._x : function (s) { return s; };
    var _n = ( window.wp && window.wp.i18n && window.wp.i18n._n ) ? window.wp.i18n._n : function (s, p, n) { return n === 1 ? s : p; };
    var _sprintf = ( window.wp && window.wp.i18n && window.wp.i18n.sprintf ) ? window.wp.i18n.sprintf : function (s) { return s; };

    function init() {
        var ul = document.getElementById('product_brandchecklist');
        if (!ul) { return; }
        // Tag the metabox so we don't re-init on every mutation pass.
        if (ul.dataset.aieoEnhanced === '1') { return; }
        ul.dataset.aieoEnhanced = '1';

        injectSearch(ul);
        sortAlphabetically(ul);

        // Watch for newly-added brands (from the inline "+ Add new brand"
        // panel — WP appends an <li> via wp_lists). Re-sort + re-filter on
        // any DOM change inside the list.
        if (typeof MutationObserver !== 'undefined') {
            var obs = new MutationObserver(function () {
                sortAlphabetically(ul);
                applyFilter();
            });
            obs.observe(ul, { childList: true });
        }
    }

    function sortAlphabetically(ul) {
        var items = Array.prototype.slice.call(ul.children).filter(function (n) {
            return n.tagName === 'LI';
        });
        if (items.length < 2) { return; }
        items.sort(function (a, b) {
            return labelText(a).localeCompare(labelText(b), undefined, { sensitivity: 'base' });
        });
        // Re-append in sorted order. appendChild on existing nodes moves
        // them; checkbox state is preserved.
        items.forEach(function (li) { ul.appendChild(li); });
    }

    function labelText(li) {
        var lbl = li.querySelector('label');
        return (lbl ? lbl.textContent : li.textContent || '').trim();
    }

    var filterInput = null;
    var allItems   = [];

    function injectSearch(ul) {
        var wrap = document.createElement('div');
        wrap.style.padding = '6px 4px';
        wrap.style.borderBottom = '1px solid #e5e7eb';
        wrap.style.marginBottom = '4px';

        filterInput = document.createElement('input');
        filterInput.type = 'search';
        filterInput.placeholder = (window.aieoToolsBrand && window.aieoToolsBrand.placeholder) || __( 'Search brands…', 'ai-eshop-optimizer' );
        filterInput.style.width = '100%';
        filterInput.style.padding = '6px 8px';
        filterInput.style.boxSizing = 'border-box';
        filterInput.setAttribute('aria-label', filterInput.placeholder);
        filterInput.addEventListener('input', applyFilter);

        wrap.appendChild(filterInput);

        // Insert above the All Brands <ul>. The parent .tabs-panel works
        // as the anchor — sits inside #product_brand-all.
        var panel = document.getElementById('product_brand-all') || ul.parentNode;
        panel.insertBefore(wrap, ul);

        // Status line (e.g. "No brands match.").
        var status = document.createElement('p');
        status.id = 'aieo-brand-filter-status';
        status.style.margin = '6px 4px 0';
        status.style.fontSize = '11px';
        status.style.color = '#6b7280';
        status.style.display = 'none';
        wrap.appendChild(status);
    }

    function applyFilter() {
        var ul = document.getElementById('product_brandchecklist');
        if (!ul) { return; }
        var status = document.getElementById('aieo-brand-filter-status');
        var q = (filterInput ? filterInput.value : '').trim().toLowerCase();
        var items = ul.querySelectorAll('li');
        var visible = 0;
        for (var i = 0; i < items.length; i++) {
            var name = labelText(items[i]).toLowerCase();
            var match = q === '' || name.indexOf(q) !== -1;
            items[i].style.display = match ? '' : 'none';
            if (match) { visible++; }
        }
        if (status) {
            if (q !== '' && visible === 0) {
                status.style.display = '';
                status.textContent = (window.aieoToolsBrand && window.aieoToolsBrand.noResults) || __( 'No brands match.', 'ai-eshop-optimizer' );
            } else {
                status.style.display = 'none';
            }
        }
    }

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