{% extends "base.html" %}

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

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <h1>Template Management</h1>
            <p>Manage video overlay templates and create custom designs.</p>
            
            <!-- Template Upload -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>Upload Template</h5>
                </div>
                <div class="card-body">
                    <form id="upload-template-form" enctype="multipart/form-data">
                        <div class="row">
                            <div class="col-md-8">
                                <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. Uploaded templates with the same name will override built-in templates.</div>
                            </div>
                            <div class="col-md-4">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="fas fa-upload"></i> Upload Template
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Template List -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>Available Templates</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Source</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="templates-table-body">
                                <!-- Template rows will be populated by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- Template Preview -->
            <div class="card">
                <div class="card-header">
                    <h5>Template Preview</h5>
                </div>
                <div class="card-body">
                    <div id="template-preview" class="template-preview-container">
                        <p>Select a template to preview</p>
                    </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;

    // Load templates on page load
    function loadTemplates() {
        fetch('/api/templates')
            .then(response => response.json())
            .then(data => {
                const tbody = document.getElementById('templates-table-body');
                tbody.innerHTML = '';
                
                data.templates.forEach(template => {
                    const row = document.createElement('tr');
                    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" data-name="${template.name}" title="Delete template">
                            <i class="fas fa-trash"></i>
                        </button>` : '';
                    
                    row.innerHTML = `
                        <td>
                            <strong>${template.name}</strong>
                            ${template.source === 'uploaded' ? '<span class="badge bg-primary ms-2">Override</span>' : ''}
                        </td>
                        <td>${sourceIcon} ${template.source === 'uploaded' ? 'Uploaded' : 'Built-in'}</td>
                        <td>
                            <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 ms-1" data-name="${template.name}" title="View template code">
                                <i class="fas fa-code"></i>
                            </button>
                            ${deleteButton}
                        </td>
                    `;
                    tbody.appendChild(row);
                });
                
                // Add event listeners to action buttons
                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);
                    });
                });
            })
            .catch(error => {
                console.error('Error loading templates:', error);
                showAlert('Error loading templates: ' + error.message, 'danger');
            });
    }
    
    // Preview template in popup window
    function previewTemplate(templateName) {
        // Open template in a new popup window
        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 {
            // Set popup title after it loads
            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');
                loadTemplates(); // Reload the template list
            } 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();
                loadTemplates(); // Reload the template list
            } 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;
        
        // Load template content
        fetch(`/api/templates/${templateName}`)
            .then(response => response.text())
            .then(html => {
                const codeElement = document.querySelector('#template-code-content code');
                codeElement.textContent = html;
                
                // Store the code for copying
                window.currentTemplateCode = html;
                
                // Show the modal
                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');
                
                // Briefly change button text to show feedback
                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');
            });
        }
    }
    
    // Utility function to escape HTML for preview
    function escapeHtml(unsafe) {
        return unsafe
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
    
    // 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;
        
        // Auto-dismiss after 5 seconds
        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() {
        loadTemplates();
        
        // 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);
    });
</script>
{% endblock %}