// Text Editor untuk Edit Mode dengan Upload Gambar
class SimpleTextEditor {
    constructor(textarea) {
        this.textarea = textarea;
        this.toolbar = textarea.previousElementSibling;
        this.isEditMode = textarea.closest('.edit-form') !== null;
        this.init();
    }

    init() {
        // Add event listeners to toolbar buttons
        this.toolbar.addEventListener('click', (e) => {
            if (e.target.tagName === 'BUTTON') {
                e.preventDefault();
                const command = e.target.dataset.command;
                if (command === 'uploadImage') {
                    this.openImageUpload();
                } else {
                    this.executeCommand(command);
                }
            }
        });

        // Add keyboard shortcuts
        this.textarea.addEventListener('keydown', (e) => {
            // Ctrl+B for bold
            if (e.ctrlKey && e.key === 'b') {
                e.preventDefault();
                this.executeCommand('bold');
            }
            // Ctrl+I for italic
            if (e.ctrlKey && e.key === 'i') {
                e.preventDefault();
                this.executeCommand('italic');
            }
            // Ctrl+U for underline
            if (e.ctrlKey && e.key === 'u') {
                e.preventDefault();
                this.executeCommand('underline');
            }
        });

        // Add input event for character counting
        this.textarea.addEventListener('input', () => {
            this.updateCharacterCounter();
        });

        // Initialize character counter
        this.updateCharacterCounter();

        // Add image upload button if not exists
        this.addImageUploadButton();
        
        // Auto-resize textarea
        this.autoResize();
    }

    addImageUploadButton() {
        // Cek apakah tombol upload gambar sudah ada
        const existingUploadBtn = this.toolbar.querySelector('[data-command="uploadImage"]');
        if (!existingUploadBtn) {
            const uploadBtn = document.createElement('button');
            uploadBtn.type = 'button';
            uploadBtn.dataset.command = 'uploadImage';
            uploadBtn.title = 'Upload Gambar';
            uploadBtn.innerHTML = '<i class="fas fa-image"></i>';
            uploadBtn.style.marginLeft = '5px';
            this.toolbar.appendChild(uploadBtn);
        }
    }

    openImageUpload() {
        // Create modal for image upload
        const modal = this.createImageUploadModal();
        document.body.appendChild(modal);
        
        // Show modal
        modal.style.display = 'block';
        
        // Handle modal events
        this.setupImageUploadModal(modal);
    }

    createImageUploadModal() {
        const modal = document.createElement('div');
        modal.className = 'image-upload-modal';
        modal.style.cssText = `
            display: none;
            position: fixed;
            z-index: 10000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        `;

        modal.innerHTML = `
            <div style="
                background-color: white;
                margin: 10% auto;
                padding: 20px;
                border-radius: 5px;
                width: 400px;
                max-width: 90%;
            ">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                    <h3 style="margin: 0;">Upload Gambar</h3>
                    <span class="close-modal" style="font-size: 24px; cursor: pointer;">&times;</span>
                </div>
                <div class="upload-area" style="
                    border: 2px dashed #ccc;
                    border-radius: 5px;
                    padding: 20px;
                    text-align: center;
                    margin-bottom: 15px;
                    cursor: pointer;
                ">
                    <i class="fas fa-cloud-upload-alt" style="font-size: 48px; color: #667eea; margin-bottom: 10px;"></i>
                    <p>Klik atau seret gambar ke sini</p>
                    <input type="file" class="file-input" accept="image/*" style="display: none;">
                    <img class="upload-preview" src="" alt="Preview" style="max-width: 100%; max-height: 200px; margin-top: 10px; display: none;">
                </div>
                <div class="upload-buttons" style="display: flex; justify-content: flex-end; gap: 10px;">
                    <button class="btn btn-secondary cancel-upload">Batal</button>
                    <button class="btn btn-primary insert-image">Sisipkan</button>
                </div>
            </div>
        `;

        return modal;
    }

