// Text Editor untuk Edit Mode
class SimpleTextEditor {
    constructor(textarea) {
        this.textarea = textarea;
        this.toolbar = textarea.previousElementSibling;
        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;
                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();
    }

    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';
            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';
        }
    }
}

// Auto-expand textareas based on content
function autoResizeTextareas() {
    const textareas = document.querySelectorAll('.edit-form .rich-text');
    textareas.forEach(textarea => {
        // Set initial height
        textarea.style.height = 'auto';
        textarea.style.height = (textarea.scrollHeight) + 'px';
        
        // Add input event listener
        textarea.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });
    });
}


// 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);
    });

    // Auto-resize textareas in edit mode
    autoResizeTextareas();

    // Auto-expand textareas based on content (untuk edit mode)
    const textareas = document.querySelectorAll('.edit-form .rich-text');
    textareas.forEach(textarea => {
        textarea.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });
        
        // Trigger initial resize
        setTimeout(() => {
            textarea.style.height = 'auto';
            textarea.style.height = (textarea.scrollHeight) + 'px';
        }, 100);
    });

    // Juga initialize advanced text editors untuk edit mode
    const textEditorContainers = document.querySelectorAll('.text-editor');
    if (typeof AdvancedTextEditor !== 'undefined') {
        textEditorContainers.forEach(container => {
            // Cek apakah container sudah memiliki editor
            if (!container.hasAttribute('data-editor-initialized')) {
                new AdvancedTextEditor(container);
                container.setAttribute('data-editor-initialized', 'true');
            }
        });
    }

    // Form validation untuk edit mode
    const editForm = document.getElementById('editSoalForm');
    if (editForm) {
        editForm.addEventListener('submit', function(e) {
            // Sync semua editor sebelum submit di edit mode
            if (typeof syncAllEditorsBeforeSubmit !== 'undefined') {
                syncAllEditorsBeforeSubmit();
            }
            
            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;
            }

            return true;
        });
    }


// JavaScript untuk halaman list soal teori
document.addEventListener('DOMContentLoaded', function() {
    // Auto-scroll to active soal item
    const activeItem = document.querySelector('.soal-item.active');
    if (activeItem) {
        activeItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }

    // Keyboard navigation
    document.addEventListener('keydown', function(e) {
        const soalItems = document.querySelectorAll('.soal-item');
        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];
            window.location.href = nextItem.getAttribute('onclick').match(/'([^']+)'/)[1];
        } else if (e.key === 'ArrowUp' && activeIndex > 0) {
            e.preventDefault();
            const prevItem = soalItems[activeIndex - 1];
            window.location.href = prevItem.getAttribute('onclick').match(/'([^']+)'/)[1];
        }
    });

    // 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);
        });
    }
});

// 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;
                }
                @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);
}

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

// 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
document.addEventListener('DOMContentLoaded', function() {
    handleResize();
    window.addEventListener('resize', handleResize);
    
    // Juga panggil setelah konten dimuat
    setTimeout(handleResize, 100);
});
});

// Advanced Text Editor dengan ContentEditable DIV (salin dari bank_soal_teori.js)
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 AdvancedTextEditor for:', this.editableDiv?.id);
        
        if (!this.editableDiv || !this.hiddenInput) {
            console.error('Required elements not found in container');
            return;
        }

        // 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', () => {
            this.syncToHiddenInput();
            this.updateCharacterCounter();
        });

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

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

        // Initial sync
        this.syncToHiddenInput();
    }

}

// Fungsi untuk sync semua editor sebelum submit di edit mode
function syncAllEditorsBeforeSubmit() {
    console.log('Syncing all editors before submit in edit mode');
    const editors = document.querySelectorAll('.text-editor');
    let syncedCount = 0;
    
    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;
            syncedCount++;
            console.log('Synced editor:', hiddenInput.name, 'Content length:', content.length);
        }
    });
    
    console.log('Total editors synced:', syncedCount);
    return syncedCount > 0;
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded - initializing editors for list_soal_teori.php');
    
    // Initialize all advanced text editors untuk edit mode
    const textEditorContainers = document.querySelectorAll('.text-editor');
    console.log('Found text editors:', textEditorContainers.length);
    
    if (typeof AdvancedTextEditor !== 'undefined') {
        textEditorContainers.forEach(container => {
            // Cek apakah container sudah memiliki editor
            if (!container.hasAttribute('data-editor-initialized')) {
                try {
                    new AdvancedTextEditor(container);
                    container.setAttribute('data-editor-initialized', 'true');
                    console.log('AdvancedTextEditor initialized for:', container.id);
                } catch (error) {
                    console.error('Error initializing AdvancedTextEditor:', error);
                }
            }
        });
    }

    // Form validation untuk edit mode
    const editForm = document.getElementById('editSoalForm');
    if (editForm) {
        console.log('Edit form found, adding submit handler');
        
        editForm.addEventListener('submit', function(e) {
            console.log('Edit form submit triggered');
            
            // Sync semua editor sebelum submit
            const syncResult = syncAllEditorsBeforeSubmit();
            console.log('Sync result:', syncResult);
            
            // Debug: log semua form data
            const formData = new FormData(editForm);
            console.log('=== FORM DATA BEFORE SUBMIT ===');
            for (let [key, value] of formData.entries()) {
                console.log('Form data:', key, '=', value.substring(0, 100) + (value.length > 100 ? '...' : ''));
            }
            console.log('===============================');
            
            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('Edit form validation passed, submitting...');
            return true;
        });
    }

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

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


