let selectedAudits = [];
const SEVERITY_ORDER = ['critical', 'high', 'medium', 'low', 'info'];
const SEVERITY_COLORS = {
    critical: '#ef4444',
    high: '#f97316',
    medium: '#eab308',
    low: '#6b7280',
    info: '#3b82f6'
};
const SEVERITY_BG = {
    critical: 'rgba(239, 68, 68, 0.15)',
    high: 'rgba(249, 115, 22, 0.15)',
    medium: 'rgba(234, 179, 8, 0.15)',
    low: 'rgba(107, 114, 128, 0.15)',
    info: 'rgba(59, 130, 246, 0.15)'
};

const TOAST_ICONS = {
    success: '<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>',
    error: '<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>',
    warning: '<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>',
    info: '<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>'
};

function showToast(title, message, type = 'info', duration = 4000) {
    const container = document.getElementById('toast-container');
    if (!container) return;

    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `
        <div class="toast-icon">${TOAST_ICONS[type] || TOAST_ICONS.info}</div>
        <div class="toast-content">
            <div class="toast-title">${escapeHtml(title)}</div>
            ${message ? `<div class="toast-message">${escapeHtml(message)}</div>` : ''}
        </div>
        <button class="toast-close" onclick="closeToast(this.parentElement)">
            <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6 6 18M6 6l12 12"/></svg>
        </button>
    `;

    container.appendChild(toast);

    if (duration > 0) {
        setTimeout(() => closeToast(toast), duration);
    }

    return toast;
}

function closeToast(toast) {
    if (!toast || toast.classList.contains('toast-exit')) return;
    toast.classList.add('toast-exit');
    setTimeout(() => toast.remove(), 200);
}

function toggleCard(card) {
    card.classList.toggle('expanded');
}

function switchTab(tabElement, contentId) {
    const card = tabElement.closest('.audit-card');
    card.querySelectorAll('.detail-tab').forEach(t => t.classList.remove('active'));
    card.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
    tabElement.classList.add('active');
    document.getElementById(contentId).classList.add('active');
}

function toggleLensGroup(group) {
    group.classList.toggle('collapsed');
}

function selectAudit(timelineItem) {
    const id = timelineItem.dataset.id;
    const card = document.querySelector(`.audit-card[data-id="${id}"]`);
    if (card) {
        document.querySelectorAll('.timeline-item').forEach(t => t.classList.remove('selected'));
        timelineItem.classList.add('selected');
        card.scrollIntoView({ behavior: 'smooth', block: 'start' });
        if (!card.classList.contains('expanded')) {
            card.classList.add('expanded');
        }
    }
}

function toggleCompareSelection(checkbox) {
    const id = checkbox.dataset.id;
    const lens = checkbox.dataset.lens;

    if (checkbox.checked) {
        if (selectedAudits.length > 0 && selectedAudits[0].lens !== lens) {
            checkbox.checked = false;
            showToast('Different Audit Types', 'You can only compare audits of the same type.', 'warning');
            return;
        }
        if (selectedAudits.length >= 2) {
            checkbox.checked = false;
            showToast('Limit Reached', 'You can only compare 2 audits at a time.', 'warning');
            return;
        }
        selectedAudits.push({ id, lens });
    } else {
        selectedAudits = selectedAudits.filter(a => a.id !== id);
    }

    updateCompareUI();
}

function updateCompareUI() {
    const controls = document.getElementById('compare-controls');
    const countEl = document.getElementById('compare-count');
    const compareBtn = document.getElementById('compare-btn');

    if (selectedAudits.length > 0) {
        controls.classList.add('active');
        document.body.classList.add('compare-mode');
    } else {
        controls.classList.remove('active');
        document.body.classList.remove('compare-mode');
    }

    countEl.textContent = selectedAudits.length;
    compareBtn.disabled = selectedAudits.length !== 2;
}

function cancelCompare() {
    selectedAudits = [];
    document.querySelectorAll('.timeline-checkbox').forEach(cb => cb.checked = false);
    updateCompareUI();
}

function runComparison() {
    if (selectedAudits.length !== 2) return;

    const auditA = auditData[selectedAudits[0].id];
    const auditB = auditData[selectedAudits[1].id];

    if (!auditA || !auditB) {
        showToast('Comparison Error', 'Could not load audit data for comparison.', 'error');
        return;
    }

    const [before, after] = auditA.timestamp < auditB.timestamp ? [auditA, auditB] : [auditB, auditA];
    const result = compareAudits(before, after);
    renderComparison(before, after, result);

    document.getElementById('comparison-overlay').classList.add('active');
}

