/* A1-WooBay - Product Metabox JS v0.8.3 */
(function($) {
    'use strict';

    $(function() {

        var $result   = $('#a1wb-push-result');

        function btn(id) { return $(id); }

        function setLoading(selector, msg) {
            btn(selector).prop('disabled', true);
            $result.html('<em>' + msg + '</em>');
        }

        function handleResponse(selector, res, successReload) {
            btn(selector).prop('disabled', false);
            if (res.success) {
                $result.html('<span style="color:#46b450;">' + res.data.message + '</span>');
                if (successReload !== false) {
                    setTimeout(function() { location.reload(); }, 1800);
                }
            } else {
                $result.html('<span style="color:#dc3232;">' + res.data.message + '</span>');
            }
        }

        function handleFail(selector) {
            btn(selector).prop('disabled', false);
            $result.html('<span style="color:#dc3232;">Request failed. Check your connection and try again.</span>');
        }

        // ---- Per-product category search ----
        var $catSearch    = $('#a1wb-prod-cat-search');
        var $catBtn       = $('#a1wb-prod-cat-btn');
        var $catResults   = $('#a1wb-prod-cat-results');
        var $catSelected  = $('#a1wb-prod-cat-selected');
        var $catIdInput   = $('#a1wb_ebay_cat_id');
        var $catNameInput = $('#a1wb_ebay_cat_name');

        // Browser state
        var aspectsCache = null;
        var BADGE_COLORS = { REQUIRED: '#c0392b', RECOMMENDED: '#d97706', OPTIONAL: '#888' };
        var BADGE_LABELS = { REQUIRED: 'REQ', RECOMMENDED: 'REC', OPTIONAL: 'OPT' };

        function renderCatSelected(id, name) {
            $catIdInput.val(id);
            $catNameInput.val(name);
            $catSelected.html(
                '<strong>' + $('<span>').text(name).html() + '</strong>' +
                ' <span style="color:#888;">(ID: ' + $('<span>').text(id).html() + ')</span>' +
                ' <a href="#" id="a1wb-prod-cat-clear" style="float:right;color:#dc3232;text-decoration:none;" title="Clear">&times;</a>'
            ).show();
            $catResults.hide().empty();
            $catSearch.val('');
        }

        function doCatSearch() {
            var q = $catSearch.val().trim();
            if (q.length < 2) return;
            $catBtn.prop('disabled', true).text('Searching...');
            $catResults.show().html('<div style="padding:6px;color:#888;">Searching...</div>');
            $.post(a1woobay.ajax_url, {
                action: 'a1woobay_search_categories',
                nonce:  a1woobay.search_nonce,
                query:  q
            })
            .done(function(res) {
                $catBtn.prop('disabled', false).text('Search');
                if (!res.success) {
                    $catResults.html('<div style="padding:6px;color:#dc3232;">' + (res.data && res.data.message ? res.data.message : 'Search failed.') + '</div>');
                    return;
                }
                if (!res.data.categories || !res.data.categories.length) {
                    $catResults.html('<div style="padding:6px;color:#888;">No results found.</div>');
                    return;
                }
                var html = '';
                $.each(res.data.categories, function(i, cat) {
                    html += '<div class="a1wb-cat-result" data-id="' + cat.id + '" data-name="' + $('<span>').text(cat.name).html() + '"' +
                        ' style="padding:5px 8px;cursor:pointer;border-bottom:1px solid #f0f0f0;">' +
                        $('<span>').text(cat.name).html() +
                        '<span style="color:#aaa;font-size:11px;"> (' + cat.id + ')</span></div>';
                });
                $catResults.html(html);
            })
            .fail(function() {
                $catBtn.prop('disabled', false).text('Search');
                $catResults.html('<div style="padding:6px;color:#dc3232;">Search failed.</div>');
            });
        }

        $catBtn.on('click', doCatSearch);
        $catSearch.on('keydown', function(e) {
            if (e.which === 13) { e.preventDefault(); doCatSearch(); }
        });

        $(document).on('click', '.a1wb-cat-result', function() {
            renderCatSelected($(this).data('id'), $(this).data('name'));
            aspectsCache = null;
            $('#a1wb-aspects-browser').hide();
            showAspectsBar();
        });

        $(document).on('mouseenter', '.a1wb-cat-result', function() {
            $(this).css('background', '#f0f8ff');
        }).on('mouseleave', '.a1wb-cat-result', function() {
            $(this).css('background', '');
        });

        $(document).on('click', '#a1wb-prod-cat-clear', function(e) {
            e.preventDefault();
            $catIdInput.val('');
            $catNameInput.val('');
            $catSelected.hide().empty();
            aspectsCache = null;
            $('#a1wb-aspects-browser').hide();
            showAspectsBar();
        });

        // ---- Aspects bar show/hide ----
        var $aspectsBar  = $('#a1wb-aspects-bar');
        var $aspectsMsg  = $('#a1wb-aspects-msg');
        var SKIP_ASPECTS = ['Brand', 'MPN', 'UPC', 'EAN', 'ISBN', 'GTIN', 'Manufacturer Part Number'];

        function showAspectsBar() {
            if ($catIdInput.val()) {
                $aspectsBar.show();
            } else {
                $aspectsBar.hide();
                $aspectsMsg.text('');
            }
        }
        showAspectsBar();

        // Helper: names already in the spec table
        function existingSpecNames() {
            var names = [];
            $('#a1wb-spec-tbody tr').each(function() {
                var n = $(this).find('input[name*="[name]"]').val();
                if (n) names.push(n.trim().toLowerCase());
            });
            return names;
        }

        // Add a spec row; attach datalist if predefined values exist
        function addAspectRow(asp) {
            var val = (asp.values && asp.values.length === 1) ? asp.values[0] : '';
            var idx = specIndex++;
            $('#a1wb-spec-tbody').append(specRowHtml(idx, asp.name, 'custom', val));
            if (asp.values && asp.values.length > 1) {
                var listId    = 'a1wb-dl-' + idx;
                var $valInput = $('#a1wb-spec-tbody tr:last').find('input[name*="[value]"]');
                var dlHtml    = '<datalist id="' + listId + '">';
                $.each(asp.values, function(i, v) {
                    dlHtml += '<option value="' + $('<div>').text(v).html() + '">';
                });
                dlHtml += '</datalist>';
                $('body').append(dlHtml);
                $valInput.attr('list', listId);
            }
        }

        // ---- "Load Suggested Specifics" ----
        $(document).on('click', '#a1wb-load-aspects-btn', function() {
            var catId = $catIdInput.val();
            if (!catId) { $aspectsMsg.css('color','#dc3232').text('Select a category first.'); return; }

            $('#a1wb-load-aspects-btn').prop('disabled', true);
            $aspectsMsg.css('color','#888').text('Loading...');

            $.post(a1woobay.ajax_url, {
                action:      'a1woobay_get_category_aspects',
                nonce:       a1woobay.search_nonce,
                category_id: catId
            })
            .done(function(res) {
                $('#a1wb-load-aspects-btn').prop('disabled', false);
                if (!res.success) {
                    $aspectsMsg.css('color', '#dc3232').text(res.data.message || 'Failed.');
                    return;
                }
                if (!aspectsCache) { renderAspectsBrowser(res.data); $('#a1wb-aspects-browser').hide(); }
                var required    = res.data.required    || [];
                var recommended = res.data.recommended || [];
                var existing    = existingSpecNames();
                var added = 0, skipped = 0;
                $.each(required.concat(recommended), function(i, asp) {
                    if (SKIP_ASPECTS.indexOf(asp.name) !== -1) return;
                    if (existing.indexOf(asp.name.trim().toLowerCase()) !== -1) { skipped++; return; }
                    addAspectRow(asp);
                    existing.push(asp.name.trim().toLowerCase());
                    added++;
                });
                var parts = [];
                if (added)   parts.push(added + ' added');
                if (skipped) parts.push(skipped + ' already present');
                var msg = parts.length ? parts.join(', ') + '.' : 'No new specifics for this category.';
                var reqCount = required.length;
                if (reqCount) msg = reqCount + ' required field' + (reqCount !== 1 ? 's' : '') + '. ' + msg;
                $aspectsMsg.css('color', '#888').text(msg);
            })
            .fail(function() {
                $('#a1wb-load-aspects-btn').prop('disabled', false);
                $aspectsMsg.css('color', '#dc3232').text('Request failed.');
            });
        });

        // ---- Item specifics browser ----

        function renderAspectsBrowser(data) {
            var all = [];
            $.each(data.required    || [], function(i, a) { all.push($.extend({}, a, {_usage: 'REQUIRED'})); });
            $.each(data.recommended || [], function(i, a) { all.push($.extend({}, a, {_usage: 'RECOMMENDED'})); });
            $.each(data.optional    || [], function(i, a) { all.push($.extend({}, a, {_usage: 'OPTIONAL'})); });
            aspectsCache = all;
            filterAspectsBrowser();
        }

        function filterAspectsBrowser() {
            if (!aspectsCache) return;
            var q        = ($('#a1wb-aspects-search').val() || '').toLowerCase().trim();
            var filter   = $('#a1wb-aspects-filter').val() || 'all';
            var $list    = $('#a1wb-aspects-list');
            var existing = existingSpecNames();

            var items = aspectsCache.filter(function(a) {
                if (filter !== 'all' && a._usage !== filter) return false;
                if (q && a.name.toLowerCase().indexOf(q) === -1) return false;
                return true;
            });

            if (!items.length) {
                $list.html('<div style="color:#888;padding:6px;font-size:12px;">No matching specifics.</div>');
                return;
            }

            var html = '';
            $.each(items, function(i, a) {
                var color   = BADGE_COLORS[a._usage] || '#888';
                var badge   = BADGE_LABELS[a._usage] || 'OPT';
                var isAdded = existing.indexOf(a.name.trim().toLowerCase()) !== -1;
                var safeN   = $('<span>').text(a.name).html();
                var valHtml;
                if (a.values && a.values.length > 1) {
                    valHtml = '<select class="a1wb-asp-val" style="font-size:11px;max-width:130px;flex-shrink:0;">' +
                        '<option value="">-- pick --</option>';
                    $.each(a.values, function(j, v) {
                        valHtml += '<option>' + $('<span>').text(v).html() + '</option>';
                    });
                    valHtml += '</select>';
                } else {
                    valHtml = '<input type="text" class="a1wb-asp-val" placeholder="value" style="font-size:11px;width:90px;flex-shrink:0;">';
                }
                html += '<div class="a1wb-asp-row" style="display:flex;align-items:center;gap:4px;padding:3px 2px;border-bottom:1px solid #f0f0f0;" data-name="' + safeN + '">';
                html += '<span style="display:inline-block;min-width:32px;text-align:center;padding:1px 3px;border-radius:2px;font-size:10px;font-weight:700;color:#fff;background:' + color + ';">' + badge + '</span>';
                html += '<span style="flex:1;font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="' + safeN + '">' + safeN + '</span>';
                html += valHtml;
                if (isAdded) {
                    html += '<button type="button" class="button a1wb-asp-add" style="font-size:11px;padding:0 6px;color:#888;" disabled>Added</button>';
                } else {
                    html += '<button type="button" class="button a1wb-asp-add" style="font-size:11px;padding:0 6px;">Add</button>';
                }
                html += '</div>';
            });
            $list.html(html);
        }

        $(document).on('click', '#a1wb-browse-aspects-btn', function() {
            var catId    = $catIdInput.val();
            if (!catId) { $aspectsMsg.css('color','#dc3232').text('Select a category first.'); return; }
            var $browser = $('#a1wb-aspects-browser');
            if ($browser.is(':visible') && aspectsCache) { $browser.hide(); return; }
            $browser.show();
            if (aspectsCache) { filterAspectsBrowser(); return; }
            $('#a1wb-aspects-list').html('<div style="color:#888;padding:6px;font-size:12px;">Loading...</div>');
            $aspectsMsg.css('color','#888').text('');
            $.post(a1woobay.ajax_url, {
                action:      'a1woobay_get_category_aspects',
                nonce:       a1woobay.search_nonce,
                category_id: catId
            })
            .done(function(res) {
                if (!res.success) {
                    $('#a1wb-aspects-list').html('<div style="color:#dc3232;padding:6px;font-size:12px;">' + (res.data && res.data.message ? res.data.message : 'Failed.') + '</div>');
                    return;
                }
                renderAspectsBrowser(res.data);
            })
            .fail(function() {
                $('#a1wb-aspects-list').html('<div style="color:#dc3232;padding:6px;font-size:12px;">Request failed.</div>');
            });
        });

        $(document).on('click', '#a1wb-aspects-close', function() { $('#a1wb-aspects-browser').hide(); });
        $('#a1wb-aspects-search').on('input',  function() { filterAspectsBrowser(); });
        $('#a1wb-aspects-filter').on('change', function() { filterAspectsBrowser(); });

        $(document).on('click', '.a1wb-asp-add', function() {
            var $row  = $(this).closest('.a1wb-asp-row');
            var name  = $row.data('name') || '';
            if (!name) return;
            var value = $row.find('.a1wb-asp-val').val() || '';
            addAspectRow({ name: name, values: value ? [value] : [] });
            $(this).prop('disabled', true).text('Added').css('color', '#888');
        });

        // Custom listing title character counter
        var $customTitle  = $('#a1wb_custom_title');
        var $titleCounter = $('#a1wb-title-counter');
        $customTitle.on('input', function() {
            var len = $(this).val().length;
            $titleCounter.text(len + '/80');
            $titleCounter.css('color', len > 80 ? '#dc3232' : len > 65 ? '#d97706' : '#888');
        });

        // ---- eBay action buttons ----

        $(document).on('click', '#a1wb-verify-btn', function() {
            setLoading('#a1wb-verify-btn', 'Verifying with eBay...');
            $.post(a1woobay.ajax_url, {
                action:            'a1woobay_verify_product',
                nonce:             a1woobay.nonce,
                product_id:        a1woobay.product_id,
                cat_id:            $('#a1wb_ebay_cat_id').val(),
                cat_name:          $('#a1wb_ebay_cat_name').val(),
                product_condition: $('#a1wb_product_condition').val()
            })
            .done(function(res) { handleResponse('#a1wb-verify-btn', res); })
            .fail(function()    { handleFail('#a1wb-verify-btn'); });
        });

        $(document).on('click', '#a1wb-push-btn', function() {
            setLoading('#a1wb-push-btn', 'Publishing...');
            $.post(a1woobay.ajax_url, {
                action:     'a1woobay_push_product',
                nonce:      a1woobay.nonce,
                product_id: a1woobay.product_id
            })
            .done(function(res) { handleResponse('#a1wb-push-btn', res); })
            .fail(function()    { handleFail('#a1wb-push-btn'); });
        });

        $(document).on('click', '#a1wb-revise-btn', function() {
            setLoading('#a1wb-revise-btn', 'Updating eBay...');
            $.post(a1woobay.ajax_url, {
                action:            'a1woobay_verify_product',
                nonce:             a1woobay.nonce,
                product_id:        a1woobay.product_id,
                cat_id:            $('#a1wb_ebay_cat_id').val(),
                cat_name:          $('#a1wb_ebay_cat_name').val(),
                product_condition: $('#a1wb_product_condition').val()
            })
            .done(function(res) {
                if (!res.success) { handleResponse('#a1wb-revise-btn', res); return; }
                $result.html('<em>Syncing listing...</em>');
                $.post(a1woobay.ajax_url, {
                    action:     'a1woobay_push_product',
                    nonce:      a1woobay.nonce,
                    product_id: a1woobay.product_id
                })
                .done(function(r2) { handleResponse('#a1wb-revise-btn', r2); })
                .fail(function()   { handleFail('#a1wb-revise-btn'); });
            })
            .fail(function() { handleFail('#a1wb-revise-btn'); });
        });

        $(document).on('click', '#a1wb-end-btn', function() {
            if (!confirm('End this eBay listing? It will be removed from eBay.')) return;
            setLoading('#a1wb-end-btn', 'Ending listing...');
            $.post(a1woobay.ajax_url, {
                action:     'a1woobay_end_listing',
                nonce:      a1woobay.nonce,
                product_id: a1woobay.product_id
            })
            .done(function(res) { handleResponse('#a1wb-end-btn', res); })
            .fail(function()    { handleFail('#a1wb-end-btn'); });
        });

        $(document).on('click', '#a1wb-sold-btn', function() {
            if (!confirm('Mark as sold? This will end the eBay listing and set WooCommerce stock to 0.')) return;
            setLoading('#a1wb-sold-btn', 'Marking as sold...');
            $.post(a1woobay.ajax_url, {
                action:     'a1woobay_mark_sold',
                nonce:      a1woobay.nonce,
                product_id: a1woobay.product_id
            })
            .done(function(res) { handleResponse('#a1wb-sold-btn', res); })
            .fail(function()    { handleFail('#a1wb-sold-btn'); });
        });

        $(document).on('click', '#a1wb-relist-btn', function() {
            setLoading('#a1wb-relist-btn', 'Re-verifying...');
            $.post(a1woobay.ajax_url, {
                action:            'a1woobay_verify_product',
                nonce:             a1woobay.nonce,
                product_id:        a1woobay.product_id,
                cat_id:            $('#a1wb_ebay_cat_id').val(),
                cat_name:          $('#a1wb_ebay_cat_name').val(),
                product_condition: $('#a1wb_product_condition').val()
            })
            .done(function(res) {
                if (!res.success) { handleResponse('#a1wb-relist-btn', res); return; }
                $result.html('<em>Verified - publishing...</em>');
                $.post(a1woobay.ajax_url, {
                    action:     'a1woobay_push_product',
                    nonce:      a1woobay.nonce,
                    product_id: a1woobay.product_id
                })
                .done(function(r2) { handleResponse('#a1wb-relist-btn', r2); })
                .fail(function()   { handleFail('#a1wb-relist-btn'); });
            })
            .fail(function() { handleFail('#a1wb-relist-btn'); });
        });

        // ---- Price source show/hide ----
        $('#a1wb_price_type').on('change', function() {
            $('#a1wb-price-value-row').toggle($(this).val() === 'fixed');
        });


    }); // end DOM-ready

    // ---- Per-product item specifics ----
    var specIndex = $('#a1wb-spec-tbody tr').length;

    function specEsc(str) {
        return $('<div>').text(str).html().replace(/"/g, '&quot;');
    }

    function specRowHtml(idx, name, source, value) {
        var custSel = source !== 'attribute' ? ' selected' : '';
        var attrSel = source === 'attribute'  ? ' selected' : '';
        var ph      = source === 'attribute' ? 'e.g. pa_pattern' : 'e.g. Floral';
        return '<tr class="a1wb-spec-row">' +
            '<td style="padding:2px 4px;"><input type="text" name="a1wb_specifics[' + idx + '][name]" value="' + specEsc(name) + '" placeholder="e.g. Pattern" style="width:100%;font-size:12px;"></td>' +
            '<td style="padding:2px 4px;"><select name="a1wb_specifics[' + idx + '][source]" class="a1wb-spec-source" style="width:100%;font-size:12px;">' +
                '<option value="custom"' + custSel + '>Custom</option>' +
                '<option value="attribute"' + attrSel + '>WC Attribute</option>' +
            '</select></td>' +
            '<td style="padding:2px 4px;"><input type="text" name="a1wb_specifics[' + idx + '][value]" value="' + specEsc(value) + '" placeholder="' + ph + '" style="width:100%;font-size:12px;"></td>' +
            '<td style="padding:2px 4px;"><button type="button" class="button a1wb-spec-remove" style="padding:0 5px;color:#dc3232;min-width:0;">&times;</button></td>' +
        '</tr>';
    }

    $(document).on('click', '#a1wb-spec-add', function() {
        $('#a1wb-spec-tbody').append(specRowHtml(specIndex++, '', 'custom', ''));
    });

    $(document).on('click', '.a1wb-spec-remove', function() {
        $(this).closest('tr').remove();
    });

    $(document).on('change', '.a1wb-spec-source', function() {
        var $row = $(this).closest('tr');
        var $val = $row.find('input[name*="[value]"]');
        $val.attr('placeholder', $(this).val() === 'attribute' ? 'e.g. pa_pattern' : 'e.g. Floral');
    });

}(jQuery));
