/* jshint esversion: 6 */
/* globals ajaxurl, flowdino_ajax, flowdino_data, jQuery */

jQuery(document).ready(function($) {
    var searchTimeout = null;
    var currentSearchRequests = {};

    function searchBrands(searchTerm, container) {
        var resultsDiv = container.find('.flowdino-brand-results');
        var wcBrandId  = container.data('wc-brand');

        if (currentSearchRequests[wcBrandId]) {
            currentSearchRequests[wcBrandId].abort();
        }

        if (searchTerm.length < 2) {
            resultsDiv.hide();
            return;
        }

        resultsDiv.html('<div class="flowdino-brand-loading">' + flowdino_data.i18n.searching + '</div>').show();

        currentSearchRequests[wcBrandId] = $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'flowdino_search_brands',
                search_term: searchTerm,
                nonce: flowdino_ajax.search_nonce
            },
            success: function(response) {
                if (response.success && response.data.brands) {
                    var html = '';
                    if (response.data.brands.length > 0) {
                        $.each(response.data.brands, function(index, brand) {
                            if (brand.id && brand.name) {
                                html += '<div class="flowdino-brand-result-item" data-brand-id="' + brand.id + '" data-brand-name="' + brand.name + '">';
                                html += '<div class="flowdino-brand-result-name">' + brand.name + '</div>';
                                if (brand.description && brand.description !== '') {
                                    html += '<div class="flowdino-brand-result-description">' + brand.description + '</div>';
                                }
                                html += '</div>';
                            }
                        });
                    } else {
                        html = '<div class="flowdino-brand-no-results">' + flowdino_data.i18n.no_brands_found + '</div>';
                    }
                    resultsDiv.html(html).show();
                } else {
                    resultsDiv.html('<div class="flowdino-brand-no-results">' + ((response.data && response.data.message) ? response.data.message : flowdino_data.i18n.error_searching_brands) + '</div>').show();
                }
            },
            error: function(xhr, status) {
                if (status !== 'abort') {
                    resultsDiv.html('<div class="flowdino-brand-no-results">' + flowdino_data.i18n.error_searching_brands + '</div>').show();
                }
            },
            complete: function() {
                delete currentSearchRequests[wcBrandId];
            }
        });
    }

    $(document).on('input', '.flowdino-brand-search', function() {
        var searchInput = $(this);
        var searchTerm  = searchInput.val().trim();
        var container   = searchInput.closest('.flowdino-brand-search-container');

        clearTimeout(searchTimeout);

        if (searchTerm.length === 0) {
            container.find('.flowdino-brand-results').hide();
            return;
        }

        searchTimeout = setTimeout(function() {
            searchBrands(searchTerm, container);
        }, 300);
    });

    $(document).on('click', '.flowdino-brand-result-item', function() {
        var item      = $(this);
        var brandId   = item.data('brand-id');
        var brandName = item.data('brand-name');
        var container = item.closest('.flowdino-brand-search-container');
        var wcBrandId = container.data('wc-brand');

        container.find('.flowdino-brand-value').val(brandId);
        container.find('.flowdino-brand-name').val(brandName);
        container.find('.flowdino-brand-search').val('');
        container.find('.flowdino-brand-results').hide();

        var currentDiv = container.find('.flowdino-brand-current');
        if (wcBrandId === 'default') {
            currentDiv.html(flowdino_data.i18n.default_brand_label + ' <strong>' + brandName + '</strong> <button type="button" class="flowdino-brand-clear" style="margin-left:10px;font-size:0.8em;" title="' + flowdino_data.i18n.clear_default_brand + '">✕</button>');
        } else {
            currentDiv.html(flowdino_data.i18n.currently_mapped_to + ' <strong>' + brandName + '</strong> <button type="button" class="flowdino-brand-clear" style="margin-left:10px;font-size:0.8em;" title="' + flowdino_data.i18n.clear_mapping + '">✕</button>');
        }
    });

    $(document).on('click', '.flowdino-brand-clear', function() {
        var container = $(this).closest('.flowdino-brand-search-container');
        var wcBrandId = container.data('wc-brand');

        container.find('.flowdino-brand-value').val('');
        container.find('.flowdino-brand-name').val('');

        if (wcBrandId === 'default') {
            container.find('.flowdino-brand-current').html(flowdino_data.i18n.no_default_brand);
        } else {
            container.find('.flowdino-brand-current').html(flowdino_data.i18n.no_brand_selected);
        }
    });

    $(document).on('click', function(e) {
        if (!$(e.target).closest('.flowdino-brand-search-container').length) {
            $('.flowdino-brand-results').hide();
        }
    });

    $(document).on('focus', '.flowdino-brand-search', function() {
        var searchInput = $(this);
        var searchTerm  = searchInput.val().trim();
        var container   = searchInput.closest('.flowdino-brand-search-container');
        if (searchTerm.length >= 2) {
            searchBrands(searchTerm, container);
        }
    });

    // Create Brand
    $('#flowdino-create-brand-btn').on('click', function() {
        var btn      = $(this);
        var nameInput = $('#flowdino-new-brand-name');
        var name     = nameInput.val().trim();
        var noticeDiv = $('#flowdino-create-brand-notice');

        noticeDiv.hide().removeClass('notice-success notice-error');

        if (!name) {
            noticeDiv
                .addClass('notice notice-error')
                .html('<p>' + flowdino_data.i18n.brand_name_required + '</p>')
                .show();
            return;
        }

        btn.prop('disabled', true).text(flowdino_data.i18n.creating_brand);

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action:     'flowdino_create_brand',
                brand_name: name,
                nonce:      flowdino_ajax.create_brand_nonce
            },
            success: function(response) {
                if (response.success && response.data.brand) {
                    var brand = response.data.brand;
                    noticeDiv
                        .addClass('notice notice-success')
                        .html('<p>' + flowdino_data.i18n.brand_created + ' <strong>' + brand.name + '</strong> (ID: ' + brand.id + ')</p>')
                        .show();
                    nameInput.val('');

                    // Refresh all open search dropdowns so the new brand appears immediately
                    $('.flowdino-brand-search').each(function() {
                        var input     = $(this);
                        var container = input.closest('.flowdino-brand-search-container');
                        var term      = input.val().trim();
                        if (term.length >= 2) {
                            searchBrands(term, container);
                        }
                    });
                } else {
                    var msg = (response.data && response.data.message) ? response.data.message : flowdino_data.i18n.error_creating_brand;
                    noticeDiv
                        .addClass('notice notice-error')
                        .html('<p>' + flowdino_data.i18n.error_creating_brand + ' ' + msg + '</p>')
                        .show();
                }
            },
            error: function() {
                noticeDiv
                    .addClass('notice notice-error')
                    .html('<p>' + flowdino_data.i18n.error_creating_brand + '</p>')
                    .show();
            },
            complete: function() {
                btn.prop('disabled', false).text(flowdino_data.i18n.create_brand);
            }
        });
    });
});