function compareAudits(before, after) {
    const severityDelta = {};
    for (const sev of SEVERITY_ORDER) {
        const beforeCount = before.by_severity[sev] || 0;
        const afterCount = after.by_severity[sev] || 0;
        severityDelta[sev] = {
            before: beforeCount,
            after: afterCount,
            delta: afterCount - beforeCount
        };
    }

    const findingsComparison = compareFindingsDetailed(before.findings || [], after.findings || []);

    const beforeTotal = before.total_findings || 0;
    const afterTotal = after.total_findings || 0;
    let improvementPercentage = 0;
    if (beforeTotal > 0) {
        improvementPercentage = Math.round(((beforeTotal - afterTotal) / beforeTotal) * 100);
    }

    let trend = 'STABLE';
    if (afterTotal < beforeTotal) trend = 'IMPROVING';
    else if (afterTotal > beforeTotal) trend = 'REGRESSING';

    return {
        severity_delta: severityDelta,
        findings_comparison: findingsComparison,
        improvement_percentage: improvementPercentage,
        trend
    };
}

function getFindingKey(finding) {
    const category = (finding.category || '').toLowerCase();
    const severity = (finding.severity || '').toLowerCase();
    const description = (finding.description || '').toLowerCase().substring(0, 100);
    const files = normalizeAffectedFiles(finding.affected_files || []);
    const firstFile = (files[0] || '').toLowerCase();
    return `${severity}::${category}::${firstFile}::${description}`;
}

function compareFindingsDetailed(beforeFindings, afterFindings) {
    const beforeMap = new Map();
    const afterMap = new Map();

    beforeFindings.forEach(f => {
        const key = getFindingKey(f);
        beforeMap.set(key, f);
    });

    afterFindings.forEach(f => {
        const key = getFindingKey(f);
        afterMap.set(key, f);
    });

    const resolved = [];
    const newFindings = [];
    const persisting = [];
    const improved = [];
    const worsened = [];

    beforeMap.forEach((finding, key) => {
        if (!afterMap.has(key)) {
            resolved.push(finding);
        } else {
            const afterFinding = afterMap.get(key);
            const beforeSevIdx = SEVERITY_ORDER.indexOf(finding.severity || 'info');
            const afterSevIdx = SEVERITY_ORDER.indexOf(afterFinding.severity || 'info');

            if (afterSevIdx > beforeSevIdx) {
                improved.push({ before: finding, after: afterFinding });
            } else if (afterSevIdx < beforeSevIdx) {
                worsened.push({ before: finding, after: afterFinding });
            } else {
                persisting.push(afterFinding);
            }
        }
    });

    afterMap.forEach((finding, key) => {
        if (!beforeMap.has(key)) {
            newFindings.push(finding);
        }
    });

    return { resolved, new: newFindings, persisting, improved, worsened };
}

function formatDate(timestamp) {
    if (!timestamp) return 'Unknown';
    try {
        const d = new Date(timestamp);
        return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
    } catch {
        return timestamp.split('T')[0];
    }
}

function renderComparison(before, after, result) {
    document.getElementById('comparison-before-date').textContent = formatDate(before.timestamp);
    document.getElementById('comparison-before-findings').textContent = `${before.total_findings} findings`;
    document.getElementById('comparison-after-date').textContent = formatDate(after.timestamp);
    document.getElementById('comparison-after-findings').textContent = `${after.total_findings} findings`;

    const trendEl = document.getElementById('comparison-trend');
    const indicatorEl = document.getElementById('trend-indicator');
    const labelEl = document.getElementById('trend-label');
    const percentEl = document.getElementById('trend-percentage');

    trendEl.className = 'comparison-trend ' + result.trend.toLowerCase();
    labelEl.className = 'trend-label ' + result.trend.toLowerCase();
    labelEl.textContent = result.trend;

    if (result.trend === 'IMPROVING') {
        indicatorEl.textContent = '↓';
        percentEl.textContent = `${Math.abs(result.improvement_percentage)}% reduction in findings`;
    } else if (result.trend === 'REGRESSING') {
        indicatorEl.textContent = '↑';
        percentEl.textContent = `${Math.abs(result.improvement_percentage)}% increase in findings`;
    } else {
        indicatorEl.textContent = '→';
        percentEl.textContent = 'No change in finding count';
    }

    const deltaGrid = document.getElementById('severity-delta-grid');
    deltaGrid.innerHTML = '';
    for (const sev of ['critical', 'high', 'medium', 'low']) {
        const data = result.severity_delta[sev] || { before: 0, after: 0, delta: 0 };
        const color = SEVERITY_COLORS[sev];

        let changeClass = 'neutral';
        let changeText = '—';
        if (data.delta < 0) {
            changeClass = 'positive';
            changeText = `${data.delta}`;
        } else if (data.delta > 0) {
            changeClass = 'negative';
            changeText = `+${data.delta}`;
        }

        deltaGrid.innerHTML += `
            <div class="severity-delta-item">
                <div class="severity-delta-label" style="color: ${color};">${sev.toUpperCase()}</div>
                <div class="severity-delta-values">
                    <span>${data.before}</span>
                    <span class="severity-delta-arrow">→</span>
                    <span>${data.after}</span>
                </div>
                <div class="severity-delta-change ${changeClass}">${changeText}</div>
            </div>
        `;
    }

    const fc = result.findings_comparison;
    document.getElementById('count-resolved').textContent = fc.resolved.length;
    document.getElementById('count-new').textContent = fc.new.length;
    document.getElementById('count-persisting').textContent = fc.persisting.length;
    document.getElementById('count-improved').textContent = fc.improved.length;
    document.getElementById('count-worsened').textContent = fc.worsened.length;

    renderBreakdownPanel('resolved', fc.resolved);
    renderBreakdownPanel('new', fc.new);
    renderBreakdownPanel('persisting', fc.persisting);
    renderBreakdownPanel('improved', fc.improved.map(i => i.after));
    renderBreakdownPanel('worsened', fc.worsened.map(i => i.after));

    showBreakdownTab('resolved');
}

