(function ($) {
    'use strict';

    var panel = {

        init: function () {
            $('#jra-fetch-google-status').on('click', function (e) {
                e.preventDefault();
                if (jraMerchantPanel.variations && jraMerchantPanel.variations.length > 0) {
                    panel.fetchVariations();
                } else {
                    panel.fetch();
                }
            });

            $('#jra-sync-product').on('click', function (e) {
                e.preventDefault();
                panel.syncProduct();
            });

            $(document).on('click', '.jra-fetch-variation-status', function (e) {
                e.preventDefault();
                panel.fetchVariation($(this));
            });

            $(document).on('click', '.jra-preview-variation', function (e) {
                e.preventDefault();
                panel.previewVariation($(this));
            });

            $('#jra-preview-product').on('click', function (e) {
                e.preventDefault();
                panel.previewProduct();
            });
        },

        fetch: function () {
            var $btn        = $('#jra-fetch-google-status');
            var $loading    = $('#jra-status-loading');
            var $marketView = $('#jra-market-view');
            var $error      = $('#jra-status-error');

            $btn.prop('disabled', true);
            $loading.show();
            $marketView.empty();
            $error.hide();

            $.post(jraMerchantPanel.ajaxUrl, {
                action:     'jra_merchant_fetch_product_status',
                nonce:      jraMerchantPanel.nonce,
                product_id: jraMerchantPanel.productId,
                market:     $('#jra-market-select').val() || '',
            })
            .done(function (response) {
                if (response.success) {
                    $marketView.append(panel.renderMarket(response.data.market));
                } else {
                    $error.find('.jra-status-error-msg').text(response.data || 'Unknown error.');
                    $error.show();
                }
            })
            .fail(function () {
                $error.find('.jra-status-error-msg').text('Request failed. Please try again.');
                $error.show();
            })
            .always(function () {
                $btn.prop('disabled', false);
                $loading.hide();
            });
        },

        fetchVariation: function ($btn) {
            var loop        = $btn.data('loop');
            var varId       = $btn.data('variation-id');
            var $loading    = $('#jra-status-loading-' + loop);
            var $marketView = $('#jra-market-view-' + loop);
            var $error      = $('#jra-status-error-' + loop);
            var market      = $('.jra-variation-market-select[data-loop="' + loop + '"]').val() || '';

            $btn.prop('disabled', true);
            $loading.show();
            $marketView.empty();
            $error.hide();

            $.post(jraMerchantPanel.ajaxUrl, {
                action:     'jra_merchant_fetch_product_status',
                nonce:      jraMerchantPanel.nonce,
                product_id: varId,
                market:     market,
            })
            .done(function (response) {
                if (response.success) {
                    $marketView.append(panel.renderMarket(response.data.market));
                } else {
                    $error.find('.jra-status-error-msg').text(response.data || 'Unknown error.');
                    $error.show();
                }
            })
            .fail(function () {
                $error.find('.jra-status-error-msg').text('Request failed. Please try again.');
                $error.show();
            })
            .always(function () {
                $btn.prop('disabled', false);
                $loading.hide();
            });
        },

        syncProduct: function () {
            var $btn    = $('#jra-sync-product');
            var $result = $('#jra-sync-result');

            $btn.prop('disabled', true);
            $result.hide().removeClass('jra-text-error').text('');

            $.post(jraMerchantPanel.ajaxUrl, {
                action:     'jra_merchant_sync_product',
                nonce:      jraMerchantPanel.nonce,
                product_id: jraMerchantPanel.productId,
            })
            .done(function (response) {
                if (response.success) {
                    $result.text(response.data.message).show();
                } else {
                    $result.addClass('jra-text-error').text(response.data || 'Sync failed.').show();
                }
            })
            .fail(function () {
                $result.addClass('jra-text-error').text('Request failed.').show();
            })
            .always(function () {
                $btn.prop('disabled', false);
            });
        },

        fetchVariations: function () {
            var $btn        = $('#jra-fetch-google-status');
            var $loading    = $('#jra-status-loading');
            var $marketView = $('#jra-market-view');
            var $error      = $('#jra-status-error');
            var market      = $('#jra-market-select').val() || '';
            var variations  = jraMerchantPanel.variations;

            $btn.prop('disabled', true);
            $loading.show();
            $marketView.empty();
            $error.hide();

            var pending  = variations.length;
            var $panels  = {};

            // Render placeholder panels in variation order
            $.each(variations, function (i, v) {
                var $p = $('<div class="jra-variation-panel"></div>');
                $p.append('<p class="jra-variation-label"><strong>' + panel.esc(v.label || '#' + v.id) + '</strong></p>');
                $p.append('<div class="jra-variation-placeholder"><span class="spinner is-active" style="float:none;vertical-align:middle;"></span></div>');
                $marketView.append($p);
                $panels[v.id] = $p;
            });

            $.each(variations, function (i, v) {
                $.post(jraMerchantPanel.ajaxUrl, {
                    action:     'jra_merchant_fetch_product_status',
                    nonce:      jraMerchantPanel.nonce,
                    product_id: v.id,
                    market:     market,
                })
                .done(function (response) {
                    var $ph = $panels[v.id].find('.jra-variation-placeholder');
                    if (response.success) {
                        $ph.replaceWith(panel.renderMarket(response.data.market));
                    } else {
                        $ph.replaceWith('<p class="jra-text-error">' + panel.esc(response.data || 'Unknown error.') + '</p>');
                    }
                })
                .fail(function () {
                    $panels[v.id].find('.jra-variation-placeholder').replaceWith('<p class="jra-text-error">Request failed.</p>');
                })
                .always(function () {
                    pending--;
                    if (pending === 0) {
                        $btn.prop('disabled', false);
                        $loading.hide();
                    }
                });
            });
        },

        renderMarket: function (market) {
            var $m = $('<div class="jra-market-result"></div>');

            $m.append('<p class="jra-google-id"><code>' + panel.esc(market.google_id) + '</code></p>');

            if (market.error) {
                $m.append('<p class="jra-text-error" style="margin:0 0 8px;">' + panel.esc(market.error) + '</p>');
                return $m;
            }

            // Destination statuses
            if (market.status && market.status.destinations.length) {
                var $dests = $('<div class="jra-destinations"></div>');
                $.each(market.status.destinations, function (j, dest) {
                    $dests.append(
                        '<span class="jra-dest-name">' + panel.esc(dest.destination) + '</span> ' +
                        '<span class="jra-badge ' + panel.statusBadgeClass(dest.status) + '">' + panel.esc(dest.status) + '</span> '
                    );
                });
                $m.append($dests);
            }

            // Issues
            if (market.issues && market.issues.length) {
                var $issuesWrap = $('<div class="jra-issues-list"></div>');
                $issuesWrap.append('<p class="jra-issues-heading"><strong>Issues (' + market.issues.length + ')</strong></p>');
                var $ul = $('<ul></ul>');
                $.each(market.issues, function (j, issue) {
                    var $li  = $('<li class="jra-issue jra-issue--' + panel.esc(issue.severity) + '"></li>');
                    var html =
                        '<span class="jra-issue-badge jra-issue-badge--' + panel.esc(issue.severity) + '">' + panel.esc(issue.severity) + '</span> ' +
                        '<strong>' + panel.esc(issue.description) + '</strong>';
                    if (issue.attribute) {
                        html += ' <span class="jra-issue-attr">(' + panel.esc(issue.attribute) + ')</span>';
                    }
                    if (issue.detail) {
                        html += '<br><span class="jra-issue-detail">' + panel.esc(issue.detail) + '</span>';
                    }
                    if (issue.documentation) {
                        html += ' <a href="' + panel.esc(issue.documentation) + '" target="_blank" rel="noopener noreferrer">Help &rarr;</a>';
                    }
                    $li.html(html);
                    $ul.append($li);
                });
                $issuesWrap.append($ul);
                $m.append($issuesWrap);
            } else {
                $m.append('<p class="jra-no-issues">&#10003; No issues found.</p>');
            }

            // Indexed product data
            if (market.product) {
                var p      = market.product;
                var fields = [
                    ['Title',                    p.title],
                    ['Price',                    p.price],
                    ['Availability',             p.availability],
                    ['Availability date',        p.availability_date, true],
                    ['Brand',                    p.brand],
                    ['GTIN',                     p.gtin],
                    ['MPN',                      p.mpn],
                    ['Google product category',  p.google_product_category],
                    ['Color',                    p.color],
                    ['Size',                     p.size],
                    ['Material',                 p.material],
                    ['Pattern',                  p.pattern],
                    ['Age group',                p.age_group],
                    ['Gender',                   p.gender],
                ];
                var $dataSection = $('<div class="jra-indexed-data"></div>');
                $dataSection.append('<p class="jra-indexed-heading"><strong>Indexed data</strong></p>');
                var $table = $('<table class="jra-indexed-table"></table>');
                $.each(fields, function (j, field) {
                    var alwaysShow = field[2];
                    if (field[1] || alwaysShow) {
                        $table.append('<tr><th>' + panel.esc(field[0]) + '</th><td>' + panel.esc(field[1] ? String(field[1]) : '—') + '</td></tr>');
                    }
                });
                $dataSection.append($table);
                var allImages = [];
                if (p.image) allImages.push(p.image);
                if (p.additional_images && p.additional_images.length) {
                    allImages = allImages.concat(p.additional_images);
                }
                if (allImages.length) {
                    var $strip = $('<div class="jra-image-strip"></div>');
                    $.each(allImages, function (i, url) {
                        $strip.append('<img src="' + panel.esc(url) + '" alt="" class="jra-indexed-image" title="' + (i === 0 ? 'Main image' : 'Additional image ' + i) + '">');
                    });
                    $dataSection.append($strip);
                }
                $m.append($dataSection);
            }

            return $m;
        },

        previewProduct: function () {
            var $btn         = $('#jra-preview-product');
            var $loading     = $('#jra-preview-loading');
            var $previewView = $('#jra-preview-view');
            var $error       = $('#jra-preview-error');

            $btn.prop('disabled', true);
            $loading.show();
            $previewView.empty();
            $error.hide();

            $.post(jraMerchantPanel.ajaxUrl, {
                action:     'jra_merchant_preview_product',
                nonce:      jraMerchantPanel.nonce,
                product_id: jraMerchantPanel.productId,
                market:     $('#jra-market-select').val() || '',
            })
            .done(function (response) {
                if (response.success) {
                    $previewView.append(panel.renderPreview(response.data));
                } else {
                    $error.find('.jra-preview-error-msg').text(response.data || 'Unknown error.');
                    $error.show();
                }
            })
            .fail(function () {
                $error.find('.jra-preview-error-msg').text('Request failed. Please try again.');
                $error.show();
            })
            .always(function () {
                $btn.prop('disabled', false);
                $loading.hide();
            });
        },

        previewVariation: function ($btn) {
            var loop        = $btn.data('loop');
            var varId       = $btn.data('variation-id');
            var $loading    = $('#jra-preview-loading-' + loop);
            var $previewView = $('#jra-preview-view-' + loop);
            var $error      = $('#jra-preview-error-' + loop);
            var market      = $('.jra-variation-market-select[data-loop="' + loop + '"]').val() || '';

            $btn.prop('disabled', true);
            $loading.show();
            $previewView.empty();
            $error.hide();

            $.post(jraMerchantPanel.ajaxUrl, {
                action:       'jra_merchant_preview_variation',
                nonce:        jraMerchantPanel.nonce,
                variation_id: varId,
                market:       market,
            })
            .done(function (response) {
                if (response.success) {
                    $previewView.append(panel.renderPreview(response.data));
                } else {
                    $error.find('.jra-preview-error-msg').text(response.data || 'Unknown error.');
                    $error.show();
                }
            })
            .fail(function () {
                $error.find('.jra-preview-error-msg').text('Request failed. Please try again.');
                $error.show();
            })
            .always(function () {
                $btn.prop('disabled', false);
                $loading.hide();
            });
        },

        renderPreview: function (data) {
            var $wrap = $('<div class="jra-preview-result jra-indexed-data"></div>');
            $wrap.append('<p class="jra-indexed-heading"><strong>Sync preview</strong> <span style="color:#646970;font-weight:normal;font-size:11px;">Fields that will be submitted to Google</span></p>');

            var p      = data.product;
            var fields = [
                ['Offer ID',                 data.offer_id],
                ['Item group ID',            p.item_group_id],
                ['Title',                    p.title],
                ['Description',              p.description],
                ['Price',                    p.price],
                ['Availability',             p.availability],
                ['Availability date',        p.availability_date, true],
                ['Brand',                    p.brand],
                ['GTIN',                     p.gtin],
                ['MPN',                      p.mpn],
                ['Google product category',  p.google_product_category],
                ['Color',                    p.color],
                ['Size',                     p.size],
                ['Material',                 p.material],
                ['Pattern',                  p.pattern],
                ['Age group',                p.age_group],
                ['Gender',                   p.gender],
                ['Custom label 0',           p.custom_label_0],
                ['Custom label 1',           p.custom_label_1],
                ['Custom label 2',           p.custom_label_2],
                ['Custom label 3',           p.custom_label_3],
                ['Custom label 4',           p.custom_label_4],
            ];

            var $table = $('<table class="jra-indexed-table"></table>');
            $.each(fields, function (j, field) {
                var alwaysShow = field[2];
                if (field[1] || alwaysShow) {
                    $table.append('<tr><th>' + panel.esc(field[0]) + '</th><td>' + panel.esc(field[1] ? String(field[1]) : '—') + '</td></tr>');
                }
            });
            $wrap.append($table);

            var allImages = [];
            if (p.image) allImages.push(p.image);
            if (p.additional_images && p.additional_images.length) {
                allImages = allImages.concat(p.additional_images);
            }
            if (allImages.length) {
                var $strip = $('<div class="jra-image-strip"></div>');
                $.each(allImages, function (i, url) {
                    $strip.append('<img src="' + panel.esc(url) + '" alt="" class="jra-indexed-image" title="' + (i === 0 ? 'Main image' : 'Additional image ' + i) + '">');
                });
                $wrap.append($strip);
            }

            return $wrap;
        },

        statusBadgeClass: function (status) {
            var map = {
                approved:    'jra-badge--green',
                disapproved: 'jra-badge--red',
                pending:     'jra-badge--orange',
            };
            return map[status] || 'jra-badge--blue';
        },

        esc: function (str) {
            if (str === null || str === undefined) return '';
            return String(str)
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;');
        },
    };

    $(function () {
        panel.init();
    });

}(jQuery));
