{% extends "base.html" %}

{% block content %}
<div class="max-w-7xl mx-auto">
    <!-- Hero Section -->
    <section class="text-center mb-16 fade-in">
        <div class="gradient-bg rounded-2xl p-12 mb-8">
            <h1 class="text-5xl font-bold mb-6">Automated YARA Rule Generation</h1>
            <p class="text-xl text-gray-200 mb-8 max-w-3xl mx-auto">
                Transform malware samples into precise YARA rules with powerful analysis.
                Fast and accurate.
            </p>
            <div class="flex justify-center space-x-4">
                <a href="#upload"
                    class="bg-white text-gray-900 px-8 py-4 rounded-lg font-semibold hover:bg-gray-100 transition-colors">
                    <i class="fas fa-rocket mr-2"></i>Start Analyzing
                </a>
                <button onclick="toggleTheme()"
                    class="glass-effect px-6 py-4 rounded-lg font-semibold hover:bg-gray-800 transition-colors flex items-center space-x-2">
                    <i id="theme-icon" class="fas fa-moon"></i>
                    <span id="theme-text">Dark Mode</span>
                </button>
            </div>
        </div>

        <!-- Stats -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-12">
            <div class="glass-effect p-6 rounded-xl text-center">
                <i class="fas fa-bolt text-yellow-400 text-3xl mb-3"></i>
                <h3 class="text-2xl font-bold mb-2">Fast</h3>
                <p class="text-gray-400">Generate rules in seconds</p>
            </div>
            <div class="glass-effect p-6 rounded-xl text-center">
                <i class="fas fa-shield-alt text-green-400 text-3xl mb-3"></i>
                <h3 class="text-2xl font-bold mb-2">Accurate</h3>
                <p class="text-gray-400">High-quality, precise rules</p>
            </div>
            <div class="glass-effect p-6 rounded-xl text-center">
                <i class="fas fa-robot text-blue-400 text-3xl mb-3"></i>
                <h3 class="text-2xl font-bold mb-2">Smart</h3>
                <p class="text-gray-400">Intelligent analysis</p>
            </div>
            <div class="glass-effect p-6 rounded-xl text-center">
                <i class="fas fa-cloud-upload-alt text-purple-400 text-3xl mb-3"></i>
                <h3 class="text-2xl font-bold mb-2">Easy</h3>
                <p class="text-gray-400">Drag & drop interface</p>
            </div>
        </div>
    </section>

    <!-- Upload Section -->
    <section id="upload" class="mb-16 fade-in">
        <h2 class="text-3xl font-bold mb-8 text-center">Analyze Files</h2>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- File Upload -->
            <div class="lg:col-span-2">
                <div id="file-drop-zone"
                    class="file-drop-zone rounded-2xl p-8 text-center cursor-pointer transition-all duration-300 hover:border-blue-400">
                    <i class="fas fa-cloud-upload-alt text-6xl text-gray-400 mb-4"></i>
                    <h3 class="text-2xl font-bold mb-2">Drop files here</h3>
                    <p class="text-gray-400 mb-4">or click to browse</p>
                    <input type="file" id="file-input" multiple class="hidden"
                        accept=".exe,.dll,.bin,.sys,.scr,.com,.bat,.cmd,.vbs,.js,.ps1,.php,.asp,.aspx,.jsp,.war,.py">
                    <button onclick="document.getElementById('file-input').click()"
                        class="bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-lg font-semibold transition-colors">
                        <i class="fas fa-folder-open mr-2"></i>Browse Files
                    </button>
                </div>

                <!-- File List -->
                <div id="file-list" class="mt-6 max-h-64 overflow-y-auto"></div>
            </div>

            <!-- Analysis Settings -->
            <div class="space-y-6">
                <div class="glass-effect rounded-2xl p-6">
                    <h3 class="text-xl font-bold mb-4 flex items-center">
                        <i class="fas fa-cog text-blue-400 mr-2"></i>
                        Analysis Settings
                    </h3>

                    <div class="space-y-4">
                        <!-- Basic Settings -->
                        {% for field in form_config.basic %}
                        <div>
                            {% if field.type == 'checkbox' %}
                            <div class="flex items-center space-x-2">
                                <input type="checkbox" 
                                       id="{{ field.form_field if field.form_field else field.name }}" 
                                       name="{{ field.name }}"
                                       {% if field.default %}checked{% endif %}
                                       class="rounded bg-gray-800 border-gray-700">
                                <label for="{{ field.form_field if field.form_field else field.name }}" 
                                       class="text-sm">{{ field.label }}</label>
                            </div>
                            {% else %}
                            <label class="block text-sm font-medium mb-2">{{ field.label }}</label>
                            <input type="{{ field.type }}" 
                                   id="{{ field.name }}" 
                                   name="{{ field.name }}"
                                   value="{{ field.default }}"
                                   {% if field.min %}min="{{ field.min }}"{% endif %}
                                   {% if field.max %}max="{{ field.max }}"{% endif %}
                                   class="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white">
                            {% endif %}
                        </div>
                        {% endfor %}

                        <!-- Advanced Settings Toggle -->
                        <div class="pt-4 border-t border-gray-700">
                            <details>
                                <summary class="cursor-pointer text-sm font-medium text-blue-400 hover:text-blue-300">
                                    <i class="fas fa-sliders-h mr-2"></i>Advanced Settings
                                </summary>
                                <div class="mt-4 space-y-4">
                                    {% for field in form_config.advanced %}
                                    <div>
                                        {% if field.type == 'checkbox' %}
                                        <div class="flex items-center space-x-2">
                                            <input type="checkbox" 
                                                   id="{{ field.form_field if field.form_field else field.name }}" 
                                                   name="{{ field.name }}"
                                                   {% if field.default %}checked{% endif %}
                                                   class="rounded bg-gray-800 border-gray-700">
                                            <label for="{{ field.form_field if field.form_field else field.name }}" 
                                                   class="text-sm">{{ field.label }}</label>
                                        </div>
                                        {% else %}
                                        <label class="block text-sm font-medium mb-2">{{ field.label }}</label>
                                        <input type="{{ field.type }}" 
                                               id="{{ field.name }}" 
                                               name="{{ field.name }}"
                                               value="{{ field.default }}"
                                               {% if field.min %}min="{{ field.min }}"{% endif %}
                                               {% if field.max %}max="{{ field.max }}"{% endif %}
                                               class="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white">
                                        {% endif %}
                                    </div>
                                    {% endfor %}
                                </div>
                            </details>
                        </div>
                    </div>

                    <button id="analyze-btn" onclick="analyzeFiles()" disabled
                        class="w-full mt-6 bg-gradient-to-r from-blue-500 to-purple-600 text-white py-3 rounded-lg font-semibold disabled:opacity-50 disabled:cursor-not-allowed transition-all">
                        <i class="fas fa-magic mr-2"></i>Generate YARA Rules
                    </button>
                </div>

                <!-- Progress Bar -->
                <div id="progress-container" class="hidden glass-effect rounded-2xl p-6">
                    <h3 class="text-xl font-bold mb-4">Analysis Progress</h3>
                    <div class="w-full bg-gray-700 rounded-full h-2">
                        <div id="progress-bar" class="progress-bar bg-green-500 h-2 rounded-full w-0"></div>
                    </div>
                    <p id="progress-text" class="text-sm text-gray-400 mt-2">Initializing...</p>
                </div>
            </div>
        </div>
    </section>

    <!-- Results Section -->
    <section id="results" class="hidden fade-in">
        <h2 class="text-3xl font-bold mb-8 text-center">Generated YARA Rules</h2>

        <div class="glass-effect rounded-2xl p-6 mb-6">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold">Analysis Results</h3>
                <div class="flex space-x-2">
                    <button onclick="copyRules()"
                        class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg text-sm">
                        <i class="fas fa-copy mr-1"></i>Copy Rules
                    </button>
                    <button onclick="downloadRules()"
                        class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg text-sm">
                        <i class="fas fa-download mr-1"></i>Download
                    </button>
                </div>
            </div>

            <div class="bg-gray-900 rounded-lg p-4 max-h-96 overflow-y-auto">
                <pre><code id="rules-output" class="language-c hljs"></code></pre>
            </div>
        </div>

        <!-- Statistics -->
        <div id="stats-container" class="grid grid-cols-1 md:grid-cols-3 gap-6 hidden">
            <div class="glass-effect rounded-xl p-6 text-center">
                <div class="text-3xl font-bold text-green-400 mb-2" id="rules-count">0</div>
                <div class="text-gray-400">Rules Generated</div>
            </div>
            <div class="glass-effect rounded-xl p-6 text-center">
                <div class="text-3xl font-bold text-blue-400 mb-2" id="files-count">0</div>
                <div class="text-gray-400">Files Analyzed</div>
            </div>
            <div class="glass-effect rounded-xl p-6 text-center">
                <div class="text-3xl font-bold text-purple-400 mb-2" id="analysis-time">0s</div>
                <div class="text-gray-400">Analysis Time</div>
            </div>
        </div>
    </section>
