<script>
document.addEventListener('DOMContentLoaded', function() {
    // Form toggle elements
    const formCard = document.getElementById('formCard');
    const showFormBtn = document.getElementById('showFormBtn');
    const closeFormBtn = document.getElementById('closeFormBtn');
    const emptyStateBtn = document.getElementById('emptyStateBtn');
    
    // Delete modal elements
    const deleteModal = document.getElementById('deleteModal');
    const deleteModalBackdrop = document.getElementById('deleteModalBackdrop');
    const closeDeleteModal = document.getElementById('closeDeleteModal');
    const cancelDeleteBtn = document.getElementById('cancelDeleteBtn');
    const deleteForm = document.getElementById('deleteForm');
    const deleteId = document.getElementById('deleteId');
    const deleteConfirmText = document.getElementById('deleteConfirmText');
    
    // Show form
    if (showFormBtn) {
        showFormBtn.addEventListener('click', function() {
            formCard.style.display = 'block';
            document.getElementById('name').focus();
        });
    }
    
    // Hide form
    if (closeFormBtn) {
        closeFormBtn.addEventListener('click', function() {
            formCard.style.display = 'none';
        });
    }
    
    // Empty state button
    if (emptyStateBtn) {
        emptyStateBtn.addEventListener('click', function() {
            formCard.style.display = 'block';
            document.getElementById('name').focus();
        });
    }
    
    // Close delete modal
    function hideDeleteModal() {
        if (deleteModal) deleteModal.style.display = 'none';
        if (deleteModalBackdrop) deleteModalBackdrop.style.display = 'none';
    }
    
    // Delete modal event listeners
    if (closeDeleteModal) {
        closeDeleteModal.addEventListener('click', hideDeleteModal);
    }
    
    if (cancelDeleteBtn) {
        cancelDeleteBtn.addEventListener('click', hideDeleteModal);
    }
    
    if (deleteModalBackdrop) {
        deleteModalBackdrop.addEventListener('click', hideDeleteModal);
    }
    
    // Add direct event listeners to all delete buttons
    document.querySelectorAll('.films-btn-delete').forEach(function(button) {
        button.addEventListener('click', function(e) {
            e.preventDefault(); // Prevent default onclick behavior
            const filmId = this.getAttribute('data-film-id');
            const filmName = this.getAttribute('data-film-name');
        
            if (filmId && filmName) {
                // Show the modal and backdrop
                if (deleteModal) deleteModal.style.display = 'block';
                if (deleteModalBackdrop) deleteModalBackdrop.style.display = 'block';
            
                // Set the delete ID and confirmation text
                if (deleteId) deleteId.value = filmId;
                if (deleteConfirmText) deleteConfirmText.textContent = `Are you sure you want to delete "${filmName}"?`;
            } else {
                console.error("Missing film ID or name attributes");
            }
        });
    });
    
    // KDM date validation
    const kdmStartInput = document.getElementById('kdmStart');
    const kdmEndInput = document.getElementById('kdmEnd');
    
    if (kdmStartInput && kdmEndInput) {
        kdmStartInput.addEventListener('change', function() {
            if (kdmEndInput.value && kdmStartInput.value > kdmEndInput.value) {
                alert('KDM start date cannot be after end date');
                kdmStartInput.value = '';
            }
        });
        
        kdmEndInput.addEventListener('change', function() {
            if (kdmStartInput.value && kdmStartInput.value > kdmEndInput.value) {
                alert('KDM end date cannot be before start date');
                kdmEndInput.value = '';
            }
        });
    }

    // File input enhancement for poster upload
    const imageInput = document.getElementById('image');
    if (imageInput) {
        const imagePreviewContainer = document.getElementById('imagePreviewContainer');
        const imagePreview = document.getElementById('imagePreview');
        const fileNameDisplay = imageInput.closest('.films-file-input-wrapper').querySelector('.films-file-name');
        
        imageInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                // Update filename display
                const fileName = this.files[0].name;
                fileNameDisplay.textContent = fileName;
                this.closest('.films-file-input-wrapper').classList.add('has-file');
                
                // Show image preview
                const reader = new FileReader();
                reader.onload = function(e) {
                    imagePreview.src = e.target.result;
                    imagePreviewContainer.style.display = 'block';
                };
                reader.readAsDataURL(this.files[0]);
            } else {
                fileNameDisplay.textContent = 'No file selected';
                this.closest('.films-file-input-wrapper').classList.remove('has-file');
                imagePreviewContainer.style.display = 'none';
            }
        });
    }
    
    // File input enhancement for KDM upload
    const kdmFileInput = document.getElementById('kdm_file');
    if (kdmFileInput) {
        const kdmFileNameDisplay = kdmFileInput.closest('.films-file-input-wrapper').querySelector('.films-file-name');
        
        kdmFileInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                // Update filename display
                const fileName = this.files[0].name;
                kdmFileNameDisplay.textContent = fileName;
                this.closest('.films-file-input-wrapper').classList.add('has-file');
            } else {
                kdmFileNameDisplay.textContent = 'No file selected';
                this.closest('.films-file-input-wrapper').classList.remove('has-file');
            }
        });
    }
    
    // Check for error messages and scroll to them
    const errorAlert = document.querySelector('.films-alert-error');
    if (errorAlert) {
        errorAlert.scrollIntoView({ behavior: 'smooth', block: 'center' });
        
        // Highlight the error message with a subtle animation
        setTimeout(function() {
            errorAlert.classList.add('films-alert-highlight');
            setTimeout(function() {
                errorAlert.classList.remove('films-alert-highlight');
            }, 500);
        }, 300);
    }
});
</script>

<style>
/* Animation for error highlighting */
@keyframes errorHighlight {
    0% { transform: translateX(0); }
    25% { transform: translateX(-5px); }
    50% { transform: translateX(5px); }
    75% { transform: translateX(-5px); }
    100% { transform: translateX(0); }
}

.films-alert-highlight {
    animation: errorHighlight 0.5s ease;
}

/* Improve error message visibility */
.films-alert-error {
    border-left: 4px solid #e50914;
    background-color: rgba(229, 9, 20, 0.1);
}

/* Ensure modal displays properly */
.films-modal-backdrop {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1000;
    display: none;
}

.films-modal {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: var(--surface);
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
    z-index: 1001;
    width: 90%;
    max-width: 500px;
    display: none;
}
</style>