<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SentinelDF - Interactive Scanner</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
            animation: fadeInDown 0.6s ease;
        }

        .header h1 {
            font-size: 3em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }

        .main-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }

        @media (max-width: 1024px) {
            .main-grid {
                grid-template-columns: 1fr;
            }
        }

        .card {
            background: white;
            border-radius: 16px;
            padding: 30px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            animation: fadeInUp 0.6s ease;
        }

        .upload-zone {
            border: 3px dashed #667eea;
            border-radius: 12px;
            padding: 60px 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        }

        .upload-zone:hover {
            border-color: #764ba2;
            background: linear-gradient(135deg, #e0e7ff 0%, #cfd9df 100%);
            transform: translateY(-2px);
        }

        .upload-zone.dragover {
            border-color: #10b981;
            background: #d1fae5;
            transform: scale(1.02);
        }

        .upload-icon {
            font-size: 4em;
            margin-bottom: 20px;
        }

        .upload-text {
            font-size: 1.3em;
            color: #374151;
            margin-bottom: 10px;
            font-weight: 600;
        }

        .upload-subtext {
            color: #6b7280;
            font-size: 0.95em;
        }

        .folder-input {
            margin-top: 20px;
            display: flex;
            gap: 10px;
        }

        .folder-input input {
            flex: 1;
            padding: 12px;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            font-size: 1em;
        }

        button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            font-size: 1em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.4);
        }

        button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            color: white;
            animation: scaleIn 0.5s ease;
        }

        .stat-value {
            font-size: 2.5em;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 0.9em;
            opacity: 0.9;
        }

        .progress-bar {
            width: 100%;
            height: 8px;
            background: #e5e7eb;
            border-radius: 10px;
            overflow: hidden;
            margin: 20px 0;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #10b981 0%, #059669 100%);
            width: 0%;
            transition: width 0.3s ease;
            border-radius: 10px;
        }

        .results-container {
            margin-top: 20px;
        }

        .result-item {
            background: #f9fafb;
            border-left: 4px solid #667eea;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 8px;
            animation: slideInLeft 0.4s ease;
        }

        .result-item.quarantine {
            border-left-color: #ef4444;
            background: #fee2e2;
        }

        .result-item.safe {
            border-left-color: #10b981;
            background: #d1fae5;
        }

        .result-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .result-filename {
            font-weight: 600;
            font-size: 1.1em;
            color: #111827;
        }

        .result-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.85em;
            font-weight: 600;
        }

        .badge-safe {
            background: #10b981;
            color: white;
        }

        .badge-quarantine {
            background: #ef4444;
            color: white;
        }

        .risk-score {
            font-size: 1.5em;
            font-weight: bold;
            margin: 10px 0;
        }

        .risk-low { color: #10b981; }
        .risk-medium { color: #f59e0b; }
        .risk-high { color: #ef4444; }

        .reasons-list {
            list-style: none;
            margin-top: 10px;
        }

        .reasons-list li {
            padding: 5px 0;
            color: #4b5563;
        }

        .reasons-list li:before {
            content: "⚠️ ";
            margin-right: 5px;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }

        .btn-download {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        }

        .btn-download:hover {
            box-shadow: 0 10px 20px rgba(16, 185, 129, 0.4);
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #9ca3af;
        }

        .empty-state-icon {
            font-size: 5em;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 40px;
        }

        .loading.active {
            display: block;
        }

        .spinner {
            border: 4px solid #f3f4f6;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        .signal-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
            margin-top: 15px;
        }

        .signal-item {
            background: white;
            padding: 10px;
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .signal-name {
            font-weight: 500;
            color: #374151;
        }

        .signal-value {
            font-weight: bold;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 0.9em;
        }

        .signal-high {
            background: #fecaca;
            color: #991b1b;
        }

        .signal-medium {
            background: #fed7aa;
            color: #9a3412;
        }

        .signal-low {
            background: #d1fae5;
            color: #065f46;
        }

        @keyframes fadeInDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes slideInLeft {
            from {
                opacity: 0;
                transform: translateX(-20px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @keyframes scaleIn {
            from {
                opacity: 0;
                transform: scale(0.8);
            }
            to {
                opacity: 1;
                transform: scale(1);
            }
        }

        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            background: white;
            padding: 15px 25px;
            border-radius: 8px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            z-index: 1000;
            animation: slideInRight 0.4s ease;
            display: none;
        }

        .toast.show {
            display: block;
        }

        .toast.success {
            border-left: 4px solid #10b981;
        }

        .toast.error {
            border-left: 4px solid #ef4444;
        }

        @keyframes slideInRight {
            from {
                opacity: 0;
                transform: translateX(100px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1>🛡️ SentinelDF Interactive Scanner</h1>
            <p>Scan files and folders for threats with real-time visualization</p>
        </div>

        <!-- Main Grid -->
        <div class="main-grid">
            <!-- Upload Section -->
            <div class="card">
                <h2 style="margin-bottom: 20px;">📁 Upload Files</h2>
                
                <div class="upload-zone" id="uploadZone">
                    <div class="upload-icon">📤</div>
                    <div class="upload-text">Drag & Drop Files Here</div>
                    <div class="upload-subtext">or click to browse</div>
                    <input type="file" id="fileInput" multiple hidden>
                </div>

                <div class="folder-input">
                    <input type="text" id="folderPath" placeholder="Enter folder path to scan...">
                    <button onclick="scanFolder()">Scan Folder</button>
                </div>

                <div id="loading" class="loading">
                    <div class="spinner"></div>
                    <div style="color: #667eea; font-weight: 600;">Scanning files...</div>
                </div>
            </div>

            <!-- Stats Section -->
            <div class="card">
                <h2 style="margin-bottom: 20px;">📊 Scan Summary</h2>
                
                <div class="stats-grid" id="statsGrid">
                    <div class="stat-card">
                        <div class="stat-value" id="totalFiles">0</div>
                        <div class="stat-label">Total Files</div>
                    </div>
                    <div class="stat-card" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                        <div class="stat-value" id="safeFiles">0</div>
                        <div class="stat-label">Safe</div>
                    </div>
                    <div class="stat-card" style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);">
                        <div class="stat-value" id="quarantinedFiles">0</div>
                        <div class="stat-label">Quarantined</div>
                    </div>
                    <div class="stat-card" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                        <div class="stat-value" id="avgRisk">0</div>
                        <div class="stat-label">Avg Risk</div>
                    </div>
                </div>

                <div class="progress-bar">
                    <div class="progress-fill" id="progressFill"></div>
                </div>

                <div class="action-buttons" id="actionButtons" style="display: none;">
                    <button class="btn-download" onclick="downloadHTMLReport()">
                        📄 Download HTML Report
                    </button>
                    <button class="btn-download" onclick="downloadJSONReport()">
                        📊 Download JSON Report
                    </button>
                </div>
            </div>
        </div>

        <!-- Results Section -->
        <div class="card">
            <h2 style="margin-bottom: 20px;">🔍 Scan Results</h2>
            
            <div id="resultsContainer" class="results-container">
                <div class="empty-state">
                    <div class="empty-state-icon">📂</div>
                    <div style="font-size: 1.2em; font-weight: 600; margin-bottom: 10px;">No scans yet</div>
                    <div>Upload files or scan a folder to get started</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Toast Notification -->
    <div class="toast" id="toast"></div>

    <script>
        let currentScanId = null;

        // Setup drag and drop
        const uploadZone = document.getElementById('uploadZone');
        const fileInput = document.getElementById('fileInput');

        uploadZone.addEventListener('click', () => fileInput.click());
        
        uploadZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadZone.classList.add('dragover');
        });

        uploadZone.addEventListener('dragleave', () => {
            uploadZone.classList.remove('dragover');
        });

        uploadZone.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadZone.classList.remove('dragover');
            const files = e.dataTransfer.files;
            handleFiles(files);
        });

        fileInput.addEventListener('change', (e) => {
            handleFiles(e.target.files);
        });

        function handleFiles(files) {
            if (files.length === 0) return;

            const formData = new FormData();
            for (let file of files) {
                formData.append('files', file);
            }

            showLoading(true);
            
            fetch('/api/scan-files', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    showToast(data.error, 'error');
                    return;
                }
                currentScanId = data.scan_id;
                displayResults(data);
                showToast('Scan completed successfully!', 'success');
            })
            .catch(error => {
                showToast('Error scanning files: ' + error, 'error');
            })
            .finally(() => {
                showLoading(false);
                fileInput.value = '';
            });
        }

        function scanFolder() {
            const folderPath = document.getElementById('folderPath').value;
            if (!folderPath) {
                showToast('Please enter a folder path', 'error');
                return;
            }

            showLoading(true);

            fetch('/api/scan-folder', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({folder_path: folderPath})
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    showToast(data.error, 'error');
                    return;
                }
                currentScanId = data.scan_id;
                displayResults(data);
                showToast('Folder scan completed!', 'success');
            })
            .catch(error => {
                showToast('Error scanning folder: ' + error, 'error');
            })
            .finally(() => {
                showLoading(false);
            });
        }

        function displayResults(data) {
            const { results, summary } = data;

            // Update stats
            document.getElementById('totalFiles').textContent = summary.total;
            document.getElementById('safeFiles').textContent = summary.safe;
            document.getElementById('quarantinedFiles').textContent = summary.quarantined;
            document.getElementById('avgRisk').textContent = summary.avg_risk.toFixed(1);
            document.getElementById('progressFill').style.width = '100%';

            // Show action buttons
            document.getElementById('actionButtons').style.display = 'flex';

            // Display results
            const container = document.getElementById('resultsContainer');
            container.innerHTML = '';

            results.forEach(result => {
                const item = createResultItem(result);
                container.appendChild(item);
            });
        }

        function createResultItem(result) {
            const div = document.createElement('div');
            div.className = `result-item ${result.quarantine ? 'quarantine' : 'safe'}`;

            const riskClass = result.risk < 30 ? 'risk-low' : result.risk < 70 ? 'risk-medium' : 'risk-high';

            let signalsHTML = '';
            if (result.signals) {
                signalsHTML = '<div class="signal-grid">';
                for (const [key, value] of Object.entries(result.signals)) {
                    const signalClass = value > 0.7 ? 'signal-high' : value > 0.3 ? 'signal-medium' : 'signal-low';
                    signalsHTML += `
                        <div class="signal-item">
                            <span class="signal-name">${key}</span>
                            <span class="signal-value ${signalClass}">${(value * 100).toFixed(0)}%</span>
                        </div>
                    `;
                }
                signalsHTML += '</div>';
            }

            div.innerHTML = `
                <div class="result-header">
                    <div class="result-filename">${result.doc_id}</div>
                    <span class="result-badge ${result.quarantine ? 'badge-quarantine' : 'badge-safe'}">
                        ${result.quarantine ? '🚨 QUARANTINED' : '✅ SAFE'}
                    </span>
                </div>
                <div class="risk-score ${riskClass}">
                    Risk Score: ${result.risk}/100
                </div>
                ${result.reasons.length > 0 ? `
                    <ul class="reasons-list">
                        ${result.reasons.map(r => `<li>${r}</li>`).join('')}
                    </ul>
                ` : ''}
                ${signalsHTML}
            `;

            return div;
        }

        function downloadHTMLReport() {
            if (!currentScanId) return;
            window.location.href = `/api/download-report/${currentScanId}`;
        }

        function downloadJSONReport() {
            if (!currentScanId) return;
            window.location.href = `/api/download-json/${currentScanId}`;
        }

        function showLoading(show) {
            const loading = document.getElementById('loading');
            if (show) {
                loading.classList.add('active');
            } else {
                loading.classList.remove('active');
            }
        }

        function showToast(message, type = 'success') {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.className = `toast show ${type}`;
            
            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }
    </script>
</body>
</html>