</div>
{% endblock %}

{% block scripts %}
<script>
    // File input handler
    document.getElementById('file-input').addEventListener('change', function (e) {
        handleFiles(e.target.files);
    });

    // File handling functions
    function handleFiles(files) {
        const fileList = document.getElementById('file-list');
        const analyzeBtn = document.getElementById('analyze-btn');
        fileList.innerHTML = '';
        
        if (files.length > 0) {
            analyzeBtn.disabled = false;
            
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                const fileItem = document.createElement('div');
                fileItem.className = 'flex items-center justify-between bg-gray-800 p-3 rounded-lg mb-2';
                fileItem.innerHTML = `
                    <div class="flex items-center">
                        <i class="fas fa-file text-blue-400 mr-3"></i>
                        <span class="text-sm truncate max-w-xs">${file.name}</span>
                    </div>
                    <div class="text-xs text-gray-400">
                        ${(file.size / 1024).toFixed(2)} KB
                    </div>
                `;
                fileList.appendChild(fileItem);
            }
        } else {
            analyzeBtn.disabled = true;
        }
    }

    // Drag and drop functionality
    const dropZone = document.getElementById('file-drop-zone');
    const fileInput = document.getElementById('file-input');

    dropZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        dropZone.classList.add('border-blue-400', 'border-2');
    });

    dropZone.addEventListener('dragleave', () => {
        dropZone.classList.remove('border-blue-400', 'border-2');
    });

    dropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropZone.classList.remove('border-blue-400', 'border-2');
        
        if (e.dataTransfer.files.length) {
            fileInput.files = e.dataTransfer.files;
            handleFiles(e.dataTransfer.files);
        }
    });

    // Analysis function
    async function analyzeFiles() {
        const files = document.getElementById('file-input').files;
        if (files.length === 0) return;

        // Show progress
        const progressContainer = document.getElementById('progress-container');
        const progressBar = document.getElementById('progress-bar');
        const progressText = document.getElementById('progress-text');
        progressContainer.classList.remove('hidden');

        // Update progress
        progressBar.style.width = '30%';
        progressText.textContent = 'Uploading files...';

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

        // Add analysis parameters from all form fields
        const formElements = document.querySelectorAll('input, select, textarea');
        formElements.forEach(element => {
            if (element.name && element.type !== 'file') {
                if (element.type === 'checkbox') {
                    formData.append(element.name, element.checked ? 'true' : 'false');
                } else {
                    formData.append(element.name, element.value);
                }
            }
        });

        try {
            progressBar.style.width = '60%';
            progressText.textContent = 'Analyzing files...';

            const response = await fetch('/api/analyze', {
                method: 'POST',
                body: formData
            });

            progressBar.style.width = '90%';
            progressText.textContent = 'Generating rules...';

            const data = await response.json();

            if (response.ok) {
                progressBar.style.width = '100%';
                progressText.textContent = 'Complete!';

                // Show results
                showResults(data);
            } else {
                throw new Error(data.error || 'Analysis failed');
            }

        } catch (error) {
            progressText.textContent = 'Error: ' + error.message;
            progressBar.style.backgroundColor = 'red';
            console.error('Analysis error:', error);
            
            // Show error alert
            alert('Analysis failed: ' + error.message);
        }
    }

    // Show results function
    function showResults(data) {
        const resultsSection = document.getElementById('results');
        const statsContainer = document.getElementById('stats-container');
        const rulesOutput = document.getElementById('rules-output');
        const rulesCount = document.getElementById('rules-count');
        const filesCount = document.getElementById('files-count');
        const analysisTime = document.getElementById('analysis-time');

        // Update rules content
        rulesOutput.textContent = data.rules_content || 'No rules generated';
        if (window.hljs) {
            hljs.highlightElement(rulesOutput);
        }

        // Update statistics
        rulesCount.textContent = data.rules_count || 0;
        filesCount.textContent = data.files_analyzed || 0;
        analysisTime.textContent = '1.2s'; // Mock time, you can calculate real time

        // Show sections
        resultsSection.classList.remove('hidden');
        statsContainer.classList.remove('hidden');

        // Scroll to results
        resultsSection.scrollIntoView({ behavior: 'smooth' });
    }

    // Copy rules to clipboard
    function copyRules() {
        const rulesText = document.getElementById('rules-output').textContent;
        navigator.clipboard.writeText(rulesText).then(() => {
            // Show success message
            const button = event.target;
            const originalText = button.innerHTML;
            button.innerHTML = '<i class="fas fa-check mr-1"></i>Copied!';
            setTimeout(() => {
                button.innerHTML = originalText;
            }, 2000);
        });
    }

    // Download rules
    function downloadRules() {
        const rulesText = document.getElementById('rules-output').textContent;
        const blob = new Blob([rulesText], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'yarobot_rules.yar';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }
</script>
{% endblock %}