
jQuery(function ($) {

    let currentPage = 1;

    function loadTable(page = 1) {
        currentPage = page;
        $('.meliconnect-loading').show(); // mostrar spinner

        $.get(ajaxurl, {
            action: 'meliconnect_get_sync_items',
            nonce: meliconnect_translations.meliconnect_sync_nonce,
            page: page,
            status: $('#filter-status').val(),
            type: $('#filter-type').val(),
            seller: $('#filter-seller').val(),
            listing: $('#filter-listing').val(),
            needs_sync: $('#filter-needs-sync').val()
        }, function (res) {

            $('#sync-total').text(`Total: ${res.total}`);

            let tbody = $('#sync-table tbody');
            tbody.empty();

            res.items.forEach(item => {

                tbody.append(`
                    <tr>
                        <td>${item.id}</td>
                        <td>
                            <a href="${item.edit_link}" target="_blank" data-woo-product-id="${item.woo_product_id}">
                                ${item.title ? item.title : item.woo_product_id}
                            </a>
                        </td>
                        <td>
                            <a href="${item.meli_permalink}" target="_blank">
                                ${item.meli_item_id}
                            </a>
                        </td>
                        <td>${item.sync_type}</td>
                        <td>${badgeStatus(item.sync_status)}</td>
                        <td>${item.needs_sync}</td>
                        <td>${item.source ?? ''}</td>
                        <td>${item.priority}</td>
                        <td>${item.retry_count}</td>
                        <td>${item.locked_at ?? ''}</td>
                        <td>${item.updated_at}</td>
                        <td>${item.last_error ?? ''}</td>
                    </tr>
                `);
            });

            renderPagination(res.pages, res.current);
        }).always(function () {
            $('.meliconnect-loading').hide();
        });
    }

    function loadLogs(page = 1) {

        $('#logs-tab .meliconnect-loading').show();

        jQuery.get(ajaxurl, {
            action: 'meliconnect_get_sync_logs',
            nonce: meliconnect_translations.meliconnect_sync_nonce,
            page: page,
            action_filter: jQuery('#log-action').val(),
            status: jQuery('#log-status').val(),
            listing: jQuery('#log-listing').val()
        }, function (res) {

            let tbody = jQuery('#logs-table tbody');
            tbody.empty();

            res.items.forEach(row => {

                let oldVal = tryParse(row.old_value);
                let newVal = tryParse(row.new_value);

                tbody.append(`
                <tr class="log-row" data-id="${row.id}">
                    <td><i class="fas fa-angle-down"></i></td>
                    <td>
                        <div class="meliconnect-product-cell">

                            <div class="meliconnect-product-main">
                                ${row.woo_title
                        ? `<strong>${row.woo_title || 'Product #' + row.woo_product_id}</strong>`
                        : `<strong>${row.woo_product_id || '-'}</strong>`
                    }
                            </div>

                            <div class="meliconnect-actions">
                                ${row.woo_edit_link
                        ? `<a href="${row.woo_edit_link}" target="_blank" class="meliconnect-button meliconnect-is-primary meliconnect-is-small">Edit</a>`
                        : ''
                    }

                                ${row.meli_permalink
                        ? `<a href="${row.meli_permalink}" target="_blank" class="meliconnect-button meliconnect-is-link meliconnect-is-small">
                                            View Meli
                                    </a>`
                        : ''
                    }
                            </div>

                        </div>
                    </td>
                    <td>${row.created_at}</td>
                    <td>${row.action}</td>
                    <td>${badgeStatus(row.status)}</td>
                    <td>${row.source}</td>
                    <td><button class="meliconnect-button meliconenct-sm show-settings" data-settings="${encodeURIComponent(row.settings || '')}">View</button></td>
                </tr>

                <tr class="log-details" id="details-${row.id}" style="display:none;">
                    <td colspan="9">
                        <pre>
                        ${JSON.stringify({ old: oldVal, new: newVal }, null, 2)}
                        </pre>
                    </td>
                </tr>
            `);
            });

            renderPaginationLogs(res.pages, res.current);
        }).always(function () {
            $('#logs-tab .meliconnect-loading').hide();
        });
    }

    $('#run-seeder').on('click', function () {

        MeliconSwal.fire({
            title: 'What is the Seeder?',
            html: `
            <div class="meliconnect-has-text-center">

                <p class="meliconnect-mb-3">
                    <strong>Seeder</strong> creates missing records in the <code>sync table</code> from your WooCommerce products.
                </p>

                <p class="meliconnect-mb-3">

                    Records are usually created automatically via WordPress hooks.

                </p>
                <p class="meliconnect-mb-3">
                    If some products are missing (e.g. due to third-party plugins), run the Seeder manually.
                </p>

                <div class="meliconnect-notification meliconnect-is-warning meliconnect-is-light meliconnect-mt-3">
                    Safe to run multiple times. No duplicates will be created.
                </div>

            </div>
            `,
            icon: 'info',
            showCancelButton: true,
            confirmButtonText: 'Run Seeder',
            cancelButtonText: 'Cancel',
            customClass: {
                confirmButton: 'meliconnect-button meliconnect-is-warning',
                cancelButton: 'meliconnect-button'
            }
        }).then(result => {
            if (result.isConfirmed) {
                runSeederProcess();
            }
        });

    });

    function runSeederProcess() {

        let offset = 0;
        let limit = 50;
        let total = null;
        let processedTotal = 0;
        let isCancelled = false;

        MeliconSwal.fire({
            title: 'Running Seeder...',
            html: `
            <div style="text-align:left">
                <div id="seeder-progress-text">Starting...</div>
                <progress id="seeder-progress-bar" value="0" max="100" style="width:100%"></progress>
            </div>
        `,
            allowOutsideClick: false,
            showConfirmButton: false,
            showCancelButton: true,
            cancelButtonText: 'Stop',
            didOpen: () => {
                $('.swal2-cancel').on('click', function () {
                    isCancelled = true;
                });
                runBatch();
            }
        });

        function runBatch() {

            if (isCancelled) return;

            $.post(ajaxurl, {
                action: 'meliconnect_seed_sync_table',
                nonce: meliconnect_translations.meliconnect_sync_nonce,
                offset: offset,
                limit: limit
            }, function (res) {

                if (!res.success) {
                    MeliconSwal.fire('Error', 'Seeder failed', 'error');
                    return;
                }

                let data = res.data;

                // TOTAL viene del backend (transient)
                if (total === null) {
                    total = data.total || 0;
                }

                processedTotal += data.processed;
                offset = data.next_offset;

                let percent = total > 0
                    ? Math.min(100, Math.round((processedTotal / total) * 100))
                    : 0;

                $('#seeder-progress-bar').val(percent);
                $('#seeder-progress-text').text(
                    `Processed ${processedTotal} / ${total} (${percent}%)`
                );

                if (data.has_more) {
                    runBatch(); // siguiente lote
                } else {
                    MeliconSwal.fire({
                        title: 'Seeder Completed',
                        text: `Processed ${processedTotal} items`,
                        icon: 'success'
                    });

                    loadTable(1); // refresh tabla
                }

            });

        }
    }

    jQuery('#log-action, #log-status, #log-listing').on('change keyup', function () {
        loadLogs(1); // siempre volvés a la página 1 al filtrar
    });

    $(document).on('click', '#pagination-logs button', function () {
        loadLogs($(this).data('page'));
    });

    function renderPaginationLogs(totalPages, current) {

        let container = $('#pagination-logs');

        if (!container.length) {
            $('#logs-table').after('<div id="pagination-logs" class="meliconnect-pagination"></div>');
            container = $('#pagination-logs');
        }

        container.empty();

        for (let i = 1; i <= totalPages; i++) {
            container.append(`
            <button class="meliconnect-button ${i === current ? 'meliconnect-is-primary' : ''}" data-page="${i}">
                ${i}
            </button>
        `);
        }
    }

    jQuery(document).on('click', '#clean-logs', function () {

        Swal.fire({
            title: 'Delete logs?',
            text: 'This action cannot be undone',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, delete',
            cancelButtonText: 'Cancel',
            customClass: {
                confirmButton: 'meliconnect-button meliconnect-is-danger',
                cancelButton: 'meliconnect-button meliconnect-is-secondary'
            }
        }).then((result) => {

            if (!result.isConfirmed) return;

            MeliconSwal.fire({
                title: 'Cleaning logs...',
                allowOutsideClick: false,
                didOpen: () => Swal.showLoading()
            });

            jQuery.post(ajaxurl, {
                action: 'meliconnect_clean_logs',
                nonce: meliconnect_translations.meliconnect_sync_nonce
            }, function (res) {

                MeliconSwal.close();

                if (res.success) {
                    MeliconSwal.fire({
                        title: 'Done',
                        text: 'Deleted ${res.data.deleted} logs successfully.',
                        icon: 'success',
                        confirmButtonText: 'OK'
                    });

                    loadLogs(1); // recargar tabla
                } else {
                    MeliconSwal.fire({
                        title: 'Error',
                        text: res.data?.message || 'Something went wrong',
                        icon: 'error'
                    });
                }

            });
        });
    });

    function tryParse(val) {
        try { return JSON.parse(val); } catch { return val; }
    }

    function formatVal(val) {
        if (typeof val === 'object') return JSON.stringify(val);
        return val ?? '';
    }

    // expand row
    jQuery(document).on('click', '.log-row', function () {

        let id = jQuery(this).data('id');
        let currentDetails = jQuery(`#details-${id}`);
        let currentIcon = jQuery(this).find('td:first i');

        // cerrar todos
        jQuery('.log-details').not(currentDetails).hide();
        jQuery('.log-row i.fas')
            .removeClass('fa-angle-up')
            .addClass('fa-angle-down');

        // toggle actual
        currentDetails.toggle();
        currentIcon.toggleClass('fa-angle-down fa-angle-up');
    });

    // settings popup 
    jQuery(document).on('click', '.show-settings', function (e) {
        e.stopPropagation();

        let settings = jQuery(this).data('settings') || '';

        // decode si usaste encodeURIComponent
        settings = decodeURIComponent(settings);

        try {
            settings = typeof settings === 'string' ? JSON.parse(settings) : settings;
        } catch (e) {
            console.warn('Error parsing settings', settings);
        }

        MeliconSwal.fire({
            title: 'Used Settings',
            html: `<pre style="text-align:left; max-height:400px; overflow:auto;">${escapeHtml(JSON.stringify(settings, null, 2))}</pre>`,
            width: 700,
            showConfirmButton: false,
            showCloseButton: true,
            customClass: {
                confirmButton: 'meliconnect-button meliconnect-is-primary'
            }
        });
    });

    function escapeHtml(text) {
        return text
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;");
    }

    jQuery(document).on('click', '.meliconnect-modal-close, .meliconnect-modal-background', function () {
        jQuery('#settings-modal').hide();
    });

    function renderPagination(totalPages, current) {

        let container = $('#pagination');
        if (!container.length) {
            $('.meliconnect-table-container').after('<div id="pagination" class="meliconnect-pagination"></div>');
            container = $('#pagination');
        }

        container.empty();

        for (let i = 1; i <= totalPages; i++) {
            container.append(`
                <button class="meliconnect-button ${i === current ? 'meliconnect-is-primary' : ''}" data-page="${i}">
                    ${i}
                </button>
            `);
        }
    }

    function badgeStatus(status) {
        const map = {
            pending: 'is-warning',
            processing: 'is-info',
            error: 'is-danger',
            synced: 'is-success'
        };

        return `<span class="meliconnect-tag meliconnect-${map[status] || ''}">${status}</span>`;
    }

    jQuery('.meliconnect-tabs li').on('click', function () {

        let tab = jQuery(this).data('tab');

        jQuery('.meliconnect-tabs li').removeClass('meliconnect-is-active');
        jQuery(this).addClass('meliconnect-is-active');

        if (tab === 'logs') {
            jQuery('#state-tab').hide();
            jQuery('#logs-tab').show();
            loadLogs();
        } else {
            jQuery('#logs-tab').hide();
            jQuery('#state-tab').show();
        }
    });

    // eventos
    $(document).on('click', '#pagination button', function () {
        loadTable($(this).data('page'));
    });

    $('#refresh').on('click', () => loadTable(1));

    $('#filter-status, #filter-type, #filter-needs-sync').on('change', () => loadTable(1));

    $('#filter-seller, #filter-listing').on(
        'keyup',
        debounce(() => loadTable(1), 400)
    );

    function debounce(func, delay) {
        let timeout;
        return function () {
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(this, arguments), delay);
        };
    }

    // init
    loadTable();
});