    setupImageUploadModal(modal) {
        const closeModal = modal.querySelector('.close-modal');
        const cancelUpload = modal.querySelector('.cancel-upload');
        const uploadArea = modal.querySelector('.upload-area');
        const fileInput = modal.querySelector('.file-input');
        const uploadPreview = modal.querySelector('.upload-preview');
        const insertImageBtn = modal.querySelector('.insert-image');

        let uploadedImageUrl = null;

        // Close modal functions
        const closeModalFunc = () => {
            modal.remove();
        };

        closeModal.addEventListener('click', closeModalFunc);
        cancelUpload.addEventListener('click', closeModalFunc);

        // Upload area events
        uploadArea.addEventListener('click', () => {
            fileInput.click();
        });

        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.style.borderColor = '#667eea';
            uploadArea.style.backgroundColor = '#f0f0f0';
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.style.borderColor = '#ccc';
            uploadArea.style.backgroundColor = '';
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.style.borderColor = '#ccc';
            uploadArea.style.backgroundColor = '';
            
            if (e.dataTransfer.files.length) {
                this.handleImageFile(e.dataTransfer.files[0], uploadPreview)
                    .then(url => {
                        uploadedImageUrl = url;
                    })
                    .catch(error => {
                        alert(error);
                    });
            }
        });

        // File input change
        fileInput.addEventListener('change', () => {
            if (fileInput.files.length) {
                this.handleImageFile(fileInput.files[0], uploadPreview)
                    .then(url => {
                        uploadedImageUrl = url;
                    })
                    .catch(error => {
                        alert(error);
                    });
            }
        });

        // Insert image
        insertImageBtn.addEventListener('click', () => {
            if (uploadedImageUrl) {
                this.insertImageIntoTextarea(uploadedImageUrl);
                closeModalFunc();
            } else {
                alert('Silakan pilih gambar terlebih dahulu');
            }
        });
    }

    handleImageFile(file, previewElement) {
        return new Promise((resolve, reject) => {
            // Validasi tipe file
            if (!file.type.match('image.*')) {
                reject('Hanya file gambar yang diizinkan');
                return;
            }

            // Validasi ukuran file (maksimal 2MB)
            if (file.size > 2 * 1024 * 1024) {
                reject('Ukuran file maksimal 2MB');
                return;
            }

            // Tampilkan preview
            const reader = new FileReader();
            reader.onload = function(e) {
                previewElement.src = e.target.result;
                previewElement.style.display = 'block';
                resolve(e.target.result);
            };
            reader.onerror = function() {
                reject('Gagal membaca file');
            };
            reader.readAsDataURL(file);
        });
    }

    insertImageIntoTextarea(imageUrl) {
        const cursorPos = this.textarea.selectionStart;
        const textBefore = this.textarea.value.substring(0, cursorPos);
        const textAfter = this.textarea.value.substring(cursorPos);
        
        // Optimasi: gunakan placeholder sementara untuk base64 yang panjang
        const tempId = 'img_' + Date.now();
        const imgTag = `[GAMBAR:${tempId}]`;
        
        // Simpan base64 data secara terpisah untuk dikirim ke server
        if (!window.tempImages) window.tempImages = {};
        window.tempImages[tempId] = imageUrl;
        
        this.textarea.value = textBefore + imgTag + textAfter;
        
        // Trigger input event untuk update counter dan auto-resize
        this.textarea.dispatchEvent(new Event('input'));
        
        // Set cursor position setelah gambar
        const newCursorPos = cursorPos + imgTag.length;
        this.textarea.setSelectionRange(newCursorPos, newCursorPos);
        this.textarea.focus();
    }

    executeCommand(command) {
        this.textarea.focus();
        
        try {
            // For simple formatting commands
            document.execCommand(command, false, null);
            
            // Update the textarea value to reflect changes
            this.updateTextareaValue();
        } catch (error) {
            console.warn(`Command ${command} not supported`);
        }
    }

    updateTextareaValue() {
        // This method ensures the textarea value stays in sync
        // with the formatted content (for basic formatting)
        const selection = window.getSelection();
        if (selection.rangeCount > 0) {
            const range = selection.getRangeAt(0);
            const content = range.startContainer.textContent || range.startContainer.innerText;
            // You can add more sophisticated content synchronization here
        }
    }

    updateCharacterCounter() {
        let counter = this.textarea.parentNode.querySelector('.char-counter');
        if (!counter) {
            counter = document.createElement('div');
            counter.className = 'char-counter';
            counter.style.cssText = 'font-size: 12px; color: #666; text-align: right; margin-top: 5px;';
            this.textarea.parentNode.appendChild(counter);
        }
        
        const count = this.textarea.value.length;
        counter.textContent = `${count} karakter`;
        
        if (count > 5000) {
            counter.style.color = '#dc3545';
        } else if (count > 3000) {
            counter.style.color = '#ffc107';
        } else {
            counter.style.color = '#666';
        }
    }

    autoResize() {
        // Set initial height
        this.textarea.style.height = 'auto';
        this.textarea.style.height = (this.textarea.scrollHeight) + 'px';
        
        // Add input event listener
        this.textarea.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });
    }
}

