jQuery(document).ready(function ($) {
    $('#vulntitan-start-integrity-scan').off('click').on('click', function () {
        const $btn = $(this);
        const $btnVul = $('#vulntitan-start-vulnerability-scan');
        const $btnMlw = $('#vulntitan-start-malware-scan');
        const $legendContainer = $('#vulntitan-integrity-legend-container');
        const $problematicContainer = $('#vulntitan-integrity-problematic-container');
        const $problematicSummary = $('#vulntitan-integrity-problematic-summary');
        const $problematicList = $('#vulntitan-integrity-problematic-list');
        const $nextStepsContainer = $('#vulntitan-integrity-next-steps-container');
        const $nextStepsList = $('#vulntitan-integrity-next-steps-list');
        const $malwareOverviewContainer = $('#vulntitan-malware-overview-container');
        const $malwareOverviewContent = $('#vulntitan-malware-overview-content');
        const $malwareProblematicContainer = $('#vulntitan-malware-problematic-container');
        const $malwareProblematicSummary = $('#vulntitan-malware-problematic-summary');
        const $malwareProblematicList = $('#vulntitan-malware-problematic-list');
        const $vulnOverviewContainer = $('#vulntitan-vuln-overview-container');
        const $vulnOverviewContent = $('#vulntitan-vuln-overview-content');
        const $resultsContainer = $('#vulntitan-scan-results-container');
        const $resultsList = $('#vulntitan-scan-results');
        const $progressBarContainer = $('#vulntitan-scan-progress-bar-container');
        const $progressNote = $('#vulntitan-scan-progress-note');
        const problematicFiles = [];
        const statusColors = {
            ok: '#10b981',
            modified: '#f59e0b',
            missing: '#ef4444',
            unexpected: '#38bdf8',
            error: '#a78bfa',
            unknown: '#94a3b8'
        };

        function getStatusColor(status) {
            return statusColors[status] || statusColors.unknown;
        }

        function escapeHtml(str) {
            return String(str).replace(/[&<>"']/g, function (m) {
                return {
                    '&': '&amp;',
                    '<': '&lt;',
                    '>': '&gt;',
                    '"': '&quot;',
                    "'": '&#039;'
                }[m];
            });
        }

        function setProgressNote(text) {
            if (!$progressNote.length) {
                return;
            }

            if (text) {
                $progressNote.text(text).show();
                return;
            }

            $progressNote.text('').hide();
        }

        function formatScanTarget(path) {
            if (!path) {
                return '';
            }

            const normalized = String(path).replace(/\\/g, '/');
            if (normalized.indexOf('wp-config.php') !== -1) {
                return 'wp-config.php';
            }

            const pluginRoot = 'wp-content/plugins/';
            const themeRoot = 'wp-content/themes/';

            if (normalized.indexOf(pluginRoot) !== -1) {
                const slug = normalized.split(pluginRoot)[1].split('/')[0];
                if (slug) {
                    return `${VulnTitan.i18n.vuln_type_plugin || 'Plugin'}: ${slug}`;
                }
            }

            if (normalized.indexOf(themeRoot) !== -1) {
                const slug = normalized.split(themeRoot)[1].split('/')[0];
                if (slug) {
                    return `${VulnTitan.i18n.vuln_type_theme || 'Theme'}: ${slug}`;
                }
            }

            const basename = normalized.split('/').pop();
            return basename || normalized;
        }

        function renderProblematicFiles() {
            if (!problematicFiles.length) {
                $problematicSummary.html(
                    `<div style="font-size:13px;color:#86efac;font-weight:600;">${escapeHtml(VulnTitan.i18n.no_problematic_files || 'No problematic files detected.')}</div>`
                );
                $problematicList.empty();
                $problematicContainer.show();
                $nextStepsList.empty();
                $nextStepsContainer.hide();
                return;
            }

            const counts = {};
            problematicFiles.forEach((item) => {
                counts[item.status] = (counts[item.status] || 0) + 1;
            });

            const statusOrder = ['modified', 'missing', 'unexpected', 'error', 'unknown'];
            const badges = statusOrder
                .filter((status) => counts[status])
                .map((status) => `
                    <span style="display:inline-flex;align-items:center;gap:6px;padding:4px 8px;border:1px solid #3b2020;border-radius:999px;background:#161017;color:#f3f4f6;font-size:12px;">
                        <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:${getStatusColor(status)};"></span>
                        ${escapeHtml(status.toUpperCase())}: ${counts[status]}
                    </span>
                `).join('');

            const rows = problematicFiles.map((item) => {
                const note = getInternalFileNotice(item.status, item.file_path);
                const noteHtml = note
                    ? `<div style="font-size:11px;color:#93c5fd;margin-top:4px;">${escapeHtml(note)}</div>`
                    : '';
                const errorSuffix = item.error
                    ? ` <span style="color:#f9a8d4;">(${escapeHtml(item.error)})</span>`
                    : '';

                return `
                    <div style="display:flex;align-items:flex-start;gap:10px;border:1px solid #3b2020;border-radius:6px;background:#161017;padding:8px 10px;">
                        <span style="display:inline-block;min-width:95px;font-size:11px;font-weight:700;letter-spacing:0.03em;color:${getStatusColor(item.status)};text-transform:uppercase;">
                            ${escapeHtml(item.status)}
                        </span>
                        <span style="font-size:12px;color:#e5e7eb;word-break:break-all;">
                            ${escapeHtml(item.file_path)}${errorSuffix}
                            ${noteHtml}
                        </span>
                    </div>
                `;
            }).join('');

            $problematicSummary.html(`
                <div style="font-size:13px;color:#fecaca;font-weight:600;">
                    ${problematicFiles.length} ${escapeHtml(VulnTitan.i18n.problematic_files_detected || 'problematic file(s) detected.')}
                </div>
                <div style="display:flex;flex-wrap:wrap;gap:8px;margin-top:8px;">
                    ${badges}
                </div>
            `);
            $problematicList.html(rows);
            $problematicContainer.show();
            renderNextSteps();
        }

        function getInternalFileNotice(status, filePath) {
            const normalizedPath = String(filePath || '').replace(/\\/g, '/').toLowerCase();
            if (status !== 'unexpected') {
                return '';
            }

            if (normalizedPath.startsWith('wp-content/plugins/vulntitan/storage/queues/')) {
                return VulnTitan.i18n.integrity_internal_queue_notice
                    || 'This is a temporary VulnTitan queue file generated during scanning.';
            }

            if (normalizedPath.startsWith('wp-content/plugins/vulntitan/storage/')) {
                return VulnTitan.i18n.integrity_internal_storage_notice
                    || 'This file is inside VulnTitan internal storage.';
            }

            return '';
        }

        function getFileCategory(filePath) {
            const normalizedPath = String(filePath || '').replace(/\\/g, '/').toLowerCase();

            if (
                normalizedPath.startsWith('wp-admin/')
                || normalizedPath.startsWith('wp-includes/')
                || /^wp-[^/]+\.php$/.test(normalizedPath)
                || normalizedPath === 'xmlrpc.php'
                || normalizedPath === 'index.php'
            ) {
                return 'core';
            }

            if (normalizedPath.startsWith('wp-content/plugins/')) {
                return 'plugin';
            }

            if (normalizedPath.startsWith('wp-content/themes/')) {
                return 'theme';
            }

            if (normalizedPath.startsWith('wp-content/mu-plugins/')) {
                return 'mu-plugin';
            }

            return 'other';
        }

        function renderNextSteps() {
            if (!problematicFiles.length) {
                $nextStepsList.empty();
                $nextStepsContainer.hide();
                return;
            }

            const statuses = new Set(problematicFiles.map((file) => file.status));
            const categories = new Set(problematicFiles.map((file) => getFileCategory(file.file_path)));
            const steps = [];

            if (statuses.has('modified') && categories.has('core')) {
                steps.push(VulnTitan.i18n.integrity_next_step_core_modified
                    || 'Core files are modified. Replace them with clean WordPress core files for the same WordPress version.');
            }

            if (
                statuses.has('modified')
                && (categories.has('plugin') || categories.has('theme') || categories.has('mu-plugin'))
            ) {
                steps.push(VulnTitan.i18n.integrity_next_step_extension_modified
                    || 'Plugin/theme files are modified. If changes are not intentional, reinstall affected plugins/themes from trusted sources.');
            }

            if (statuses.has('missing')) {
                steps.push(VulnTitan.i18n.integrity_next_step_missing
                    || 'Some expected files are missing. Restore from a trusted package or backup.');
            }

            if (statuses.has('unexpected')) {
                steps.push(VulnTitan.i18n.integrity_next_step_unexpected
                    || 'Unexpected files were detected. Verify file ownership and purpose before deletion.');
            }

            if (statuses.has('error')) {
                steps.push(VulnTitan.i18n.integrity_next_step_error
                    || 'Some files could not be analyzed. Check file permissions and server access, then rerun the scan.');
            }

            steps.push(VulnTitan.i18n.integrity_next_step_finalize
                || 'After fixes, rerun Integrity scan and regenerate baseline only when results are expected.');

            const listHtml = steps.map((step) => `<li style="margin-bottom:6px;">${escapeHtml(step)}</li>`).join('');
            $nextStepsList.html(listHtml);
            $nextStepsContainer.show();
        }

        $btn.prop('disabled', true).addClass('scanning').text(VulnTitan.i18n.scanning+'...');
        $btnVul.prop('disabled', true);
        $btnMlw.prop('disabled', true);
        $legendContainer.show();
        $problematicSummary.empty();
        $problematicList.empty();
        $problematicContainer.hide();
        $nextStepsList.empty();
        $nextStepsContainer.hide();
        $malwareOverviewContainer.hide();
        $malwareOverviewContent.empty();
        $vulnOverviewContainer.hide();
        $vulnOverviewContent.empty();
        $malwareProblematicContainer.hide();
        $malwareProblematicSummary.empty();
        $malwareProblematicList.empty();
        $resultsContainer.find('.vuln-scan-result-item, .vulntitan-scan-result').remove();
        $resultsList.empty();
        $resultsContainer.show().removeClass('is-vulnerability-layout');
        $progressBarContainer.show();

        $('#vulntitan-scan-progress-bar').css('width', '0%');
        $('#vulntitan-scan-progress-text').text('0%');
        setProgressNote(VulnTitan.i18n.preparing || 'Preparing...');
        $resultsList.html(`<p>${VulnTitan.i18n.preparing}</p>`);

        $.post(VulnTitan.ajaxUrl, {
            action: 'vulntitan_integrity_scan_init',
            nonce: VulnTitan.nonce
        }, function (res) {
            if (res.success) {
                const queueId = res.data.queue_id;
                const total = parseInt(res.data.total || 0, 10);
                let offset = 0;
                let processed = 0;
                let currentBatchSize = 30;
                const minBatchSize = 10;
                const maxBatchSize = 60;
                const fastBatchMs = 1200;
                const slowBatchMs = 3200;
                let consecutiveFailures = 0;

                if (!total || !queueId) {
                    $resultsList.html(`<p>${VulnTitan.i18n.no_files_to_scan}</p>`);
                    resetUI();
                    return;
                }

                function tuneBatchSize(batchCount, processingMs) {
                    const duration = parseInt(processingMs || 0, 10);
                    if (!Number.isFinite(duration) || duration <= 0) {
                        return;
                    }

                    if (duration > slowBatchMs) {
                        currentBatchSize = Math.max(minBatchSize, currentBatchSize - 5);
                        return;
                    }

                    if (duration < fastBatchMs && batchCount >= currentBatchSize) {
                        currentBatchSize = Math.min(maxBatchSize, currentBatchSize + 5);
                    }
                }

                function scanNextBatch() {
                    $.ajax({
                        url: VulnTitan.ajaxUrl,
                        method: 'POST',
                        timeout: 45000,
                        data: {
                            action: 'vulntitan_integrity_scan_batch',
                            nonce: VulnTitan.nonce,
                            queue_id: queueId,
                            offset: offset,
                            limit: currentBatchSize
                        }
                    }).done(function (res) {
                        if (res.success && Array.isArray(res.data.results)) {
                            consecutiveFailures = 0;
                            const batchCount = res.data.results.length;
                            const scanPrefix = VulnTitan.i18n.scanning || 'Scanning';

                            if (batchCount) {
                                const lastResult = res.data.results[batchCount - 1];
                                const lastLabel = formatScanTarget(lastResult.file_path || '');
                                if (lastLabel) {
                                    setProgressNote(`${scanPrefix}: ${lastLabel}`);
                                }
                            }

                            res.data.results.forEach(result => {
                                const status = (result.status || 'unknown').toLowerCase();
                                const filePath = result.file_path || '(unknown path)';
                                const color = getStatusColor(status);
                                const note = getInternalFileNotice(status, filePath);
                                const noteHtml = note
                                    ? `<div style="font-size:12px;color:#93c5fd;margin-top:4px;">${escapeHtml(note)}</div>`
                                    : '';

                                if (status !== 'ok') {
                                    problematicFiles.push({
                                        status: status,
                                        file_path: filePath,
                                        error: result.error || ''
                                    });
                                }
                
                                $resultsList.append(`
                                    <div class="vuln-scan-result-item" style="padding: 10px 0; border-bottom: 1px solid #20252F;">
                                        <div style="font-weight: bold; color: ${color}; text-transform: uppercase;">${escapeHtml(status)}</div>
                                        <div style="font-size: 14px; color: #e5e7eb;">
                                            ${escapeHtml(filePath)}
                                            ${noteHtml}
                                        </div>
                                    </div>
                                `);
                            });
                
                            $resultsContainer.scrollTop($resultsContainer.prop('scrollHeight'));
                            tuneBatchSize(batchCount, res.data.processing_ms);
                        } else if (!res.success) {
                            $resultsList.append(`<p>${VulnTitan.i18n.scan_init_failed}</p>`);
                            renderProblematicFiles();
                            resetUI();
                            return;
                        }

                        processed += Array.isArray(res.data.results) ? res.data.results.length : 0;
                        offset = typeof res.data.next_offset === 'number' ? res.data.next_offset : offset;

                        const percent = res.data.done ? 100 : Math.min(100, Math.round((processed / total) * 100));
                        $('#vulntitan-scan-progress-bar').css('width', percent + '%');
                        $('#vulntitan-scan-progress-text').text(`${percent}%`);

                        if (res.data.done) {
                            $('#vulntitan-scan-progress-text').text(VulnTitan.i18n.scan_finished);
                            setProgressNote(VulnTitan.i18n.scan_finished || 'Scan finished.');
                            renderProblematicFiles();
                            resetUI();
                            return;
                        }

                        setTimeout(scanNextBatch, 200); // optional delay between batches
                    }).fail(function () {
                        consecutiveFailures += 1;
                        currentBatchSize = Math.max(minBatchSize, currentBatchSize - 5);

                        if (consecutiveFailures <= 2) {
                            setTimeout(scanNextBatch, 500);
                            return;
                        }

                        $resultsList.append(`<p>${VulnTitan.i18n.scan_init_failed}</p>`);
                        renderProblematicFiles();
                        resetUI();
                    });
                }

                scanNextBatch();
            } else {
                $resultsList.html(`<p>${VulnTitan.i18n.scan_init_failed}</p>`);
                resetUI();
            }
        });

        function resetUI() {
            $btn.prop('disabled', false).removeClass('scanning').text(VulnTitan.i18n.start_scan);
            $btnVul.prop('disabled', false);
            $btnMlw.prop('disabled', false);
            $progressBarContainer.hide();
            setProgressNote('');
        }
    });
});
