/* A1-WooBay - Profiles Admin JS
 * Handles: category search, policy loader
 */
(function($) {
    'use strict';

    // ---- Category Search ----

    var $catSearch   = $('#a1wb-cat-search');
    var $catBtn      = $('#a1wb-cat-search-btn');
    var $catResults  = $('#a1wb-cat-results');
    var $cat2Search  = $('#a1wb-cat2-search');
    var $cat2Btn     = $('#a1wb-cat2-search-btn');
    var $cat2Results = $('#a1wb-cat2-results');

    function renderResults($resultsEl, $idField, $nameField, suggestions) {
        $resultsEl.empty();
        if (!suggestions.length) {
            $resultsEl.html('<p style="color:#888;margin:4px 0;">No results found.</p>');
            return;
        }
        var $ul = $('<ul>').css({
            'margin': '4px 0 0',
            'padding': '0',
            'list-style': 'none',
            'border': '1px solid #ddd',
            'border-radius': '3px',
            'max-height': '200px',
            'overflow-y': 'auto',
            'background': '#fff',
        });
        $.each(suggestions, function(i, s) {
            var label = s.name + ' <span style="color:#888;font-size:11px;">(' + s.id + ')</span>';
            if (s.path) label += '<br><small style="color:#888;">' + s.path + '</small>';
            var $li = $('<li>').html(label).css({
                'padding': '6px 10px',
                'cursor': 'pointer',
                'border-bottom': '1px solid #eee',
                'font-size': '13px',
            }).hover(
                function() { $(this).css('background', '#f0f6fc'); },
                function() { $(this).css('background', '#fff'); }
            ).on('click', function() {
                $idField.val(s.id);
                $nameField.val(s.name);
                $resultsEl.empty();
                $catSearch.val('');
                $cat2Search.val('');
            });
            $ul.append($li);
        });
        $resultsEl.append($ul);
    }

    function doSearch($input, $results, $idField, $nameField) {
        var q = $input.val().trim();
        if (!q) return;
        $results.html('<p style="color:#888;margin:4px 0;">Searching...</p>');
        $.post(a1woobayAdmin.ajax_url, {
            action: 'a1woobay_search_categories',
            nonce:  a1woobayAdmin.nonce,
            q:      q
        }, function(res) {
            if (res.success) {
                renderResults($results, $idField, $nameField, res.data.categories);
            } else {
                $results.html('<p style="color:#dc3232;margin:4px 0;">' + (res.data.message || 'Error') + '</p>');
            }
        }).fail(function() {
            $results.html('<p style="color:#dc3232;margin:4px 0;">Request failed.</p>');
        });
    }

    $catBtn.on('click', function() {
        doSearch($catSearch, $catResults, $('#prf_cat_id'), $('#prf_cat_name'));
    });
    $catSearch.on('keypress', function(e) {
        if (e.which === 13) { e.preventDefault(); $catBtn.trigger('click'); }
    });

    $cat2Btn.on('click', function() {
        doSearch($cat2Search, $cat2Results, $('#prf_cat2_id'), $('#prf_cat2_name'));
    });
    $cat2Search.on('keypress', function(e) {
        if (e.which === 13) { e.preventDefault(); $cat2Btn.trigger('click'); }
    });

    // ---- Policy Loader ----

    $('#a1wb-load-policies').on('click', function() {
        var $btn = $(this);
        $btn.prop('disabled', true).text('Loading...');
        $('#a1wb-policy-status').html('<em style="color:#888;">Fetching policies from eBay...</em>');

        $.post(a1woobayAdmin.ajax_url, {
            action: 'a1woobay_get_policies',
            nonce:  a1woobayAdmin.nonce
        }, function(res) {
            $btn.prop('disabled', false).text('Reload Policies');
            if (!res.success) {
                $('#a1wb-policy-status').html('<span style="color:#dc3232;">' + (res.data.message || 'Error') + '</span>');
                return;
            }
            var d = res.data;

            // Replace text inputs with selects
            buildPolicySelect('#prf_policy_ship',   d.fulfillment, 'Select shipping policy...');
            buildPolicySelect('#prf_policy_ret',    d.return,      'Select return policy...');
            buildPolicySelect('#prf_policy_pay',    d.payment,     'Select payment policy...');

            var statusMsg = 'Loaded: ' + d.fulfillment.length + ' shipping, ' + d.return.length + ' return, ' + d.payment.length + ' payment policies.';
            if (d.errors && d.errors.length) {
                statusMsg += ' <span style="color:#dc3232;">Errors: ' + d.errors.join('; ') + '</span>';
            }
            $('#a1wb-policy-status').html('<span style="color:#46b450;">' + statusMsg + '</span>');
        }).fail(function() {
            $btn.prop('disabled', false).text('Reload Policies');
            $('#a1wb-policy-status').html('<span style="color:#dc3232;">Request failed.</span>');
        });
    });

    function buildPolicySelect(inputId, policies, placeholder) {
        var $input    = $(inputId);
        var currentId = $input.val();
        var $select   = $('<select>').attr('id', $input.attr('id')).attr('name', $input.attr('name')).css('width', '100%');
        $select.append($('<option>').val('').text(placeholder));
        $.each(policies, function(i, p) {
            var $opt = $('<option>').val(p.id).text(p.name + ' (' + p.id.slice(-6) + ')');
            if (p.id === currentId) $opt.prop('selected', true);
            $select.append($opt);
        });
        $input.replaceWith($select);
    }

    // ---- Price value row toggle ----
    $('#prf_price_type').on('change', function() {
        $('#a1wb-price-value-row').toggle(this.value === 'percent' || this.value === 'fixed');
    });

    // ---- Item Specifics ----
    $('#a1wb-add-spec').on('click', function() {
        var $tbody = $('#a1wb-specifics-rows');
        var $row = $('<tr class="a1wb-spec-row" style="border-bottom:1px solid #eee;">' +
            '<td style="padding:4px 8px;"><input type="text" class="a1wb-spec-name" style="width:100%;" placeholder="e.g. Brand"></td>' +
            '<td style="padding:4px 8px;"><select class="a1wb-spec-source" style="width:100%;"><option value="custom">Custom Value</option><option value="attribute">WC Attribute</option></select></td>' +
            '<td style="padding:4px 8px;"><input type="text" class="a1wb-spec-value" style="width:100%;" placeholder="Value or attribute (e.g. pa_brand)"></td>' +
            '<td style="padding:4px 8px;text-align:center;"><button type="button" class="a1wb-remove-spec button-link" style="color:#dc3232;">&times;</button></td>' +
            '</tr>');
        $tbody.append($row);
    });

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

    // Serialize item specifics on submit
    $('#a1wb-profile-form').on('submit', function() {
        var data = [];
        $('.a1wb-spec-row').each(function() {
            var name  = $(this).find('.a1wb-spec-name').val().trim();
            var src   = $(this).find('.a1wb-spec-source').val();
            var value = $(this).find('.a1wb-spec-value').val().trim();
            if (name) data.push({ name: name, source: src, value: value });
        });
        $('#prf_item_specifics').val(JSON.stringify(data));
    });

}(jQuery));
