/**
 * UltraGuard Pro — Antivirus real-time scan monitor & UI controller
 *
 * DOM CONTRACT — what the PHP RenderEngine actually outputs:
 *
 *  #ug-scan-panel                    card wrapper (data-nonce, data-running, data-scan-id)
 *    .ultraguard-card-title
 *      .ultraguard-badge             status badge (no id; swapped by setBadgeState())
 *    #ug-progress-fill               render_wrapper outer div (show/hide + class toggle)
 *      .ultraguard-component
 *        .ultraguard-security-suitegress-container
 *          .ultraguard-security-suitegress-label  "Scanning… X%" text — updated by JS
 *          .ultraguard-security-suitegress
 *            .ultraguard-security-suitegress-bar  actual CSS fill bar — width set by JS
 *          [data-rt-progress-label]    percentage span — updated by JS
 *    .ug-scan-live-stats              PHP-rendered list (only when $is_running=true at load)
 *      .ultraguard-list-item (×2)     Files / Threats — badge updated by position
 *    #ug-scan-actions                 button-group wrapper
 *
 * When page loads IDLE (most common) the .ug-scan-live-stats list is NOT in the DOM.
 * JS injects a single stats bar (#ug-live-stats-injected) only in that case.
 * When page loads already RUNNING the PHP list IS in the DOM and JS targets it directly.
 */

