{% extends "base.html" %}

{% block title %}Words to Readlang - Preview {{ upload.filename }}{% endblock %}

{% block content %}
<div class="preview-container">
    {% if new_session %}
    <div class="alert alert-info">
        <strong>New session created!</strong> Your magic phrase is: <strong>{{ user_session.magic_phrase }}</strong>
        <br>
        <small>This phrase will let you access your uploads for the next 30 days. Make sure to copy it!</small>
    </div>
    {% endif %}

    <div class="preview-header">
        <h2>{{ upload.filename }}</h2>
        <div class="preview-meta">
            <span class="badge">{{ upload.file_format }}</span>
            <span class="badge" style="background: white; color: #111827; border: 1px solid #d1d5db;">{{ upload|language_pair }}</span>
            <span>{{ upload.entry_count }} entries</span>
            <span>Uploaded {{ upload.uploaded_at.strftime('%Y-%m-%d %H:%M') }}</span>
        </div>
    </div>

    <div class="validation-stats">
        <h3>Validation Status</h3>
        <div class="stats-grid">
            <div class="stat-card stat-valid">
                <div class="stat-value">{{ stats.valid }}</div>
                <div class="stat-label">Valid</div>
            </div>
            <div class="stat-card stat-warning">
                <div class="stat-value">{{ stats.invalid_no_example }}</div>
                <div class="stat-label">No Example</div>
            </div>
            <div class="stat-card stat-error">
                <div class="stat-value">{{ stats.invalid_word_missing }}</div>
                <div class="stat-label">Word Missing</div>
            </div>
        </div>
        <button hx-post="{{ url_for('validate.validate_upload', upload_id=upload.id) }}"
                hx-target="#validation-stats"
                class="btn btn-sm">
            Re-validate All
        </button>
    </div>

    {% if stats.invalid_no_example + stats.invalid_word_missing > 0 %}
    <div class="batch-fetch-container" style="background: white; padding: 1.5rem; border-radius: 0.5rem; margin-bottom: 1rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
        <h3>Fetch Missing Examples</h3>
        <p style="color: #6b7280; margin-bottom: 1rem;">Automatically fetch example sentences for all {{ stats.invalid_no_example + stats.invalid_word_missing }} invalid entries from Tatoeba and Leipzig Corpora Collection.</p>

        <div style="display: flex; align-items: center; gap: 1rem; margin-bottom: 1rem; flex-wrap: wrap;">
            <div style="display: flex; align-items: center; gap: 0.5rem;">
                <label style="font-size: 0.875rem; color: #374151; font-weight: 500;">Prefer:</label>
                <label style="display: flex; align-items: center; gap: 0.25rem; font-size: 0.875rem; cursor: pointer;">
                    <input type="radio" name="prefer-source" value="tatoeba" checked> Tatoeba first
                </label>
                <label style="display: flex; align-items: center; gap: 0.25rem; font-size: 0.875rem; cursor: pointer;">
                    <input type="radio" name="prefer-source" value="leipzig"> Leipzig first
                </label>
            </div>
            <button id="fetch-all-btn" class="btn btn-warning">
                Fetch All Missing Examples
            </button>
        </div>

        <div id="fetch-progress" style="display: none; margin-top: 1rem;">
            <div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem;">
                <span id="progress-text">Processing...</span>
                <span id="progress-count">0 / {{ stats.invalid_no_example + stats.invalid_word_missing }}</span>
            </div>
            <div style="background-color: #e5e7eb; border-radius: 0.5rem; height: 1.5rem; overflow: hidden;">
                <div id="progress-bar" style="background-color: #3b82f6; height: 100%; width: 0%; transition: width 0.3s;"></div>
            </div>
        </div>
    </div>

    <script>
        document.getElementById('fetch-all-btn').addEventListener('click', function() {
            const btn = this;
            const progress = document.getElementById('fetch-progress');
            const progressBar = document.getElementById('progress-bar');
            const progressText = document.getElementById('progress-text');
            const progressCount = document.getElementById('progress-count');
            const prefer = document.querySelector('input[name="prefer-source"]:checked').value;

            // Disable button and show progress
            btn.disabled = true;
            btn.textContent = 'Fetching...';
            progress.style.display = 'block';
            progressBar.style.backgroundColor = '#3b82f6';

            // Create EventSource for SSE
            const url = '{{ url_for("tatoeba.fetch_all_missing", upload_id=upload.id) }}?prefer=' + prefer;
            const source = new EventSource(url);

            const sourceLabels = { tatoeba: 'Tatoeba', leipzig: 'Leipzig' };

            source.onmessage = function(e) {
                const data = JSON.parse(e.data);

                if (data.done) {
                    // Complete
                    source.close();
                    btn.disabled = false;
                    btn.textContent = 'Fetch All Missing Examples';
                    progressText.textContent = data.message || 'Complete!';
                    progressBar.style.width = '100%';
                    progressBar.style.backgroundColor = '#10b981';

                    // Refresh the page after 2 seconds to show updated entries
                    setTimeout(() => location.reload(), 2000);
                } else {
                    // Progress update
                    const percent = (data.current / data.total) * 100;
                    progressBar.style.width = percent + '%';
                    progressCount.textContent = data.current + ' / ' + data.total;

                    if (data.success) {
                        const src = data.source ? ' [' + sourceLabels[data.source] + ']' : '';
                        progressText.textContent = 'Found example for: ' + data.word + src;
                    } else {
                        progressText.textContent = 'No example for: ' + data.word;
                    }
                }
            };

            source.onerror = function() {
                source.close();
                btn.disabled = false;
                btn.textContent = 'Fetch All Missing Examples';
                progressText.textContent = 'Error occurred. Please try again.';
                progressBar.style.backgroundColor = '#ef4444';
            };
        });
    </script>
    {% endif %}

    <div class="table-width-toggle">
        <button id="table-width-btn" onclick="toggleTableWidth()" title="Toggle full-width table">
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M1 8h14M1 8l3-3M1 8l3 3M15 8l-3-3M15 8l-3 3" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            <span id="table-width-label">Expand table</span>
        </button>
    </div>

    <div class="entries-table-container">
        <table class="entries-table">
            <thead>
                <tr>
                    <th>Status</th>
                    <th>Word</th>
                    <th>Translation</th>
                    <th>Example</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="entries-tbody">
                {% for entry in entries %}
                {% include 'components/entry_row.html' %}
                {% endfor %}

                {% if has_more %}
                <tr id="load-more-{{ upload.id }}-{{ page + 1 }}"
                    hx-get="{{ url_for('preview.get_entries', upload_id=upload.id, page=page+1) }}"
                    hx-trigger="revealed"
                    hx-target="this"
                    hx-swap="outerHTML">
                    <td colspan="5" class="loading-row">Loading more...</td>
                </tr>
                {% endif %}
            </tbody>
        </table>
    </div>

    {% if stats.invalid_no_example + stats.invalid_word_missing > 0 %}
    <div class="alert alert-warning" style="margin-top: 1rem;">
        <strong>Export Notice:</strong> {{ stats.invalid_no_example + stats.invalid_word_missing }} entries with invalid examples will be excluded from export. Only valid entries ({{ stats.valid }}) will be included.
    </div>
    {% endif %}

    <div class="preview-actions">
        <a href="{{ url_for('export.export_download', upload_id=upload.id) }}" class="btn btn-primary">
            Export to Readlang
        </a>
        <a href="{{ url_for('main.index') }}" class="btn btn-secondary">
            Back to Home
        </a>
        <button hx-delete="{{ url_for('upload.delete_upload', upload_id=upload.id) }}"
                hx-confirm="Are you sure you want to delete '{{ upload.filename }}'? This will delete all {{ upload.entry_count }} entries and cannot be undone."
                class="btn btn-danger">
            Delete Upload
        </button>
    </div>
</div>

<script>
    // Full-width table toggle, persisted in localStorage
    const TABLE_WIDTH_KEY = 'tableFullWidth';

    function applyTableWidth(fullWidth) {
        const btn = document.getElementById('table-width-btn');
        const label = document.getElementById('table-width-label');
        if (fullWidth) {
            document.body.classList.add('table-full-width');
            btn.classList.add('active');
            label.textContent = 'Collapse table';
        } else {
            document.body.classList.remove('table-full-width');
            btn.classList.remove('active');
            label.textContent = 'Expand table';
        }
    }

    function toggleTableWidth() {
        const current = localStorage.getItem(TABLE_WIDTH_KEY) === 'true';
        const next = !current;
        localStorage.setItem(TABLE_WIDTH_KEY, next);
        applyTableWidth(next);
    }

    // Apply on load
    applyTableWidth(localStorage.getItem(TABLE_WIDTH_KEY) === 'true');
</script>
{% endblock %}