// Fungsi untuk memproses gambar sebelum submit
function processImagesBeforeSubmit(form) {
    const textareas = form.querySelectorAll('.rich-text');
    textareas.forEach(textarea => {
        let content = textarea.value;
        
        // Ganti placeholder dengan base64 data untuk dikirim ke server
        const regex = /\[GAMBAR:([^\]]+)\]/g;
        let match;
        
        while ((match = regex.exec(content)) !== null) {
            const tempId = match[1];
            if (window.tempImages && window.tempImages[tempId]) {
                content = content.replace(match[0], `<img src="${window.tempImages[tempId]}" alt="Gambar" style="max-width: 100%; height: auto;">`);
            }
        }
        
        textarea.value = content;
    });
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', function() {
    // Initialize all text editors
    const textEditors = document.querySelectorAll('.text-editor .rich-text');
    textEditors.forEach(textarea => {
        new SimpleTextEditor(textarea);
    });

    // Form validation untuk semua form
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            // Proses gambar sebelum submit
            processImagesBeforeSubmit(this);
            
            const nomorRegistrasi = this.querySelector('#nomor_registrasi')?.value.trim();
            const tinjauan1 = this.querySelector('#tinjauan1')?.value.trim();
            const pertanyaan = this.querySelector('#pertanyaan')?.value.trim();

            if (nomorRegistrasi !== undefined || tinjauan1 !== undefined || pertanyaan !== undefined) {
                let isValid = true;
                let errorMessage = '';

                if (nomorRegistrasi !== undefined && !nomorRegistrasi) {
                    isValid = false;
                    errorMessage += '• Nomor Registrasi harus diisi\n';
                }

                if (tinjauan1 !== undefined && !tinjauan1) {
                    isValid = false;
                    errorMessage += '• Kompetensi Utama harus diisi\n';
                }

                if (pertanyaan !== undefined && !pertanyaan) {
                    isValid = false;
                    errorMessage += '• Pertanyaan/Instruksi harus diisi\n';
                }

                if (!isValid) {
                    e.preventDefault();
                    alert('Harap perbaiki kesalahan berikut:\n\n' + errorMessage);
                    return false;
                }
            }

            return true;
        });
    });

    // Auto-save draft functionality
    const mainForm = document.getElementById('soalTeoriForm');
    if (mainForm) {
        let autoSaveTimer;
        const formInputs = mainForm.querySelectorAll('input, textarea, select');
        
        formInputs.forEach(input => {
            input.addEventListener('input', function() {
                clearTimeout(autoSaveTimer);
                autoSaveTimer = setTimeout(saveDraft, 3000);
            });
        });

        function saveDraft() {
            const formData = new FormData(mainForm);
            const draft = {};
            
            formData.forEach((value, key) => {
                draft[key] = value;
            });

            // Simpan temp images juga
            if (window.tempImages) {
                draft.tempImages = window.tempImages;
            }

            localStorage.setItem('soalTeoriDraft', JSON.stringify(draft));
            showNotification('Draft disimpan secara otomatis', 'info');
        }

        function loadDraft() {
            const draft = localStorage.getItem('soalTeoriDraft');
            if (draft) {
                const draftData = JSON.parse(draft);
                Object.keys(draftData).forEach(key => {
                    if (key !== 'tempImages') {
                        const element = document.querySelector(`[name="${key}"]`);
                        if (element) {
                            element.value = draftData[key];
                        }
                    }
                });
                
                // Load temp images
                if (draftData.tempImages) {
                    window.tempImages = draftData.tempImages;
                }
                
                showNotification('Draft sebelumnya dimuat', 'info');
            }
        }

        // Clear draft on successful form submission
        mainForm.addEventListener('submit', function() {
            localStorage.removeItem('soalTeoriDraft');
            window.tempImages = {};
        });

        // Load draft on page load
        loadDraft();

        // Add confirmation for reset button
        const resetButton = mainForm.querySelector('button[type="reset"]');
        if (resetButton) {
            resetButton.addEventListener('click', function(e) {
                if (!confirm('Yakin ingin mengosongkan semua field?')) {
                    e.preventDefault();
                } else {
                    localStorage.removeItem('soalTeoriDraft');
                    window.tempImages = {};
                }
            });
        }
    }

    // Notification function
    function showNotification(message, type = 'info') {
        // Remove existing notification
        const existingNotification = document.querySelector('.auto-save-notification');
        if (existingNotification) {
            existingNotification.remove();
        }

        const notification = document.createElement('div');
        notification.className = `auto-save-notification alert alert-${type}`;
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            min-width: 200px;
            padding: 10px 15px;
            border-radius: 4px;
            background: ${type === 'info' ? '#d1ecf1' : type === 'success' ? '#d4edda' : '#f8d7da'};
            color: ${type === 'info' ? '#0c5460' : type === 'success' ? '#155724' : '#721c24'};
            border: 1px solid ${type === 'info' ? '#bee5eb' : type === 'success' ? '#c3e6cb' : '#f5c6cb'};
        `;
        notification.textContent = message;

        document.body.appendChild(notification);

        // Auto remove after 3 seconds
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }

    // Search functionality enhancement
    const searchInput = document.querySelector('input[name="search"]');
    if (searchInput) {
        let searchTimer;
        searchInput.addEventListener('input', function() {
            clearTimeout(searchTimer);
            searchTimer = setTimeout(() => {
                if (this.value.length >= 3 || this.value.length === 0) {
                    this.form.submit();
                }
            }, 500);
        });
    }

    // Keyboard navigation untuk list page
    const soalItems = document.querySelectorAll('.soal-item');
    if (soalItems.length > 0) {
        document.addEventListener('keydown', function(e) {
            const activeIndex = Array.from(soalItems).findIndex(item => 
                item.classList.contains('active')
            );

            if (e.key === 'ArrowDown' && activeIndex < soalItems.length - 1) {
                e.preventDefault();
                const nextItem = soalItems[activeIndex + 1];
                const onclickAttr = nextItem.getAttribute('onclick');
                if (onclickAttr) {
                    const url = onclickAttr.match(/'([^']+)'/)[1];
                    window.location.href = url;
                }
            } else if (e.key === 'ArrowUp' && activeIndex > 0) {
                e.preventDefault();
                const prevItem = soalItems[activeIndex - 1];
                const onclickAttr = prevItem.getAttribute('onclick');
                if (onclickAttr) {
                    const url = onclickAttr.match(/'([^']+)'/)[1];
                    window.location.href = url;
                }
            }
        });

        // Auto-scroll to active soal item
        const activeItem = document.querySelector('.soal-item.active');
        if (activeItem) {
            activeItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
    }
});

// Print functionality
function printPreview() {
    const printableArea = document.getElementById('printableArea');
    if (!printableArea) return;

    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Print Soal Teori</title>
            <style>
                body { 
                    font-family: Arial, sans-serif; 
                    line-height: 1.6;
                    color: #333;
                    margin: 20px;
                }
                .preview-section { 
                    margin-bottom: 25px; 
                    page-break-inside: avoid;
                }
                .preview-section h3 {
                    color: #333;
                    border-bottom: 2px solid #007bff;
                    padding-bottom: 5px;
                    margin-bottom: 10px;
                }
                .header-section {
                    text-align: center;
                    padding: 15px;
                    background: #f5f5f5;
                    border-radius: 5px;
                    margin-bottom: 20px;
                }
                .vignette-content,
                .pertanyaan-content {
                    background: #f9f9f9;
                    padding: 15px;
                    border-radius: 5px;
                    border-left: 4px solid #007bff;
                }
                .pilihan-item {
                    margin-bottom: 8px;
                    padding: 10px;
                    border: 1px solid #ddd;
                    border-radius: 4px;
                }
                .pilihan-item.kunci-jawaban {
                    border-color: #28a745;
                    background: #f8fff9;
                }
                .kunci-label {
                    background: #28a745;
                    color: white;
                    padding: 2px 6px;
                    border-radius: 3px;
                    font-size: 10px;
                    margin-left: 10px;
                }
                .info-grid {
                    display: grid;
                    grid-template-columns: 1fr 1fr;
                    gap: 15px;
                }
                .info-item {
                    background: #f5f5f5;
                    padding: 10px;
                    border-radius: 4px;
                }
                img {
                    max-width: 100%;
                    height: auto;
                }
                @media print {
                    body { margin: 0; }
                    .preview-section { margin-bottom: 20px; }
                }
            </style>
        </head>
        <body>
            ${printableArea.innerHTML}
        </body>
        </html>
    `);
    
    printWindow.document.close();
    printWindow.focus();
    
    setTimeout(() => {
        printWindow.print();
        printWindow.close();
    }, 500);
}

