{% extends "base.html" %}

{% block title %}{{ page_title }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12 mb-3">
            <h1>Template Management</h1>
            <p>Manage video overlay templates and assign them to specific outcomes.</p>
        </div>
    </div>
    
    <div class="row">
        <!-- Left Column: Available Templates (max 1/3 width) -->
        <div class="col-lg-4 col-xl-3 mb-4">
            <!-- Template Upload -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5><i class="fas fa-upload me-2"></i>Upload Template</h5>
                </div>
                <div class="card-body">
                    <form id="upload-template-form" enctype="multipart/form-data">
                        <div class="mb-3">
                            <input type="file" class="form-control" id="template-file" name="template" accept=".html" required>
                            <div class="form-text">Select an HTML template file to upload.</div>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-upload"></i> Upload Template
                        </button>
                    </form>
                </div>
            </div>

            <!-- Available Templates List -->
            <div class="card">
                <div class="card-header">
                    <h5><i class="fas fa-layer-group me-2"></i>Available Templates</h5>
                </div>
                <div class="card-body p-0">
                    <div class="list-group list-group-flush" id="templates-list">
                        <!-- Template items will be populated by JavaScript -->
                    </div>
                </div>
            </div>
        </div>

        <!-- Right Column: Intro Drop Area and Outcome Template Assignments -->
        <div class="col-lg-8 col-xl-9">
            <!-- Intro Templates Drop Area -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5><i class="fas fa-video me-2"></i>Intro Templates</h5>
                    <small class="text-muted">Drag templates here to create intro sequences with custom timing</small>
                </div>
                <div class="card-body">
                    <div class="intro-drop-zone" id="introDropZone">
                        <div class="drop-zone-placeholder">
                            <i class="fas fa-plus-circle fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">Drag Templates Here</h5>
                            <p class="text-muted mb-0">Drop templates from the list to create intro sequences</p>
                        </div>
                        <div class="intro-templates-list" id="introTemplatesList">
                            <!-- Dropped templates will appear here -->
                        </div>
                    </div>
                    
                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label class="form-label">Default Show Time</label>
                            <input type="text" class="form-control" id="defaultShowTime"
                                   placeholder="00:15" pattern="[0-9]{1,2}:[0-5][0-9]">
                            <div class="form-text">Default display duration (MM:SS)</div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Rotating Interval</label>
                            <input type="text" class="form-control" id="rotatingTime"
                                   placeholder="00:15" pattern="[0-9]{1,2}:[0-5][0-9]">
                            <div class="form-text">Time between template rotations (MM:SS)</div>
                        </div>
                    </div>
                    
                    <div class="mt-3 d-flex justify-content-end">
                        <button type="button" class="btn btn-success me-2" id="save-intro-templates">
                            <i class="fas fa-save me-1"></i>Save Intro Configuration
                        </button>
                        <button type="button" class="btn btn-outline-secondary" id="clear-intro-templates">
                            <i class="fas fa-trash me-1"></i>Clear All
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- Outcome Template Assignments -->
            <div class="card">
                <div class="card-header">
                    <h5><i class="fas fa-cogs me-2"></i>Outcome Template Assignments</h5>
                    <small class="text-muted">Assign templates to specific match outcomes for automatic display</small>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-12">
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle me-2"></i>
                                <strong>How it works:</strong> When a match result is determined, the system will automatically display the assigned template for that outcome. Select "None" to disable automatic display for an outcome.
                            </div>
                        </div>
                    </div>
                    
                    <div class="row" id="outcome-assignments">
                        <!-- Outcome assignment cards will be populated by JavaScript -->
                    </div>
                    
                    <div class="mt-4 d-flex justify-content-end">
                        <button type="button" class="btn btn-success me-2" id="save-assignments">
                            <i class="fas fa-save me-1"></i>Save Assignments
                        </button>
                        <button type="button" class="btn btn-outline-secondary" id="reset-assignments">
                            <i class="fas fa-undo me-1"></i>Reset to Defaults
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteTemplateModal" tabindex="-1" aria-labelledby="deleteTemplateModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteTemplateModalLabel">Delete Template</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete the template "<span id="delete-template-name"></span>"?</p>
                <p class="text-muted">This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirm-delete-btn">Delete</button>
            </div>
        </div>
    </div>
</div>

<!-- View Template Code Modal -->
<div class="modal fade" id="viewTemplateModal" tabindex="-1" aria-labelledby="viewTemplateModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewTemplateModalLabel">Template Code</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="mb-0">Template: <span id="view-template-name"></span></h6>
                    <button type="button" class="btn btn-sm btn-outline-primary" id="copy-template-code">
                        <i class="fas fa-copy me-1"></i>Copy Code
                    </button>
                </div>
                <div class="border rounded p-3" style="background-color: #f8f9fa;">
                    <pre id="template-code-content" class="mb-0" style="max-height: 500px; overflow-y: auto; font-size: 14px; line-height: 1.4;"><code></code></pre>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
    let templateToDelete = null;
    let availableTemplates = [];
    let outcomeAssignments = {};
    let introTemplates = [];
    let defaultShowTime = '00:15';
    let rotatingTime = '00:15';
    
    // Define all possible outcomes
    const allOutcomes = [
        { key: 'WIN1', label: 'Win 1', description: 'Fighter 1 wins', category: 'winner' },
        { key: 'WIN2', label: 'Win 2', description: 'Fighter 2 wins', category: 'winner' },
        { key: 'X', label: 'Draw', description: 'Match ends in draw', category: 'draw' },
        { key: 'DKO', label: 'Double KO', description: 'Double knockout', category: 'draw' },
        { key: 'KO1', label: 'KO 1', description: 'Fighter 1 wins by knockout', category: 'method' },
        { key: 'KO2', label: 'KO 2', description: 'Fighter 2 wins by knockout', category: 'method' },
        { key: 'PTS1', label: 'Points 1', description: 'Fighter 1 wins by points', category: 'method' },
        { key: 'PTS2', label: 'Points 2', description: 'Fighter 2 wins by points', category: 'method' },
        { key: 'RET1', label: 'Retirement 1', description: 'Fighter 2 retires', category: 'method' },
        { key: 'RET2', label: 'Retirement 2', description: 'Fighter 1 retires', category: 'method' },
        { key: 'UNDER', label: 'Under', description: 'Total rounds under prediction', category: 'totals' },
        { key: 'OVER', label: 'Over', description: 'Total rounds over prediction', category: 'totals' }
    ];

    // Load templates and outcome assignments on page load
    function loadTemplatesAndAssignments() {
        Promise.all([
            fetch('/api/templates').then(r => r.json()),
            loadOutcomeAssignments(),
            loadIntroTemplates()
        ]).then(([templatesData]) => {
            availableTemplates = templatesData.templates || [];
            renderTemplatesList();
            renderOutcomeAssignments();
            renderIntroTemplates();
        }).catch(error => {
            console.error('Error loading templates and assignments:', error);
            showAlert('Error loading templates: ' + error.message, 'danger');
        });
    }
    
    // Load outcome assignments from server
    function loadOutcomeAssignments() {
        return fetch('/api/outcome-assignments')
            .then(response => response.json())
            .then(data => {
                outcomeAssignments = data.assignments || {};
            })
            .catch(error => {
                console.error('Error loading outcome assignments:', error);
                // Initialize with empty assignments if loading fails
                outcomeAssignments = {};
            });
    }
    
    // Render templates list in left column
    function renderTemplatesList() {
        const templatesList = document.getElementById('templates-list');
        templatesList.innerHTML = '';
        
        if (availableTemplates.length === 0) {
            templatesList.innerHTML = '<div class="list-group-item text-muted text-center">No templates available</div>';
            return;
        }
        
        availableTemplates.forEach(template => {
            const sourceIcon = template.source === 'uploaded' ?
                '<i class="fas fa-cloud text-primary" title="Uploaded template"></i>' :
                '<i class="fas fa-box text-secondary" title="Built-in template"></i>';
            
            const deleteButton = template.can_delete ?
                `<button class="btn btn-sm btn-danger delete-template ms-1" data-name="${template.name}" title="Delete template">
                    <i class="fas fa-trash"></i>
                </button>` : '';
            
            const item = document.createElement('div');
            item.className = 'list-group-item';
            item.draggable = true;
            item.setAttribute('data-template-name', template.name);
            item.innerHTML = `
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="fw-bold">${template.name}</div>
                        <small class="text-muted">${sourceIcon} ${template.source === 'uploaded' ? 'Uploaded' : 'Built-in'}</small>
                        ${template.source === 'uploaded' ? '<span class="badge bg-primary ms-1">Override</span>' : ''}
                    </div>
                    <div class="btn-group">
                        <button class="btn btn-sm btn-info preview-template" data-name="${template.name}" title="Preview template">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-sm btn-secondary view-template" data-name="${template.name}" title="View template code">
                            <i class="fas fa-code"></i>
                        </button>
                        ${deleteButton}
                    </div>
                </div>
            `;
            templatesList.appendChild(item);
        });
        
        // Add event listeners
        attachTemplateEventListeners();
        attachDragAndDropListeners();
    }
    
    // Render outcome assignments in right column
    function renderOutcomeAssignments() {
        const assignmentsContainer = document.getElementById('outcome-assignments');
        assignmentsContainer.innerHTML = '';
        
        // Group outcomes by category
        const categorizedOutcomes = {
            'winner': allOutcomes.filter(o => o.category === 'winner'),
            'draw': allOutcomes.filter(o => o.category === 'draw'),
            'method': allOutcomes.filter(o => o.category === 'method'),
            'totals': allOutcomes.filter(o => o.category === 'totals')
        };
        
        const categoryLabels = {
            'winner': 'Match Winners',
            'draw': 'Draw Outcomes',
            'method': 'Win Methods',
            'totals': 'Round Totals'
        };
        
        Object.entries(categorizedOutcomes).forEach(([category, outcomes]) => {
            if (outcomes.length === 0) return;
            
            const categoryCol = document.createElement('div');
            categoryCol.className = 'col-lg-6 col-xl-4 mb-4';
            
            const categoryCard = document.createElement('div');
            categoryCard.className = 'card h-100';
            categoryCard.innerHTML = `
                <div class="card-header">
                    <h6 class="mb-0 text-primary">${categoryLabels[category]}</h6>
                </div>
                <div class="card-body">
                    ${outcomes.map(outcome => `
                        <div class="mb-3">
                            <label class="form-label fw-bold">${outcome.label}</label>
                            <small class="text-muted d-block mb-1">${outcome.description}</small>
                            <select class="form-select outcome-template-select" data-outcome="${outcome.key}">
                                <option value="">None</option>
                                ${availableTemplates.map(template => 
                                    `<option value="${template.name}" ${outcomeAssignments[outcome.key] === template.name ? 'selected' : ''}>${template.name}</option>`
                                ).join('')}
                            </select>
                        </div>
                    `).join('')}
                </div>
            `;
            
            categoryCol.appendChild(categoryCard);
            assignmentsContainer.appendChild(categoryCol);
        });
    }
    
    // Attach event listeners to template action buttons
    function attachTemplateEventListeners() {
        document.querySelectorAll('.preview-template').forEach(btn => {
            btn.addEventListener('click', function() {
                const templateName = this.getAttribute('data-name');
                previewTemplate(templateName);
            });
        });
        
        document.querySelectorAll('.view-template').forEach(btn => {
            btn.addEventListener('click', function() {
                const templateName = this.getAttribute('data-name');
                viewTemplateCode(templateName);
            });
        });
        
        document.querySelectorAll('.delete-template').forEach(btn => {
            btn.addEventListener('click', function() {
                const templateName = this.getAttribute('data-name');
                showDeleteConfirmation(templateName);
            });
        });
    }
    
    // Preview template in popup window
    function previewTemplate(templateName) {
        const previewUrl = `/api/templates/${templateName}`;
        const popup = window.open(previewUrl, `template-preview-${templateName}`,
            'width=800,height=600,scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no');
        
        if (!popup) {
            showAlert('Popup blocked. Please allow popups for template preview.', 'warning');
        } else {
            popup.onload = function() {
                try {
                    popup.document.title = `Template Preview: ${templateName}`;
                } catch (e) {
                    // Ignore cross-origin errors
                }
            };
        }
    }
    
    // Show delete confirmation modal
    function showDeleteConfirmation(templateName) {
        templateToDelete = templateName;
        document.getElementById('delete-template-name').textContent = templateName;
        const modal = new bootstrap.Modal(document.getElementById('deleteTemplateModal'));
        modal.show();
    }
    
    // Delete template
    function deleteTemplate(templateName) {
        fetch(`/api/templates/${templateName}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert(`Template "${templateName}" deleted successfully`, 'success');
                loadTemplatesAndAssignments(); // Reload everything
            } else {
                showAlert(`Error deleting template: ${data.error}`, 'danger');
            }
        })
        .catch(error => {
            console.error('Error deleting template:', error);
            showAlert(`Error deleting template: ${error.message}`, 'danger');
        });
    }
    
    // Upload template
    function uploadTemplate(formData) {
        fetch('/api/templates/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert(`Template "${data.filename}" uploaded successfully`, 'success');
                document.getElementById('upload-template-form').reset();
                loadTemplatesAndAssignments(); // Reload everything
            } else {
                showAlert(`Error uploading template: ${data.error}`, 'danger');
            }
        })
        .catch(error => {
            console.error('Error uploading template:', error);
            showAlert(`Error uploading template: ${error.message}`, 'danger');
        });
    }
    
    // View template code in modal
    function viewTemplateCode(templateName) {
        document.getElementById('view-template-name').textContent = templateName;
        
        fetch(`/api/templates/${templateName}`)
            .then(response => response.text())
            .then(html => {
                const codeElement = document.querySelector('#template-code-content code');
                codeElement.textContent = html;
                
                window.currentTemplateCode = html;
                
                const modal = new bootstrap.Modal(document.getElementById('viewTemplateModal'));
                modal.show();
            })
            .catch(error => {
                console.error('Error loading template code:', error);
                showAlert(`Error loading template code: ${error.message}`, 'danger');
            });
    }
    
    // Copy template code to clipboard
    function copyTemplateCode() {
        if (window.currentTemplateCode) {
            navigator.clipboard.writeText(window.currentTemplateCode).then(() => {
                showAlert('Template code copied to clipboard!', 'success');
                
                const copyBtn = document.getElementById('copy-template-code');
                const originalText = copyBtn.innerHTML;
                copyBtn.innerHTML = '<i class="fas fa-check me-1"></i>Copied!';
                copyBtn.classList.remove('btn-outline-primary');
                copyBtn.classList.add('btn-success');
                
                setTimeout(() => {
                    copyBtn.innerHTML = originalText;
                    copyBtn.classList.remove('btn-success');
                    copyBtn.classList.add('btn-outline-primary');
                }, 2000);
            }).catch(err => {
                console.error('Failed to copy template code:', err);
                showAlert('Failed to copy template code to clipboard', 'danger');
            });
        }
    }
    
    // Save outcome assignments
    function saveOutcomeAssignments() {
        const assignments = {};
        document.querySelectorAll('.outcome-template-select').forEach(select => {
            const outcome = select.getAttribute('data-outcome');
            const template = select.value;
            if (template) {
                assignments[outcome] = template;
            }
        });
        
        fetch('/api/outcome-assignments', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ assignments })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('Outcome assignments saved successfully', 'success');
                outcomeAssignments = assignments;
            } else {
                showAlert(`Error saving assignments: ${data.error}`, 'danger');
            }
        })
        .catch(error => {
            console.error('Error saving outcome assignments:', error);
            showAlert(`Error saving assignments: ${error.message}`, 'danger');
        });
    }
    
    // Reset assignments to defaults
    function resetOutcomeAssignments() {
        if (confirm('Are you sure you want to reset all assignments to defaults? This will clear all current assignments.')) {
            document.querySelectorAll('.outcome-template-select').forEach(select => {
                select.value = '';
            });
            outcomeAssignments = {};
            showAlert('Assignments reset to defaults', 'info');
        }
    }
    
    // Load intro templates configuration
    function loadIntroTemplates() {
        return fetch('/api/intro-templates')
            .then(response => response.json())
            .then(data => {
                introTemplates = data.templates || [];
                defaultShowTime = data.default_show_time || '00:15';
                rotatingTime = data.rotating_time || '00:15';

                // Set default intro templates if none exist
                if (introTemplates.length === 0) {
                    // Check if fixtures and match templates are available
                    const fixturesTemplate = availableTemplates.find(t => t.name === 'fixtures');
                    const matchTemplate = availableTemplates.find(t => t.name === 'match');

                    if (fixturesTemplate) {
                        introTemplates.push({
                            name: 'fixtures',
                            show_time: '00:15'
                        });
                    }

                    if (matchTemplate) {
                        introTemplates.push({
                            name: 'match',
                            show_time: '00:15'
                        });
                    }
                }

                document.getElementById('defaultShowTime').value = defaultShowTime;
                document.getElementById('rotatingTime').value = rotatingTime;
            })
            .catch(error => {
                console.error('Error loading intro templates:', error);
                introTemplates = [];

                // Set default intro templates on error too
                const fixturesTemplate = availableTemplates.find(t => t.name === 'fixtures');
                const matchTemplate = availableTemplates.find(t => t.name === 'match');

                if (fixturesTemplate) {
                    introTemplates.push({
                        name: 'fixtures',
                        show_time: '00:15'
                    });
                }

                if (matchTemplate) {
                    introTemplates.push({
                        name: 'match',
                        show_time: '00:15'
                    });
                }
            });
    }
    
    // Render intro templates
    function renderIntroTemplates() {
        const introTemplatesList = document.getElementById('introTemplatesList');
        
        if (introTemplates.length === 0) {
            introTemplatesList.className = 'intro-templates-list';
            introTemplatesList.innerHTML = '';
            return;
        }
        
        introTemplatesList.className = 'intro-templates-list has-templates';
        introTemplatesList.innerHTML = '';
        
        introTemplates.forEach((template, index) => {
            const item = document.createElement('div');
            item.className = 'intro-template-item';
            item.innerHTML = `
                <div class="intro-template-info">
                    <div class="fw-bold">${template.name}</div>
                    <small class="text-muted">Position: ${index + 1}</small>
                </div>
                <div class="intro-template-controls">
                    <label class="form-label mb-0 me-2">Show Time:</label>
                    <input type="text" class="form-control intro-template-time"
                           value="${template.show_time}" data-index="${index}"
                           pattern="[0-9]{1,2}:[0-5][0-9]" placeholder="MM:SS">
                    <button class="btn btn-sm btn-outline-primary move-up" data-index="${index}"
                            ${index === 0 ? 'disabled' : ''}>
                        <i class="fas fa-arrow-up"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-primary move-down" data-index="${index}"
                            ${index === introTemplates.length - 1 ? 'disabled' : ''}>
                        <i class="fas fa-arrow-down"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-danger remove-template" data-index="${index}">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            `;
            introTemplatesList.appendChild(item);
        });
        
        // Add event listeners for controls
        attachIntroTemplateControls();
    }
    
    // Attach drag and drop listeners
    function attachDragAndDropListeners() {
        const templateItems = document.querySelectorAll('.list-group-item[draggable="true"]');
        const dropZone = document.getElementById('introDropZone');
        
        templateItems.forEach(item => {
            item.addEventListener('dragstart', handleDragStart);
            item.addEventListener('dragend', handleDragEnd);
        });
        
        dropZone.addEventListener('dragover', handleDragOver);
        dropZone.addEventListener('drop', handleDrop);
        dropZone.addEventListener('dragenter', handleDragEnter);
        dropZone.addEventListener('dragleave', handleDragLeave);
    }
    
    // Drag and drop handlers
    function handleDragStart(e) {
        e.dataTransfer.setData('text/plain', e.target.getAttribute('data-template-name'));
        e.target.classList.add('template-dragging');
    }
    
    function handleDragEnd(e) {
        e.target.classList.remove('template-dragging');
    }
    
    function handleDragOver(e) {
        e.preventDefault();
    }
    
    function handleDragEnter(e) {
        e.preventDefault();
        document.getElementById('introDropZone').classList.add('drag-over');
    }
    
    function handleDragLeave(e) {
        if (!e.currentTarget.contains(e.relatedTarget)) {
            document.getElementById('introDropZone').classList.remove('drag-over');
        }
    }
    
    function handleDrop(e) {
        e.preventDefault();
        document.getElementById('introDropZone').classList.remove('drag-over');
        
        const templateName = e.dataTransfer.getData('text/plain');
        const defaultTime = document.getElementById('defaultShowTime').value || '00:30';
        
        // Add template to intro list
        const newTemplate = {
            name: templateName,
            show_time: defaultTime
        };
        
        introTemplates.push(newTemplate);
        renderIntroTemplates();
        showAlert(`Template "${templateName}" added to intro sequence`, 'success');
    }
    
    // Attach intro template controls
    function attachIntroTemplateControls() {
        // Time input changes
        document.querySelectorAll('.intro-template-time').forEach(input => {
            input.addEventListener('change', function() {
                const index = parseInt(this.getAttribute('data-index'));
                introTemplates[index].show_time = this.value;
            });
        });
        
        // Move up/down buttons
        document.querySelectorAll('.move-up').forEach(button => {
            button.addEventListener('click', function() {
                const index = parseInt(this.getAttribute('data-index'));
                if (index > 0) {
                    [introTemplates[index - 1], introTemplates[index]] = [introTemplates[index], introTemplates[index - 1]];
                    renderIntroTemplates();
                }
            });
        });
        
        document.querySelectorAll('.move-down').forEach(button => {
            button.addEventListener('click', function() {
                const index = parseInt(this.getAttribute('data-index'));
                if (index < introTemplates.length - 1) {
                    [introTemplates[index], introTemplates[index + 1]] = [introTemplates[index + 1], introTemplates[index]];
                    renderIntroTemplates();
                }
            });
        });
        
        // Remove template buttons
        document.querySelectorAll('.remove-template').forEach(button => {
            button.addEventListener('click', function() {
                const index = parseInt(this.getAttribute('data-index'));
                const templateName = introTemplates[index].name;
                introTemplates.splice(index, 1);
                renderIntroTemplates();
                showAlert(`Template "${templateName}" removed from intro sequence`, 'info');
            });
        });
    }
    
    // Save intro templates configuration
    function saveIntroTemplates() {
        const defaultTime = document.getElementById('defaultShowTime').value;
        const rotatingInterval = document.getElementById('rotatingTime').value;
        
        // Validate time format
        const timePattern = /^[0-9]{1,2}:[0-5][0-9]$/;
        if (defaultTime && !timePattern.test(defaultTime)) {
            showAlert('Invalid default show time format. Use MM:SS format.', 'danger');
            return;
        }
        
        if (rotatingInterval && !timePattern.test(rotatingInterval)) {
            showAlert('Invalid rotating time format. Use MM:SS format.', 'danger');
            return;
        }
        
        const data = {
            templates: introTemplates,
            default_show_time: defaultTime || '00:15',
            rotating_time: rotatingInterval || '00:15'
        };
        
        fetch('/api/intro-templates', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('Intro templates configuration saved successfully', 'success');
                defaultShowTime = data.default_show_time;
                rotatingTime = data.rotating_time;
            } else {
                showAlert(`Error saving intro templates: ${data.error}`, 'danger');
            }
        })
        .catch(error => {
            console.error('Error saving intro templates:', error);
            showAlert(`Error saving intro templates: ${error.message}`, 'danger');
        });
    }
    
    // Clear all intro templates
    function clearIntroTemplates() {
        if (confirm('Are you sure you want to clear all intro templates? This will remove all templates from the sequence.')) {
            introTemplates = [];
            renderIntroTemplates();
            showAlert('All intro templates cleared', 'info');
        }
    }
    
    // Utility function to show alerts
    function showAlert(message, type) {
        const alertContainer = document.getElementById('alert-container') || createAlertContainer();
        const alertId = 'alert-' + Date.now();
        
        const alertHtml = `
            <div class="alert alert-${type} alert-dismissible fade show" role="alert" id="${alertId}">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        `;
        
        alertContainer.innerHTML = alertHtml;
        
        setTimeout(() => {
            const alert = document.getElementById(alertId);
            if (alert) {
                const bsAlert = bootstrap.Alert.getOrCreateInstance(alert);
                bsAlert.close();
            }
        }, 5000);
    }
    
    // Create alert container if it doesn't exist
    function createAlertContainer() {
        const container = document.createElement('div');
        container.id = 'alert-container';
        container.className = 'position-fixed top-0 end-0 p-3';
        container.style.zIndex = '1050';
        document.body.appendChild(container);
        return container;
    }
    
    // Event listeners
    document.addEventListener('DOMContentLoaded', function() {
        loadTemplatesAndAssignments();
        
        // Template upload form
        document.getElementById('upload-template-form').addEventListener('submit', function(e) {
            e.preventDefault();
            const fileInput = document.getElementById('template-file');
            const file = fileInput.files[0];
            
            if (!file) {
                showAlert('Please select a template file', 'warning');
                return;
            }
            
            if (!file.name.endsWith('.html')) {
                showAlert('Please select an HTML file', 'warning');
                return;
            }
            
            const formData = new FormData();
            formData.append('template', file);
            uploadTemplate(formData);
        });
        
        // Delete confirmation
        document.getElementById('confirm-delete-btn').addEventListener('click', function() {
            if (templateToDelete) {
                deleteTemplate(templateToDelete);
                templateToDelete = null;
                const modal = bootstrap.Modal.getInstance(document.getElementById('deleteTemplateModal'));
                modal.hide();
            }
        });
        
        // Copy template code button
        document.getElementById('copy-template-code').addEventListener('click', copyTemplateCode);
        
        // Save assignments button
        document.getElementById('save-assignments').addEventListener('click', saveOutcomeAssignments);
        
        // Reset assignments button
        document.getElementById('reset-assignments').addEventListener('click', resetOutcomeAssignments);
        
        // Intro templates buttons
        document.getElementById('save-intro-templates').addEventListener('click', saveIntroTemplates);
        document.getElementById('clear-intro-templates').addEventListener('click', clearIntroTemplates);
    });
