<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload ZIP - Fixture Manager</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .header {
            background-color: #007bff;
            color: white;
            padding: 1rem 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .logo {
            font-size: 1.5rem;
            font-weight: bold;
        }
        .nav {
            display: flex;
            gap: 1rem;
        }
        .nav a {
            color: white;
            text-decoration: none;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            transition: background-color 0.3s;
        }
        .nav a:hover {
            background-color: rgba(255,255,255,0.1);
        }
        .container {
            max-width: 800px;
            margin: 2rem auto;
            padding: 0 2rem;
        }
        .upload-section {
            background: white;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 1.5rem;
        }
        label {
            display: block;
            margin-bottom: 0.5rem;
            color: #333;
            font-weight: bold;
        }
        input[type="file"], textarea {
            width: 100%;
            padding: 12px;
            border: 2px dashed #ddd;
            border-radius: 4px;
            background-color: #fafafa;
            cursor: pointer;
            box-sizing: border-box;
        }
        textarea {
            border: 1px solid #ddd;
            cursor: text;
            resize: vertical;
        }
        input[type="file"]:hover {
            border-color: #007bff;
        }
        .btn {
            padding: 12px 24px;
            background-color: #007bff;
            color: white;
            text-decoration: none;
            border: none;
            border-radius: 4px;
            display: inline-block;
            margin: 1rem 0;
            font-size: 1rem;
            font-weight: bold;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .btn:hover {
            background-color: #0056b3;
        }
        .btn-secondary {
            background-color: #6c757d;
            margin-left: 1rem;
        }
        .btn-secondary:hover {
            background-color: #545b62;
        }
        .alert {
            padding: 12px;
            margin-bottom: 1rem;
            border-radius: 4px;
        }
        .alert-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .match-info {
            background-color: #e7f3ff;
            border: 1px solid #b3d9ff;
            padding: 1rem;
            border-radius: 4px;
            margin-bottom: 1.5rem;
        }
        .match-info h3 {
            margin-top: 0;
            color: #0066cc;
        }
    </style>
    <script>
        const CHUNK_SIZE = 1024 * 1024; // 1MB chunks

        function uploadFileInChunks(file, matchId) {
            const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
            const uploadId = Date.now() + '_' + Math.random().toString(36).substr(2, 9);

            let currentChunk = 0;
            const progressBar = document.createElement('div');
            progressBar.style.cssText = `
                width: 100%;
                height: 20px;
                background-color: #f0f0f0;
                border-radius: 10px;
                margin: 10px 0;
                overflow: hidden;
            `;
            const progressFill = document.createElement('div');
            progressFill.style.cssText = `
                height: 100%;
                background-color: #007bff;
                width: 0%;
                transition: width 0.3s;
            `;
            progressBar.appendChild(progressFill);

            const form = document.querySelector('form');
            form.style.display = 'none';
            form.parentNode.insertBefore(progressBar, form);

            const statusDiv = document.createElement('div');
            statusDiv.textContent = 'Uploading... 0%';
            progressBar.parentNode.insertBefore(statusDiv, progressBar);

            function uploadChunk() {
                if (currentChunk >= totalChunks) {
                    // All chunks uploaded, finalize
                    finalizeUpload(uploadId, file.name, matchId);
                    return;
                }

                const start = currentChunk * CHUNK_SIZE;
                const end = Math.min(start + CHUNK_SIZE, file.size);
                const chunk = file.slice(start, end);

                const formData = new FormData();
                formData.append('chunk', chunk);
                formData.append('chunkIndex', currentChunk);
                formData.append('totalChunks', totalChunks);
                formData.append('uploadId', uploadId);
                formData.append('fileName', file.name);
                formData.append('matchId', matchId || '');

                fetch('/upload/chunk', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        currentChunk++;
                        const progress = (currentChunk / totalChunks) * 100;
                        progressFill.style.width = progress + '%';
                        statusDiv.textContent = `Uploading... ${Math.round(progress)}%`;
                        uploadChunk();
                    } else {
                        throw new Error(data.error || 'Upload failed');
                    }
                })
                .catch(error => {
                    statusDiv.textContent = 'Upload failed: ' + error.message;
                    statusDiv.style.color = 'red';
                });
            }

            uploadChunk();
        }

        function finalizeUpload(uploadId, fileName, matchId) {
            fetch('/upload/finalize', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    uploadId: uploadId,
                    fileName: fileName,
                    matchId: matchId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    window.location.href = data.redirect || '/';
                } else {
                    document.querySelector('div').textContent = 'Finalization failed: ' + (data.error || 'Unknown error');
                    document.querySelector('div').style.color = 'red';
                }
            })
            .catch(error => {
                document.querySelector('div').textContent = 'Finalization failed: ' + error.message;
                document.querySelector('div').style.color = 'red';
            });
        }

        document.addEventListener('DOMContentLoaded', function() {
            const form = document.querySelector('form');
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                const fileInput = document.querySelector('input[type="file"]');
                const file = fileInput.files[0];
                if (!file) {
                    alert('Please select a file');
                    return;
                }

                const pathParts = window.location.pathname.split('/');
                const matchId = pathParts[pathParts.length - 1] || '';

                uploadFileInChunks(file, matchId);
            });
        });
    </script>
</head>
<body>
    <div class="header">
        <div class="logo">🥊 Fixture Manager</div>
        <div class="nav">
            <a href="{{ url_for('main.dashboard') }}">Dashboard</a>
            <a href="{{ url_for('main.fixtures') }}">Fixtures</a>
            <a href="{{ url_for('main.uploads') }}">Uploads</a>
            <a href="{{ url_for('main.statistics') }}">Statistics</a>
            <a href="{{ url_for('main.user_tokens') }}">API Tokens</a>
            {% if current_user.is_admin %}
                <a href="{{ url_for('main.admin_panel') }}">Admin</a>
            {% endif %}
            <a href="{{ url_for('auth.logout') }}">Logout</a>
        </div>
    </div>

    <div class="container">
        <h1>Upload ZIP File</h1>
        
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    <div class="alert alert-{{ 'error' if category == 'error' else 'success' }}">
                        {{ message }}
                    </div>
                {% endfor %}
            {% endif %}
        {% endwith %}

        {% if match %}
        <div class="match-info">
            <h3>📁 Match Information</h3>
            <p><strong>Match #{{ match.match_number }}:</strong> {{ match.fighter1_township }} vs {{ match.fighter2_township }}</p>
            <p><strong>Venue:</strong> {{ match.venue_kampala_township }}</p>
        </div>
        {% endif %}

        <div class="upload-section">
            <form method="POST" enctype="multipart/form-data">
                {{ form.hidden_tag() }}
                
                <div class="form-group">
                    {{ form.zip_file.label }}
                    {{ form.zip_file() }}
                    <div style="font-size: 0.9rem; color: #666; margin-top: 0.5rem;">
                        <small>Supported format: .zip (Max size: 5GB)</small>
                    </div>
                </div>
                
                {% if form.description %}
                <div class="form-group">
                    {{ form.description.label }}
                    {{ form.description(rows="3", placeholder="Optional description for this ZIP upload...") }}
                </div>
                {% endif %}
                
                <div class="form-group">
                    {{ form.submit(class="btn") }}
                    <a href="{{ url_for('main.dashboard') }}" class="btn btn-secondary">Cancel</a>
                </div>
            </form>
        </div>
    </div>
</body>
</html>