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

    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: 1000;
            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);
        });
    }

    // Di bagian insertImageIntoTextarea, pastikan menggunakan format yang sama:
insertImageIntoTextarea(imageUrl) {
    const cursorPos = this.textarea.selectionStart;
    const textBefore = this.textarea.value.substring(0, cursorPos);
    const textAfter = this.textarea.value.substring(cursorPos);
    
    const imgTag = `<img src="${imageUrl}" alt="Gambar" style="max-width: 100%; height: auto;">`;
    
    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';
        }
    }
}

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

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

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

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

// 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('soalTeoriForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            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 += '• Tinjauan 1: 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;
        });
    }

    // 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('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 => {
                const element = document.querySelector(`[name="${key}"]`);
                if (element) {
                    element.value = draftData[key];
                }
            });
            showNotification('Draft sebelumnya dimuat', 'info');
        }
    }

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

    // 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 = '200px';
        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?')) {
                e.preventDefault();
            } else {
                localStorage.removeItem('soalTeoriDraft');
            }
        });
    }
});

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

// JavaScript untuk fungsi upload gambar dan ukuran font
document.addEventListener('DOMContentLoaded', function() {
    // Variabel global
    let currentTextarea = null;
    let uploadedImageUrl = null;
    
    // Fungsi untuk eksekusi perintah pada textarea
    function execCommand(command, value = null) {
        if (currentTextarea) {
            currentTextarea.focus();
            document.execCommand(command, false, value);
        }
    }
    
    // Event listener untuk toolbar buttons
    document.querySelectorAll('.toolbar button[data-command]').forEach(button => {
        button.addEventListener('click', function() {
            const command = this.getAttribute('data-command');
            execCommand(command);
        });
    });
    
    // Event listener untuk ukuran font
    document.querySelectorAll('.font-size-selector').forEach(select => {
        select.addEventListener('change', function() {
            if (this.value) {
                execCommand('fontSize', this.value);
                this.value = ''; // Reset dropdown
            }
        });
    });
    
    // Event listener untuk fokus pada textarea
    document.querySelectorAll('.rich-text').forEach(textarea => {
        textarea.addEventListener('focus', function() {
            currentTextarea = this;
        });
    });
    
    // Modal untuk upload gambar
    const modal = document.getElementById('imageUploadModal');
    const uploadBtn = document.getElementById('uploadImageBtn');
    const closeModal = document.querySelector('.close-modal');
    const cancelUpload = document.getElementById('cancelUpload');
    const uploadArea = document.getElementById('uploadArea');
    const imageFile = document.getElementById('imageFile');
    const uploadPreview = document.getElementById('uploadPreview');
    const insertImageBtn = document.getElementById('insertImage');
    
    // Buka modal upload gambar
    uploadBtn.addEventListener('click', function() {
        if (currentTextarea) {
            modal.style.display = 'block';
            uploadedImageUrl = null;
            uploadPreview.style.display = 'none';
            imageFile.value = '';
        } else {
            alert('Silakan fokus pada textarea terlebih dahulu');
        }
    });
    
    // Tutup modal
    function closeImageModal() {
        modal.style.display = 'none';
    }
    
    closeModal.addEventListener('click', closeImageModal);
    cancelUpload.addEventListener('click', closeImageModal);
    
    // Event untuk area upload
    uploadArea.addEventListener('click', function() {
        imageFile.click();
    });
    
    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        this.style.borderColor = '#667eea';
        this.style.backgroundColor = '#f0f0f0';
    });
    
    uploadArea.addEventListener('dragleave', function() {
        this.style.borderColor = '#ccc';
        this.style.backgroundColor = '';
    });
    
    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        this.style.borderColor = '#ccc';
        this.style.backgroundColor = '';
        
        if (e.dataTransfer.files.length) {
            handleImageFile(e.dataTransfer.files[0]);
        }
    });
    
    // Event untuk input file
    imageFile.addEventListener('change', function() {
        if (this.files.length) {
            handleImageFile(this.files[0]);
        }
    });
    
    // Fungsi untuk menangani file gambar
    function handleImageFile(file) {
        // Validasi tipe file
        if (!file.type.match('image.*')) {
            alert('Hanya file gambar yang diizinkan');
            return;
        }
        
        // Validasi ukuran file (maksimal 2MB)
        if (file.size > 2 * 1024 * 1024) {
            alert('Ukuran file maksimal 2MB');
            return;
        }
        
        // Tampilkan preview
        const reader = new FileReader();
        reader.onload = function(e) {
            uploadPreview.src = e.target.result;
            uploadPreview.style.display = 'block';
            uploadedImageUrl = e.target.result;
        };
        reader.readAsDataURL(file);
    }
    
    // Event untuk tombol sisipkan gambar
    insertImageBtn.addEventListener('click', function() {
        if (uploadedImageUrl) {
            // Sisipkan gambar ke textarea sebagai base64
            const imgHTML = `<img src="${uploadedImageUrl}" alt="Gambar" style="max-width: 100%; height: auto;">`;
            
            // Untuk textarea biasa, kita perlu menambahkan tag img secara manual
            if (currentTextarea) {
                const cursorPos = currentTextarea.selectionStart;
                const textBefore = currentTextarea.value.substring(0, cursorPos);
                const textAfter = currentTextarea.value.substring(cursorPos);
                
                currentTextarea.value = textBefore + imgHTML + textAfter;
                
                // Trigger input event untuk update counter dan auto-resize
                currentTextarea.dispatchEvent(new Event('input'));
                
                // Set cursor position setelah gambar
                const newCursorPos = cursorPos + imgHTML.length;
                currentTextarea.setSelectionRange(newCursorPos, newCursorPos);
                currentTextarea.focus();
            }
            
            closeImageModal();
        } else {
            alert('Silakan pilih gambar terlebih dahulu');
        }
    });

    // Auto-resize textareas
    const textareas = document.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);
    });
});