</script>

<!-- Add bottom spacing for better scrolling -->
<div style="height: 100px; margin-bottom: 50px;"></div>

<style>
    .intro-drop-zone {
        min-height: 200px;
        border: 2px dashed #dee2e6;
        border-radius: 8px;
        position: relative;
        padding: 20px;
        transition: all 0.3s ease;
    }
    
    .intro-drop-zone.drag-over {
        border-color: #007bff;
        background-color: rgba(0, 123, 255, 0.05);
    }
    
    .drop-zone-placeholder {
        text-align: center;
        padding: 40px 20px;
    }
    
    .intro-templates-list {
        display: none;
    }
    
    .intro-templates-list.has-templates {
        display: block;
    }
    
    .intro-templates-list.has-templates + .drop-zone-placeholder {
        display: none;
    }
    
    .intro-template-item {
        border: 1px solid #dee2e6;
        border-radius: 6px;
        padding: 15px;
        margin-bottom: 10px;
        background: #f8f9fa;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .intro-template-item:hover {
        background: #e9ecef;
    }
    
    .intro-template-info {
        flex: 1;
    }
    
    .intro-template-controls {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .intro-template-time {
        width: 80px;
    }
    
    .template-dragging {
        opacity: 0.5;
        transform: rotate(5deg);
    }
    
    .templates-list .list-group-item {
        cursor: grab;
        transition: all 0.2s ease;
    }
    
    .templates-list .list-group-item:hover {
        background-color: #f8f9fa;
        transform: translateX(3px);
    }
    
    .templates-list .list-group-item:active {
        cursor: grabbing;
    }
    
</style>

{% endblock %}
