/* Webshoptiger Catalog Sync for WooCommerce – Admin JS */
(function ($) {
    'use strict';

    $(document).ready(function () {

        if (typeof window.webshoptigerCatalogSync === 'undefined') {
            console.error('Webshoptiger Catalog Sync: webshoptigerCatalogSync not found.');
            return;
        }

        var ajaxUrl = window.webshoptigerCatalogSync.ajaxUrl;
        var nonce   = window.webshoptigerCatalogSync.nonce;
        var pollTimer = null;

        // -------------------------------------------------------------------------
        // Helpers
        // -------------------------------------------------------------------------

        function ajax(action, data, $feedback) {
            if ($feedback && $feedback.length) feedback($feedback, 'Working...', 'loading');
            return $.post(ajaxUrl, $.extend({ action: action, nonce: nonce }, data))
                .then(function (res) {
                    if (res.success) {
                        if ($feedback && $feedback.length) {
                            var msg = (res.data && res.data.message) ? res.data.message : (res.data || 'Done!');
                            feedback($feedback, msg, 'success');
                        }
                    } else {
                        if ($feedback && $feedback.length) feedback($feedback, res.data || 'An error occurred.', 'error');
                    }
                    return res;
                })
                .fail(function () {
                    if ($feedback && $feedback.length) feedback($feedback, 'Network error.', 'error');
                });
        }

        function feedback($el, msg, type) {
            $el.text(msg).removeClass('success error loading').addClass(type).show();
            if (type !== 'loading') {
                setTimeout(function () { $el.fadeOut(400, function () { $el.removeClass('success error loading'); }); }, 4000);
            }
        }

        // -------------------------------------------------------------------------
        // Save site type
        // -------------------------------------------------------------------------

        $('#sc-sitetype-save').on('click', function () {
            ajax('webshoptigercatalogsync_save_sitetype', { is_source: $('#sc-sitetype-select').val() }, $('#sc-sitetype-feedback'))
                .then(function (res) { if (res.success) setTimeout(function () { location.reload(); }, 800); });
        });

        // -------------------------------------------------------------------------
        // Settings tab
        // -------------------------------------------------------------------------

        $('#sc-save-settings').on('click', function () {
            ajax('webshoptigercatalogsync_save_settings', {
                openai_key:           $('#sc-openai-key').val(),
                openai_prompt:        $('#sc-openai-prompt').val(),
                interval:             $('#sc-interval').val(),
                rewrite_descriptions: $('#sc-rewrite').is(':checked') ? 1 : 0
            }, $('#sc-settings-feedback'));
        });

        $('#sc-test-openai').on('click', function () {
            ajax('webshoptigercatalogsync_test_openai', { api_key: $('#sc-openai-key').val() }, $('#sc-openai-feedback'));
        });

        // -------------------------------------------------------------------------
        // Status tab – starting synchronization
        // -------------------------------------------------------------------------

        $('#sc-clear-brand-cache').on('click', function () {
            if (!confirm('Clear brand cache? The next sync will look up all brands on the destination site(s) again.')) return;
            ajax('webshoptigercatalogsync_clear_brand_cache', {}, $('#sc-brand-cache-feedback'));
        });

        $('#sc-clear-cat-cache').on('click', function () {
            if (!confirm('Clear category cache? The next sync will look up all categories on the destination site(s) again.')) return;
            ajax('webshoptigercatalogsync_clear_cat_cache', {}, $('#sc-cat-cache-feedback'));
        });

        $('#sc-manual-sync').on('click', function () {
            if (!confirm('Queue all active websites for synchronization now?')) return;
            ajax('webshoptigercatalogsync_manual', {}, $('#webshoptigercatalogsync-sync-feedback'))
                .then(function (res) { if (res.success) startPolling(); });
        });

        $(document).on('click', '.webshoptigercatalogsync-sync-one', function () {
            var $btn = $(this);
            var siteId = $btn.data('id');
            $btn.prop('disabled', true);
            ajax('webshoptigercatalogsync_sync_site', { site_id: siteId }, $('#webshoptigercatalogsync-sync-feedback'))
                .then(function (res) {
                    $btn.prop('disabled', false);
                    if (res.success) startPolling();
                });
        });

        // Save batch size
        $('#sc-save-batch').on('click', function () {
            ajax('webshoptigercatalogsync_save_batch_size', { batch_size: $('#sc-batch-size').val() }, $('#sc-batch-feedback'));
        });

        // -------------------------------------------------------------------------
        // Product search and manual sync
        // -------------------------------------------------------------------------

        var productSearchTimer = null;

        $('#sc-product-search').on('input', function () {
            var term = $(this).val();
            clearTimeout(productSearchTimer);

            if (term.length < 2) {
                $('#sc-product-search-results').empty();
                return;
            }

            productSearchTimer = setTimeout(function () {
                $.post(ajaxUrl, { action: 'webshoptigercatalogsync_search_products', nonce: nonce, term: term })
                    .then(function (res) {
                        if (!res.success) return;
                        renderProductResults(res.data);
                    });
            }, 350); // debounce
        });

        function renderProductResults(products) {
            var $results = $('#sc-product-search-results');

            if (!products || products.length === 0) {
                $results.html('<div class="sc-product-search-empty">No products found.</div>');
                return;
            }

            var html = '<div class="sc-product-results-list">';
            products.forEach(function (p) {
                var thumb = p.image ? p.image : '';
                html += '<div class="sc-product-result-row" data-product-id="' + p.id + '">';
                if (thumb) {
                    html += '<img class="sc-product-result-thumb" src="' + escAttr(thumb) + '" alt="">';
                } else {
                    html += '<div class="sc-product-result-thumb"></div>';
                }
                html += '<div class="sc-product-result-info">';
                html += '<span class="sc-product-result-name">' + escHtml(p.name) + '</span>';
                html += '<span class="sc-product-result-meta">ID: ' + p.id + (p.sku ? ' • SKU: ' + escHtml(p.sku) : '') + ' • ' + escHtml(p.type) + '</span>';
                html += '</div>';
                html += '<button type="button" class="button button-small button-primary webshoptigercatalogsync-sync-this-product" data-product-id="' + p.id + '">Sync</button>';
                html += '</div>';
            });
            html += '</div>';

            $results.html(html);
        }

        $(document).on('click', '.webshoptigercatalogsync-sync-this-product', function () {
            var $btn = $(this);
            var productId = $btn.data('product-id');
            var siteId = $('#sc-product-target-site').val();

            $btn.prop('disabled', true).text('Working...');

            $.post(ajaxUrl, {
                action: 'webshoptigercatalogsync_sync_single_product',
                nonce: nonce,
                product_id: productId,
                site_id: siteId
            }).then(function (res) {
                $btn.prop('disabled', false).text('Sync');
                if (res.success) {
                    feedback($('#sc-product-sync-feedback'), res.data.message || 'Started', 'success');
                    startPolling();
                } else {
                    feedback($('#sc-product-sync-feedback'), res.data || 'An error occurred.', 'error');
                }
            }).fail(function () {
                $btn.prop('disabled', false).text('Sync');
                feedback($('#sc-product-sync-feedback'), 'Network error.', 'error');
            });
        });

        // escHtml is defined further down in this file (shared with job rendering)
        function escAttr(str) {
            return String(str).replace(/"/g, '&quot;');
        }

        // -------------------------------------------------------------------------
        // Job progress – polling
        // -------------------------------------------------------------------------

        function startPolling() {
            if (pollTimer) return; // already active
            pollTimer = setInterval(pollJobs, 3000);
            pollJobs(); // call immediately
        }

        function stopPolling() {
            if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
        }

        function pollJobs() {
            $.post(ajaxUrl, { action: 'webshoptigercatalogsync_job_status', nonce: nonce })
                .then(function (res) {
                    if (!res.success) return;
                    renderJobs(res.data);

                    // Keep polling while there are running jobs
                    var hasRunning = res.data.some(function (j) { return j.status === 'running'; });
                    if (!hasRunning) {
                        // One extra poll to show the final status, then stop
                        setTimeout(stopPolling, 2000);
                    }
                });
        }

        function renderJobs(jobs) {
            var $list = $('#sc-jobs-list');
            if (!jobs || jobs.length === 0) {
                $list.html('<p class="sc-empty">No synchronizations found.</p>');
                return;
            }

            var html = '';
            jobs.forEach(function (job) {
                var pct      = job.pct || 0;
                var total    = parseInt(job.total) || 0;
                var done     = parseInt(job.done) || 0;
                var synced   = parseInt(job.synced) || 0;
                var failed   = parseInt(job.failed) || 0;
                var label    = job.site_label ? job.site_label : 'All sites';
                var barClass = job.status === 'running'   ? 'sc-bar-running'
                             : job.status === 'completed' ? 'sc-bar-done'
                             : 'sc-bar-cancelled';
                var statusLabel = { running: 'Running', completed: 'Completed', cancelled: 'Cancelled' }[job.status] || job.status;
                var badgeClass  = { running: 'running', completed: 'ok', cancelled: 'off' }[job.status] || 'off';
                var started  = job.started_at ? 'Started: ' + job.started_at : '';
                var finished = job.finished_at ? ' &nbsp;|&nbsp; Finished: ' + job.finished_at : '';

                html += '<div class="sc-job-row" data-job-id="' + job.job_id + '">';

                // Header
                html += '<div class="sc-job-header">';
                html += '<span class="sc-job-label">' + escHtml(label) + '</span>';
                html += '<span class="sc-badge-' + badgeClass + '">' + statusLabel + '</span>';
                if (job.status === 'running') {
                    html += '<button type="button" class="button button-small sc-cancel-job" data-job-id="' + job.job_id + '">Cancel</button>';
                }
                if (job.is_stuck) {
                    html += '<button type="button" class="button button-small button-primary sc-resume-job" data-job-id="' + job.job_id + '">&#9654; Resume</button>';
                    html += '<span class="sc-stuck-warning">Stuck (' + job.minutes_idle + ' min idle)</span>';
                }
                html += '</div>';

                // Progress bar
                html += '<div class="sc-progress-wrap" title="' + pct + '%">';
                html += '<div class="sc-progress-bar ' + barClass + '" style="width:' + pct + '%"></div>';
                html += '</div>';

                // Stats
                html += '<div class="sc-job-stats">';
                html += '<span class="sc-stat"><strong>' + pct + '%</strong> synced</span>';
                html += '<span class="sc-stat-sep">|</span>';
                html += '<span class="sc-stat">' + synced + ' of ' + total + ' products synced</span>';
                if (failed > 0) {
                    html += '<span class="sc-stat-sep">|</span>';
                    html += '<span class="sc-job-errors">' + failed + ' error(s)</span>';
                }
                html += '</div>';

                // Timestamp
                if (started) {
                    html += '<div class="sc-job-time">' + escHtml(started) + finished + '</div>';
                }

                html += '</div>';
            });

            $list.html(html);
        }

        function escHtml(str) {
            return String(str)
                .replace(/&/g, '&amp;').replace(/</g, '&lt;')
                .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
        }

        // Cancel job
        $(document).on('click', '.sc-cancel-job', function () {
            var jobId = $(this).data('job-id');
            if (!confirm('Cancel this job?')) return;
            ajax('webshoptigercatalogsync_cancel_job', { job_id: jobId }, null)
                .then(function () { pollJobs(); });
        });

        // Resume a stuck job
        $(document).on('click', '.sc-resume-job', function () {
            var jobId = $(this).data('job-id');
            var $btn = $(this);
            $btn.prop('disabled', true).text('Working...');
            ajax('webshoptigercatalogsync_resume_job', { job_id: jobId }, null)
                .then(function (res) {
                    $btn.prop('disabled', false).text('\u25b6 Resume');
                    if (res.success) {
                        startPolling();
                        pollJobs();
                    }
                });
        });

        // Remove completed jobs
        $('#sc-clear-jobs').on('click', function () {
            var $btn = $(this);
            $btn.prop('disabled', true).text('Removing...');
            ajax('webshoptigercatalogsync_clear_jobs', {}, null)
                .then(function (res) {
                    $btn.prop('disabled', false).text('Remove completed');
                    if (res.success) {
                        // Always refresh the job list after clearing
                        ajax('webshoptigercatalogsync_job_status', { nonce: window.webshoptigerCatalogSync.nonce }, null)
                            .then(function (r) { if (r.success) renderJobs(r.data); });
                    }
                });
        });

        // Start polling when the page loads on the status tab
        if ($('#sc-jobs-list').length) {
            startPolling();
        }

        // -------------------------------------------------------------------------
        // Log tab
        // -------------------------------------------------------------------------

        $('#sc-clear-log').on('click', function () {
            if (!confirm('Clear the sync log?')) return;
            ajax('webshoptigercatalogsync_clear_log', {}, $('#sc-log-feedback'))
                .then(function (res) { if (res.success) location.reload(); });
        });

        // -------------------------------------------------------------------------
        // Websites tab
        // -------------------------------------------------------------------------

        var $form      = $('#sc-site-form');
        var $formTitle = $('#sc-form-title');
        var $siteId    = $('#sc-site-id');

        function resetForm() {
            $siteId.val('0');
            $formTitle.text('New website');
            $('#sc-label, #sc-site-url, #sc-api-key, #sc-api-secret').val('');
            $('#sc-enabled').prop('checked', true);
            $('#webshoptigercatalogsync-sync-desc').prop('checked', true);
            $('.sc-cat-cb').prop('checked', false);
            $('#sc-site-feedback').hide().text('');
            // New fields
            $('#sc-sync-interval').val('global');
            $('#sc-price-adjustment').val('none');
            $('#sc-price-value').val('0');
            $('#sc-all-fields').prop('checked', true);
            $('.sc-field-cb').prop('checked', true);
            $('#sc-field-checkboxes').hide();
            $('#sc-report-email').val('');
        }

        $('#sc-add-site').on('click', function () {
            resetForm();
            $form.slideDown(200);
        });

        $('#sc-cancel-site').on('click', function () {
            $form.slideUp(200);
        });

        // Toggle individual field checkboxes when "All fields" is unchecked
        $('#sc-all-fields').on('change', function () {
            if ($(this).is(':checked')) {
                $('#sc-field-checkboxes').hide();
                $('.sc-field-cb').prop('checked', true);
            } else {
                $('#sc-field-checkboxes').show();
            }
        });

        $(document).on('click', '.sc-edit-site', function () {
            var site = $(this).closest('tr').data('site');
            if (!site) return;
            resetForm();
            $siteId.val(site.id);
            $formTitle.text('Edit website: ' + site.label);
            $('#sc-label').val(site.label);
            $('#sc-site-url').val(site.site_url);
            $('#sc-api-key').val(site.api_key);
            $('#sc-api-secret').val(site.api_secret);
            $('#sc-enabled').prop('checked', parseInt(site.enabled, 10) === 1);
            $('#webshoptigercatalogsync-sync-desc').prop('checked', parseInt(site.sync_description !== undefined ? site.sync_description : 1, 10) === 1);
            var cats = Array.isArray(site.categories) ? site.categories.map(Number) : [];
            $('.sc-cat-cb').each(function () {
                $(this).prop('checked', cats.indexOf(parseInt($(this).val(), 10)) !== -1);
            });
            // New fields
            $('#sc-sync-interval').val(site.sync_interval || 'global');
            $('#sc-price-adjustment').val(site.price_adjustment || 'none');
            $('#sc-price-value').val(site.price_value || '0');
            $('#sc-report-email').val(site.report_email || '');
            if (Array.isArray(site.sync_fields)) {
                $('#sc-all-fields').prop('checked', false);
                $('#sc-field-checkboxes').show();
                $('.sc-field-cb').each(function () {
                    $(this).prop('checked', site.sync_fields.indexOf($(this).val()) !== -1);
                });
            } else {
                $('#sc-all-fields').prop('checked', true);
                $('#sc-field-checkboxes').hide();
                $('.sc-field-cb').prop('checked', true);
            }
            $form.slideDown(200);
            $('html, body').animate({ scrollTop: $form.offset().top - 80 }, 300);
        });

        $('#sc-save-site').on('click', function () {
            var categories = [];
            $('.sc-cat-cb:checked').each(function () { categories.push($(this).val()); });

            // Collect sync_fields — null if all selected
            var syncFields = null;
            if (!$('#sc-all-fields').is(':checked')) {
                syncFields = [];
                $('.sc-field-cb:checked').each(function () { syncFields.push($(this).val()); });
            }

            ajax('webshoptigercatalogsync_save_site', {
                id:               $siteId.val(),
                label:            $('#sc-label').val(),
                site_url:         $('#sc-site-url').val(),
                api_key:          $('#sc-api-key').val(),
                api_secret:       $('#sc-api-secret').val(),
                categories:       categories,
                enabled:          $('#sc-enabled').is(':checked') ? 1 : 0,
                sync_description: $('#webshoptigercatalogsync-sync-desc').is(':checked') ? 1 : 0,
                sync_interval:    $('#sc-sync-interval').val() || 'global',
                price_adjustment: $('#sc-price-adjustment').val() || 'none',
                price_value:      $('#sc-price-value').val() || '0',
                sync_fields:      syncFields,
                report_email:     $('#sc-report-email').val() || ''
            }, $('#sc-site-feedback'))
                .then(function (res) { if (res.success) setTimeout(function () { location.reload(); }, 1000); });
        });

        $('#sc-test-site').on('click', function () {
            ajax('webshoptigercatalogsync_test_site', {
                site_url:   $('#sc-site-url').val(),
                api_key:    $('#sc-api-key').val(),
                api_secret: $('#sc-api-secret').val()
            }, $('#sc-site-feedback'));
        });

        $(document).on('click', '.sc-delete-site', function () {
            var id = $(this).data('id');
            if (!confirm('Delete website #' + id + '?')) return;
            ajax('webshoptigercatalogsync_delete_site', { id: id }, null)
                .then(function (res) { if (res.success) location.reload(); });
        });

        $(document).on('click', '.sc-reset-remote-ids', function () {
            var id   = $(this).data('id');
            var name = $(this).closest('tr').find('td:first strong').text();
            if (!confirm('Reset sync state for "' + name + '"?\n\nThis clears the plugin\'s memory of which products exist on that destination site. The next sync will re-create all products there from scratch.\n\nProducts on the destination site are NOT deleted — only the plugin\'s internal record is cleared.')) return;
            ajax('webshoptigercatalogsync_reset_remote_ids', { site_id: id }, $('#webshoptigercatalogsync-sync-feedback'));
        });

        // -------------------------------------------------------------------------
        // Report settings
        // -------------------------------------------------------------------------

        $('#sc-save-report-settings').on('click', function () {
            ajax('webshoptigercatalogsync_save_report_settings', {
                report_email:     $('#sc-report-email-global').val(),
                report_frequency: $('#sc-report-frequency').val()
            }, $('#sc-report-feedback'));
        });

        $('#sc-send-test-report').on('click', function () {
            ajax('webshoptigercatalogsync_send_test_report', {}, $('#sc-report-feedback'));
        });

        // -------------------------------------------------------------------------
        // Descriptions tab
        // -------------------------------------------------------------------------

        $(document).on('click', '.sc-regen-desc', function () {
            var productId = $(this).data('product-id');
            var $btn = $(this);
            if (!confirm('Regenerate the description for product #' + productId + '?')) return;
            $btn.prop('disabled', true).text('Working...');
            ajax('webshoptigercatalogsync_regen_desc', { product_id: productId }, $('#sc-desc-feedback'))
                .then(function (res) {
                    $btn.prop('disabled', false).text('Regenerate');
                    if (res.success) setTimeout(function () { location.reload(); }, 1200);
                });
        });

        $(document).on('click', '.sc-delete-desc', function () {
            var $row = $(this).closest('tr');
            var productId = $(this).data('product-id');
            if (!confirm('Delete the cached description for product #' + productId + '?')) return;
            ajax('webshoptigercatalogsync_delete_desc', { product_id: productId }, $('#sc-desc-feedback'))
                .then(function (res) { if (res.success) $row.fadeOut(); });
        });

        $(document).on('click', '.sc-desc-expand', function (e) {
            e.preventDefault();
            var full = $(this).data('full');
            $('#sc-desc-modal-body').html('<p>' + $('<div>').text(full).html().replace(/\n/g, '<br>') + '</p>');
            $('#sc-desc-modal').show();
        });

        $(document).on('click', '.sc-modal-close', function () { $('#sc-desc-modal').hide(); });
        $(document).on('click', '#sc-desc-modal', function (e) { if (e.target === this) $(this).hide(); });

    }); // end document.ready

})(jQuery);
