// Text Editor Sederhana untuk Bank 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';
        }
    }
}

// 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
    const form = document.getElementById('soalPraktikForm');
    if (form) {
        form.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 += '• Tinjauan 1: 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;
        });
    }

    // Auto-save draft functionality
    let autoSaveTimer;
    const formInputs = form ? form.querySelectorAll('input, textarea, select') : [];
    
    formInputs.forEach(input => {
        input.addEventListener('input', function() {
            clearTimeout(autoSaveTimer);
            autoSaveTimer = setTimeout(saveDraft, 3000);
        });
    });

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

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

    function loadDraft() {
        const draft = localStorage.getItem('soalPraktikDraft');
        if (draft) {
            const draftData = JSON.parse(draft);
            Object.keys(draftData).forEach(key => {
                const element = document.querySelector(`[name="${key}"]`);
                if (element) {
                    element.value = draftData[key];
                }
            });
            showNotification('Draft soal praktik sebelumnya dimuat', 'info');
        }
    }

    // Clear draft on successful form submission
    if (form) {
        form.addEventListener('submit', function() {
            localStorage.removeItem('soalPraktikDraft');
        });
    }

    // Load draft on page load
    loadDraft();

    // 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.position = 'fixed';
        notification.style.top = '20px';
        notification.style.right = '20px';
        notification.style.zIndex = '1000';
        notification.style.minWidth = '250px';
        notification.textContent = message;

        document.body.appendChild(notification);

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

    // Add confirmation for reset button
    const resetButton = form ? form.querySelector('button[type="reset"]') : null;
    if (resetButton) {
        resetButton.addEventListener('click', function(e) {
            if (!confirm('Yakin ingin mengosongkan semua field? Semua data yang belum disimpan akan hilang.')) {
                e.preventDefault();
            } else {
                localStorage.removeItem('soalPraktikDraft');
                showNotification('Form telah direset', 'info');
            }
        });
    }

    // Auto-expand textareas based on content
    const textareas = form ? form.querySelectorAll('.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);
    });
});

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