// Handle window resize untuk maintain scroll functionality
function handleResize() {
    const previewContent = document.querySelector('.soal-preview-content');
    const layoutContainer = document.querySelector('.layout-container');
    
    if (previewContent && layoutContainer) {
        // Reset height calculations on resize
        const headerHeight = document.querySelector('.preview-header')?.offsetHeight || 0;
        const availableHeight = layoutContainer.offsetHeight - headerHeight - 60; // 60px untuk padding
        
        previewContent.style.maxHeight = availableHeight + 'px';
    }
}

// Initial call dan event listener untuk resize
document.addEventListener('DOMContentLoaded', function() {
    handleResize();
    window.addEventListener('resize', handleResize);
    
    // Juga panggil setelah konten dimuat
    setTimeout(handleResize, 100);
});

// Export functions for potential module use
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { SimpleTextEditor, printPreview };
}

// Advanced Text Editor dengan ContentEditable DIV
class AdvancedTextEditor {
    constructor(container) {
        this.container = container;
        this.editableDiv = container.querySelector('.rich-text[contenteditable="true"]');
        this.hiddenInput = container.querySelector('input[type="hidden"]');
        this.toolbar = container.querySelector('.toolbar');
        this.init();
    }

    init() {
        console.log('Initializing editor for:', this.editableDiv.id);
        
        // Add event listeners to toolbar buttons
        this.toolbar.addEventListener('click', (e) => {
            if (e.target.tagName === 'BUTTON' || e.target.parentElement.tagName === 'BUTTON') {
                e.preventDefault();
                const button = e.target.tagName === 'BUTTON' ? e.target : e.target.parentElement;
                const command = button.dataset.command;
                console.log('Toolbar button clicked:', command);
                
                if (command === 'uploadImage') {
                    this.openImageUpload();
                } else {
                    this.executeCommand(command);
                }
            }
        });

        // Handle font size selector
        const fontSizeSelector = this.toolbar.querySelector('.font-size-selector');
        if (fontSizeSelector) {
            fontSizeSelector.addEventListener('change', (e) => {
                if (e.target.value) {
                    this.executeCommand('fontSize', e.target.value);
                    e.target.value = ''; // Reset dropdown
                }
            });
        }

        // Sync content to hidden input on input
        this.editableDiv.addEventListener('input', () => {
            console.log('Editor content changed');
            this.syncToHiddenInput();
            this.updateCharacterCounter();
        });

        // Sync on blur juga untuk memastikan data tersimpan
        this.editableDiv.addEventListener('blur', () => {
            console.log('Editor blur - syncing');
            this.syncToHiddenInput();
        });

        // Initialize character counter
        this.updateCharacterCounter();
        
        // Auto-resize
        this.autoResize();

        // Initial sync
        this.syncToHiddenInput();
    }

