/**
 * Image Boost — Admin JavaScript
 * Handles bulk optimization, single optimization, restore, and settings save.
 */

(function ($) {
    'use strict';

    // ─── State ────────────────────────────────────
    let bulkRunning = false;
    let bulkPaused = false;
    let totalToProcess = 0;
    let totalProcessed = 0;
    let startTime = 0;
    let currentPage = 1;
    const rowsPerPage = 20;

    // ─── Toast System ─────────────────────────────
    function showToast(message, type = 'success') {
        let $toastContainer = $('#imgboost-toast-container');
        if (!$toastContainer.length) {
            $toastContainer = $('<div id="imgboost-toast-container"></div>').appendTo('body');
        }

        const $toast = $('<div>').addClass('imgboost-toast imgboost-toast-' + type).text(message);
        $toastContainer.append($toast);

        // Animate in
        setTimeout(() => $toast.addClass('imgboost-toast-visible'), 10);

        // Auto remove
        setTimeout(() => {
            $toast.removeClass('imgboost-toast-visible');
            setTimeout(() => $toast.remove(), 300);
        }, 4000);
    }

    // ─── Init ─────────────────────────────────────
    // Initialize modules
    $(document).ready(function () {
        initBulkOptimize();
        initSingleOptimize();
        initRestore();
        initSettings();
        initLevelCards();
        initProFeatures();
        initQuickToggles();
    });

    // ─── Bulk Optimization ────────────────────────
    function initBulkOptimize() {
        const $start = $('#imgboost-start-bulk');
        const $pause = $('#imgboost-pause-bulk');
        const $resume = $('#imgboost-resume-bulk');

        if (!$start.length) return;

        $start.on('click', function () {
            bulkRunning = true;
            bulkPaused = false;
            totalProcessed = 0;
            startTime = Date.now();

            // Get pending count
            totalToProcess = parseInt($('#bulk-pending').text(), 10) || 0;

            if (totalToProcess === 0) {
                showToast(imgboost.strings.complete, 'success');
                return;
            }

            $start.hide();
            $pause.show();
            $('#bulk-progress-section').slideDown(300);
            $('#bulk-results-section').slideDown(300);

            processBatch();
        });

        $pause.on('click', function () {
            bulkPaused = true;
            $pause.hide();
            $resume.show();
            $('#bulk-progress-status').text(imgboost.strings.paused);
        });

        $resume.on('click', function () {
            bulkPaused = false;
            $resume.hide();
            $pause.show();
            processBatch();
        });
    }

    let retryCount = 0;
    const MAX_RETRIES = 3;

    function processBatch() {
        if (!bulkRunning || bulkPaused) return;

        $('#bulk-progress-status').text(imgboost.strings.processing);

        $.ajax({
            url: imgboost.ajaxurl,
            type: 'POST',
            data: {
                action: 'imgboost_bulk_optimize',
                nonce: imgboost.nonce
            },
            success: function (response) {
                if (!response.success) {
                    bulkRunning = false;
                    $('#imgboost-pause-bulk').hide();
                    $('#imgboost-start-bulk').show();
                    $('#bulk-progress-status').text(imgboost.strings.error + ': ' + (response.data?.message || 'Unknown'));
                    return;
                }

                const data = response.data;
                totalProcessed += data.processed;

                // Update progress
                const pct = totalToProcess > 0
                    ? Math.min(100, Math.round((totalProcessed / totalToProcess) * 100))
                    : 100;

                $('#bulk-progress-bar').css('width', pct + '%');
                $('#bulk-progress-pct').text(pct + '%');
                $('#bulk-progress-count').text(totalProcessed + ' / ' + totalToProcess);

                // Calculate speed
                const elapsed = (Date.now() - startTime) / 1000;
                const rawSpeed = elapsed > 0 ? totalProcessed / elapsed : 0;
                const speedDisplay = elapsed > 0 ? rawSpeed.toFixed(1) : "0.0";
                const remaining = data.remaining;
                const eta = rawSpeed > 0 ? Math.round(remaining / rawSpeed) : 0;
                $('#bulk-progress-speed').text(speedDisplay + ' img/s — ETA: ' + formatTime(eta));

                // Update summary counts
                const optimized = parseInt($('#bulk-optimized').text(), 10) + data.processed;
                const pending = Math.max(0, parseInt($('#bulk-pending').text(), 10) - data.processed);
                
                $('#bulk-optimized').text(optimized);
                $('#bulk-pending').text(pending);

                // Append results
                if (data.results && data.results.length) {
                    data.results.forEach(function (item) {
                        appendResult(item);
                    });
                }

                // Continue or finish
                if (data.complete || data.remaining === 0) {
                    bulkRunning = false;
                    $('#bulk-progress-status').text('🎉 ' + imgboost.strings.complete);
                    $('#imgboost-pause-bulk').hide();
                    $('#imgboost-start-bulk').hide();
                    $('#bulk-progress-bar').css('width', '100%');
                    $('#bulk-progress-pct').text('100%');

                    // Show All Done banner
                    var totalOpt = parseInt($('#bulk-optimized').text(), 10) || 0;
                    var $controls = $('.imgboost-bulk-controls');
                    var $allDone = $('<div>').addClass('imgboost-all-done').css({
                        'flex-direction': 'column',
                        'text-align': 'center',
                        'justify-content': 'center',
                        'padding': '40px',
                        'margin-top': '10px',
                        'animation': 'imgboost-fadeIn 0.5s ease-out'
                    });
                    $allDone.append($('<span>').css({ 'font-size': '48px', 'display': 'block', 'margin-bottom': '16px' }).text('🎉'));
                    $allDone.append($('<h2>').css({ 'color': '#6ee7b7', 'font-size': '24px', 'margin': '0 0 10px', 'font-weight': '700' }).text(imgboost.strings.all_optimized || 'All Images Are Optimized!'));
                    $allDone.append($('<p>').css({ 'color': '#a7f3d0', 'font-size': '16px', 'margin': '0' }).text(imgboost.strings.compressed_summary ? imgboost.strings.compressed_summary.replace('%1$d', totalOpt).replace('%2$s', data.total_saved_human || '') : totalOpt + ' images optimized.'));

                    // Replace buttons area with the banner
                    $('.imgboost-bulk-actions').replaceWith($allDone);

                    // Build pagination for the results table
                    buildPagination();
                } else {
                    // Reset retries and continue to next batch
                    retryCount = 0;
                    setTimeout(processBatch, 200);
                }
            },
            error: function (xhr, status, error) {
                if (xhr.status >= 500 && retryCount < MAX_RETRIES) {
                    retryCount++;
                    $('#bulk-progress-status').text(imgboost.strings.server_error + retryCount + '/' + MAX_RETRIES + ' in 5s...');
                    setTimeout(processBatch, 5000); // Backoff for 5s
                } else {
                    $('#bulk-progress-status').text(imgboost.strings.error + ': ' + error);
                    bulkRunning = false;
                }
            }
        });
    }

    function appendResult(item) {
        const $tbody = $('#bulk-results-body');
        const levelIcons = { normal: '🟢', pro: '🔵', ultra: '🟣' };

        const statusClass = item.status === 'optimized'
            ? 'imgboost-result-status-ok'
            : 'imgboost-result-status-err';

        const statusText = item.status === 'optimized' ? imgboost.strings.label_done : '❌ ' + (item.message || 'Error');

        const $tr = $('<tr>');
        
        // Thumbnail
        if (item.thumbnail) {
            $tr.append($('<td>').append($('<img>', { src: item.thumbnail, class: 'imgboost-result-thumb', alt: '' })));
        } else {
            $tr.append($('<td>').text('—'));
        }

        $tr.append($('<td>').text(item.title || '#' + item.id));
        $tr.append($('<td>').text(item.original_size || '—'));
        $tr.append($('<td>').text(item.new_size || '—'));
        $tr.append($('<td>').addClass('imgboost-result-savings').text(item.savings || '—'));
        $tr.append($('<td>').text((levelIcons[item.level] || '') + ' ' + (item.level || '—')));
        $tr.append($('<td>').addClass(statusClass).text(statusText));

        $tbody.prepend($tr);
    }

    function formatTime(seconds) {
        if (seconds < 60) return seconds + 's';
        const m = Math.floor(seconds / 60);
        const s = seconds % 60;
        return m + 'm ' + s + 's';
    }

    // ─── Table Pagination ─────────────────────────
    function buildPagination() {
        var $tbody = $('#bulk-results-body');
        var $rows = $tbody.find('tr');
        var totalRows = $rows.length;
        var totalPages = Math.ceil(totalRows / rowsPerPage);

        if (totalPages <= 1) return;

        currentPage = 1;

        // Remove existing pagination if any
        $('#imgboost-pagination').remove();

        var $paginationWrap = $('<div>').attr('id', 'imgboost-pagination').css({
            'display': 'flex',
            'justify-content': 'center',
            'align-items': 'center',
            'gap': '8px',
            'margin-top': '20px',
            'flex-wrap': 'wrap'
        });

        for (var i = 1; i <= totalPages; i++) {
            var $pageBtn = $('<button>').attr('type', 'button').text(i).css({
                'padding': '8px 14px',
                'border-radius': '8px',
                'border': '1px solid rgba(255,255,255,0.1)',
                'background': i === 1 ? 'var(--imgboost-primary, #6366f1)' : 'rgba(0,0,0,0.3)',
                'color': '#fff',
                'cursor': 'pointer',
                'font-weight': '600',
                'font-size': '14px',
                'transition': 'all 0.2s'
            }).data('page', i);
            $paginationWrap.append($pageBtn);
        }

        $('.imgboost-results-table-wrap').after($paginationWrap);

        showPage(1);

        $paginationWrap.on('click', 'button', function () {
            var p = $(this).data('page');
            currentPage = p;
            showPage(p);
            // Active styling
            $paginationWrap.find('button').css('background', 'rgba(0,0,0,0.3)');
            $(this).css('background', 'var(--imgboost-primary, #6366f1)');
        });
    }

    function showPage(page) {
        var $tbody = $('#bulk-results-body');
        var $rows = $tbody.find('tr');
        var start = (page - 1) * rowsPerPage;
        var end = start + rowsPerPage;

        $rows.hide();
        $rows.slice(start, end).show();
    }

    // ─── Single Optimize (Media Library) ──────────
    function initSingleOptimize() {
        $(document).on('click', '.imgboost-optimize-btn', function (e) {
            e.preventDefault();
            const $btn = $(this);
            const id = $btn.data('id');

            // Hide the "Not Optimized" badge immediately
            $btn.siblings('.imgboost-badge').hide();
            $btn.prop('disabled', true).html('&#x23F3; ' + imgboost.strings.optimizing);

            $.ajax({
                url: imgboost.ajaxurl,
                type: 'POST',
                data: {
                    action: 'imgboost_single_optimize',
                    nonce: imgboost.nonce,
                    attachment_id: id,
                },
                success: function (response) {
                    if (response.success) {
                        const d = response.data;
                        const $col = $btn.closest('.imgboost-col');
                        const $badge = $('<span>', { class: 'imgboost-badge imgboost-optimized', text: imgboost.strings.label_optimized });
                        const $savings = $('<span>', { class: 'imgboost-savings', text: d.savings + ' ' + imgboost.strings.label_saved });
                        const $sizes = $('<span>', { class: 'imgboost-sizes', text: d.original_size + ' → ' + d.new_size });
                        const $btnRest = $('<button>', { type: 'button', class: 'button button-small imgboost-restore-btn', 'data-id': d.id, text: imgboost.strings.btn_restore });
                        const $details = $('<div>', { class: 'imgboost-details' }).append($savings, $sizes, $btnRest);
                        $col.empty().append($badge, $details);

                    } else {
                        $btn.siblings('.imgboost-badge').show(); // Show badge again
                        $btn.prop('disabled', false).text(imgboost.strings.btn_optimize);
                        
                        showToast(response.data?.message || 'Error', 'error');
                    }
                },
                error: function () {
                    $btn.siblings('.imgboost-badge').show(); // Show badge again
                    $btn.prop('disabled', false).text(imgboost.strings.btn_optimize);
                    showToast('Network error. Image might be too large.', 'error');
                }
            });
        });
    }

    // ─── Restore ──────────────────────────────────
    function initRestore() {
        $(document).on('click', '.imgboost-restore-btn', function (e) {
            e.preventDefault();
            const $btn = $(this);
            const id = $btn.data('id');

            if (!$btn.hasClass('imgboost-confirm')) {
                $btn.addClass('imgboost-confirm').text(imgboost.strings.confirm_restore);
                setTimeout(() => {
                    $btn.removeClass('imgboost-confirm').text(imgboost.strings.btn_restore);
                }, 3000);
                return;
            }

            $btn.removeClass('imgboost-confirm').prop('disabled', true).text('...');

            $.ajax({
                url: imgboost.ajaxurl,
                type: 'POST',
                data: {
                    action: 'imgboost_restore_image',
                    nonce: imgboost.nonce,
                    attachment_id: id,
                },
                success: function (response) {
                    if (response.success) {
                        const $col = $btn.closest('.imgboost-col');
                        const $badge = $('<span>', { class: 'imgboost-badge imgboost-pending', text: imgboost.strings.label_not_opt });
                        const $btnOpt = $('<button>', { type: 'button', class: 'button button-small imgboost-optimize-btn', 'data-id': id, text: imgboost.strings.btn_optimize });
                        $col.empty().append($badge, $btnOpt);
                    } else {
                        $btn.prop('disabled', false).text(imgboost.strings.btn_restore);
                        showToast(imgboost.strings.error + ": " + (response.data?.message || 'Unknown Error'), 'error');
                    }
                },
                error: function (xhr, status, error) {
                    $btn.prop('disabled', false).text(imgboost.strings.btn_restore);
                    showToast(imgboost.strings.network_error + ": " + error, 'error');
                }
            });
        });
    }

    // ─── Settings ─────────────────────────────────
    function initSettings() {
        $('#imgboost-settings-form').on('submit', function (e) {
            e.preventDefault();

            const $form = $(this);
            const $status = $('#imgboost-save-status');
            const $btn = $form.find('.imgboost-btn-save');

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

            $.ajax({
                url: imgboost.ajaxurl,
                type: 'POST',
                data: $form.serialize() + '&action=imgboost_save_settings&nonce=' + imgboost.nonce,
                success: function (response) {
                    $btn.prop('disabled', false).text('💾 Save Settings');

                    if (response.success) {
                        $status.text('✅ ' + imgboost.strings.saved).addClass('visible');
                        setTimeout(function () {
                            $status.removeClass('visible');
                        }, 3000);
                        showToast(imgboost.strings.saved, 'success');
                    } else {
                        showToast(response.data?.message || 'Error saving settings', 'error');
                    }
                },
                error: function () {
                    $btn.prop('disabled', false).text('💾 Save Settings');
                    showToast('Network error', 'error');
                }
            });
        });
    }

    // ─── Quick Toggles ────────────────────────────
    function initQuickToggles() {
        $(document).on('change', '.imgboost-quick-toggle-btn', function () {
            const $checkbox = $(this);
            const settingName = $checkbox.data('setting');
            const newValue = $checkbox.is(':checked') ? '1' : '0';
            
            // Add a subtle spinning/loading class if you want, but fast UX is fine.
            $checkbox.prop('disabled', true);

            $.ajax({
                url: imgboost.ajaxurl,
                type: 'POST',
                data: {
                    action: 'imgboost_quick_toggle',
                    nonce: imgboost.nonce,
                    setting: settingName,
                    value: newValue
                },
                success: function (response) {
                    $checkbox.prop('disabled', false);
                    if (response.success) {
                        showToast(imgboost.strings.saved, 'success');
                    } else {
                        showToast(response.data?.message || 'Error', 'error');
                        $checkbox.prop('checked', !$checkbox.is(':checked')); // Revert
                    }
                },
                error: function () {
                    $checkbox.prop('disabled', false);
                    showToast('Network error', 'error');
                    $checkbox.prop('checked', !$checkbox.is(':checked')); // Revert
                }
            });
        });
    }

    // ─── Level Card Click (Dashboard) ─────────────
    function initLevelCards() {
        $(document).on('click', '.imgboost-level-card', function () {
            const level = $(this).data('level');
            if (!level) return;

            // Update UI
            $('.imgboost-level-card').removeClass('imgboost-level-active');
            $('.imgboost-level-active-badge').remove();
            $(this).addClass('imgboost-level-active');
            $(this).append('<div class="imgboost-level-active-badge">✓ Active</div>');

            // Save via AJAX
            $.ajax({
                url: imgboost.ajaxurl,
                type: 'POST',
                data: {
                    action: 'imgboost_save_level',
                    nonce: imgboost.nonce,
                    compression_level: level,
                },
            });
        });
    }

    function initProFeatures() {
        // Chart.js — 30-Day Savings
        if (typeof Chart !== 'undefined' && $('#imgboost-savings-chart').length && window.imgboostChartData) {
            const ctx = document.getElementById('imgboost-savings-chart').getContext('2d');
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: window.imgboostChartData.labels,
                    datasets: [{
                        label: 'Saved Space (MB)',
                        data: window.imgboostChartData.data,
                        backgroundColor: 'rgba(0, 123, 255, 0.1)',
                        borderColor: '#007bff',
                        borderWidth: 2,
                        pointBackgroundColor: '#fff',
                        pointBorderColor: '#007bff',
                        pointHoverBackgroundColor: '#007bff',
                        fill: true,
                        tension: 0.3
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    layout: {
                        padding: { top: 30, bottom: 5, left: 10, right: 10 }
                    },
                    scales: {
                        y: { beginAtZero: true, display: false },
                        x: { 
                            grid: { display: false, drawBorder: false },
                            ticks: { color: '#ffffff', font: { size: 12 } }
                        }
                    },
                    plugins: { legend: { display: false } }
                }
            });
        }
    }

})(jQuery);
