/**
 * TitanCart — Search Suggestions (Typeahead)
 *
 * Attaches to all `.tc-nav__search-input` and `.tc-mobile-menu__search input`
 * fields. Fetches suggestions from GET /store/search-suggest?q=... as the
 * user types (debounced 250ms, min 2 chars). Renders a dropdown below the
 * search input with product thumbnails, names, and prices.
 *
 * Reads API URL from `titancartConfig.apiUrl` (already localised by StorefrontModule).
 *
 * @package TitanCart
 */
(function () {
    'use strict';

    var cfg    = window.titancartConfig || {};
    var apiUrl = (cfg.apiUrl || '/wp-json/titancart/v1') + '/store/search-suggest';
    var symbol = cfg.symbol || '$';
    var minLen = parseInt(cfg.searchMinLength, 10) || 2;

    // ── Helpers ──────────────────────────────────────────────────────────

    function debounce(fn, ms) {
        var timer;
        return function () {
            var ctx = this, args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () { fn.apply(ctx, args); }, ms);
        };
    }

    function esc(s) {
        var d = document.createElement('div');
        d.textContent = s;
        return d.innerHTML;
    }

    function formatPrice(price, listPrice) {
        var html = '';
        if (listPrice > 0 && listPrice > price) {
            html += '<span class="tc-suggest__old-price">' + symbol + Number(listPrice).toFixed(2) + '</span> ';
        }
        html += '<span class="tc-suggest__price">' + symbol + Number(price).toFixed(2) + '</span>';
        return html;
    }

    // ── Build dropdown ──────────────────────────────────────────────────

    function createDropdown(input) {
        // Attach to closest form (both desktop and mobile search forms use form > input).
        var wrap = input.closest('form') || input.parentElement;
        if (!wrap) return null;

        // Make wrapper position:relative for dropdown positioning.
        wrap.style.position = 'relative';

        var dd = document.createElement('div');
        dd.className = 'tc-suggest-dropdown';
        dd.style.display = 'none';
        wrap.appendChild(dd);
        return dd;
    }

    function renderResults(dropdown, results, query) {
        if (!results || !results.length) {
            dropdown.innerHTML = '<div class="tc-suggest__empty">No products found for "' + esc(query) + '"</div>';
            dropdown.style.display = 'block';
            return;
        }

        var html = '';
        results.forEach(function (item) {
            html += '<a href="' + esc(item.url) + '" class="tc-suggest__item">';
            if (item.image) {
                html += '<img src="' + esc(item.image) + '" alt="" class="tc-suggest__thumb" loading="lazy">';
            } else {
                html += '<div class="tc-suggest__thumb tc-suggest__thumb--empty"><i class="bi bi-image"></i></div>';
            }
            html += '<div class="tc-suggest__info">';
            html += '<span class="tc-suggest__name">' + esc(item.name) + '</span>';
            html += '<span class="tc-suggest__prices">' + formatPrice(item.price, item.list_price) + '</span>';
            html += '</div>';
            html += '</a>';
        });

        // "View all results" link
        html += '<a href="' + esc(window.location.origin + '/search/?q=' + encodeURIComponent(query)) + '" class="tc-suggest__viewall">';
        html += 'View all results <i class="bi bi-arrow-right"></i>';
        html += '</a>';

        dropdown.innerHTML = html;
        dropdown.style.display = 'block';
    }

    // ── Fetch suggestions ───────────────────────────────────────────────

    var activeRequest = null;

    function fetchSuggestions(query, dropdown) {
        if (activeRequest) activeRequest.abort();

        var controller = new AbortController();
        activeRequest = controller;

        fetch(apiUrl + '?q=' + encodeURIComponent(query), {
            signal: controller.signal,
            credentials: 'same-origin',
        })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                activeRequest = null;
                renderResults(dropdown, data, query);
            })
            .catch(function (e) {
                if (e.name !== 'AbortError') {
                    dropdown.style.display = 'none';
                }
            });
    }

    // ── Attach to search inputs ─────────────────────────────────────────

    function initSearchInput(input) {
        var dropdown = createDropdown(input);
        if (!dropdown) return;

        var onInput = debounce(function () {
            var q = input.value.trim();
            if (q.length < minLen) {
                dropdown.style.display = 'none';
                return;
            }
            fetchSuggestions(q, dropdown);
        }, 250);

        input.addEventListener('input', onInput);

        // Close on blur (with slight delay so link clicks register).
        input.addEventListener('blur', function () {
            setTimeout(function () { dropdown.style.display = 'none'; }, 200);
        });

        // Re-show on focus if there's a query.
        input.addEventListener('focus', function () {
            if (input.value.trim().length >= minLen && dropdown.innerHTML) {
                dropdown.style.display = 'block';
            }
        });

        // Keyboard: Escape closes dropdown.
        input.addEventListener('keydown', function (e) {
            if (e.key === 'Escape') {
                dropdown.style.display = 'none';
            }
        });
    }

    // Init on DOM ready — attach to all nav search inputs.
    document.querySelectorAll('.nav-search-control').forEach(initSearchInput);

})();
