// Text Editor Sederhana untuk List Soal Praktik
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 > 10000) {
            counter.style.color = '#dc3545';
        } else if (count > 5000) {
            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();

    // Form validation untuk edit mode
    const editForm = document.getElementById('editSoalForm');
    if (editForm) {
        editForm.addEventListener('submit', function(e) {
            const nomorRegistrasi = document.getElementById('nomor_registrasi').value.trim();
            const tinjauan1 = document.getElementById('tinjauan1').value.trim();
            const skenarioKlinik = document.getElementById('skenario_klinik').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 (!skenarioKlinik) {
                isValid = false;
                errorMessage += '• Skenario Klinik harus diisi\n';
            }

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

            return true;
        });
    }

    // Search functionality
    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 Praktik</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 #dc3545;
                    padding-bottom: 5px;
                    margin-bottom: 10px;
                }
                .header-section {
                    text-align: center;
                    padding: 15px;
                    background: #f5f5f5;
                    border-radius: 5px;
                    margin-bottom: 20px;
                }
                .tujuan-content,
                .skenario-content,
                .tugas-kandidat-content,
                .tugas-penguji-content,
                .instruksi-pasien-content,
                .peralatan-content {
                    background: #f9f9f9;
                    padding: 15px;
                    border-radius: 5px;
                    border-left: 4px solid #dc3545;
                }
                .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 = { SimpleTextEditor, printPreview };
}