(function($) {
    'use strict';

    /* ── Config ─────────────────────────────────────────────────────────────── */
    const POLL_INTERVAL_MS  = 2500;
    const MAX_ERRORS        = 5;
    const COMPLETE_DELAY_MS = 2000;

    /* ── State ──────────────────────────────────────────────────────────────── */
    let pollTimer         = null;
    let currentScanId     = null;
    let isPolling         = false;
    let consecutiveErrors = 0;
    // Did the list already exist when the page loaded (PHP-rendered while running)?
    let phpListExists     = false;

    /* ── Ajax helper ─────────────────────────────────────────────────────────── */
    function ajaxUrl() {
        return (window.ultraguardPro && window.ultraguardPro.ajaxurl)
            || window.ajaxurl
            || '/wp-admin/admin-ajax.php';
    }

    function ajaxPost(action, data, nonce) {
        return $.ajax({
            url:      ajaxUrl(),
            type:     'POST',
            dataType: 'json',
            data:     Object.assign({ action, nonce: nonce || '' }, data),
        });
    }

    /* ── DOM selectors ───────────────────────────────────────────────────────── */
    function panel()        { return $('#ug-scan-panel'); }
    function progressWrap() { return $('#ug-progress-fill'); }

    // Actual CSS fill bar (nested inside render_wrapper outer div)
    function progressBar()  { return $('#ug-progress-fill .ultraguard-security-suitegress-bar'); }

    // Progress label text "Scanning… X%" — rendered by PHP, updated by JS
    function progressLabel(){ return $('#ug-progress-fill .ultraguard-security-suitegress-label'); }

    // Percentage span with [data-rt-progress-label]
    function progressPct()  { return $('#ug-progress-fill [data-rt-progress-label]'); }

    // Status badge in card header
    function statusBadge()  { return panel().find('.ultraguard-card-title .ultraguard-badge'); }

    // Button group
    function scanActions()  { return $('#ug-scan-actions'); }

    // PHP-rendered stats list (present only when page loaded while running)
    function phpStatsList() { return panel().find('.ug-scan-live-stats'); }

    // JS-injected stats bar (present only when JS started the scan from idle)
    function injectedStats(){ return $('#ug-live-stats-injected'); }

    /* ── Initialise ──────────────────────────────────────────────────────────── */
    function init() {
        if (!$('.ultraguard-antivirus-dashboard-page, .ultraguard-file-scanner-page').length &&
            !panel().length) {
            return;
        }

        // Record whether the PHP list was already in the DOM on load
        phpListExists = phpStatsList().length > 0;

        bindEvents();
        checkForActiveScans();
    }

    function bindEvents() {
        $(document).on('click', '.ultraguard-start-scan-btn', function(e) {
            e.preventDefault();
            startScan($(this));
        });

        $(document).on('click', '.ug-stop-scan-btn', function(e) {
            e.preventDefault();
            stopScan($(this));
        });

        // Legacy event from core AJAX manager
        $(document).on('ultraguard:ajax:success', function(e, action, data) {
            if (action === 'ultraguard_antivirus_start_scan' || action === 'ultraguard_start_scan') {
                const scanId = data && (data.scan_id || (data.data && data.data.scan_id));
                if (scanId) {
                    currentScanId = scanId;
                    panel().data('scan-id', scanId);
                    setRunningUI(true);
                    startPolling();
                }
            }
        });
    }

    /* ── Active scan check on load ───────────────────────────────────────────── */
    function checkForActiveScans() {
        const $panel = panel();
        if (!$panel.length) return;

        if ($panel.data('running') == '1') {
            currentScanId = $panel.data('scan-id') || null;
            setRunningUI(true);
            startPolling();
            return;
        }

        ajaxPost('ultraguard_check_active_scan', {}, $panel.data('nonce') || '')
            .done(function(resp) {
                if (resp.success && resp.data && resp.data.active_scan) {
                    currentScanId = resp.data.scan_id;
                    panel().data('scan-id', currentScanId);
                    setRunningUI(true);
                    startPolling();
                }
            });
    }

    /* ── Start scan ──────────────────────────────────────────────────────────── */
    function startScan($btn) {
        if (isPolling) return;

        const scanType   = $btn.data('scan-type')        || 'quick';
        const nonce      = $btn.data('nonce')             || panel().data('nonce') || '';
        const inputId    = $btn.data('custom-path-input');
        const customPath = inputId ? ($('#' + inputId).val() || '') : '';

        $('button.ultraguard-start-scan-btn').prop('disabled', true);

        const postData = { scan_type: scanType };
        if (customPath) postData.custom_path = customPath;

        ajaxPost('ultraguard_antivirus_start_scan', postData, nonce)
            .done(function(resp) {
                if (resp.success) {
                    currentScanId = resp.data.scan_id;
                    panel().data('scan-id', currentScanId)
                           .attr('data-scan-id', currentScanId)
                           .attr('data-running', '1');
                    setRunningUI(true);
                    startPolling();
                    showToast('info', resp.data.message || 'Scan started');
                } else {
                    showToast('error', (resp.data && resp.data.message) || 'Failed to start scan');
                    $('button.ultraguard-start-scan-btn').prop('disabled', false);
                }
            })
            .fail(function() {
                showToast('error', 'Network error — could not start scan');
                $('button.ultraguard-start-scan-btn').prop('disabled', false);
            });
    }

    /* ── Stop scan ───────────────────────────────────────────────────────────── */
    function stopScan($btn) {
        const scanId = currentScanId || $btn.data('scan-id') || '';
        const nonce  = $btn.data('nonce') || panel().data('nonce') || '';

        ajaxPost('ultraguard_antivirus_stop_scan', { scan_id: scanId }, nonce)
            .done(function(resp) {
                if (resp.success) {
                    stopPolling();
                    currentScanId = null;
                    panel().attr('data-running', '0');
                    setRunningUI(false);
                    showToast('info', resp.data.message || 'Scan stopped');
                }
            });
    }

    /* ── Polling ─────────────────────────────────────────────────────────────── */
    function startPolling() {
        if (isPolling) return;
        isPolling         = true;
        consecutiveErrors = 0;
        poll();
    }

    function stopPolling() {
        isPolling = false;
        if (pollTimer) { clearTimeout(pollTimer); pollTimer = null; }
    }

    function poll() {
        if (!isPolling) return;
        const scanId = currentScanId || panel().data('scan-id') || '';
        const nonce  = panel().data('nonce') || '';

        ajaxPost('ultraguard_antivirus_scan_chunk', { scan_id: scanId }, nonce)
            .done(function(resp) {
                consecutiveErrors = 0;
                if (resp.success && resp.data) {
                    updateProgressUI(resp.data);
                    const status = resp.data.status || '';
                    if (status === 'complete' || status === 'cancelled' || status === 'error') {
                        if (status === 'cancelled' && resp.data.error) showToast('error', resp.data.error);
                        handleScanFinished(resp.data);
                        return;
                    }
                }
                scheduleNextPoll();
            })
            .fail(function() {
                consecutiveErrors++;
                if (consecutiveErrors >= MAX_ERRORS) {
                    stopPolling();
                    showToast('error', 'Lost connection to scan — please refresh the page.');
                } else {
                    scheduleNextPoll();
                }
            });
    }

    function scheduleNextPoll() {
        if (!isPolling) return;
        pollTimer = setTimeout(poll, POLL_INTERVAL_MS);
    }

    /* ── Live stats management ───────────────────────────────────────────────── */

    /**
     * Inject a stats bar only when the PHP list was NOT already in the DOM
     * (i.e. the page loaded while idle and the scan was just started by the user).
     * When PHP already rendered the list (.ug-scan-live-stats), we update it directly.
     */
    function ensureStatsVisible() {
        if (phpStatsList().length) {
            // PHP list exists — just make sure it's visible
            phpStatsList().removeClass('ug-hidden').show();
            return;
        }

        // PHP did not render a list — inject our own compact bar
        if (injectedStats().length) return;

        const $bar = $(
            '<div id="ug-live-stats-injected" class="ug-scan-stats-bar">' +
                '<span class="ug-scan-stat">' +
                    '<span class="dashicons dashicons-media-code"></span>' +
                    '<span class="ug-scan-stat-label">Files:</span>' +
                    '<span class="ultraguard-badge ultraguard-badge-info" id="ug-files-scanned">0</span>' +
                '</span>' +
                '<span class="ug-scan-stat">' +
                    '<span class="dashicons dashicons-warning"></span>' +
                    '<span class="ug-scan-stat-label">Threats:</span>' +
                    '<span class="ultraguard-badge ultraguard-badge-success" id="ug-threats-live">0</span>' +
                '</span>' +
                '<span id="ug-current-file" class="ug-scan-current-file"></span>' +
            '</div>'
        );

        // Insert after the progress bar wrapper, before the button group
        progressWrap().after($bar);
    }

    function removeInjectedStats() {
        injectedStats().remove();
    }

    /* ── Running / idle UI ───────────────────────────────────────────────────── */
    function setRunningUI(running) {
        const $stop = $('.ug-stop-scan-btn');

        if (running) {
            // Show progress bar
            progressWrap().show().removeClass('ug-hidden');
            // Reset if fresh start
            if (!currentScanId) {
                progressBar().css('width', '0%');
                progressPct().text('0%');
                progressLabel().text('Scanning… 0%');
            }

            ensureStatsVisible();

            $stop.show();
            scanActions().find('.ultraguard-start-scan-btn').prop('disabled', true);
            setBadgeState('running', i18n('Running'));
        } else {
            $stop.hide();
            scanActions().find('.ultraguard-start-scan-btn').prop('disabled', false);
            setBadgeState('idle', i18n('Idle'));
            // Hide the PHP list; remove the injected bar
            phpStatsList().hide();
            removeInjectedStats();
        }
    }

    /* ── Badge state ─────────────────────────────────────────────────────────── */
    function setBadgeState(state, text) {
        const $badge = statusBadge();
        if (!$badge.length) return;

        const typeMap = { running: 'warning', idle: 'secondary', complete: 'success', error: 'danger' };
        const newType = typeMap[state] || 'secondary';

        $badge.removeClass(function(i, cls) {
            return (cls.match(/\bultraguard-badge-\S+/g) || []).join(' ');
        });
        $badge.addClass('ultraguard-badge-' + newType);

        if (text !== undefined) $badge.text(text);
    }

    /* ── Progress UI update ──────────────────────────────────────────────────── */
    function updateProgressUI(data) {
        const pct     = Math.min(100, Math.max(0, parseInt(data.progress || 0, 10)));
        const files   = parseInt(data.files_scanned || 0, 10);
        const threats = parseInt(data.threats_found || 0, 10);
        const curFile = data.current_file || '';
        const pctText = pct + '%';

        // 1. Update the actual CSS fill bar
        progressBar().css('width', pctText);

        // 2. Update the [data-rt-progress-label] span (percentage number)
        progressPct().text(pctText);

        // 3. Update the label text "Scanning… X%" (PHP renders this static, JS keeps it live)
        progressLabel().text('Scanning… ' + pctText);

        // 4. Update file/threat counts
        //    — PHP list exists: target badges inside list items by position
        const $phpList = phpStatsList();
        if ($phpList.length) {
            $phpList.find('.ultraguard-list-item').eq(0).find('.ultraguard-list-badge').text(files.toLocaleString());
            const $threatBadge = $phpList.find('.ultraguard-list-item').eq(1).find('.ultraguard-list-badge');
            $threatBadge.text(threats);
            // Swap badge colour when threats found
            if (threats > 0) {
                $threatBadge.removeClass('ultraguard-badge-success').addClass('ultraguard-badge-danger');
            } else {
                $threatBadge.removeClass('ultraguard-badge-danger').addClass('ultraguard-badge-success');
            }
        } else {
            // JS-injected bar
            $('#ug-files-scanned').text(files.toLocaleString());
            const $tBadge = $('#ug-threats-live');
            $tBadge.text(threats);
            if (threats > 0) {
                $tBadge.removeClass('ultraguard-badge-success').addClass('ultraguard-badge-danger');
            } else {
                $tBadge.removeClass('ultraguard-badge-danger').addClass('ultraguard-badge-success');
            }
        }

        // 5. Current file
        if (curFile) {
            const display = '…' + curFile.slice(-60);
            if ($phpList.length) {
                // Append or update a current-file line below the PHP list
                let $cf = panel().find('#ug-current-file');
                if (!$cf.length) {
                    $cf = $('<div id="ug-current-file" class="ug-scan-current-file"></div>');
                    $phpList.after($cf);
                }
                $cf.text(display);
            } else {
                $('#ug-current-file').text(display);
            }
        }
    }

    /* ── Scan finished ───────────────────────────────────────────────────────── */
    function handleScanFinished(data) {
        stopPolling();
        panel().attr('data-running', '0');
        currentScanId = null;

        const status  = data.status || 'complete';
        const threats = parseInt(data.threats_found || 0, 10);

        setBadgeState(
            status === 'complete' ? 'complete' : 'error',
            status === 'complete' ? i18n('Complete') : status === 'cancelled' ? i18n('Stopped') : i18n('Error')
        );

        if (status === 'complete') {
            progressBar().css('width', '100%');
            progressPct().text('100%');
            progressLabel().text('Scan complete — 100%');
        }

        if (threats > 0) {
            showToast('error', threats + ' threat(s) detected! Review and quarantine infected files.');
        } else if (status === 'complete') {
            showToast('success', 'Scan complete — no threats found.');
        }

        $(document).trigger('ultraguard:scan:completed', [data]);

        setTimeout(function() { window.location.reload(); }, COMPLETE_DELAY_MS);
    }

    /* ── Toast (correct function: UltraGuardComponents.showMessage) ──────────── */
    function showToast(type, message) {
        if (window.UltraGuardComponents && window.UltraGuardComponents.showMessage) {
            window.UltraGuardComponents.showMessage(
                { escapeHtml: function(s) { return $('<div>').text(s).html(); } },
                message, type, 5000
            );
        } else {
        }
    }

    /* ── i18n shim ───────────────────────────────────────────────────────────── */
    function i18n(key) {
        const map = {
            Running:  (window.ultraguardI18n && window.ultraguardI18n.scanning) || 'Running…',
            Complete: (window.ultraguardI18n && window.ultraguardI18n.complete)  || 'Complete',
            Stopped:  (window.ultraguardI18n && window.ultraguardI18n.stopped)   || 'Stopped',
            Error:    (window.ultraguardI18n && window.ultraguardI18n.error)     || 'Error',
            Idle:     (window.ultraguardI18n && window.ultraguardI18n.idle)      || 'Idle',
        };
        return map[key] || key;
    }

    /* ── Boot ────────────────────────────────────────────────────────────────── */
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})(window.jQuery || {});