    openImageUpload() {
        console.log('Opening image upload modal');
        // Create modal for image upload
        const modal = this.createImageUploadModal();
        document.body.appendChild(modal);
        
        // Show modal
        modal.style.display = 'block';
        
        // Handle modal events
        this.setupImageUploadModal(modal);
    }

    createImageUploadModal() {
        const modal = document.createElement('div');
        modal.className = 'image-upload-modal';
        modal.style.cssText = `
            display: none;
            position: fixed;
            z-index: 10000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        `;

        modal.innerHTML = `
            <div style="
                background-color: white;
                margin: 10% auto;
                padding: 20px;
                border-radius: 5px;
                width: 400px;
                max-width: 90%;
            ">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                    <h3 style="margin: 0;">Upload Gambar</h3>
                    <span class="close-modal" style="font-size: 24px; cursor: pointer;">&times;</span>
                </div>
                <div class="upload-area" style="
                    border: 2px dashed #ccc;
                    border-radius: 5px;
                    padding: 20px;
                    text-align: center;
                    margin-bottom: 15px;
                    cursor: pointer;
                ">
                    <i class="fas fa-cloud-upload-alt" style="font-size: 48px; color: #667eea; margin-bottom: 10px;"></i>
                    <p>Klik atau seret gambar ke sini</p>
                    <input type="file" class="file-input" accept="image/*" style="display: none;">
                    <img class="upload-preview" src="" alt="Preview" style="max-width: 100%; max-height: 200px; margin-top: 10px; display: none;">
                </div>
                <div class="upload-buttons" style="display: flex; justify-content: flex-end; gap: 10px;">
                    <button class="btn btn-secondary cancel-upload">Batal</button>
                    <button class="btn btn-primary insert-image">Sisipkan</button>
                </div>
            </div>
        `;

        return modal;
    }

