// Bud-list autocomplete for #id_recipient inputs (post share panel + my_buds
// add panel). Mirrors the sky.html birth-place picker pattern: debounced
// fetch on input, top-3 suggestions rendered as buttons, click-to-fill,
// Escape closes, click-outside closes. No keyboard arrow/Enter cycling.
//
// Usage:
//     <div class="bud-panel-wrap">
//         <input id="id_recipient" ...>
//         <div id="id_bud_suggestions" class="bud-suggestions" hidden></div>
//     </div>
//     <script src="{% static 'apps/billboard/bud-autocomplete.js' %}"></script>
//     <script>bindBudAutocomplete(
//         document.getElementById('id_recipient'),
//         document.getElementById('id_bud_suggestions'),
//         { searchUrl: '{% url "billboard:search_buds" %}' }
//     );</script>

(function () {
    'use strict';

    var DEBOUNCE_MS = 250;
    var MIN_CHARS = 1;

    function _esc(s) {
        var d = document.createElement('div');
        d.textContent = s == null ? '' : s;
        return d.innerHTML;
    }

    window.bindBudAutocomplete = function (input, suggestions, options) {
        if (!input || !suggestions || !options || !options.searchUrl) return;

        var debounceTimer = null;
        var lastQuery = '';

        function _hide() {
            suggestions.hidden = true;
            suggestions.innerHTML = '';
        }

        function _render(buds) {
            if (!buds || !buds.length) {
                _hide();
                return;
            }
            suggestions.innerHTML = buds.map(function (b) {
                // data-email + data-username so the click handler can fill the
                // input with whichever the user originally typed (email if they
                // started with `@`, else username).
                return (
                    '<button type="button" class="bud-suggestion-item" ' +
                    'data-email="'    + _esc(b.email)    + '" ' +
                    'data-username="' + _esc(b.username) + '">' +
                        _esc(b.username) +
                    '</button>'
                );
            }).join('');
            suggestions.hidden = false;
        }

        function _fetch(q) {
            var url = options.searchUrl + '?q=' + encodeURIComponent(q);
            fetch(url, {
                credentials: 'same-origin',
                headers: { 'Accept': 'application/json' },
            })
                .then(function (r) { return r.ok ? r.json() : Promise.reject(r.status); })
                .then(function (data) {
                    // Drop late responses if the user has typed past this query.
                    if (input.value.trim() !== q) return;
                    _render(data.buds || []);
                })
                .catch(function () { _hide(); });
        }

        input.addEventListener('input', function () {
            var q = input.value.trim();
            lastQuery = q;
            if (q.length < MIN_CHARS) { _hide(); return; }
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(function () { _fetch(q); }, DEBOUNCE_MS);
        });

        input.addEventListener('keydown', function (e) {
            if (e.key === 'Escape') _hide();
        });

        suggestions.addEventListener('click', function (e) {
            var btn = e.target.closest('.bud-suggestion-item');
            if (!btn) return;
            // Stop propagation so the bud-panel's document-level click-
            // outside handler doesn't fire and close+clear the panel —
            // _hide() about to detach the target makes a `sg.contains(e.target)`
            // check at the document level unreliable.
            e.stopPropagation();
            // Fill w. whichever form the user was typing (email vs username).
            // If the input value already contains '@', prefer email; else
            // prefer username. This keeps the OK-submit semantics consistent
            // w. what the user intended.
            var typed = input.value.trim();
            input.value = typed.indexOf('@') !== -1
                ? btn.dataset.email
                : btn.dataset.username;
            _hide();
            input.focus();
        });

        document.addEventListener('click', function (e) {
            if (suggestions.hidden) return;
            if (suggestions.contains(e.target)) return;
            if (e.target === input) return;
            _hide();
        });
    };
}());
