<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>DAJIN2</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
    <link href="/static/css/style.css" rel="stylesheet" type="text/css" media="all">
</head>

<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <!-- Main Form -->
                <div id="main-form" class="card">
                    <div class="card-header">
                        <h1 class="text-center mb-0">DAJIN2</h1>
                        <p class="text-center text-muted mb-0">Genotyping tool for genome editing</p>
                    </div>
                    <div class="card-body">
                        <!-- Mode Selection -->
                        <div class="mb-4">
                            <label class="form-label">Analysis Mode</label>
                            <div class="btn-group w-100" role="group" aria-label="Analysis mode selection">
                                <input type="radio" class="btn-check" name="mode" id="single-mode" value="single" checked>
                                <label class="btn btn-outline-primary" for="single-mode">Single Sample Analysis</label>
                                
                                <input type="radio" class="btn-check" name="mode" id="batch-mode" value="batch">
                                <label class="btn btn-outline-primary" for="batch-mode">Batch Processing</label>
                            </div>
                        </div>

                        <!-- Single Sample Form -->
                        <form id="dajin-form" enctype="multipart/form-data">
                            <div id="single-sample-fields">
                                <div class="mb-3">
                                    <label for="name" class="form-label">Project Name <span class="text-danger">*</span></label>
                                    <input class="form-control" type="text" id="name" name="name" required 
                                           placeholder="e.g. experiment_001" />
                                    <div class="form-text">This will be the name of the result folder</div>
                                </div>

                            <div class="mb-3">
                                <label for="sample" class="form-label">Sample Directory <span class="text-danger">*</span></label>
                                <input class="form-control" type="file" id="sample" name="sample" 
                                       accept=".fastq,.fq,.fastq.gz,.fq.gz,.fasta,.fa,.fasta.gz,.fa.gz,.bam" multiple required webkitdirectory />
                                <div class="form-text">
                                    <strong>Select a folder containing sample files</strong><br>
                                    <small class="text-muted">
                                        • Supported formats: FASTQ (.fastq, .fq, .fastq.gz, .fq.gz), FASTA (.fasta, .fa, .fasta.gz, .fa.gz), or BAM (.bam)<br>
                                        • All files in the folder must have the same format<br>
                                        • Click "Choose Files" and select any file in your sample directory
                                    </small>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label for="control" class="form-label">Control Directory <span class="text-danger">*</span></label>
                                <input class="form-control" type="file" id="control" name="control" 
                                       accept=".fastq,.fq,.fastq.gz,.fq.gz,.fasta,.fa,.fasta.gz,.fa.gz,.bam" multiple webkitdirectory />
                                <div class="form-text">
                                    <strong>Select a folder containing control files</strong><br>
                                    <small class="text-muted">
                                        • Supported formats: FASTQ (.fastq, .fq, .fastq.gz, .fq.gz), FASTA (.fasta, .fa, .fasta.gz, .fa.gz), or BAM (.bam)<br>
                                        • All files in the folder must have the same format<br>
                                        • Click "Choose Files" and select any file in your control directory
                                    </small>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label for="allele" class="form-label">Allele FASTA <span class="text-danger">*</span></label>
                                <input class="form-control" type="file" id="allele" name="allele" 
                                       accept=".fasta,.fa" multiple required />
                                <div class="form-text">Multiple files can be selected (.fasta, .fa)</div>
                            </div>

                            <div class="mb-3">
                                <label for="genome" class="form-label">Reference Genome <span class="text-muted">(Optional)</span></label>
                                <input class="form-control" type="text" id="genome" name="genome" 
                                       placeholder="e.g. hg38, mm39" />
                                <div class="form-text">Enter genome ID if using reference</div>
                            </div>

                            <div class="mb-3">
                                <label for="bed" class="form-label">BED File <span class="text-muted">(Optional)</span></label>
                                <input class="form-control" type="file" id="bed" name="bed" 
                                       accept=".bed" />
                                <div class="form-text">
                                    <strong>Upload a BED6 file for genomic coordinates</strong><br>
                                    <small class="text-muted">
                                        • Use when reference genome is not from UCSC<br>
                                        • BED6 format required (6 columns)<br>
                                        • Strand must match FASTA allele orientation
                                    </small>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label for="threads" class="form-label">Threads <span class="text-muted">(Optional)</span></label>
                                <input class="form-control" type="number" id="threads" name="threads" 
                                       min="1" max="32" value="1" />
                                <div class="form-text">Number of parallel processing threads (1-32)</div>
                            </div>
                            
                            <div class="form-check mb-3">
                                <input class="form-check-input" type="checkbox" id="no-filter" name="no-filter">
                                <label class="form-check-label" for="no-filter">
                                    Disable minor allele filtering (keep alleles <0.5%)
                                </label>
                                <div class="form-text">
                                    <small class="text-muted">
                                        Enable this for detecting rare mutations or somatic mosaicism
                                    </small>
                                </div>
                            </div>
                            </div>

                            <!-- Batch Processing Fields -->
                            <div id="batch-fields" style="display: none;">
                                <div class="mb-3">
                                    <label for="batch-file" class="form-label">Batch File <span class="text-danger">*</span></label>
                                    <input class="form-control" type="file" id="batch-file" name="batch-file" 
                                           accept=".csv,.xlsx" />
                                    <div class="form-text">
                                        <strong>Upload a CSV or Excel file with sample information</strong><br>
                                        <small class="text-muted">
                                            Required columns: <code>sample</code>, <code>control</code>, <code>allele</code>, <code>name</code><br>
                                            Optional columns: <code>genome</code>, <code>bed</code> (or <code>genome_coordinate</code>)<br>
                                            <a href="https://docs.google.com/presentation/d/e/2PACX-1vSMEmXJPG2TNjfT66XZJRzqJd82aAqO5gJrdEzyhn15YBBr_Li-j5puOgVChYf3jA/embed?start=false&loop=false&delayms=3000" target="_blank">View batch file format guide</a>
                                        </small>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="batch-threads" class="form-label">Threads <span class="text-muted">(Optional)</span></label>
                                    <input class="form-control" type="number" id="batch-threads" name="batch-threads" 
                                           min="1" max="32" value="1" />
                                    <div class="form-text">Number of parallel processing threads (1-32)</div>
                                </div>
                                
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="batch-no-filter" name="batch-no-filter">
                                    <label class="form-check-label" for="batch-no-filter">
                                        Disable minor allele filtering (keep alleles <0.5%)
                                    </label>
                                </div>
                            </div>

                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary btn-lg">
                                    <span id="submit-text">Start Analysis</span>
                                    <span id="submit-spinner" class="spinner-border spinner-border-sm ms-2" style="display: none;"></span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Analysis Log Panel -->
                <div id="progress-panel" class="card mt-4" style="display: none;">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">Analysis Log</h5>
                        <div class="d-flex flex-column align-items-end">
                            <div id="analysis-clock" class="badge bg-primary mb-1" style="font-family: monospace; font-size: 0.9rem;">
                                00:00:00
                            </div>
                            <small class="text-muted">Live updates from DAJIN2</small>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div id="log-container" class="p-3 bg-dark text-light" style="height: 400px; overflow-y: auto; font-family: 'Courier New', monospace; font-size: 0.85em; line-height: 1.4; border: 1px solid #444;">
                            <div id="log-messages">
                                <div class="log-entry text-info">Starting analysis...</div>
                            </div>
                        </div>
                        <div class="card-footer bg-light">
                            <small class="text-muted">
                                <span id="log-status">Analysis in progress...</span>
                                <span class="float-end">
                                    <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearLog()">Clear Log</button>
                                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="scrollToBottom()">↓ Scroll to Bottom</button>
                                </span>
                            </small>
                        </div>
                    </div>
                </div>

                <!-- Result Panel -->
                <div id="result-panel" class="card mt-4" style="display: none;">
                    <div class="card-header">
                        <h5 class="mb-0">Analysis Results</h5>
                    </div>
                    <div class="card-body text-center">
                        <div id="result-message" class="mb-3"></div>
                        <div id="result-path-display" class="mb-3 p-3 bg-light rounded">
                            <div class="mb-2">
                                <small class="text-muted">Unix Path:</small><br>
                                <code id="result-path-unix" class="d-block"></code>
                            </div>
                            <div id="windows-path-container" style="display: none;">
                                <small class="text-muted">Windows Path:</small><br>
                                <code id="result-path-windows" class="d-block"></code>
                            </div>
                        </div>
                        <div id="result-actions">
                            <button type="button" class="btn btn-success me-2" onclick="openResultFolder()">
                                📁 Open Results Folder
                            </button>
                            <div class="btn-group me-2" role="group">
                                <button type="button" class="btn btn-info" onclick="copyResultPath('unix')">
                                    📋 Copy Unix Path
                                </button>
                                <button type="button" class="btn btn-info" onclick="copyResultPath('windows')" id="copy-windows-btn" style="display: none;">
                                    📋 Copy Windows Path
                                </button>
                            </div>
                            <button type="button" class="btn btn-secondary" onclick="startNewAnalysis()">
                                🔄 Start New Analysis
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Error Panel -->
                <div id="error-panel" class="alert alert-danger mt-4" style="display: none;">
                    <h6 class="alert-heading">An Error Occurred</h6>
                    <p id="error-message" class="mb-0"></p>
                    <hr>
                    <button type="button" class="btn btn-outline-danger btn-sm" onclick="startNewAnalysis()">
                        🔄 Retry
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="mt-5 py-3 bg-light">
        <div class="container text-center">
            <div class="text-muted">
                <a href="https://github.com/akikuno/DAJIN2" target="_blank" class="text-decoration-none">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-github" viewBox="0 0 16 16">
                        <path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.012 8.012 0 0 0 16 8c0-4.42-3.58-8-8-8z"/>
                    </svg>
                    DAJIN2 on GitHub
                </a>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
        crossorigin="anonymous"></script>

    <script>
        let currentAnalysisId = null;
        let eventSource = null;
        let analysisStartTime = null;
        let clockInterval = null;

        // Add directory selection feedback
        document.addEventListener('DOMContentLoaded', function() {
            const sampleInput = document.getElementById('sample');
            const controlInput = document.getElementById('control');
            
            sampleInput.addEventListener('change', function(e) {
                updateDirectoryFeedback(e.target, 'sample');
            });
            
            controlInput.addEventListener('change', function(e) {
                updateDirectoryFeedback(e.target, 'control');
            });

            // Mode switching
            const singleMode = document.getElementById('single-mode');
            const batchMode = document.getElementById('batch-mode');
            const singleFields = document.getElementById('single-sample-fields');
            const batchFields = document.getElementById('batch-fields');

            singleMode.addEventListener('change', function() {
                if (this.checked) {
                    singleFields.style.display = 'block';
                    batchFields.style.display = 'none';
                    // Update required attributes
                    document.getElementById('name').required = true;
                    document.getElementById('sample').required = true;
                    document.getElementById('control').required = true;
                    document.getElementById('allele').required = true;
                    document.getElementById('batch-file').required = false;
                }
            });

            batchMode.addEventListener('change', function() {
                if (this.checked) {
                    singleFields.style.display = 'none';
                    batchFields.style.display = 'block';
                    // Update required attributes
                    document.getElementById('name').required = false;
                    document.getElementById('sample').required = false;
                    document.getElementById('control').required = false;
                    document.getElementById('allele').required = false;
                    document.getElementById('batch-file').required = true;
                }
            });
        });

        function updateDirectoryFeedback(input, type) {
            const files = input.files;
            const container = input.closest('.mb-3');
            let feedbackElement = container.querySelector('.directory-feedback');
            
            if (!feedbackElement) {
                feedbackElement = document.createElement('div');
                feedbackElement.className = 'directory-feedback mt-2 p-2 bg-info text-white rounded';
                container.appendChild(feedbackElement);
            }
            
            if (files.length > 0) {
                // Get directory name from first file path
                const firstFilePath = files[0].webkitRelativePath || files[0].name;
                const dirName = firstFilePath.split('/')[0] || 'Selected files';
                
                feedbackElement.innerHTML = `
                    <strong>✓ Directory selected:</strong> ${dirName}<br>
                    <small>${files.length} file(s) found</small>
                `;
                feedbackElement.className = 'directory-feedback mt-2 p-2 bg-success text-white rounded';
            } else {
                feedbackElement.innerHTML = '<strong>⚠ No directory selected</strong>';
                feedbackElement.className = 'directory-feedback mt-2 p-2 bg-warning text-dark rounded';
            }
        }

        // Form submission handler
        document.getElementById('dajin-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const submitBtn = document.querySelector('button[type="submit"]');
            const submitText = document.getElementById('submit-text');
            const submitSpinner = document.getElementById('submit-spinner');
            
            // Add mode to form data
            const mode = document.querySelector('input[name="mode"]:checked').value;
            formData.append('mode', mode);
            
            // Show loading state
            submitBtn.disabled = true;
            submitText.textContent = 'Starting analysis...';
            submitSpinner.style.display = 'inline-block';
            
            try {
                const endpoint = mode === 'batch' ? '/submit-batch' : '/submit';
                const response = await fetch(endpoint, {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (response.ok) {
                    // Success - start progress monitoring
                    currentAnalysisId = result.analysis_id;
                    showProgressPanel();
                    startProgressMonitoring(currentAnalysisId);
                } else {
                    // Error
                    showError(result.error || 'Unknown error occurred');
                }
            } catch (error) {
                showError('Communication with server failed: ' + error.message);
            } finally {
                // Reset button state
                submitBtn.disabled = false;
                submitText.textContent = 'Start Analysis';
                submitSpinner.style.display = 'none';
            }
        });

        function startProgressMonitoring(analysisId) {
            if (eventSource) {
                eventSource.close();
            }
            
            eventSource = new EventSource(`/progress/${analysisId}`);
            
            eventSource.onmessage = function(event) {
                const data = JSON.parse(event.data);
                
                if (data.status === 'log') {
                    addLogMessage(data.message, 'info');
                } else if (data.status === 'completed') {
                    addLogMessage(data.message, 'success');
                    stopAnalysisClock();
                    showResult(data.message, data.result_path);
                    eventSource.close();
                } else if (data.status === 'error') {
                    addLogMessage(data.message, 'error');
                    stopAnalysisClock();
                    showError(data.message);
                    eventSource.close();
                } else if (data.status === 'heartbeat') {
                    // Keep connection alive
                }
            };
            
            eventSource.onerror = function(event) {
                console.error('EventSource error:', event);
                stopAnalysisClock();
                showError('Error occurred during progress monitoring');
                eventSource.close();
            };
        }

        function showProgressPanel() {
            document.getElementById('main-form').style.display = 'none';
            document.getElementById('progress-panel').style.display = 'block';
            document.getElementById('result-panel').style.display = 'none';
            document.getElementById('error-panel').style.display = 'none';
            
            // Start the analysis timer
            startAnalysisClock();
        }

        function addLogMessage(message, type = 'info') {
            const logMessages = document.getElementById('log-messages');
            const logEntry = document.createElement('div');
            logEntry.className = 'log-entry mb-1';
            
            // Parse DAJIN2 log format: timestamp, level, message
            let parsedMessage = message;
            let logLevel = type;
            
            // Check if message matches DAJIN2 log format
            const logFormatMatch = message.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}),\s*(\w+),\s*(.+)$/);
            if (logFormatMatch) {
                const [, timestamp, level, content] = logFormatMatch;
                logLevel = level.toLowerCase();
                
                // Color code different log levels
                let levelColor = 'text-light';
                if (logLevel === 'error') {
                    levelColor = 'text-danger';
                } else if (logLevel === 'warning' || logLevel === 'warn') {
                    levelColor = 'text-warning';
                } else if (logLevel === 'info') {
                    levelColor = 'text-info';
                } else if (logLevel === 'debug') {
                    levelColor = 'text-muted';
                }
                
                // Format with colored timestamp and level
                parsedMessage = `<span class="text-muted">${timestamp}</span> <span class="text-secondary">[${level}]</span> <span class="${levelColor}">${content}</span>`;
            } else {
                // Non-DAJIN2 formatted messages
                if (type === 'error') {
                    logEntry.className += ' text-danger';
                } else if (type === 'success') {
                    logEntry.className += ' text-success';
                } else if (type === 'warning') {
                    logEntry.className += ' text-warning';
                } else {
                    logEntry.className += ' text-light';
                }
                parsedMessage = message.replace(/\n/g, '<br>');
            }
            
            logEntry.innerHTML = parsedMessage;
            logMessages.appendChild(logEntry);
            
            // Auto-scroll to bottom
            scrollToBottom();
            
            // Update status
            updateLogStatus(message, type);
        }
        
        function updateLogStatus(message, type) {
            const statusElement = document.getElementById('log-status');
            if (type === 'success') {
                statusElement.textContent = 'Analysis completed successfully';
                statusElement.className = 'text-success';
            } else if (type === 'error') {
                statusElement.textContent = 'Analysis failed - see log for details';
                statusElement.className = 'text-danger';
            } else {
                statusElement.textContent = 'Analysis in progress...';
                statusElement.className = 'text-muted';
            }
        }
        
        function clearLog() {
            const logMessages = document.getElementById('log-messages');
            logMessages.innerHTML = '<div class="log-entry text-info">Log cleared...</div>';
        }
        
        function scrollToBottom() {
            const logContainer = document.getElementById('log-container');
            logContainer.scrollTop = logContainer.scrollHeight;
        }

        function showResult(message, resultPath) {
            document.getElementById('progress-panel').style.display = 'none';
            document.getElementById('result-panel').style.display = 'block';
            document.getElementById('result-message').innerHTML = message;
            
            // Store result path and display both Unix and Windows formats
            window.resultPath = resultPath;
            document.getElementById('result-path-unix').textContent = resultPath;
            
            // Show Windows path if it looks like a Windows system or WSL
            function convertToWindowsPath(unixPath) {
                // Convert WSL mount paths (/mnt/drive/) to Windows drive letters
                const wslPattern = /^\/mnt\/([a-z])(\/.*)?$/i;
                const match = unixPath.match(wslPattern);
                
                if (match) {
                    const driveLetter = match[1].toUpperCase();
                    const restOfPath = match[2] || '';
                    return `${driveLetter}:${restOfPath}`.replace(/\//g, '\\');
                } else {
                    // For non-WSL paths, just convert slashes
                    return unixPath.replace(/\//g, '\\');
                }
            }
            
            const windowsPath = convertToWindowsPath(resultPath);
            if (resultPath.includes('/mnt/') || navigator.platform.includes('Win')) {
                document.getElementById('windows-path-container').style.display = 'block';
                document.getElementById('result-path-windows').textContent = windowsPath;
                document.getElementById('copy-windows-btn').style.display = 'inline-block';
                window.windowsPath = windowsPath;
            }
        }

        function showError(message) {
            document.getElementById('progress-panel').style.display = 'none';
            document.getElementById('error-panel').style.display = 'block';
            document.getElementById('error-message').textContent = message;
        }

        async function openResultFolder() {
            if (!currentAnalysisId) {
                alert('No analysis ID available');
                return;
            }
            
            try {
                const response = await fetch(`/open-folder/${currentAnalysisId}`);
                const result = await response.json();
                
                if (response.ok) {
                    // Show success message with path info
                    let successMsg = `Folder opened successfully!\n\nUnix Path: ${result.path}`;
                    if (result.windows_path && result.windows_path !== result.path) {
                        successMsg += `\nWindows Path: ${result.windows_path}`;
                    }
                    alert(successMsg);
                } else {
                    // Show detailed error information for debugging
                    let errorMsg = `Could not open folder automatically.\n\n`;
                    
                    if (result.debug_info) {
                        errorMsg += `Debug Info: ${result.debug_info}\n\n`;
                    }
                    
                    errorMsg += `Please manually navigate to:\nUnix: ${result.path || window.resultPath || 'Unknown path'}`;
                    
                    if (result.windows_path || window.windowsPath) {
                        errorMsg += `\nWindows: ${result.windows_path || window.windowsPath}`;
                    }
                    
                    if (result.suggestion) {
                        errorMsg += `\n\n${result.suggestion}`;
                    }
                    
                    alert(errorMsg);
                }
            } catch (error) {
                // Enhanced fallback with both path formats
                let fallbackMsg = `Could not open folder automatically.\nError: ${error.message}\n\n`;
                fallbackMsg += `Please manually navigate to:\nUnix: ${window.resultPath || 'Unknown path'}`;
                
                if (window.windowsPath) {
                    fallbackMsg += `\nWindows: ${window.windowsPath}`;
                }
                
                alert(fallbackMsg);
            }
        }
        
        function copyResultPath(type = 'unix') {
            let pathToCopy;
            let pathLabel;
            
            if (type === 'windows' && window.windowsPath) {
                pathToCopy = window.windowsPath;
                pathLabel = 'Windows path';
            } else {
                pathToCopy = window.resultPath;
                pathLabel = 'Unix path';
            }
            
            if (pathToCopy) {
                navigator.clipboard.writeText(pathToCopy).then(function() {
                    // Show temporary notification
                    const btn = event.target;
                    const originalText = btn.innerHTML;
                    btn.innerHTML = '✅ Copied!';
                    btn.disabled = true;
                    
                    setTimeout(function() {
                        btn.innerHTML = originalText;
                        btn.disabled = false;
                    }, 2000);
                }).catch(function(err) {
                    // Fallback for older browsers
                    prompt(`Copy this ${pathLabel}:`, pathToCopy);
                });
            }
        }

        function startAnalysisClock() {
            // Record the start time
            analysisStartTime = new Date();
            
            // Update clock immediately
            updateAnalysisClock();
            
            // Update every second
            clockInterval = setInterval(updateAnalysisClock, 1000);
        }

        function updateAnalysisClock() {
            if (!analysisStartTime) return;
            
            const now = new Date();
            const elapsed = Math.floor((now - analysisStartTime) / 1000); // seconds
            
            const hours = Math.floor(elapsed / 3600);
            const minutes = Math.floor((elapsed % 3600) / 60);
            const seconds = elapsed % 60;
            
            const timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            
            const clockElement = document.getElementById('analysis-clock');
            if (clockElement) {
                clockElement.textContent = timeString;
            }
        }

        function stopAnalysisClock() {
            if (clockInterval) {
                clearInterval(clockInterval);
                clockInterval = null;
            }
        }

        function startNewAnalysis() {
            // Reset all panels
            document.getElementById('main-form').style.display = 'block';
            document.getElementById('progress-panel').style.display = 'none';
            document.getElementById('result-panel').style.display = 'none';
            document.getElementById('error-panel').style.display = 'none';
            
            // Reset form
            document.getElementById('dajin-form').reset();
            
            // Reset log
            const logMessages = document.getElementById('log-messages');
            logMessages.innerHTML = '<div class="log-entry text-info">Ready to start new analysis...</div>';
            
            // Reset log status
            const statusElement = document.getElementById('log-status');
            statusElement.textContent = 'Analysis ready';
            statusElement.className = 'text-muted';
            
            // Reset and stop analysis clock
            stopAnalysisClock();
            analysisStartTime = null;
            const clockElement = document.getElementById('analysis-clock');
            if (clockElement) {
                clockElement.textContent = '00:00:00';
            }
            
            // Close any existing event source
            if (eventSource) {
                eventSource.close();
                eventSource = null;
            }
            
            currentAnalysisId = null;
            window.resultPath = null;
        }
    </script>
</body>

</html>