    setupImageUploadModal(modal) {
        const closeModal = modal.querySelector('.close-modal');
        const cancelUpload = modal.querySelector('.cancel-upload');
        const uploadArea = modal.querySelector('.upload-area');
        const fileInput = modal.querySelector('.file-input');
        const uploadPreview = modal.querySelector('.upload-preview');
        const insertImageBtn = modal.querySelector('.insert-image');

        let uploadedImageUrl = null;

        // Close modal functions
        const closeModalFunc = () => {
            modal.remove();
        };

        closeModal.addEventListener('click', closeModalFunc);
        cancelUpload.addEventListener('click', closeModalFunc);

        // Upload area events
        uploadArea.addEventListener('click', () => {
            fileInput.click();
        });

        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.style.borderColor = '#667eea';
            uploadArea.style.backgroundColor = '#f0f0f0';
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.style.borderColor = '#ccc';
            uploadArea.style.backgroundColor = '';
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.style.borderColor = '#ccc';
            uploadArea.style.backgroundColor = '';
            
            if (e.dataTransfer.files.length) {
                this.handleImageFile(e.dataTransfer.files[0], uploadPreview)
                    .then(url => {
                        uploadedImageUrl = url;
                    })
                    .catch(error => {
                        alert(error);
                    });
            }
        });

        // File input change
        fileInput.addEventListener('change', () => {
            if (fileInput.files.length) {
                this.handleImageFile(fileInput.files[0], uploadPreview)
                    .then(url => {
                        uploadedImageUrl = url;
                    })
                    .catch(error => {
                        alert(error);
                    });
            }
        });

        // Insert image
        insertImageBtn.addEventListener('click', () => {
            if (uploadedImageUrl) {
                console.log('Inserting image into editor');
                this.insertImageIntoEditor(uploadedImageUrl);
                closeModalFunc();
            } else {
                alert('Silakan pilih gambar terlebih dahulu');
            }
        });
    }

    handleImageFile(file, previewElement) {
        return new Promise((resolve, reject) => {
            // Validasi tipe file
            if (!file.type.match('image.*')) {
                reject('Hanya file gambar yang diizinkan');
                return;
            }

            // Validasi ukuran file (maksimal 2MB)
            if (file.size > 2 * 1024 * 1024) {
                reject('Ukuran file maksimal 2MB');
                return;
            }

            // Tampilkan preview
            const reader = new FileReader();
            reader.onload = function(e) {
                previewElement.src = e.target.result;
                previewElement.style.display = 'block';
                resolve(e.target.result);
            };
            reader.onerror = function() {
                reject('Gagal membaca file');
            };
            reader.readAsDataURL(file);
        });
    }

    insertImageIntoEditor(imageUrl) {
        // Focus pada editor
        this.editableDiv.focus();
        
        // Buat elemen gambar
        const img = document.createElement('img');
        img.src = imageUrl;
        img.alt = 'Gambar';
        img.style.maxWidth = '100%';
        img.style.height = 'auto';
        img.style.display = 'block';
        img.style.margin = '10px 0';
        
        // Sisipkan gambar pada posisi kursor
        const selection = window.getSelection();
        if (selection.rangeCount > 0) {
            const range = selection.getRangeAt(0);
            range.insertNode(img);
            
            // Set kursor setelah gambar
            const newRange = document.createRange();
            newRange.setStartAfter(img);
            newRange.collapse(true);
            selection.removeAllRanges();
            selection.addRange(newRange);
        } else {
            // Jika tidak ada selection, tambahkan di akhir
            this.editableDiv.appendChild(img);
        }
        
        // Sync ke hidden input
        this.syncToHiddenInput();
        console.log('Image inserted and synced');
    }

    executeCommand(command, value = null) {
        this.editableDiv.focus();
        
        try {
            document.execCommand(command, false, value);
            this.syncToHiddenInput();
            console.log('Command executed:', command, value);
        } catch (error) {
            console.warn(`Command ${command} not supported`);
        }
    }

    syncToHiddenInput() {
        if (this.hiddenInput) {
            const content = this.editableDiv.innerHTML;
            this.hiddenInput.value = content;
            console.log('Synced to hidden input:', content.substring(0, 100) + '...');
        }
    }

    updateCharacterCounter() {
        let counter = this.container.querySelector('.char-counter');
        if (!counter) {
            counter = document.createElement('div');
            counter.className = 'char-counter';
            counter.style.cssText = 'font-size: 12px; color: #666; text-align: right; margin-top: 5px;';
            this.container.appendChild(counter);
        }
        
        // Hitung karakter teks saja (tanpa HTML tags)
        const textContent = this.editableDiv.textContent || '';
        const count = textContent.length;
        counter.textContent = `${count} karakter`;
        
        if (count > 5000) {
            counter.style.color = '#dc3545';
        } else if (count > 3000) {
            counter.style.color = '#ffc107';
        } else {
            counter.style.color = '#666';
        }
    }

    autoResize() {
        const resize = () => {
            this.editableDiv.style.height = 'auto';
            this.editableDiv.style.height = (this.editableDiv.scrollHeight) + 'px';
        };
        
        this.editableDiv.addEventListener('input', resize);
        
        // Initial resize
        setTimeout(resize, 100);
    }
}