function renderBreakdownPanel(panelId, findings) {
    const panel = document.getElementById(`panel-${panelId}`);
    if (!findings || findings.length === 0) {
        const checkIcon = '<svg class="icon icon-lg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>';
        panel.innerHTML = `<div class="breakdown-empty"><div class="breakdown-empty-icon">${checkIcon}</div><div>No ${panelId} findings</div></div>`;
        return;
    }

    panel.innerHTML = findings.map(f => {
        const sev = f.severity || 'info';
        const color = SEVERITY_COLORS[sev];
        const bg = SEVERITY_BG[sev];
        return `
            <div class="breakdown-item" style="border-left-color: ${color};">
                <div class="breakdown-item-header">
                    <span class="breakdown-item-category">${escapeHtml(f.category || 'Unknown')}</span>
                    <span class="breakdown-item-severity" style="background: ${bg}; color: ${color};">${sev}</span>
                </div>
                <div class="breakdown-item-description">${escapeHtml(f.description || '')}</div>
            </div>
        `;
    }).join('');
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function showBreakdownTab(tabId) {
    document.querySelectorAll('.breakdown-tab').forEach(t => t.classList.remove('active'));
    document.querySelectorAll('.breakdown-panel').forEach(p => p.classList.remove('active'));
    document.querySelector(`.breakdown-tab[data-tab="${tabId}"]`).classList.add('active');
    document.getElementById(`panel-${tabId}`).classList.add('active');
}

function closeComparison() {
    document.getElementById('comparison-overlay').classList.remove('active');
}

// Export Functions
function getProjectName() {
    const projectNameEl = document.querySelector('.project-name');
    return projectNameEl ? projectNameEl.textContent : 'optix-project';
}

function getCurrentTimestamp() {
    return new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
}

function downloadFile(content, filename, mimeType) {
    const blob = new Blob([content], { type: mimeType });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

function exportJSON() {
    const projectName = getProjectName();
    const timestamp = new Date().toISOString();
    const audits = Object.values(auditData).map(audit => ({
        id: audit.dir_name,
        lens: audit.lens,
        timestamp: audit.timestamp,
        findings_count: audit.total_findings || 0,
        by_severity: audit.by_severity || {},
        findings: audit.findings || []
    }));

    const exportData = {
        exported_at: timestamp,
        project: projectName,
        total_audits: audits.length,
        audits: audits.sort((a, b) => b.timestamp.localeCompare(a.timestamp))
    };

    const filename = `${projectName}_audit_export_${getCurrentTimestamp()}.json`;
    downloadFile(JSON.stringify(exportData, null, 2), filename, 'application/json');
    showToast('Export Complete', `Downloaded ${filename}`, 'success');
}

function exportCSV() {
    const projectName = getProjectName();
    const headers = [
        'audit_id',
        'audit_date',
        'audit_time',
        'lens',
        'confidence',
        'severity',
        'category',
        'description',
        'remediation',
        'affected_files',
        'cwe_id'
    ];

    const rows = [headers.join(',')];

    Object.values(auditData).forEach(audit => {
        const auditId = audit.dir_name || '';
        const [datePart, timePart] = (audit.timestamp || '').split('T');
        const auditDate = datePart || '';
        const auditTime = timePart ? timePart.split('.')[0] : '';
        const lens = audit.lens || '';
        const confidence = audit.confidence || '';

        const findings = audit.findings || [];
        if (findings.length === 0) {
            rows.push([
                escapeCSV(auditId),
                escapeCSV(auditDate),
                escapeCSV(auditTime),
                escapeCSV(lens),
                escapeCSV(confidence),
                '', '', '', '', '', ''
            ].join(','));
        } else {
            findings.forEach(finding => {
                const affectedFiles = normalizeAffectedFiles(finding.affected_files || []);
                rows.push([
                    escapeCSV(auditId),
                    escapeCSV(auditDate),
                    escapeCSV(auditTime),
                    escapeCSV(lens),
                    escapeCSV(confidence),
                    escapeCSV(finding.severity || ''),
                    escapeCSV(finding.category || ''),
                    escapeCSV(finding.description || ''),
                    escapeCSV(finding.remediation || ''),
                    escapeCSV(affectedFiles.join('|')),
                    escapeCSV(finding.cwe_id || '')
                ].join(','));
            });
        }
    });

    const bom = '\uFEFF';
    const filename = `${projectName}_audit_export_${getCurrentTimestamp()}.csv`;
    downloadFile(bom + rows.join('\n'), filename, 'text/csv;charset=utf-8');
    showToast('Export Complete', `Downloaded ${filename}`, 'success');
}

function escapeCSV(value) {
    if (value === null || value === undefined) return '';
    const str = String(value);
    if (str.includes(',') || str.includes('"') || str.includes('\n') || str.includes('\r')) {
        return '"' + str.replace(/"/g, '""') + '"';
    }
    return str;
}

function normalizeAffectedFiles(affectedFiles) {
    if (!affectedFiles || !Array.isArray(affectedFiles)) return [];
    return affectedFiles.map(item => {
        if (typeof item === 'string') return item;
        if (typeof item === 'object' && item !== null) {
            return item.file_path || item.path || '';
        }
        return String(item);
    }).filter(Boolean);
}

function exportMarkdown() {
    const projectName = getProjectName();
    const timestamp = new Date().toISOString().replace('T', ' ').slice(0, 19);
    const audits = Object.values(auditData).sort((a, b) => b.timestamp.localeCompare(a.timestamp));

    const totalFindings = audits.reduce((sum, a) => sum + (a.total_findings || 0), 0);

    let md = `# Audit Summary: ${projectName}\n\n`;
    md += `**Generated:** ${timestamp}\n`;
    md += `**Total Audits:** ${audits.length} | **Total Findings:** ${totalFindings}\n\n`;
    md += `## Recent Audits\n\n`;

    audits.forEach(audit => {
        const date = formatDate(audit.timestamp);
        const lens = (audit.lens || 'unknown').charAt(0).toUpperCase() + (audit.lens || 'unknown').slice(1);
        const findingsCount = audit.total_findings || 0;
        const bySeverity = audit.by_severity || {};

        md += `### ${lens} Audit - ${date}\n`;

        const severitySummary = [];
        for (const sev of ['critical', 'high', 'medium', 'low', 'info']) {
            const count = bySeverity[sev] || 0;
            if (count > 0) {
                severitySummary.push(`${count} ${sev}`);
            }
        }
        md += `- **Findings:** ${findingsCount}${severitySummary.length > 0 ? ' (' + severitySummary.join(', ') + ')' : ''}\n\n`;

        const findings = audit.findings || [];
        if (findings.length > 0) {
            const groupedBySeverity = {};
            findings.forEach(f => {
                const sev = f.severity || 'info';
                if (!groupedBySeverity[sev]) groupedBySeverity[sev] = [];
                groupedBySeverity[sev].push(f);
            });

            for (const sev of ['critical', 'high', 'medium', 'low', 'info']) {
                const sevFindings = groupedBySeverity[sev];
                if (sevFindings && sevFindings.length > 0) {
                    md += `#### ${sev.charAt(0).toUpperCase() + sev.slice(1)} Severity\n`;
                    sevFindings.forEach(f => {
                        md += `- **${f.category || 'Unknown'}** - ${f.description || 'No description'}\n`;
                        const files = normalizeAffectedFiles(f.affected_files);
                        if (files.length > 0) {
                            md += `  - Files: ${files.map(f => '`' + f + '`').join(', ')}\n`;
                        }
                        if (f.remediation) {
                            md += `  - Fix: ${f.remediation}\n`;
                        }
                    });
                    md += '\n';
                }
            }
        }

        md += `---\n\n`;
    });

    const filename = `${projectName}_audit_export_${getCurrentTimestamp()}.md`;
    downloadFile(md, filename, 'text/markdown;charset=utf-8');
    showToast('Export Complete', `Downloaded ${filename}`, 'success');
}

