/**
 * AIEO Related-tab chip-picker
 *
 * Lightweight (no jQuery dep beyond what the WP admin already loads),
 * one debounced search per picker, click-to-add, click-to-remove. The
 * source of truth is the `<ul.aieo-tr-chips>` list — every chip carries
 * a hidden input named after the picker's axis (e.g.
 * `aieo_tr[term:product_brand][]`) so a regular form submit picks them
 * all up.
 *
 * The PHP renderer pre-populates the chips on page load; the JS only
 * needs to handle interactive add/remove + the search dropdown.
 */
(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; };

    var CFG = window.aieoTrConfig || {};
    if (!CFG.ajaxUrl || !CFG.nonce) { return; }

    document.querySelectorAll('.aieo-tr-search-field').forEach(initField);

    function initField(field) {
        var source = field.getAttribute('data-source') || '';
        if (!source || source.indexOf(':') === -1) { return; }
        var parts = source.split(':');
        var kind = parts[0];        // 'term' | 'post'
        var subtype = parts[1];     // taxonomy or post-type slug

        var input    = field.querySelector('.aieo-tr-search-input');
        var results  = field.querySelector('.aieo-tr-search-results');
        var chipsUl  = field.querySelector('.aieo-tr-chips');
        if (!input || !results || !chipsUl) { return; }

        var chipName = chipsUl.getAttribute('data-name') || '';
        var debounceTimer = null;
        var lastQuery = '';

        // Search-as-you-type with 200ms debounce.
        input.addEventListener('input', function () {
            var q = input.value.trim();
            clearTimeout(debounceTimer);
            if (q.length < 2) {
                results.innerHTML = '';
                results.hidden = true;
                return;
            }
            if (q === lastQuery) { return; }
            debounceTimer = setTimeout(function () {
                lastQuery = q;
                doSearch(q);
            }, 200);
        });

        // Hide results when the input loses focus (with a small delay so
        // a click on a result still fires).
        input.addEventListener('blur', function () {
            setTimeout(function () { results.hidden = true; }, 150);
        });
        input.addEventListener('focus', function () {
            if (results.children.length > 0) { results.hidden = false; }
        });

        // Remove chip on × click.
        chipsUl.addEventListener('click', function (e) {
            if (e.target && e.target.classList.contains('aieo-tr-chip-remove')) {
                var chip = e.target.closest('.aieo-tr-chip');
                if (chip) { chip.remove(); }
            }
        });

        function doSearch(q) {
            var url = CFG.ajaxUrl
                + '?action=aieo_dmm_related_search'
                + '&nonce=' + encodeURIComponent(CFG.nonce)
                + '&kind=' + encodeURIComponent(kind)
                + '&subtype=' + encodeURIComponent(subtype)
                + '&q=' + encodeURIComponent(q);
            fetch(url, { credentials: 'same-origin' })
                .then(function (r) { return r.json(); })
                .then(function (j) {
                    results.innerHTML = '';
                    if (!j || !j.success || !j.data || !j.data.results) {
                        results.hidden = true;
                        return;
                    }
                    var existingIds = collectChipIds(chipsUl);
                    var rendered = 0;
                    j.data.results.forEach(function (row) {
                        if (existingIds.indexOf(row.id) !== -1) { return; }
                        var li = document.createElement('li');
                        li.className = 'aieo-tr-search-result';
                        li.dataset.id = row.id;
                        li.textContent = row.label;
                        li.addEventListener('mousedown', function (ev) {
                            ev.preventDefault(); // prevent input blur before click
                            addChip(row.id, row.label);
                            results.innerHTML = '';
                            results.hidden = true;
                            input.value = '';
                            input.focus();
                        });
                        results.appendChild(li);
                        rendered++;
                    });
                    results.hidden = rendered === 0;
                })
                .catch(function () {
                    results.innerHTML = '';
                    results.hidden = true;
                });
        }

        function addChip(id, label) {
            id = parseInt(id, 10);
            if (!id) { return; }
            // Defensive — don't add duplicates.
            if (collectChipIds(chipsUl).indexOf(id) !== -1) { return; }
            var li = document.createElement('li');
            li.className = 'aieo-tr-chip';
            li.dataset.id = String(id);

            var span = document.createElement('span');
            span.className = 'aieo-tr-chip-label';
            span.textContent = label;
            li.appendChild(span);

            var btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'aieo-tr-chip-remove';
            btn.setAttribute('aria-label', __( 'Remove', 'ai-eshop-optimizer' ));
            btn.textContent = '×';
            li.appendChild(btn);

            var hidden = document.createElement('input');
            hidden.type  = 'hidden';
            hidden.name  = chipName;
            hidden.value = String(id);
            li.appendChild(hidden);

            chipsUl.appendChild(li);
        }

        function collectChipIds(ul) {
            var ids = [];
            ul.querySelectorAll('.aieo-tr-chip').forEach(function (c) {
                var id = parseInt(c.dataset.id, 10);
                if (id) { ids.push(id); }
            });
            return ids;
        }
    }
})();