// Fungsi untuk sync semua editor sebelum submit
function syncAllEditorsBeforeSubmit() {
    console.log('Syncing all editors before submit');
    const editors = document.querySelectorAll('.text-editor');
    editors.forEach(container => {
        const editableDiv = container.querySelector('.rich-text[contenteditable="true"]');
        const hiddenInput = container.querySelector('input[type="hidden"]');
        if (editableDiv && hiddenInput) {
            const content = editableDiv.innerHTML;
            hiddenInput.value = content;
            console.log('Synced editor:', hiddenInput.name, 'Content length:', content.length);
        }
    });
    return true;
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded - initializing editors');
    
    // Initialize all advanced text editors
    const textEditorContainers = document.querySelectorAll('.text-editor');
    console.log('Found text editors:', textEditorContainers.length);
    
    textEditorContainers.forEach(container => {
        new AdvancedTextEditor(container);
    });

    // Form validation dan sync sebelum submit
    const mainForm = document.getElementById('soalTeoriForm');
    if (mainForm) {
        console.log('Main form found, adding submit handler');
        
        mainForm.addEventListener('submit', function(e) {
            console.log('Form submit triggered');
            
            // Sync semua editor sebelum submit
            syncAllEditorsBeforeSubmit();
            
            // Debug: log semua form data
            const formData = new FormData(mainForm);
            for (let [key, value] of formData.entries()) {
                console.log('Form data:', key, '=', value.substring(0, 100) + '...');
            }
            
            const nomorRegistrasi = document.getElementById('nomor_registrasi')?.value.trim();
            const tinjauan1 = document.getElementById('tinjauan1')?.value.trim();
            const pertanyaan = document.getElementById('pertanyaan')?.value.trim();

            let isValid = true;
            let errorMessage = '';

            if (!nomorRegistrasi) {
                isValid = false;
                errorMessage += '• Nomor Registrasi harus diisi\n';
            }

            if (!tinjauan1) {
                isValid = false;
                errorMessage += '• Kompetensi Utama harus diisi\n';
            }

            if (!pertanyaan) {
                isValid = false;
                errorMessage += '• Pertanyaan/Instruksi harus diisi\n';
            }

            if (!isValid) {
                e.preventDefault();
                alert('Harap perbaiki kesalahan berikut:\n\n' + errorMessage);
                return false;
            }

            console.log('Form validation passed, submitting...');
            return true;
        });
    }

    // Juga sync pada sebelum unload page (backup)
    window.addEventListener('beforeunload', function() {
        syncAllEditorsBeforeSubmit();
    });
});

