{% extends "base.html" %}

{% block title %}Words to Readlang - Word Pool{% endblock %}

{% block content %}
<div class="pool-container">
    <div class="preview-header">
        <h2>Word Pool</h2>
        <p style="margin-bottom: 0.5rem;">All entries for: <span class="badge" style="background: white; color: #111827; border: 1px solid #d1d5db;">{{ source_language|language_name }} → {{ target_language|language_name }}</span></p>
        {% if available_pairs|length > 1 %}
        <p style="font-size: 0.875rem; color: #6b7280;">
            <a href="{{ url_for('pool.pool') }}" style="color: #3b82f6; text-decoration: none;">← Switch language pair</a>
        </p>
        {% endif %}
    </div>

    <div class="validation-stats">
        <h3>Statistics</h3>
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-value">{{ stats.total }}</div>
                <div class="stat-label">Total Entries</div>
            </div>
            <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>
    </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="pool-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="pool-prefer-source" value="leipzig"> Leipzig first
                </label>
            </div>
            <button id="pool-fetch-all-btn" class="btn btn-warning">
                Fetch All Missing Examples
            </button>
        </div>

        <div id="pool-fetch-progress" style="display: none; margin-top: 1rem;">
            <div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem;">
                <span id="pool-progress-text">Processing...</span>
                <span id="pool-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="pool-progress-bar" style="background-color: #3b82f6; height: 100%; width: 0%; transition: width 0.3s;"></div>
            </div>
        </div>
    </div>

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

            btn.disabled = true;
            btn.textContent = 'Fetching...';
            progress.style.display = 'block';
            progressBar.style.backgroundColor = '#3b82f6';

            const url = '{{ url_for("tatoeba.fetch_pool_missing") }}?source={{ source_language }}&target={{ target_language }}&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) {
                    source.close();
                    btn.disabled = false;
                    btn.textContent = 'Fetch All Missing Examples';
                    progressText.textContent = data.message || 'Complete!';
                    progressBar.style.width = '100%';
                    progressBar.style.backgroundColor = '#10b981';

                    setTimeout(() => location.reload(), 2000);
                } else {
                    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 %}

    {% if stats.total > 0 %}
    <form id="pool-form" action="{{ url_for('pool.export_pool') }}" method="POST">
        <input type="hidden" name="source_language" value="{{ source_language }}">
        <input type="hidden" name="target_language" value="{{ target_language }}">
        <div class="pool-actions" style="background: white; padding: 1.5rem; border-radius: 0.5rem; margin-bottom: 1rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <div style="display: flex; gap: 0.5rem;">
                    <button type="button" id="select-all-btn" class="btn btn-sm btn-secondary">
                        Select All
                    </button>
                    <button type="button" id="select-valid-btn" class="btn btn-sm btn-secondary">
                        Select Valid
                    </button>
                    <button type="button" id="select-invalid-btn" class="btn btn-sm btn-secondary">
                        Select Invalid
                    </button>
                    <button type="button" id="deselect-all-btn" class="btn btn-sm btn-secondary">
                        Deselect All
                    </button>
                </div>
                <div style="display: flex; gap: 0.5rem; align-items: center;">
                    <span id="selection-count" style="color: #6b7280; font-size: 0.875rem;">0 selected</span>
                    <button type="submit" class="btn btn-primary">
                        Export Selected
                    </button>
                </div>
            </div>
            <p style="color: #6b7280; font-size: 0.875rem; margin-top: 0.5rem; margin-bottom: 0;">
                If no entries are selected, all valid entries will be exported.
            </p>
        </div>

        <div class="table-width-toggle">
            <button type="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 style="width: 50px;">
                            <input type="checkbox" id="header-checkbox" style="cursor: pointer;">
                        </th>
                        <th>Status</th>
                        <th>Word</th>
                        <th>Translation</th>
                        <th>Example</th>
                        <th>Source</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="pool-tbody">
                    {% for entry in entries %}
                    {% include 'components/pool_entry_row.html' %}
                    {% endfor %}

                    {% if has_more %}
                    <tr id="pool-load-more-{{ page + 1 }}"
                        hx-get="{{ url_for('pool.get_entries', page=page+1, source=source_language, target=target_language) }}"
                        hx-trigger="revealed"
                        hx-target="this"
                        hx-swap="outerHTML">
                        <td colspan="7" class="loading-row">Loading more...</td>
                    </tr>
                    {% endif %}
                </tbody>
            </table>
        </div>
    </form>
    {% else %}
    <div class="empty-state">
        <p>No entries in word pool yet. Upload some vocabulary files to get started!</p>
        <a href="{{ url_for('upload.upload_form') }}" class="btn btn-primary" style="margin-top: 1rem;">
            Upload Vocabulary File
        </a>
    </div>
    {% endif %}

    <div class="preview-actions" style="margin-top: 2rem;">
        <a href="{{ url_for('main.index') }}" class="btn btn-secondary">
            Back to Home
        </a>
    </div>
</div>

<script>
    // Selection management
    const form = document.getElementById('pool-form');
    const selectionCount = document.getElementById('selection-count');
    const headerCheckbox = document.getElementById('header-checkbox');

    function updateSelectionCount() {
        const checked = document.querySelectorAll('input[name="entry_ids"]:checked').length;
        selectionCount.textContent = checked + ' selected';
    }

    function selectByStatus(status) {
        document.querySelectorAll('input[name="entry_ids"]').forEach(cb => {
            if (status === 'all') {
                cb.checked = true;
            } else if (status === 'valid') {
                cb.checked = cb.dataset.status === 'valid';
            } else if (status === 'invalid') {
                cb.checked = cb.dataset.status !== 'valid';
            } else if (status === 'none') {
                cb.checked = false;
            }
        });
        updateSelectionCount();
    }

    // Button event listeners
    document.getElementById('select-all-btn').addEventListener('click', () => selectByStatus('all'));
    document.getElementById('select-valid-btn').addEventListener('click', () => selectByStatus('valid'));
    document.getElementById('select-invalid-btn').addEventListener('click', () => selectByStatus('invalid'));
    document.getElementById('deselect-all-btn').addEventListener('click', () => selectByStatus('none'));

    // Header checkbox
    if (headerCheckbox) {
        headerCheckbox.addEventListener('change', function() {
            selectByStatus(this.checked ? 'all' : 'none');
        });
    }

    // Individual checkbox change
    document.addEventListener('change', function(e) {
        if (e.target.name === 'entry_ids') {
            updateSelectionCount();
        }
    });

    // Initialize count
    updateSelectionCount();

    // 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 (!btn) return;
        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);
    }

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