<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>L1 Synthetic Data Generator</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>
</head>
<body>
    <div class="container">
        <header>
            <h1>L1 Synthetic Data Generator</h1>
            <p class="subtitle">Generate synthetic bid/ask financial data using Statistical Methods</p>
            <p class="authors">by: Mohammad, Luis, Stephano</p>
        </header>

        <!-- Control Panel -->
        <div class="control-panel">
            <form id="generatorForm">
                <div class="form-group">
                    <label for="simulationLength">Simulation Length</label>
                    <div class="input-wrapper">
                        <input
                            type="number"
                            id="simulationLength"
                            name="simulation_length"
                            value="5000"
                            min="100"
                            max="100000"
                            step="100"
                            required
                        >
                        <p class="input-hint">Number of data points to generate (100 - 100,000)</p>
                    </div>
                </div>

                <div class="form-group">
                    <label for="volatility">Volatility Multiplier</label>
                    <div class="input-wrapper">
                        <input
                            type="number"
                            id="volatility"
                            name="volatility"
                            value="1.0"
                            min="0.1"
                            max="10"
                            step="0.1"
                            required
                        >
                        <p class="input-hint">Volatility scaling factor (0.1 - 10.0, default: 1.0)</p>
                    </div>
                </div>

                <button type="submit" class="btn-generate" id="generateBtn">
                    Generate Synthetic Data
                </button>
            </form>
            <div id="errorMessage" class="error-message" style="display: none;"></div>
        </div>

        <!-- Results Section -->
        <div id="results">
            <div class="results-header">
                <h2>✓ Generation Complete</h2>
                <p id="resultsSummary"></p>
            </div>

            <!-- Statistics Grid -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-label">Data Points</div>
                    <div class="stat-value" id="statDataPoints">-</div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">Bid Mean</div>
                    <div class="stat-value" id="statBidMean">-</div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">Ask Mean</div>
                    <div class="stat-value" id="statAskMean">-</div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">Spread Mean</div>
                    <div class="stat-value" id="statSpreadMean">-</div>
                </div>
            </div>

            <!-- Shapiro-Wilk Validation -->
            <div class="validation-section">
                <h3>Shapiro-Wilk Normality Test (Bid-Ask Spread)</h3>
                <div class="test-result">
                    <span class="test-badge" id="testBadge">-</span>
                    <div>
                        <strong id="testInterpretation">-</strong>
                        <p style="color: var(--text-secondary); font-size: 0.9rem;" id="testDescription">-</p>
                    </div>
                </div>
                <div class="test-details">
                    <div class="detail-item">
                        <div class="detail-label">Statistic</div>
                        <div class="detail-value" id="testStatistic">-</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">P-Value</div>
                        <div class="detail-value" id="testPValue">-</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">Spread Std Dev</div>
                        <div class="detail-value" id="spreadStd">-</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">Sample Size</div>
                        <div class="detail-value" id="testSampleSize">-</div>
                    </div>
                </div>
            </div>

            <!-- Time Series Chart -->
            <div class="chart-container">
                <h3>Bid/Ask Time Series</h3>
                <div id="timeSeriesChart"></div>
            </div>

            <!-- Spread Distribution Chart -->
            <div class="chart-container">
                <h3>Bid-Ask Spread Distribution</h3>
                <div id="spreadChart"></div>
            </div>

            <!-- Data Preview -->
            <div class="data-preview">
                <h3>Data Preview</h3>
                <h4 style="color: var(--text-secondary); margin-bottom: 1rem;">First 10 Rows</h4>
                <div class="preview-table">
                    <table id="previewTableHead">
                        <thead>
                            <tr>
                                <th>Timestamp</th>
                                <th>Bid</th>
                                <th>Ask</th>
                            </tr>
                        </thead>
                        <tbody id="previewBodyHead"></tbody>
                    </table>
                </div>

                <h4 style="color: var(--text-secondary); margin: 1.5rem 0 1rem 0;">Last 10 Rows</h4>
                <div class="preview-table">
                    <table id="previewTableTail">
                        <thead>
                            <tr>
                                <th>Timestamp</th>
                                <th>Bid</th>
                                <th>Ask</th>
                            </tr>
                        </thead>
                        <tbody id="previewBodyTail"></tbody>
                    </table>
                </div>

                <p style="margin-top: 1rem; color: var(--text-secondary);">
                    <strong>File saved:</strong> <span id="savedFilename"></span>
                </p>
            </div>
        </div>
    </div>

    <script>
        const form = document.getElementById('generatorForm');
        const generateBtn = document.getElementById('generateBtn');
        const results = document.getElementById('results');
        const errorMessage = document.getElementById('errorMessage');

        form.addEventListener('submit', async (e) => {
            e.preventDefault();

            // Hide previous results and errors
            results.classList.remove('active');
            errorMessage.style.display = 'none';

            // Get form data
            const formData = {
                simulation_length: parseInt(document.getElementById('simulationLength').value),
                volatility: parseFloat(document.getElementById('volatility').value)
            };

            // Disable button and show loading
            generateBtn.disabled = true;
            generateBtn.classList.add('loading');
            generateBtn.innerHTML = '<span class="spinner"></span>Generating...';

            try {
                // Call API
                const response = await fetch('/generate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(formData)
                });

                const data = await response.json();

                if (!response.ok) {
                    throw new Error(data.error || 'Generation failed');
                }

                // Display results
                displayResults(data);
                results.classList.add('active');

            } catch (error) {
                errorMessage.textContent = `Error: ${error.message}`;
                errorMessage.style.display = 'block';
            } finally {
                // Re-enable button
                generateBtn.disabled = false;
                generateBtn.classList.remove('loading');
                generateBtn.innerHTML = 'Generate Synthetic Data';
            }
        });

        function displayResults(data) {
            // Summary
            document.getElementById('resultsSummary').textContent =
                `Generated ${data.statistics.data_points.toLocaleString()} data points with ${data.validation.sample_size.toLocaleString()} samples tested`;

            // Statistics
            document.getElementById('statDataPoints').textContent =
                data.statistics.data_points.toLocaleString();
            document.getElementById('statBidMean').textContent =
                data.statistics.bid_stats.mean.toFixed(2);
            document.getElementById('statAskMean').textContent =
                data.statistics.ask_stats.mean.toFixed(2);
            document.getElementById('statSpreadMean').textContent =
                data.validation.spread_stats.mean.toFixed(4);

            // Validation results
            const isNormal = data.validation.is_normal;
            const badge = document.getElementById('testBadge');
            badge.textContent = isNormal ? 'NORMAL' : 'NOT NORMAL';
            badge.className = `test-badge ${isNormal ? 'normal' : 'not-normal'}`;

            document.getElementById('testInterpretation').textContent =
                data.validation.interpretation;
            document.getElementById('testDescription').textContent =
                `The Shapiro-Wilk test ${isNormal ? 'accepts' : 'rejects'} the null hypothesis of normality (α = ${data.validation.alpha})`;
            document.getElementById('testStatistic').textContent =
                data.validation.statistic.toFixed(6);
            document.getElementById('testPValue').textContent =
                data.validation.p_value.toFixed(6);
            document.getElementById('spreadStd').textContent =
                data.validation.spread_stats.std.toFixed(4);
            document.getElementById('testSampleSize').textContent =
                data.validation.sample_size.toLocaleString();

            // Charts
            plotTimeSeries(data.visualization);
            plotSpreadDistribution(data.visualization);

            // Data preview
            displayDataPreview(data.preview);

            // Filename
            document.getElementById('savedFilename').textContent = data.filename;
        }

        function plotTimeSeries(vizData) {
            const trace1 = {
                x: vizData.timestamps,
                y: vizData.bid,
                name: 'Bid',
                type: 'scatter',
                mode: 'lines',
                line: { color: '#58a6ff', width: 2 }
            };

            const trace2 = {
                x: vizData.timestamps,
                y: vizData.ask,
                name: 'Ask',
                type: 'scatter',
                mode: 'lines',
                line: { color: '#3fb950', width: 2 }
            };

            const layout = {
                paper_bgcolor: '#161b22',
                plot_bgcolor: '#0d1117',
                font: { color: '#c9d1d9' },
                xaxis: {
                    gridcolor: '#30363d',
                    title: 'Time'
                },
                yaxis: {
                    gridcolor: '#30363d',
                    title: 'Price'
                },
                margin: { t: 30, r: 30, b: 50, l: 60 },
                legend: {
                    orientation: 'h',
                    y: 1.1
                }
            };

            Plotly.newPlot('timeSeriesChart', [trace1, trace2], layout, {responsive: true});
        }

        function plotSpreadDistribution(vizData) {
            const trace = {
                x: vizData.spread,
                type: 'histogram',
                nbinsx: vizData.spread_histogram.bins,
                marker: { color: '#58a6ff' },
                name: 'Spread'
            };

            const layout = {
                paper_bgcolor: '#161b22',
                plot_bgcolor: '#0d1117',
                font: { color: '#c9d1d9' },
                xaxis: {
                    gridcolor: '#30363d',
                    title: 'Bid-Ask Spread'
                },
                yaxis: {
                    gridcolor: '#30363d',
                    title: 'Frequency'
                },
                margin: { t: 30, r: 30, b: 50, l: 60 }
            };

            Plotly.newPlot('spreadChart', [trace], layout, {responsive: true});
        }

        function displayDataPreview(preview) {
            const headBody = document.getElementById('previewBodyHead');
            const tailBody = document.getElementById('previewBodyTail');

            headBody.innerHTML = '';
            tailBody.innerHTML = '';

            preview.head.forEach(row => {
                headBody.innerHTML += `
                    <tr>
                        <td>${row.timestamp}</td>
                        <td>${parseFloat(row.bid).toFixed(2)}</td>
                        <td>${parseFloat(row.ask).toFixed(2)}</td>
                    </tr>
                `;
            });

            preview.tail.forEach(row => {
                tailBody.innerHTML += `
                    <tr>
                        <td>${row.timestamp}</td>
                        <td>${parseFloat(row.bid).toFixed(2)}</td>
                        <td>${parseFloat(row.ask).toFixed(2)}</td>
                    </tr>
                `;
            });
        }
    </script>
</body>
</html>