// Fungsi untuk validasi form dengan nomor registrasi otomatis
function validateFormWithAutoRegistrasi() {
    const nomorRegistrasi = document.getElementById('nomor_registrasi')?.value.trim();
    const tinjauan1 = document.getElementById('tinjauan1')?.value.trim();
    const pertanyaan = document.getElementById('pertanyaan')?.value.trim();

    let isValid = true;
    let errorMessage = '';

    if (!nomorRegistrasi) {
        isValid = false;
        errorMessage += '• Nomor Registrasi harus diisi\n';
    }

    if (!tinjauan1) {
        isValid = false;
        errorMessage += '• Kompetensi Utama harus diisi\n';
    }

    if (!pertanyaan) {
        isValid = false;
        errorMessage += '• Pertanyaan/Instruksi harus diisi\n';
    }

    if (!isValid) {
        alert('Harap perbaiki kesalahan berikut:\n\n' + errorMessage);
        return false;
    }

    return true;
}

// Initialize ketika DOM loaded
document.addEventListener('DOMContentLoaded', function() {
    const mainForm = document.getElementById('soalTeoriForm');
    if (mainForm) {
        mainForm.addEventListener('submit', function(e) {
            // Sync semua editor sebelum submit
            syncAllEditorsBeforeSubmit();
            
            // Validasi form
            if (!validateFormWithAutoRegistrasi()) {
                e.preventDefault();
                return false;
            }
            
            console.log('Form dengan nomor registrasi otomatis siap disubmit');
            return true;
        });
    }
    
    // Tambahkan efek visual untuk nomor registrasi
    const nomorRegistrasiInput = document.getElementById('nomor_registrasi');
    if (nomorRegistrasiInput) {
        // Highlight ketika page load
        nomorRegistrasiInput.style.backgroundColor = '#d4edda';
        nomorRegistrasiInput.style.borderColor = '#28a745';
        
        // Reset setelah 2 detik
        setTimeout(() => {
            nomorRegistrasiInput.style.backgroundColor = '#f8f9fa';
        }, 2000);
    }
});

// Enhanced department select functionality
function enhanceDepartmentSelect() {
    const departmentSelect = document.getElementById('department');
    
    if (departmentSelect) {
        // Add visual feedback
        departmentSelect.addEventListener('change', function() {
            if (this.value) {
                this.style.borderColor = '#28a745';
                this.style.backgroundColor = '#f8fff9';
                
                // Reset after 2 seconds
                setTimeout(() => {
                    this.style.borderColor = '#e9ecef';
                    this.style.backgroundColor = 'white';
                }, 2000);
            }
        });
        
        // Add keyboard navigation
        departmentSelect.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                this.click();
            }
        });
        
        // Highlight on focus
        departmentSelect.addEventListener('focus', function() {
            this.style.borderColor = '#007bff';
            this.style.boxShadow = '0 0 0 3px rgba(0,123,255,0.1)';
        });
        
        departmentSelect.addEventListener('blur', function() {
            this.style.borderColor = '#e9ecef';
            this.style.boxShadow = 'none';
        });
    }
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', function() {
    enhanceDepartmentSelect();
    
    // Form validation update untuk include department
    const mainForm = document.getElementById('soalTeoriForm');
    if (mainForm) {
        mainForm.addEventListener('submit', function(e) {
            // Sync semua editor sebelum submit
            syncAllEditorsBeforeSubmit();
            
            const tinjauan1 = document.getElementById('tinjauan1')?.value.trim();
            const pertanyaan = document.getElementById('pertanyaan')?.value.trim();
            const department = document.getElementById('department')?.value;

            let isValid = true;
            let errorMessage = '';

            if (!tinjauan1) {
                isValid = false;
                errorMessage += '• Kompetensi Utama harus diisi\n';
            }

            if (!pertanyaan) {
                isValid = false;
                errorMessage += '• Pertanyaan/Instruksi harus diisi\n';
            }

            if (!department) {
                isValid = false;
                errorMessage += '• Department harus dipilih\n';
            }

            if (!isValid) {
                e.preventDefault();
                alert('Harap perbaiki kesalahan berikut:\n\n' + errorMessage);
                return false;
            }

            console.log('Form validation passed, submitting...');
            return true;
        });
    }
});