jQuery(document).ready(function ($) {
    $('#vulntitan-start-malware-scan').off('click').on('click', function () {
        const $btn = $(this);
        const $btnVul = $('#vulntitan-start-vulnerability-scan');
        const $btnInt = $('#vulntitan-start-integrity-scan');
        const $integrityLegend = $('#vulntitan-integrity-legend-container');
        const $integrityProblematic = $('#vulntitan-integrity-problematic-container');
        const $integrityNextSteps = $('#vulntitan-integrity-next-steps-container');
        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 $integrityProblematicSummary = $('#vulntitan-integrity-problematic-summary');
        const $integrityProblematicList = $('#vulntitan-integrity-problematic-list');
        const $integrityNextStepsList = $('#vulntitan-integrity-next-steps-list');
        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 statusColors = {
            clean: '#10b981',
            infected: '#ef4444',
            skipped: '#38bdf8',
            error: '#a78bfa',
            unknown: '#94a3b8'
        };
        const scanPrefix = VulnTitan.i18n.scanning_for_malware || VulnTitan.i18n.scanning || 'Scanning';
        const stats = {
            total: 0,
            processed: 0,
            clean: 0,
            infected: 0,
            skipped: 0,
            error: 0
        };
        const problematicFiles = [];

        $btn.prop('disabled', true).addClass('scanning').text(VulnTitan.i18n.scanning + '...');
        $btnVul.prop('disabled', true);
        $btnInt.prop('disabled', true);
        $integrityLegend.hide();
        $integrityProblematic.hide();
        $integrityNextSteps.hide();
        $malwareOverviewContainer.hide();
        $malwareOverviewContent.empty();
        $vulnOverviewContainer.hide();
        $vulnOverviewContent.empty();
        $malwareProblematicContainer.hide();
        $malwareProblematicSummary.empty();
        $malwareProblematicList.empty();
        $integrityProblematicSummary.empty();
        $integrityProblematicList.empty();
        $integrityNextStepsList.empty();
        $resultsContainer.find('.vuln-scan-result-item, .vulntitan-scan-result').remove();
        $resultsList.empty();
        $progressBarContainer.show();
        $resultsContainer.show().removeClass('is-vulnerability-layout');

        $('#vulntitan-scan-progress-bar').css('width', '0%');
        $('#vulntitan-scan-progress-text').text('0%');
        setProgressNote(VulnTitan.i18n.preparing || 'Preparing...');
        renderLayout();
        updateOverview();

        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 renderLayout() {
            $malwareOverviewContent.html(`
                <div id="vulntitan-malware-overview" style="display:grid; gap:12px;">
                    <div style="font-size:13px; font-weight:700; color:#dbeafe;">
                        ${escapeHtml(VulnTitan.i18n.malware_overview_title || 'Malware Overview')}
                    </div>
                    <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(150px, 1fr)); gap:10px;">
                        <div style="border:1px solid #1f3346; background:#101a24; border-radius:8px; padding:10px 12px;">
                            <div style="font-size:11px; color:#93c5fd; text-transform:uppercase; letter-spacing:0.04em;">${escapeHtml(VulnTitan.i18n.malware_total_files || 'Total Files')}</div>
                            <div id="vulntitan-malware-total" style="font-size:22px; line-height:1.2; font-weight:700; color:#e2e8f0; margin-top:4px;">0</div>
                        </div>
                        <div style="border:1px solid #20252F; background:#0f151c; border-radius:8px; padding:10px 12px;">
                            <div style="font-size:11px; color:#9fb3c8; text-transform:uppercase; letter-spacing:0.04em;">${escapeHtml(VulnTitan.i18n.malware_processed_files || 'Processed')}</div>
                            <div id="vulntitan-malware-processed" style="font-size:22px; line-height:1.2; font-weight:700; color:#e2e8f0; margin-top:4px;">0</div>
                        </div>
                        <div style="border:1px solid #1f3346; background:#101a24; border-radius:8px; padding:10px 12px;">
                            <div style="font-size:11px; color:#86efac; text-transform:uppercase; letter-spacing:0.04em;">${escapeHtml(VulnTitan.i18n.malware_clean_files || 'Clean')}</div>
                            <div id="vulntitan-malware-clean" style="font-size:22px; line-height:1.2; font-weight:700; color:#86efac; margin-top:4px;">0</div>
                        </div>
                        <div style="border:1px solid #3b2020; background:#1a1215; border-radius:8px; padding:10px 12px;">
                            <div style="font-size:11px; color:#fca5a5; text-transform:uppercase; letter-spacing:0.04em;">${escapeHtml(VulnTitan.i18n.malware_infected_files || 'Infected')}</div>
                            <div id="vulntitan-malware-infected" style="font-size:22px; line-height:1.2; font-weight:700; color:#fecaca; margin-top:4px;">0</div>
                        </div>
                    </div>
                    <div id="vulntitan-malware-status-breakdown" style="display:flex; flex-wrap:wrap; gap:8px;"></div>
                </div>
            `);
            $malwareOverviewContainer.show();

            $resultsList.html(`
                <div id="vulntitan-malware-details" style="margin-top:8px; border:1px solid #20252F; background:#0f151c; border-radius:8px; padding:12px 14px;">
                    <div style="font-size:13px; font-weight:700; color:#d8e2ef;">
                        ${escapeHtml(VulnTitan.i18n.scanning_for_malware || 'Scanning files for malware')}
                    </div>
                    <div id="vulntitan-malware-details-list" style="margin-top:10px; display:grid; gap:8px;"></div>
                </div>
            `);
        }

        function getStatusLabel(status) {
            switch (status) {
                case 'clean':
                    return VulnTitan.i18n.malware_status_clean || 'clean';
                case 'infected':
                    return VulnTitan.i18n.malware_status_infected || 'infected';
                case 'skipped':
                    return VulnTitan.i18n.malware_status_skipped || 'skipped';
                case 'error':
                    return VulnTitan.i18n.malware_status_error || 'error';
                default:
                    return VulnTitan.i18n.unknown || 'unknown';
            }
        }

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

        function getSeverityLabel(severity) {
            const normalized = String(severity || '').toLowerCase();
            if (normalized === 'high' || normalized === 'medium' || normalized === 'low') {
                return normalized.toUpperCase();
            }

            return (VulnTitan.i18n.unknown || 'unknown').toUpperCase();
        }

        function getSeverityColor(severity) {
            const normalized = String(severity || '').toLowerCase();
            if (normalized === 'high') {
                return '#ef4444';
            }
            if (normalized === 'medium') {
                return '#f59e0b';
            }
            if (normalized === 'low') {
                return '#facc15';
            }

            return '#94a3b8';
        }

        function renderFindingPreviewLines(finding) {
            const previewLines = Array.isArray(finding.preview) ? finding.preview : [];

            if (!previewLines.length) {
                const fallback = finding.code || finding.code_snippet || finding.message || '';
                return `
                    <div style="margin-top:8px; border:1px solid #3b2020; border-radius:6px; background:#0f1116; padding:8px;">
                        <div style="font-family:Consolas,Monaco,monospace; font-size:12px; line-height:1.5; color:#e2e8f0; white-space:pre-wrap; word-break:break-word;">
                            ${escapeHtml(fallback)}
                        </div>
                    </div>
                `;
            }

            return `
                <div style="margin-top:8px; border:1px solid #3b2020; border-radius:6px; background:#0f1116; overflow-x:auto;">
                    ${previewLines.map((entry) => {
                        const isHit = !!entry.hit;
                        const lineNumber = Number.isFinite(Number(entry.line)) ? Number(entry.line) : '';
                        const lineCode = typeof entry.code === 'string' ? entry.code : '';
                        return `
                            <div style="display:grid; grid-template-columns:52px 1fr; gap:8px; padding:4px 8px; background:${isHit ? '#3a1418' : 'transparent'};">
                                <span style="font-family:Consolas,Monaco,monospace; font-size:11px; line-height:1.6; color:${isHit ? '#fca5a5' : '#64748b'}; text-align:right; user-select:none;">${lineNumber}</span>
                                <span style="font-family:Consolas,Monaco,monospace; font-size:12px; line-height:1.6; color:${isHit ? '#fecaca' : '#e2e8f0'}; white-space:pre-wrap; word-break:break-word;">${escapeHtml(lineCode)}</span>
                            </div>
                        `;
                    }).join('')}
                </div>
            `;
        }

        function renderFindingPreview(finding, findingIndex, itemIndex) {
            const lineNumber = Number.isFinite(Number(finding.line)) ? Number(finding.line) : null;
            const lineText = VulnTitan.i18n.malware_preview_line || 'Line';
            const lineLabel = lineNumber
                ? `${lineText} ${lineNumber}`
                : (VulnTitan.i18n.unknown || 'unknown');
            const patterns = Array.isArray(finding.patterns) ? finding.patterns.join(', ') : (finding.type || '');
            const severityLabel = getSeverityLabel(finding.severity);
            const severityColor = getSeverityColor(finding.severity);
            const applyFixLabel = VulnTitan.i18n.malware_fix_apply || 'Apply Fix';
            const fixedLabel = VulnTitan.i18n.malware_fixed || 'Fixed';
            const fixAllowed = finding.fixable === true;
            const fixUnavailableLabel = VulnTitan.i18n.malware_fix_unavailable || 'Auto-fix not available for low-risk findings.';
            const fixDisabled = finding.fixed || !lineNumber || !fixAllowed;
            const fixStatus = finding.fix_message
                ? `<span class="vulntitan-malware-fix-feedback" style="font-size:11px; color:${finding.fix_error ? '#fca5a5' : '#86efac'};">${escapeHtml(finding.fix_message)}</span>`
                : (fixAllowed
                    ? '<span class="vulntitan-malware-fix-feedback" style="font-size:11px; color:#94a3b8;"></span>'
                    : `<span class="vulntitan-malware-fix-feedback" style="font-size:11px; color:#94a3b8;">${escapeHtml(fixUnavailableLabel)}</span>`);
            const fixButton = fixAllowed ? `
                        <button
                            type="button"
                            class="button button-small vulntitan-malware-fix-btn"
                            data-item-index="${itemIndex}"
                            data-finding-index="${findingIndex}"
                            style="height:26px; line-height:24px;"
                            ${fixDisabled ? 'disabled' : ''}
                        >
                            ${escapeHtml(finding.fixed ? fixedLabel : applyFixLabel)}
                        </button>
                    ` : '';

            return `
                <div style="border:1px solid #3b2020; border-radius:6px; background:#161017; padding:8px 10px;">
                    <div style="display:flex; align-items:center; justify-content:space-between; gap:8px; flex-wrap:wrap;">
                        <span style="font-size:12px; color:#fda4af; font-weight:600;">
                            #${findingIndex + 1} • ${escapeHtml(lineLabel)}
                        </span>
                        <span style="display:inline-block; padding:2px 8px; border:1px solid ${severityColor}; border-radius:999px; font-size:11px; color:${severityColor}; font-weight:700; letter-spacing:0.03em;">
                            ${escapeHtml(severityLabel)}
                        </span>
                    </div>
                    ${patterns ? `<div style="margin-top:6px; font-size:11px; color:#cbd5e1;">${escapeHtml(patterns)}</div>` : ''}
                    ${renderFindingPreviewLines(finding)}
                    <div class="vulntitan-malware-fix-actions" style="margin-top:8px; display:flex; align-items:center; gap:8px; flex-wrap:wrap;">
                        ${fixButton}
                        ${fixStatus}
                    </div>
                </div>
            `;
        }

        function bindMalwareFixActions() {
            $malwareProblematicList.off('click', '.vulntitan-malware-fix-btn').on('click', '.vulntitan-malware-fix-btn', function () {
                const $button = $(this);
                const itemIndex = parseInt($button.attr('data-item-index'), 10);
                const findingIndex = parseInt($button.attr('data-finding-index'), 10);

                if (!Number.isInteger(itemIndex) || !Number.isInteger(findingIndex)) {
                    return;
                }

                const item = problematicFiles[itemIndex];
                if (!item || !Array.isArray(item.findings)) {
                    return;
                }

                const finding = item.findings[findingIndex];
                if (!finding) {
                    return;
                }

                const lineNumber = Number.isFinite(Number(finding.line)) ? Number(finding.line) : 0;
                if (!lineNumber) {
                    window.alert(VulnTitan.i18n.malware_fix_no_line || 'This finding has no exact line, so auto-fix is not available.');
                    return;
                }

                const confirmLabel = VulnTitan.i18n.malware_fix_confirm || 'Apply safe fix for this suspicious line? A backup will be created.';
                if (!window.confirm(confirmLabel)) {
                    return;
                }

                const fixingLabel = VulnTitan.i18n.malware_fixing || 'Fixing...';
                const applyFixLabel = VulnTitan.i18n.malware_fix_apply || 'Apply Fix';
                $button.prop('disabled', true).text(fixingLabel);

                const $feedback = $button.closest('.vulntitan-malware-fix-actions').find('.vulntitan-malware-fix-feedback');
                $feedback.text('').css('color', '#94a3b8');

                $.post(ajaxurl, {
                    action: 'vulntitan_malware_fix_finding',
                    nonce: VulnTitan.nonce,
                    file_path: item.file || '',
                    line: lineNumber
                }, function (response) {
                    if (response && response.success) {
                        const fixedLabel = VulnTitan.i18n.malware_fixed || 'Fixed';
                        const successMessage = (response.data && response.data.message)
                            ? response.data.message
                            : (VulnTitan.i18n.malware_fix_success || 'Fix applied.');
                        const backupLabel = VulnTitan.i18n.malware_fix_backup || 'Backup';
                        const backupInfo = (response.data && response.data.backup_file)
                            ? ` ${backupLabel}: ${response.data.backup_file}`
                            : '';
                        const feedbackMessage = successMessage + backupInfo;

                        finding.fixed = true;
                        finding.fix_message = feedbackMessage;
                        finding.fix_error = false;
                        $button.text(fixedLabel);
                        $feedback.text(feedbackMessage).css('color', '#86efac');
                        return;
                    }

                    const errorMessage = (response && response.data && response.data.message)
                        ? response.data.message
                        : (VulnTitan.i18n.malware_fix_error || 'Auto-fix failed.');
                    finding.fix_message = errorMessage;
                    finding.fix_error = true;
                    $button.prop('disabled', false).text(applyFixLabel);
                    $feedback.text(errorMessage).css('color', '#fca5a5');
                }).fail(function () {
                    const errorMessage = VulnTitan.i18n.malware_fix_error || 'Auto-fix failed.';
                    finding.fix_message = errorMessage;
                    finding.fix_error = true;
                    $button.prop('disabled', false).text(applyFixLabel);
                    $feedback.text(errorMessage).css('color', '#fca5a5');
                });
            });
        }

        function normalizeStatus(fileResult) {
            const status = String(fileResult.status || '').toLowerCase();
            if (status === 'clean' || status === 'infected' || status === 'skipped' || status === 'error') {
                return status;
            }
            if (fileResult.skipped) {
                return 'skipped';
            }
            if (fileResult.error) {
                return 'error';
            }
            if (Array.isArray(fileResult.findings) && fileResult.findings.length) {
                return 'infected';
            }
            return 'clean';
        }

        function updateOverview() {
            $('#vulntitan-malware-total').text(stats.total);
            $('#vulntitan-malware-processed').text(stats.processed);
            $('#vulntitan-malware-clean').text(stats.clean);
            $('#vulntitan-malware-infected').text(stats.infected);

            $('#vulntitan-malware-status-breakdown').html(`
                <span style="display:inline-flex; align-items:center; gap:6px; padding:4px 8px; border:1px solid #20252F; border-radius:999px; background:#121b25; color:#e5e7eb; font-size:12px;">
                    <span style="width:9px; height:9px; border-radius:50%; background:${getStatusColor('skipped')};"></span>
                    ${escapeHtml(getStatusLabel('skipped'))}: ${stats.skipped}
                </span>
                <span style="display:inline-flex; align-items:center; gap:6px; padding:4px 8px; border:1px solid #20252F; border-radius:999px; background:#121b25; color:#e5e7eb; font-size:12px;">
                    <span style="width:9px; height:9px; border-radius:50%; background:${getStatusColor('error')};"></span>
                    ${escapeHtml(getStatusLabel('error'))}: ${stats.error}
                </span>
            `);
        }

        function renderProblematicSummary() {
            if (!problematicFiles.length) {
                $malwareProblematicSummary.html(`<span style="color:#86efac; font-weight:600;">${escapeHtml(VulnTitan.i18n.malware_problematic_none || 'No problematic files detected in malware scan.')}</span>`);
                $malwareProblematicList.empty();
                $malwareProblematicContainer.show();
                return;
            }

            $malwareProblematicSummary.html(`<span style="font-weight:600;">${problematicFiles.length} ${escapeHtml(VulnTitan.i18n.malware_problematic_detected || 'problematic file(s) detected by malware scan.')}</span>`);
            $malwareProblematicList.html(problematicFiles.map((item, itemIndex) => {
                const findings = Array.isArray(item.findings) ? item.findings : [];
                const hasPreview = item.status === 'infected' && findings.length > 0;
                const previewToggleLabel = VulnTitan.i18n.malware_preview_toggle || 'Open code preview';
                const findingsCountLabel = VulnTitan.i18n.issues_found || 'issue(s) found';

                const previewHtml = hasPreview ? `
                    <details style="margin-top:8px;">
                        <summary style="cursor:pointer; font-size:12px; color:#93c5fd; font-weight:600;">
                            ${escapeHtml(previewToggleLabel)} (${findings.length} ${escapeHtml(findingsCountLabel)})
                        </summary>
                        <div style="margin-top:8px; display:grid; gap:8px;">
                            ${findings.map((finding, index) => renderFindingPreview(finding, index, itemIndex)).join('')}
                        </div>
                    </details>
                ` : '';

                const errorHtml = item.error
                    ? `<div style="margin-top:6px; font-size:12px; color:#f9a8d4;">${escapeHtml(item.error)}</div>`
                    : '';

                return `
                    <div style="border:1px solid #3b2020; border-radius:6px; background:#161017; padding:10px;">
                        <div style="display:flex; align-items:flex-start; gap: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(getStatusLabel(item.status))}
                            </span>
                            <span style="font-size:12px; color:#e5e7eb; word-break:break-all;">
                                ${escapeHtml(item.file)}
                            </span>
                        </div>
                        ${errorHtml}
                        ${previewHtml}
                    </div>
                `;
            }).join(''));
            $malwareProblematicContainer.show();
            bindMalwareFixActions();
        }

        function renderFileResult(fileResult, scopeInfo) {
            const status = normalizeStatus(fileResult);
            const file = fileResult.file || '(unknown file)';
            const color = getStatusColor(status);
            const label = getStatusLabel(status);
            const findings = Array.isArray(fileResult.findings) ? fileResult.findings : [];
            const scope = scopeInfo && scopeInfo.scope ? scopeInfo.scope : (VulnTitan.i18n.unknown || 'unknown');
            const basePath = scopeInfo && scopeInfo.basePath ? scopeInfo.basePath : '';
            const reason = fileResult.reason ? escapeHtml(fileResult.reason) : '';
            const error = fileResult.error ? escapeHtml(fileResult.error) : '';

            let findingsHtml = '';
            if (status === 'infected' && findings.length) {
                findingsHtml = `
                    <div style="margin-top:8px; padding:8px 10px; border:1px solid #3b2020; border-radius:6px; background:#171014;">
                        <div style="font-size:12px; color:#fecaca; font-weight:600; margin-bottom:6px;">
                            ${findings.length} ${escapeHtml(VulnTitan.i18n.issues_found)}
                        </div>
                        <ul style="margin:0; padding-left:16px; color:#e5e7eb; font-size:12px; line-height:1.5;">
                            ${findings.map((finding) => `<li>${escapeHtml(finding.message || '')}</li>`).join('')}
                        </ul>
                    </div>
                `;
            }

            const meta = status === 'skipped'
                ? reason
                : (status === 'error' ? error : `${escapeHtml(scope)}${basePath ? ` • ${escapeHtml(basePath)}` : ''}`);

            return `
                <div class="vuln-scan-result-item" style="padding:10px 0; border-bottom:1px solid #20252F;">
                    <div style="display:flex; align-items:flex-start; justify-content:space-between; gap:10px;">
                        <div style="font-size:13px; color:#e5e7eb; word-break:break-all;">${escapeHtml(file)}</div>
                        <span style="display:inline-block; padding:2px 8px; border:1px solid ${color}; border-radius:999px; font-size:11px; color:${color}; text-transform:uppercase; letter-spacing:0.03em; font-weight:700;">
                            ${escapeHtml(label)}
                        </span>
                    </div>
                    <div style="margin-top:4px; font-size:12px; color:#9fb3c8;">${meta}</div>
                    ${findingsHtml}
                </div>
            `;
        }

        $.post(ajaxurl, {
            action: 'vulntitan_malware_scan_init',
            nonce: VulnTitan.nonce
        }, function (response) {
            if (response.success) {
                const files = response.data.files;
                let currentIndex = 0;
                const batchSize = 25;
                stats.total = files.length;
                updateOverview();

                if (!files.length) {
                    $('#vulntitan-malware-details-list').html('<p>' + escapeHtml(VulnTitan.i18n.no_files_to_scan) + '</p>');
                    renderProblematicSummary();
                    resetUI();
                    setProgressNote('');
                    return;
                }

                function scanNextBatch() {
                    if (currentIndex >= files.length) {
                        $('#vulntitan-malware-details-list').prepend(`
                            <div style="padding:8px 10px; border:1px solid #1f3346; border-radius:6px; background:#101a24; color:#93c5fd; font-weight:600;">
                                ${escapeHtml(VulnTitan.i18n.completed)}
                            </div>
                        `);
                        setProgressNote(VulnTitan.i18n.scan_finished || 'Scan finished.');
                        renderProblematicSummary();
                        resetUI();
                        return;
                    }

                    const batch = files.slice(currentIndex, currentIndex + batchSize);
                    const $detailsList = $('#vulntitan-malware-details-list');
                    const scanLabel = formatScanTarget(batch[0]);
                    setProgressNote(scanLabel ? `${scanPrefix}: ${scanLabel}` : scanPrefix + '...');

                    $.post(ajaxurl, {
                        action: 'vulntitan_malware_scan_batch',
                        nonce: VulnTitan.nonce,
                        file_paths: batch
                    }, function (res) {
                        if (res.success && Array.isArray(res.data.results)) {
                            if (res.data.results.length) {
                                const lastResult = res.data.results[res.data.results.length - 1];
                                const lastLabel = formatScanTarget(lastResult.file || '');
                                if (lastLabel) {
                                    setProgressNote(`${scanPrefix}: ${lastLabel}`);
                                }
                            }
                            const scopeInfo = {
                                scope: res.data.scope,
                                basePath: res.data.base_path
                            };

                            res.data.results.forEach(fileResult => {
                                const status = normalizeStatus(fileResult);
                                stats.processed += 1;
                                stats[status] = (stats[status] || 0) + 1;

                                if (status === 'infected' || status === 'error') {
                                    problematicFiles.push({
                                        file: fileResult.file || '(unknown file)',
                                        status: status,
                                        findings: Array.isArray(fileResult.findings) ? fileResult.findings : [],
                                        error: fileResult.error || ''
                                    });
                                }

                                $detailsList.append(renderFileResult(fileResult, scopeInfo));
                            });

                            updateOverview();
                            $resultsContainer.scrollTop($resultsContainer.prop('scrollHeight'));
                        } else if (!res.success) {
                            $('#vulntitan-malware-details-list').append(`
                                <div style="padding:8px 10px; border:1px solid #3b2020; border-radius:6px; background:#171014; color:#fecaca;">
                                    ${escapeHtml(VulnTitan.i18n.error)}: ${escapeHtml((res.data && res.data.message) ? res.data.message : (VulnTitan.i18n.scan_init_failed || 'Scan initialization failed.'))}
                                </div>
                            `);
                            renderProblematicSummary();
                            resetUI();
                            return;
                        }

                        currentIndex += batchSize;
                        const percent = Math.min(100, Math.round((currentIndex / files.length) * 100));
                        $('#vulntitan-scan-progress-bar').css('width', percent + '%');
                        $('#vulntitan-scan-progress-text').text(percent + '%');

                        // Delay between batches for performance throttling
                        setTimeout(scanNextBatch, 200);
                    });
                }

                scanNextBatch();
            } else {
                resetUI();
                $malwareOverviewContainer.hide();
                $malwareOverviewContent.empty();
                $malwareProblematicContainer.hide();
                $malwareProblematicSummary.empty();
                $malwareProblematicList.empty();
                $resultsList.html('<p>' + escapeHtml(VulnTitan.i18n.scan_init_failed) + '</p>');
            }
        });

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