class RichTextEditor {
    constructor(container) {
        this.container = container;
        this.targetName = container.getAttribute('data-target');
        this.targetTextarea = this.findTargetTextarea();
        this.init();
    }

    findTargetTextarea() {
        // Cari textarea berdasarkan target name
        if (this.targetName.includes('[]')) {
            // Untuk array fields, cari textarea terakhir dengan nama tersebut
            const textareas = document.querySelectorAll(`textarea[name="${this.targetName}"]`);
            return textareas[textareas.length - 1] || null;
        } else {
            return document.getElementById(this.targetName);
        }
    }

    init() {RichTextEditor
        // Create toolbar dengan tambahan upload image
        const toolbar = document.createElement('div');
        toolbar.className = 'editor-toolbar';
        toolbar.innerHTML = `
            <div class="font-size-controls">
                <button type="button" class="toolbar-btn" data-command="decreaseFontSize" title="Perkecil Ukuran Font">
                    <i class="fas fa-font"></i> <i class="fas fa-minus"></i>
                </button>
                <button type="button" class="toolbar-btn" data-command="increaseFontSize" title="Perbesar Ukuran Font">
                    <i class="fas fa-font"></i> <i class="fas fa-plus"></i>
                </button>
                <select class="font-size-select" title="Pilih Ukuran Font">
                    <option value="">Ukuran Font</option>
                    <option value="1">Sangat Kecil</option>
                    <option value="2">Kecil</option>
                    <option value="3">Normal</option>
                    <option value="4">Sedang</option>
                    <option value="5">Besar</option>
                    <option value="6">Sangat Besar</option>
                    <option value="7">Terlalu Besar</option>
                </select>
            </div>
            <button type="button" class="toolbar-btn" data-command="bold" title="Bold"><i class="fas fa-bold"></i></button>
            <button type="button" class="toolbar-btn" data-command="italic" title="Italic"><i class="fas fa-italic"></i></button>
            <button type="button" class="toolbar-btn" data-command="underline" title="Underline"><i class="fas fa-underline"></i></button>
            <button type="button" class="toolbar-btn" data-command="insertUnorderedList" title="Bullet List"><i class="fas fa-list-ul"></i></button>
            <button type="button" class="toolbar-btn" data-command="insertOrderedList" title="Numbered List"><i class="fas fa-list-ol"></i></button>
            <button type="button" class="toolbar-btn" data-command="createLink" title="Insert Link"><i class="fas fa-link"></i></button>
            <button type="button" class="toolbar-btn" data-command="insertImage" title="Insert Image from URL"><i class="fas fa-image"></i></button>
            <button type="button" class="toolbar-btn" data-command="uploadImage" title="Upload Image"><i class="fas fa-upload"></i></button>
            <button type="button" class="toolbar-btn" data-command="removeFormat" title="Clear Formatting"><i class="fas fa-eraser"></i></button>
        `;

        // Create editable div
        const editable = document.createElement('div');
        editable.className = 'editor-content';
        editable.contentEditable = true;
        
        // Set initial content dari textarea jika ada
        if (this.targetTextarea && this.targetTextarea.value) {
            editable.innerHTML = this.targetTextarea.value;
        }

        // Insert elements
        this.container.innerHTML = '';
        this.container.appendChild(toolbar);
        this.container.appendChild(editable);

        this.editable = editable;
        this.setupEventListeners();
        
        // Initial sync
        this.syncToTextarea();
    }

    setupEventListeners() {
        // Toolbar buttons
        this.container.querySelectorAll('.toolbar-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                const command = btn.getAttribute('data-command');
                
                if (command === 'createLink') {
                    this.createLink();
                } else if (command === 'insertImage') {
                    this.insertImage();
                } else if (command === 'uploadImage') {
                    this.uploadImage();
                } else if (command === 'increaseFontSize') {
                    this.increaseFontSize();
                } else if (command === 'decreaseFontSize') {
                    this.decreaseFontSize();
                } else {
                    document.execCommand(command, false, null);
                }
                this.editable.focus();
                this.syncToTextarea();
            });
        });

        // Font size select change
        const fontSizeSelect = this.container.querySelector('.font-size-select');
        if (fontSizeSelect) {
            fontSizeSelect.addEventListener('change', (e) => {
                const size = e.target.value;
                if (size) {
                    this.setFontSize(size);
                }
                this.editable.focus();
                this.syncToTextarea();
            });
        }

        

        // Update textarea on input
        this.editable.addEventListener('input', () => {
            this.syncToTextarea();
        });

        // Sync on blur
        this.editable.addEventListener('blur', () => {
            this.syncToTextarea();
        });

        // Handle paste event to clean formatting
        this.editable.addEventListener('paste', (e) => {
            e.preventDefault();
            const text = (e.clipboardData || window.clipboardData).getData('text/plain');
            document.execCommand('insertText', false, text);
            this.syncToTextarea();
        });

        // Handle paste event for images
        this.editable.addEventListener('paste', (e) => {
            const items = (e.clipboardData || e.originalEvent.clipboardData).items;
            
            for (let item of items) {
                if (item.type.indexOf('image') !== -1) {
                    e.preventDefault();
                    const file = item.getAsFile();
                    this.handleImageUpload(file);
                    break;
                }
            }
        });

        // Handle drop event for images
        this.editable.addEventListener('drop', (e) => {
            e.preventDefault();
            const files = e.dataTransfer.files;
            
            for (let file of files) {
                if (file.type.indexOf('image') !== -1) {
                    this.handleImageUpload(file);
                    break;
                }
            }
        });

        // Prevent default drop behavior
        this.editable.addEventListener('dragover', (e) => {
            e.preventDefault();
        });
    }

    syncToTextarea() {
        if (this.targetTextarea) {
            this.targetTextarea.value = this.editable.innerHTML;
        }
    }

    createLink() {
        const url = prompt('Masukkan URL:');
        if (url) {
            document.execCommand('createLink', false, url);
            this.syncToTextarea();
        }
    }

    insertImage() {
        const url = prompt('Masukkan URL gambar:');
        if (url) {
            document.execCommand('insertImage', false, url);
            this.syncToTextarea();
        }
    }

    uploadImage() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/*';
        input.multiple = false;
        
        input.onchange = (e) => {
            const file = e.target.files[0];
            if (file) {
                this.handleImageUpload(file);
            }
        };
        
        input.click();
    }

    handleImageUpload(file) {
    console.log('Handling image upload:', file.name);

    // Show loading
    this.showLoading();
    
    // Upload ke server
     this.uploadToServer(file)
        .then(serverUrl => {
            console.log('Server URL received:', serverUrl);
            
            // Insert image dengan URL lengkap
            const img = document.createElement('img');
            img.src = serverUrl;
            img.style.maxWidth = '100%';
            img.alt = 'Uploaded image';
            
            // Insert ke editor
            this.editable.focus();
            document.execCommand('insertHTML', false, img.outerHTML);
            
            this.syncToTextarea();
            this.hideLoading();
            
            console.log('Image inserted successfully');
        })
        .catch(error => {
            console.error('Upload failed:', error);
            this.hideLoading();
            
            // Fallback ke base64
            this.fallbackToBase64(file);
        });
}

// Tambahkan fallback method
fallbackToBase64(file) {
    const reader = new FileReader();
    reader.onload = (e) => {
        const base64Url = e.target.result;
        const img = document.createElement('img');
        img.src = base64Url;
        img.style.maxWidth = '100%';
        img.alt = 'Local image preview';
        
        this.editable.focus();
        document.execCommand('insertHTML', false, img.outerHTML);
        this.syncToTextarea();
        
        alert('NOTE: Gambar disimpan sebagai base64 (hanya sementara). Untuk penyimpanan permanen, pastikan upload_image.php bekerja.');
    };
    reader.onerror = () => {
        alert('Error membaca file gambar!');
    };
    reader.readAsDataURL(file);
}

    // Ganti method uploadToServer di class RichTextEditor dan MiniRichTextEditor
    uploadToServer(file) {
    return new Promise((resolve, reject) => {
        const formData = new FormData();
        formData.append('image', file);
        
        console.log('Starting upload...', file.name);
        
        // Gunakan URL absolut ke upload_image.php di folder admin
        const currentPath = window.location.pathname;
        let uploadUrl;
        
        if (currentPath.includes('/admin/')) {
            // Jika sudah di folder admin
            uploadUrl = window.location.origin + currentPath.replace(/\/[^\/]*$/, '/upload_image.php');
        } else {
            // Jika di folder lain (penguji), arahkan ke folder admin
            uploadUrl = window.location.origin + currentPath.replace(/\/[^\/]*$/, '/admin/upload_image.php');
        }
        
        console.log('Upload URL:', uploadUrl);
        
        fetch(uploadUrl, {
            method: 'POST',
            body: formData,
            credentials: 'same-origin'
        })
        .then(response => {
            console.log('Upload response status:', response.status);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('Upload response data:', data);
            if (data.success) {
                resolve(data.url);
            } else {
                reject(data.error || 'Upload failed');
            }
        })
        .catch(error => {
            console.error('Upload error:', error);
            reject('Upload failed: ' + error.message);
        });
    });
}

    showLoading() {
        // Tambahkan loading indicator
        const loading = document.createElement('div');
        loading.className = 'editor-loading';
        loading.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Mengupload gambar...';
        loading.style.cssText = `
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0,0,0,0.8);
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            z-index: 1000;
        `;
        
        this.container.style.position = 'relative';
        this.container.appendChild(loading);
    }

    hideLoading() {
        const loading = this.container.querySelector('.editor-loading');
        if (loading) {
            loading.remove();
        }
    }

    increaseFontSize() {
        this.changeFontSize(1);
    }

    decreaseFontSize() {
        this.changeFontSize(-1);
    }

    changeFontSize(direction) {
        const currentSize = this.getCurrentFontSize();
        let newSize;
        
        if (currentSize === '') {
            newSize = direction > 0 ? '4' : '2';
        } else {
            const sizeNum = parseInt(currentSize);
            newSize = Math.max(1, Math.min(7, sizeNum + direction)).toString();
        }
        
        this.setFontSize(newSize);
    }

    getCurrentFontSize() {
        const selection = window.getSelection();
        if (selection.rangeCount === 0) return '';
        
        const node = selection.getRangeAt(0).startContainer;
        const element = node.nodeType === 3 ? node.parentElement : node;
        
        if (element && element.style.fontSize) {
            const match = element.style.fontSize.match(/(\d+)/);
            return match ? match[1] : '';
        }
        
        // Check parent elements
        let parent = element;
        while (parent && parent !== this.editable) {
            if (parent.style && parent.style.fontSize) {
                const match = parent.style.fontSize.match(/(\d+)/);
                return match ? match[1] : '';
            }
            parent = parent.parentElement;
        }
        
        return '';
    }

    setFontSize(size) {
        // Map size number to actual font size
        const sizeMap = {
            '1': '8px',
            '2': '10px',
            '3': '12px',
            '4': '14px',
            '5': '18px',
            '6': '24px',
            '7': '36px'
        };
        
        const fontSize = sizeMap[size] || '14px';
        document.execCommand('fontSize', false, size);
        
        // Apply actual font size
        const selection = window.getSelection();
        if (selection.rangeCount > 0) {
            const range = selection.getRangeAt(0);
            const span = document.createElement('span');
            span.style.fontSize = fontSize;
            
            if (range.collapsed) {
                // Insert at cursor position
                range.insertNode(span);
                range.setStartAfter(span);
                range.setEndAfter(span);
                selection.removeAllRanges();
                selection.addRange(range);
            } else {
                // Wrap selected text
                range.surroundContents(span);
            }
        }
        
        this.syncToTextarea();
    }
}



// PERBAIKI class MiniRichTextEditor - tambahkan method yang lengkap
class MiniRichTextEditor {
    constructor(container) {
        this.container = container;
        this.targetName = container.getAttribute('data-target');
        this.targetTextarea = this.findTargetTextarea();
        this.init();
    }

    findTargetTextarea() {
        // Cari textarea berdasarkan target name - VERSI PERBAIKAN
        if (this.targetName.includes('[]')) {
            // Untuk array fields, cari textarea dalam aspek item yang sama
            const aspekItem = this.container.closest('.aspek-item');
            if (aspekItem) {
                const textarea = aspekItem.querySelector(`textarea[name="${this.targetName}"]`);
                console.log(`MiniEditor found textarea in aspek:`, textarea);
                return textarea;
            }
            return null;
        } else {
            return document.getElementById(this.targetName);
        }
    }

    init() {
        // Create mini toolbar dengan tombol checklist helper
        const toolbar = document.createElement('div');
        toolbar.className = 'mini-toolbar';
        toolbar.innerHTML = `
            <div class="font-size-controls">
                <button type="button" class="toolbar-btn" data-command="decreaseFontSize" title="Perkecil Font">
                    <i class="fas fa-minus"></i>
                </button>
                <button type="button" class="toolbar-btn" data-command="increaseFontSize" title="Perbesar Font">
                    <i class="fas fa-plus"></i>
                </button>
                <select class="font-size-select" title="Ukuran Font">
                    <option value="">Font</option>
                    <option value="1">XS</option>
                    <option value="2">S</option>
                    <option value="3">M</option>
                    <option value="4">L</option>
                    <option value="5">XL</option>
                </select>
            </div>
            <button type="button" class="toolbar-btn" data-command="bold" title="Bold"><i class="fas fa-bold"></i></button>
            <button type="button" class="toolbar-btn" data-command="italic" title="Italic"><i class="fas fa-italic"></i></button>
            <button type="button" class="toolbar-btn" data-command="underline" title="Underline"><i class="fas fa-underline"></i></button>
            <button type="button" class="toolbar-btn" data-command="insertUnorderedList" title="Bullet List"><i class="fas fa-list-ul"></i></button>
            <button type="button" class="toolbar-btn" data-command="insertOrderedList" title="Numbered List"><i class="fas fa-list-ol"></i></button>
            <!-- TAMBAHKAN TOMBOL CHECKLIST HELPER DI SINI -->
            <div class="checklist-helper-dropdown">
                <button type="button" class="toolbar-btn checklist-helper-btn" title="Template Checklist Helper">
                    <i class="fas fa-tasks"></i>
                </button>
                <div class="checklist-helper-menu">
                    <button type="button" class="checklist-template-btn" data-template="alat-bahan">
                        <i class="fas fa-tools"></i> Alat & Bahan
                    </button>
                    <button type="button" class="checklist-template-btn" data-template="prosedur">
                        <i class="fas fa-list-ol"></i> Prosedur
                    </button>
                    <button type="button" class="checklist-template-btn" data-template="verifikasi">
                        <i class="fas fa-check-circle"></i> Verifikasi
                    </button>
                    <button type="button" class="checklist-template-btn" data-template="custom">
                        <i class="fas fa-edit"></i> Custom
                    </button>
                </div>
            </div>
            <button type="button" class="toolbar-btn" data-command="insertChecklistItem" title="Tambah Item Checklist">
                <i class="fas fa-check-square"></i>
            </button>
            <button type="button" class="toolbar-btn" data-command="insertImage" title="Insert Image from URL"><i class="fas fa-image"></i></button>
            <button type="button" class="toolbar-btn" data-command="uploadImage" title="Upload Image"><i class="fas fa-upload"></i></button>
        `;

       // Create editable div
        const editable = document.createElement('div');
        editable.className = 'editor-content mini-editor-content';
        editable.contentEditable = true;
        
        // Set initial content
        if (this.targetTextarea && this.targetTextarea.value) {
            editable.innerHTML = this.targetTextarea.value;
        }

        // Insert elements
        this.container.innerHTML = '';
        this.container.appendChild(toolbar);
        this.container.appendChild(editable);

        this.editable = editable;
        this.setupEventListeners();
        this.setupChecklistHelperDropdown();
        
        // Initial sync
        this.syncToTextarea();
    }

      setupEventListeners() {
        // Toolbar buttons
        this.container.querySelectorAll('.toolbar-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                const command = btn.getAttribute('data-command');
                
                if (command === 'insertImage') {
                    this.insertImage();
                } else if (command === 'uploadImage') {
                    this.uploadImage();
                } else if (command === 'increaseFontSize') {
                    this.increaseFontSize();
                } else if (command === 'decreaseFontSize') {
                    this.decreaseFontSize();
                } else if (command === 'insertChecklistItem') {
                    this.insertChecklistItem();
                } else {
                    document.execCommand(command, false, null);
                }
                this.editable.focus();
                this.syncToTextarea();
            });
        });

        // Font size select change
        const fontSizeSelect = this.container.querySelector('.font-size-select');
        if (fontSizeSelect) {
            fontSizeSelect.addEventListener('change', (e) => {
                const size = e.target.value;
                if (size) {
                    this.setFontSize(size);
                }
                this.editable.focus();
                this.syncToTextarea();
            });
        }

        

        // Update textarea on input
        this.editable.addEventListener('input', () => {
            this.syncToTextarea();
        });

        // Sync on blur
        this.editable.addEventListener('blur', () => {
            this.syncToTextarea();
        });

        // Handle paste event
        this.editable.addEventListener('paste', (e) => {
            e.preventDefault();
            const text = (e.clipboardData || window.clipboardData).getData('text/plain');
            document.execCommand('insertText', false, text);
            this.syncToTextarea();
        });

        // Handle paste images
        this.editable.addEventListener('paste', (e) => {
            const items = (e.clipboardData || e.originalEvent.clipboardData).items;
            
            for (let item of items) {
                if (item.type.indexOf('image') !== -1) {
                    e.preventDefault();
                    const file = item.getAsFile();
                    this.handleImageUpload(file);
                    break;
                }
            }
        });

        // Handle paste images
        this.editable.addEventListener('paste', (e) => {
            const items = (e.clipboardData || e.originalEvent.clipboardData).items;
            
            for (let item of items) {
                if (item.type.indexOf('image') !== -1) {
                    e.preventDefault();
                    const file = item.getAsFile();
                    this.handleImageUpload(file);
                    break;
                }
            }
        });

         // Handle drop images
        this.editable.addEventListener('drop', (e) => {
            e.preventDefault();
            const files = e.dataTransfer.files;
            
            for (let file of files) {
                if (file.type.indexOf('image') !== -1) {
                    this.handleImageUpload(file);
                    break;
                }
            }
        });

        this.editable.addEventListener('dragover', (e) => {
            e.preventDefault();
        });
    }

    

    syncToTextarea() {
        if (this.targetTextarea) {
            this.targetTextarea.value = this.editable.innerHTML;
            console.log('MiniEditor sync:', this.targetName, this.targetTextarea.value.substring(0, 100));
        }
    }

    insertImage() {
        const url = prompt('Masukkan URL gambar:');
        if (url) {
            const img = document.createElement('img');
            img.src = url;
            img.style.maxWidth = '100%';
            this.editable.focus();
            document.execCommand('insertHTML', false, img.outerHTML);
            this.syncToTextarea();
        }
    }

    uploadImage() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/*';
        
        input.onchange = (e) => {
            const file = e.target.files[0];
            if (file) {
                this.handleImageUpload(file);
            }
        };
        
        input.click();
    }

   // TAMBAHKAN METHOD UNTUK CHECKLIST HELPER DROPDOWN
    setupChecklistHelperDropdown() {
        const dropdown = this.container.querySelector('.checklist-helper-dropdown');
        const menu = this.container.querySelector('.checklist-helper-menu');
        const templateButtons = this.container.querySelectorAll('.checklist-template-btn');
        
        if (dropdown && menu) {
            // Toggle dropdown
            const toggleBtn = dropdown.querySelector('.checklist-helper-btn');
            toggleBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                menu.style.display = menu.style.display === 'block' ? 'none' : 'block';
            });
            
            // Close dropdown when clicking outside
            document.addEventListener('click', (e) => {
                if (!dropdown.contains(e.target)) {
                    menu.style.display = 'none';
                }
            });
            
            // Template buttons
            templateButtons.forEach(btn => {
                btn.addEventListener('click', (e) => {
                    e.preventDefault();
                    const template = btn.getAttribute('data-template');
                    this.insertChecklistTemplate(template);
                    menu.style.display = 'none';
                });
            });
        }
    }
    
    // TAMBAHKAN METHOD UNTUK INSERT CHECKLIST TEMPLATE
    insertChecklistTemplate(templateType) {
        let checklistHTML = '';
        
        switch(templateType) {
            case 'alat-bahan':
                checklistHTML = `
                    <div class="checklist-helper" data-type="alat-bahan">
                        <div class="checklist-header">
                            <strong><i class="fas fa-tools"></i> Checklist Alat & Bahan:</strong>
                            <small style="color: #666; font-size: 12px; margin-left: 10px;">
                                (Hanya untuk verifikasi penguji)
                            </small>
                        </div>
                        <div class="checklist-items">
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Diagnostik kit</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Occlusal biterim</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Occlusal bite plane</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Sliding caliper</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Spidol</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Benang</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Gunting</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Spirtus dan korek</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Lecron</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>KAPI</label>
                            </div>
                        </div>
                        <div class="checklist-note">
                            <small style="color: #dc3545; font-style: italic;">
                                <i class="fas fa-info-circle"></i> Checklist ini hanya alat bantu penguji, tidak mempengaruhi nilai
                            </small>
                        </div>
                    </div>
                `;
                break;
                
            case 'prosedur':
                checklistHTML = `
                    <div class="checklist-helper" data-type="prosedur">
                        <div class="checklist-header">
                            <strong><i class="fas fa-list-ol"></i> Checklist Prosedur:</strong>
                        </div>
                        <div class="checklist-items">
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Persiapan alat dan bahan</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Penjelasan prosedur kepada pasien</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Pemeriksaan awal</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Pelaksanaan tindakan</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Evaluasi hasil</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Dokumentasi</label>
                            </div>
                        </div>
                    </div>
                `;
                break;
                
            case 'verifikasi':
                checklistHTML = `
                    <div class="checklist-helper" data-type="verifikasi">
                        <div class="checklist-header">
                            <strong><i class="fas fa-check-circle"></i> Checklist Verifikasi:</strong>
                        </div>
                        <div class="checklist-items">
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Teknik benar</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Urutan tepat</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Waktu sesuai</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Hasil akurat</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Komunikasi baik</label>
                            </div>
                        </div>
                    </div>
                `;
                break;
                
            case 'custom':
                checklistHTML = `
                    <div class="checklist-helper" data-type="custom">
                        <div class="checklist-header">
                            <strong><i class="fas fa-edit"></i> Checklist Custom:</strong>
                        </div>
                        <div class="checklist-items">
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Item 1</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Item 2</label>
                            </div>
                            <div class="checklist-item-helper">
                                <input type="checkbox" class="checklist-checkbox-helper">
                                <label>Item 3</label>
                            </div>
                        </div>
                    </div>
                `;
                break;
        }
        
        this.editable.focus();
        document.execCommand('insertHTML', false, checklistHTML);
        this.syncToTextarea();
    }

     // TAMBAHKAN METHOD INSERT CHECKLIST ITEM
    insertChecklistItem() {
        // Cek apakah sudah ada checklist container
        let checklistContainer = this.editable.querySelector('.checklist-helper');
        
        if (!checklistContainer) {
            // Buat checklist container baru
            const newChecklist = `
                <div class="checklist-helper" data-type="manual">
                    <div class="checklist-header">
                        <strong><i class="fas fa-tasks"></i> Checklist:</strong>
                    </div>
                    <div class="checklist-items">
                        <div class="checklist-item-helper">
                            <input type="checkbox" class="checklist-checkbox-helper">
                            <label>Item checklist</label>
                        </div>
                    </div>
                </div>
            `;
            
            this.editable.focus();
            document.execCommand('insertHTML', false, newChecklist);
        } else {
            // Tambahkan item ke checklist yang sudah ada
            const checklistItems = checklistContainer.querySelector('.checklist-items');
            if (checklistItems) {
                const newItem = document.createElement('div');
                newItem.className = 'checklist-item-helper';
                newItem.innerHTML = `
                    <input type="checkbox" class="checklist-checkbox-helper">
                    <label>Item checklist baru</label>
                `;
                checklistItems.appendChild(newItem);
            }
        }
        
        this.syncToTextarea();
    }

    syncToTextarea() {
        if (this.targetTextarea) {
            this.targetTextarea.value = this.editable.innerHTML;
            console.log('MiniEditor sync:', this.targetName, this.targetTextarea.value.substring(0, 100));
        }
    }

    // TAMBAHKAN method handleImageUpload yang lengkap
    handleImageUpload(file) {
    console.log('MiniEditor handling image upload:', file.name);
    
    // Show loading
    const originalContent = this.editable.innerHTML;
    this.editable.innerHTML = '<div style="text-align: center; padding: 10px; color: #666;"><i class="fas fa-spinner fa-spin"></i> Mengupload gambar...</div>';
    
    this.uploadToServer(file)
        .then(serverUrl => {
            console.log('MiniEditor upload success:', serverUrl);
            this.editable.innerHTML = originalContent;
            
            // Insert image dengan URL lengkap
            const img = document.createElement('img');
            img.src = serverUrl;
            img.style.maxWidth = '100%';
            img.alt = 'Uploaded image';
            
            this.editable.focus();
            document.execCommand('insertHTML', false, img.outerHTML);
            this.syncToTextarea();
            
            // Force sync untuk memastikan data tersimpan
            setTimeout(() => {
                this.syncToTextarea();
            }, 100);
        })
        .catch(error => {
            console.error('MiniEditor upload failed:', error);
            this.editable.innerHTML = originalContent;
            this.fallbackToBase64(file);
        });
}


    // TAMBAHKAN method uploadToServer
    uploadToServer(file) {
    return new Promise((resolve, reject) => {
        const formData = new FormData();
        formData.append('image', file);
        
        console.log('Starting upload...', file.name);
        
        // Gunakan URL absolut ke upload_image.php di folder admin
        const currentPath = window.location.pathname;
        let uploadUrl;
        
        if (currentPath.includes('/admin/')) {
            // Jika sudah di folder admin
            uploadUrl = window.location.origin + currentPath.replace(/\/[^\/]*$/, '/upload_image.php');
        } else {
            // Jika di folder lain (penguji), arahkan ke folder admin
            uploadUrl = window.location.origin + currentPath.replace(/\/[^\/]*$/, '/admin/upload_image.php');
        }
        
        console.log('Upload URL:', uploadUrl);
        
        fetch(uploadUrl, {
            method: 'POST',
            body: formData,
            credentials: 'same-origin'
        })
        .then(response => {
            console.log('Upload response status:', response.status);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('Upload response data:', data);
            if (data.success) {
                resolve(data.url);
            } else {
                reject(data.error || 'Upload failed');
            }
        })
        .catch(error => {
            console.error('Upload error:', error);
            reject('Upload failed: ' + error.message);
        });
    });
}

    // TAMBAHKAN method fallbackToBase64
    fallbackToBase64(file) {
        const reader = new FileReader();
        reader.onload = (e) => {
            const base64Url = e.target.result;
            const img = document.createElement('img');
            img.src = base64Url;
            img.style.maxWidth = '100%';
            img.alt = 'Local image preview';
            
            this.editable.focus();
            document.execCommand('insertHTML', false, img.outerHTML);
            this.syncToTextarea();
            
            alert('NOTE: Gambar disimpan sebagai base64 (hanya sementara).');
        };
        reader.onerror = () => {
            alert('Error membaca file gambar!');
        };
        reader.readAsDataURL(file);
    }

    // Tambahkan method untuk mengatur ukuran font (sama seperti RichTextEditor)
    increaseFontSize() {
        this.changeFontSize(1);
    }

    decreaseFontSize() {
        this.changeFontSize(-1);
    }

    changeFontSize(direction) {
        const currentSize = this.getCurrentFontSize();
        let newSize;
        
        if (currentSize === '') {
            newSize = direction > 0 ? '4' : '2';
        } else {
            const sizeNum = parseInt(currentSize);
            newSize = Math.max(1, Math.min(7, sizeNum + direction)).toString();
        }
        
        this.setFontSize(newSize);
    }

    getCurrentFontSize() {
        const selection = window.getSelection();
        if (selection.rangeCount === 0) return '';
        
        const node = selection.getRangeAt(0).startContainer;
        const element = node.nodeType === 3 ? node.parentElement : node;
        
        if (element && element.style.fontSize) {
            const match = element.style.fontSize.match(/(\d+)/);
            return match ? match[1] : '';
        }
        
        let parent = element;
        while (parent && parent !== this.editable) {
            if (parent.style && parent.style.fontSize) {
                const match = parent.style.fontSize.match(/(\d+)/);
                return match ? match[1] : '';
            }
            parent = parent.parentElement;
        }
        
        return '';
    }

    setFontSize(size) {
        const sizeMap = {
            '1': '8px',
            '2': '10px',
            '3': '12px',
            '4': '14px',
            '5': '18px',
            '6': '24px',
            '7': '36px'
        };
        
        const fontSize = sizeMap[size] || '14px';
        document.execCommand('fontSize', false, size);
        
        const selection = window.getSelection();
        if (selection.rangeCount > 0) {
            const range = selection.getRangeAt(0);
            const span = document.createElement('span');
            span.style.fontSize = fontSize;
            
            if (range.collapsed) {
                range.insertNode(span);
                range.setStartAfter(span);
                range.setEndAfter(span);
                selection.removeAllRanges();
                selection.addRange(range);
            } else {
                range.surroundContents(span);
            }
        }
        
        this.syncToTextarea();
    }
}

// Aspek Penilaian Management
class AspekManager {
    constructor() {
        this.container = document.getElementById('aspekContainer');
        this.template = document.getElementById('aspekTemplate');
        this.aspekCount = 0;
        this.maxAspek = 40;
        
        console.log('AspekManager initialized:', {
            container: this.container,
            template: this.template,
            aspekCount: this.aspekCount
        });
        
        this.init();
    }

    init() {
        console.log('AspekManager init started'); // Debug log
        
        // Add first aspek
        this.tambahAspek();

        // Event listener for tambah aspek button
        const tambahButton = document.getElementById('tambahAspek');
        if (tambahButton) {
            tambahButton.addEventListener('click', () => {
                console.log('Tambah aspek clicked'); // Debug log
                this.tambahAspek();
            });
        } else {
            console.error('Tombol tambahAspek tidak ditemukan!');
        }

        // Initialize counter display
        this.updateCounterDisplay();
    }

    tambahAspek() {
    console.log('tambahAspek called, current count:', this.aspekCount);
    
    if (this.aspekCount >= this.maxAspek) {
        alert(`Maksimal ${this.maxAspek} aspek penilaian!`);
        return;
    }

    this.aspekCount++;
    const aspekElement = this.createAspekElement();
    
    if (this.container && aspekElement) {
        this.container.appendChild(aspekElement);
        
        // Initialize rich text editors untuk aspek ini - dengan delay lebih lama
        setTimeout(() => {
            this.initRichTextEditorsForAspek(aspekElement);
        }, 300);

        // Setup skor checkbox event listeners - dengan delay
        setTimeout(() => {
            this.setupSkorCheckboxes(aspekElement);
        }, 400);

        this.updateAspekNumbers();
        this.updateNomorUrut();
        this.updateCounterDisplay();
        this.updateTambahButton();
        
        console.log('Aspek berhasil ditambahkan, total:', this.aspekCount);
    } else {
        console.error('Container aspek tidak ditemukan atau elemen aspek null!');
    }
}

    setupChecklistHelper(aspekElement) {
    const checklistToggle = aspekElement.querySelector('.has-checklist-checkbox');
    const checklistContainer = aspekElement.querySelector('.checklist-helper-container');
    const checklistTextarea = aspekElement.querySelector('.checklist-items-textarea');
    
    console.log('Setting up checklist helper:', {
        toggle: checklistToggle,
        container: checklistContainer,
        textarea: checklistTextarea
    });
    
    if (checklistToggle && checklistContainer) {
        // Toggle visibility
        checklistToggle.addEventListener('change', (e) => {
            console.log('Checklist toggle changed:', e.target.checked);
            if (e.target.checked) {
                checklistContainer.style.display = 'block';
            } else {
                checklistContainer.style.display = 'none';
            }
        });
        
        // Initial state
        if (checklistToggle.checked) {
            checklistContainer.style.display = 'block';
        }
    }
}

    setupChecklistToggle(aspekElement) {
    const checklistCheckbox = aspekElement.querySelector('.has-checklist-checkbox');
    const checklistContainer = aspekElement.querySelector('.checklist-verifikasi-container');
    
    if (checklistCheckbox && checklistContainer) {
        checklistCheckbox.addEventListener('change', (e) => {
            checklistContainer.style.display = e.target.checked ? 'block' : 'none';
        });
    }
}

    createAspekElement() {
        if (!this.template) {
            console.error('Template aspek tidak ditemukan!');
            // Fallback: create basic aspek element manually
            return this.createFallbackAspekElement();
        }

        const templateContent = this.template.innerHTML;
        console.log('Template content:', templateContent.substring(0, 100) + '...'); // Debug log
        
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = templateContent;
        
        const aspekElement = tempDiv.firstElementChild;
        
        if (!aspekElement) {
            console.error('Gagal membuat elemen aspek dari template!');
            return this.createFallbackAspekElement();
        }
        
        // Set nomor urut
        const nomorUrutInput = aspekElement.querySelector('.nomor-urut');
        if (nomorUrutInput) {
            nomorUrutInput.value = this.aspekCount;
        }
        
        // Update aspek number display
        const aspekNumber = aspekElement.querySelector('.aspek-number');
        if (aspekNumber) {
            aspekNumber.textContent = this.aspekCount;
        }
        
        // Add event listener for delete button
        const hapusButton = aspekElement.querySelector('.hapus-aspek');
        if (hapusButton) {
            hapusButton.addEventListener('click', () => {
                this.hapusAspek(aspekElement);
            });
        }
        
        // Add event listener for duplicate button
        const duplicateButton = aspekElement.querySelector('.duplicate-aspek');
        if (duplicateButton) {
            duplicateButton.addEventListener('click', () => {
                this.duplikatAspek(aspekElement);
            });
        }

        
    setTimeout(() => {
        this.setupChecklistHelper(aspekElement);
    }, 100);
    
    return aspekElement;
}

    createAspekElement() {
        if (!this.template) {
            console.error('Template aspek tidak ditemukan!');
            // Fallback: create basic aspek element manually
            return this.createFallbackAspekElement();
        }

        const templateContent = this.template.innerHTML;
        console.log('Template content:', templateContent.substring(0, 100) + '...'); // Debug log
        
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = templateContent;
        
        const aspekElement = tempDiv.firstElementChild;
        
        if (!aspekElement) {
            console.error('Gagal membuat elemen aspek dari template!');
            return this.createFallbackAspekElement();
        }
        
        // Set nomor urut
        const nomorUrutInput = aspekElement.querySelector('.nomor-urut');
        if (nomorUrutInput) {
            nomorUrutInput.value = this.aspekCount;
        }
        
        // Update aspek number display
        const aspekNumber = aspekElement.querySelector('.aspek-number');
        if (aspekNumber) {
            aspekNumber.textContent = this.aspekCount;
        }
        
        // Add event listener for delete button
        const hapusButton = aspekElement.querySelector('.hapus-aspek');
        if (hapusButton) {
            hapusButton.addEventListener('click', () => {
                this.hapusAspek(aspekElement);
            });
        }
        
        // Add event listener for duplicate button
        const duplicateButton = aspekElement.querySelector('.duplicate-aspek');
        if (duplicateButton) {
            duplicateButton.addEventListener('click', () => {
                this.duplikatAspek(aspekElement);
            });
        }

        // Setup skor checkboxes setelah elemen dibuat
    setTimeout(() => {
        this.setupSkorCheckboxes(aspekElement);
    }, 100);

        return aspekElement;
    }

    // Fallback method jika template tidak bekerja
    createFallbackAspekElement() {
        console.log('Creating fallback aspek element');
        
        const aspekElement = document.createElement('div');
        aspekElement.className = 'aspek-item';
        aspekElement.innerHTML = `
            <div class="aspek-header">
                <h5>Aspek Penilaian <span class="aspek-number">${this.aspekCount}</span></h5>
                <button type="button" class="btn btn-danger btn-sm hapus-aspek" title="Hapus aspek ini">
                    <i class="fas fa-trash"></i> Hapus
                </button>
            </div>
            
            <div class="form-group">
                <label>Nomor Urut:</label>
                <input type="number" name="nomor_urut[]" class="nomor-urut" min="1" value="${this.aspekCount}" required>
                <small class="form-hint">Urutan penampilan aspek penilaian</small>
            </div>

            <div class="form-group">
                <label>Nama Aspek:</label>
                <div class="mini-editor nama-aspek-editor with-image" data-target="aspek_nama[]"></div>
                <textarea name="aspek_nama[]" style="display: none;"></textarea>
            </div>
            
            <div class="skor-options">
                <label>Pilih Skor yang Tersedia:</label>
                <div class="checkbox-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="skor_0[]" value="1" checked> 
                        <span class="skor-badge skor-0-badge">Skor 0</span>
                    </label>
                    <label class="checkbox-label">
                        <input type="checkbox" name="skor_1[]" value="1" checked> 
                        <span class="skor-badge skor-1-badge">Skor 1</span>
                    </label>
                    <label class="checkbox-label">
                        <input type="checkbox" name="skor_2[]" value="1" checked> 
                        <span class="skor-badge skor-2-badge">Skor 2</span>
                    </label>
                </div>
                <small class="form-hint">Pilih skor yang akan digunakan untuk aspek ini</small>
            </div>
            
            <div class="skor-description">
                <div class="skor-item skor-0">
                    <label>
                        <span class="skor-badge skor-0-badge">Deskripsi Skor 0</span>
                    </label>
                    <div class="mini-editor" data-target="deskripsi_0[]"></div>
                    <textarea name="deskripsi_0[]" style="display: none;"></textarea>
                </div>
                
                <div class="skor-item skor-1">
                    <label>
                        <span class="skor-badge skor-1-badge">Deskripsi Skor 1</span>
                    </label>
                    <div class="mini-editor" data-target="deskripsi_1[]"></div>
                    <textarea name="deskripsi_1[]" style="display: none;"></textarea>
                </div>
                
                <div class="skor-item skor-2">
                    <label>
                        <span class="skor-badge skor-2-badge">Deskripsi Skor 2</span>
                    </label>
                    <div class="mini-editor" data-target="deskripsi_2[]"></div>
                    <textarea name="deskripsi_2[]" style="display: none;"></textarea>
                </div>
            </div>
            
            <div class="aspek-actions">
                <button type="button" class="btn btn-secondary btn-sm duplicate-aspek" title="Duplikat aspek ini">
                    <i class="fas fa-copy"></i> Duplikat
                </button>
            </div>
        `;
        
        // Add event listeners
        const hapusButton = aspekElement.querySelector('.hapus-aspek');
        if (hapusButton) {
            hapusButton.addEventListener('click', () => {
                this.hapusAspek(aspekElement);
            });
        }
        
        const duplicateButton = aspekElement.querySelector('.duplicate-aspek');
        if (duplicateButton) {
            duplicateButton.addEventListener('click', () => {
                this.duplikatAspek(aspekElement);
            });
        }

        return aspekElement;
    }

    initRichTextEditorsForAspek(aspekElement) {
        console.log('Initializing editors for aspek element');

        // Tunggu sedikit lebih lama untuk memastikan DOM siap
    setTimeout(() => {
        // Inisialisasi rich text editor untuk nama aspek
        const namaAspekEditor = aspekElement.querySelector('.nama-aspek-editor');
        if (namaAspekEditor && !namaAspekEditor.classList.contains('initialized')) {
            console.log('Found nama aspek editor, initializing...');
            try {
                new MiniRichTextEditor(namaAspekEditor);
                namaAspekEditor.classList.add('initialized');
            } catch (error) {
                console.error('Error initializing nama aspek editor:', error);
            }
        } else {
            console.log('Nama aspek editor not found or already initialized!');
        }

        // Inisialisasi rich text editor untuk deskripsi skor
        const skorEditors = aspekElement.querySelectorAll('.mini-editor:not(.nama-aspek-editor)');
        console.log('Found skor editors:', skorEditors.length);
        
        skorEditors.forEach((editor, index) => {
            if (!editor.classList.contains('initialized')) {
                console.log(`Initializing skor editor ${index + 1}`);
                try {
                    new MiniRichTextEditor(editor);
                    editor.classList.add('initialized');
                } catch (error) {
                    console.error(`Error initializing skor editor ${index + 1}:`, error);
                }
            }
        });
    }, 200); // Increase delay to 200ms
}

    hapusAspek(aspekElement) {
        if (this.container.children.length > 1) {
            aspekElement.remove();
            this.aspekCount--;
            this.updateAspekNumbers();
            this.updateNomorUrut();
            this.updateCounterDisplay();
            this.updateTambahButton();
        } else {
            alert('Minimal harus ada satu aspek penilaian!');
        }
    }

    duplikatAspek(sourceElement) {
    if (this.aspekCount >= this.maxAspek) {
        alert(`Maksimal ${this.maxAspek} aspek penilaian!`);
        return;
    }

    this.aspekCount++;
    const duplicatedElement = this.createDuplicatedAspek(sourceElement);
    
    if (this.container && duplicatedElement) {
        this.container.appendChild(duplicatedElement);
        
        // Initialize rich text editors untuk aspek duplikat
        setTimeout(() => {
            this.initRichTextEditorsForAspek(duplicatedElement);
        }, 300);

        // Setup skor checkbox event listeners - dengan delay
        setTimeout(() => {
            this.setupSkorCheckboxes(duplicatedElement);
        }, 400);

        this.updateAspekNumbers();
        this.updateNomorUrut();
        this.updateCounterDisplay();
        this.updateTambahButton();
        
        // Add animation
        duplicatedElement.classList.add('new-aspek');
        setTimeout(() => {
            if (duplicatedElement.classList) {
                duplicatedElement.classList.remove('new-aspek');
            }
        }, 300);
    }
}

    createDuplicatedAspek(sourceElement) {
    if (!this.template) {
        console.error('Template aspek tidak ditemukan!');
        return null;
    }

    const template = this.template.innerHTML;
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = template;
    
    const duplicatedElement = tempDiv.firstElementChild;
    
    if (!duplicatedElement) {
        console.error('Gagal membuat elemen aspek duplikat dari template!');
        return null;
    }
    
    // Copy values from source element
    const sourceNomorUrut = sourceElement.querySelector('.nomor-urut');
    const sourceAspekNamaEditor = sourceElement.querySelector('.nama-aspek-editor .editor-content');
    const sourceCheckboxes = sourceElement.querySelectorAll('input[type="checkbox"][name^="skor_"]');
    
    // Get deskripsi skor values dari source
    const sourceDeskripsiEditors = sourceElement.querySelectorAll('.mini-editor:not(.nama-aspek-editor) .editor-content');
    
    // Set values in duplicated element
    const dupNomorUrut = duplicatedElement.querySelector('.nomor-urut');
    const dupAspekNamaEditor = duplicatedElement.querySelector('.nama-aspek-editor .editor-content');
    const dupCheckboxes = duplicatedElement.querySelectorAll('input[type="checkbox"][name^="skor_"]');
    const dupDeskripsiEditors = duplicatedElement.querySelectorAll('.mini-editor:not(.nama-aspek-editor) .editor-content');
    
    if (dupNomorUrut) {
        dupNomorUrut.value = this.aspekCount;
    }
    
    // Copy nama aspek content
    if (dupAspekNamaEditor && sourceAspekNamaEditor) {
        dupAspekNamaEditor.innerHTML = sourceAspekNamaEditor.innerHTML + " (Salinan)";
    }
    
    // Copy checkbox states dan pastikan value konsisten
    if (sourceCheckboxes && dupCheckboxes) {
        sourceCheckboxes.forEach((checkbox, index) => {
            if (dupCheckboxes[index]) {
                dupCheckboxes[index].checked = checkbox.checked;
                // Pastikan value sesuai dengan checked state
                dupCheckboxes[index].value = checkbox.checked ? '1' : '0';
            }
        });
    }
    
    // Copy deskripsi skor content
    if (sourceDeskripsiEditors && dupDeskripsiEditors) {
        sourceDeskripsiEditors.forEach((editor, index) => {
            if (dupDeskripsiEditors[index]) {
                dupDeskripsiEditors[index].innerHTML = editor.innerHTML;
            }
        });
    }
    
    // Add event listener for delete button
    const hapusButton = duplicatedElement.querySelector('.hapus-aspek');
    if (hapusButton) {
        hapusButton.addEventListener('click', () => {
            this.hapusAspek(duplicatedElement);
        });
    }
    
    // Add event listener for duplicate button
    const duplicateButton = duplicatedElement.querySelector('.duplicate-aspek');
    if (duplicateButton) {
        duplicateButton.addEventListener('click', () => {
            this.duplikatAspek(duplicatedElement);
        });
    }

    return duplicatedElement;
}

    setupSkorCheckboxes(aspekElement) {
    const checkboxes = aspekElement.querySelectorAll('input[type="checkbox"][name^="skor_"]');
    
    checkboxes.forEach(checkbox => {
        // Dapatkan nilai skor dari nama checkbox
        const skorMatch = checkbox.name.match(/skor_(\d+)\[\]/);
        
        if (skorMatch) {
            const skorValue = skorMatch[1];
            const skorItem = aspekElement.querySelector(`.skor-${skorValue}`);
            
            if (skorItem) {
                // Set initial visibility berdasarkan checked state
                if (checkbox.checked) {
                    skorItem.style.display = 'block';
                } else {
                    skorItem.style.display = 'none';
                }
                
                // Add change event listener
                checkbox.addEventListener('change', (e) => {
                    console.log(`Skor ${skorValue} checkbox changed:`, e.target.checked);
                    
                    if (e.target.checked) {
                        skorItem.style.display = 'block';
                    } else {
                        skorItem.style.display = 'none';
                    }
                    
                    // Force update form data
                    this.forceUpdateSkorData(aspekElement);
                });
            }
        }
    });
    
    // Initial force update
    this.forceUpdateSkorData(aspekElement);
}

// Tambahkan method baru untuk memastikan data skor tersimpan
forceUpdateSkorData(aspekElement) {
    const checkboxes = aspekElement.querySelectorAll('input[type="checkbox"][name^="skor_"]');
    
    checkboxes.forEach(checkbox => {
        // Pastikan value selalu 1 untuk checked, 0 untuk unchecked
        if (checkbox.checked) {
            checkbox.value = '1';
        } else {
            checkbox.value = '0';
        }
    });
    
    console.log('Skor data force updated for aspek');
}

    updateAspekNumbers() {
        const aspekItems = this.container.querySelectorAll('.aspek-item');
        aspekItems.forEach((item, index) => {
            const aspekNumber = item.querySelector('.aspek-number');
            if (aspekNumber) {
                aspekNumber.textContent = index + 1;
            }
        });
    }

    updateNomorUrut() {
        const nomorUrutInputs = this.container.querySelectorAll('.nomor-urut');
        nomorUrutInputs.forEach((input, index) => {
            input.value = index + 1;
        });
    }

    updateCounterDisplay() {
        const countDisplay = document.getElementById('aspekCountDisplay');
        const maxDisplay = document.getElementById('maxAspekDisplay');
        
        if (countDisplay) {
            countDisplay.textContent = this.aspekCount;
        }
        if (maxDisplay) {
            maxDisplay.textContent = this.maxAspek;
        }
    }

    updateTambahButton() {
        const tambahButton = document.getElementById('tambahAspek');
        if (!tambahButton) return;
        
        const remaining = this.maxAspek - this.aspekCount;
        
        if (this.aspekCount >= this.maxAspek) {
            tambahButton.disabled = true;
            tambahButton.innerHTML = '<i class="fas fa-plus"></i> Maksimal Aspek Tercapai';
            tambahButton.style.opacity = '0.6';
        } else {
            tambahButton.disabled = false;
            tambahButton.innerHTML = `<i class="fas fa-plus"></i> Tambah Aspek (${remaining} tersedia)`;
            tambahButton.style.opacity = '1';
        }
    }
}


// Form Submission Handler
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM Content Loaded'); // Debug log
    
    // Initialize main editors
    try {
        const deskripsiEditor = document.getElementById('deskripsiEditor');
        const instruksiPesertaEditor = document.getElementById('instruksiPesertaEditor');
        const instruksiPengujiEditor = document.getElementById('instruksiPengujiEditor');
        const namaAspekEditor = document.getElementById('namaAspekEditor');
        
        if (deskripsiEditor) new RichTextEditor(deskripsiEditor);
        if (instruksiPesertaEditor) new RichTextEditor(instruksiPesertaEditor);
        if (instruksiPengujiEditor) new RichTextEditor(instruksiPengujiEditor);
        if (namaAspekEditor) new RichTextEditor(namaAspekEditor);
        
        console.log('Rich text editors initialized'); // Debug log
    } catch (error) {
        console.error('Error initializing rich text editors:', error);
    }
    
    // Initialize aspek manager
    try {
        const aspekManager = new AspekManager();
        console.log('AspekManager created successfully'); // Debug log
        
        // Simpan instance ke window untuk akses global jika diperlukan
        window.aspekManager = aspekManager;
    } catch (error) {
        console.error('Error initializing AspekManager:', error);
    }

    // Form submission handler - VERSI PERBAIKAN EXTREME
    const stationForm = document.getElementById('stationForm');
    if (stationForm) {
    stationForm.addEventListener('submit', function(e) {
        console.log('=== FORM SUBMISSION STARTED ===');
        
        // Sync all rich text editors sebelum submit
        syncAllRichTextEditorsImproved();
        
        // Force sync semua skor checkbox values
        forceSyncAllSkorCheckboxes();
        
        // Validate at least one aspek
        const aspekItems = document.querySelectorAll('.aspek-item');
        if (aspekItems.length === 0) {
            e.preventDefault();
            alert('Minimal harus ada satu aspek penilaian!');
            return;
        }

        // Validate each aspek has name and at least one skor selected
        let valid = true;
        let firstInvalidIndex = -1;
        let invalidReason = '';
        
        aspekItems.forEach((item, index) => {
            if (!valid) return;
            
            // CARI TEXTAREA DALAM ASPEK ITEM YANG SAMA
            const aspekNamaTextarea = item.querySelector('textarea[name="aspek_nama[]"]');
            const skorCheckboxes = item.querySelectorAll('input[type="checkbox"][name^="skor_"]:checked');
            
            console.log(`Validating aspek ${index + 1}:`, {
                textarea: aspekNamaTextarea,
                textareaValue: aspekNamaTextarea ? aspekNamaTextarea.value : 'null',
                hasContent: aspekNamaTextarea && aspekNamaTextarea.value.trim() !== '',
                skorCount: skorCheckboxes.length,
                skorDetails: Array.from(skorCheckboxes).map(cb => cb.name)
            });
            
            // Validasi nama aspek
            if (!aspekNamaTextarea || !aspekNamaTextarea.value.trim()) {
                valid = false;
                firstInvalidIndex = index;
                invalidReason = 'nama';
                return;
            }
            
            // Validasi minimal satu skor dipilih
            if (skorCheckboxes.length === 0) {
                valid = false;
                firstInvalidIndex = index;
                invalidReason = 'skor';
                return;
            }
        });

        if (!valid) {
            e.preventDefault();
            if (firstInvalidIndex !== -1) {
                if (invalidReason === 'nama') {
                    alert(`Aspek penilaian ${firstInvalidIndex + 1} harus memiliki nama!`);
                } else if (invalidReason === 'skor') {
                    alert(`Aspek penilaian ${firstInvalidIndex + 1} harus memiliki minimal satu skor yang dipilih!`);
                }
            }
        } else {
            console.log('Form validation passed');
            
            // Double check sync sebelum benar-benar submit
            forceSyncAllTextareas();
            forceSyncAllSkorCheckboxes();
            
            // Debug final state
            debugAllAspek();
            debugSkorCheckboxes();
        }
    });
}

// Function untuk force sync semua skor checkbox
function forceSyncAllSkorCheckboxes() {
    console.log('=== FORCE SYNC ALL SKOR CHECKBOXES ===');
    
    const aspekItems = document.querySelectorAll('.aspek-item');
    
    aspekItems.forEach((aspekItem, aspekIndex) => {
        const checkboxes = aspekItem.querySelectorAll('input[type="checkbox"][name^="skor_"]');
        
        checkboxes.forEach((checkbox, cbIndex) => {
            const skorMatch = checkbox.name.match(/skor_(\d+)\[\]/);
            const skorValue = skorMatch ? skorMatch[1] : 'unknown';
            
            // Pastikan value sesuai dengan checked state
            if (checkbox.checked) {
                checkbox.value = '1';
            } else {
                checkbox.value = '0';
            }
            
            console.log(`Aspek ${aspekIndex + 1} Skor ${skorValue}:`, {
                checked: checkbox.checked,
                value: checkbox.value
            });
        });
    });
    
    console.log('=== SKOR SYNC COMPLETED ===');
}

    // Function untuk force sync semua textarea - sebagai backup
    function forceSyncAllTextareas() {
        console.log('=== FORCE SYNC ALL TEXTAREAS ===');
        
        const aspekItems = document.querySelectorAll('.aspek-item');
        
        aspekItems.forEach((aspekItem, aspekIndex) => {
            // Force sync nama aspek
            const namaAspekEditor = aspekItem.querySelector('.nama-aspek-editor .editor-content');
            const namaAspekTextarea = aspekItem.querySelector('textarea[name="aspek_nama[]"]');
            
            if (namaAspekEditor && namaAspekTextarea) {
                namaAspekTextarea.value = namaAspekEditor.innerHTML;
            }
            
            // Force sync deskripsi skor
            const skorEditors = aspekItem.querySelectorAll('.mini-editor:not(.nama-aspek-editor)');
            skorEditors.forEach((editor) => {
                const contentDiv = editor.querySelector('.editor-content');
                const targetName = editor.getAttribute('data-target');
                const textarea = aspekItem.querySelector(`textarea[name="${targetName}"]`);
                
                if (contentDiv && textarea) {
                    textarea.value = contentDiv.innerHTML;
                }
            });
        });
    }

    // Juga sync ketika halaman akan di-unload
    window.addEventListener('beforeunload', syncAllRichTextEditorsImproved);
});

// Fallback initialization if DOMContentLoaded doesn't fire
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOMContentLoaded event fired');
    });
} else {
    console.log('DOM already loaded, initializing immediately');
    // Trigger initialization manually
    const event = new Event('DOMContentLoaded');
    document.dispatchEvent(event);
}

// Debug function untuk memeriksa state semua aspek termasuk skor
function debugAllAspek() {
    console.log('=== DEBUG ALL ASPEK ===');
    const aspekItems = document.querySelectorAll('.aspek-item');
    
    aspekItems.forEach((item, index) => {
        const aspekNamaTextarea = item.querySelector('textarea[name="aspek_nama[]"]');
        const namaAspekEditor = item.querySelector('.nama-aspek-editor .editor-content');
        const skorCheckboxes = item.querySelectorAll('input[type="checkbox"][name^="skor_"]');
        
        console.log(`Aspek ${index + 1}:`, {
            textarea: aspekNamaTextarea,
            textareaValue: aspekNamaTextarea ? aspekNamaTextarea.value : 'null',
            editorContent: namaAspekEditor ? namaAspekEditor.innerHTML : 'null',
            hasTextareaContent: aspekNamaTextarea && aspekNamaTextarea.value.trim() !== '',
            hasEditorContent: namaAspekEditor && namaAspekEditor.innerHTML.trim() !== '',
            skorDetails: Array.from(skorCheckboxes).map(cb => ({
                name: cb.name,
                checked: cb.checked,
                value: cb.value
            }))
        });
    });
    console.log('=== DEBUG END ===');
}

// Debug function untuk skor checkboxes
function debugSkorCheckboxes() {
    console.log('=== DEBUG SKOR CHECKBOXES ===');
    const aspekItems = document.querySelectorAll('.aspek-item');
    
    aspekItems.forEach((item, index) => {
        const checkboxes = item.querySelectorAll('input[type="checkbox"][name^="skor_"]');
        const skorItems = item.querySelectorAll('.skor-item');
        
        console.log(`Aspek ${index + 1}:`);
        checkboxes.forEach((checkbox, cbIndex) => {
            const skorMatch = checkbox.name.match(/skor_(\d+)\[\]/);
            const skorValue = skorMatch ? skorMatch[1] : 'unknown';
            const skorItem = item.querySelector(`.skor-${skorValue}`);
            
            console.log(`  Skor ${skorValue}:`, {
                checked: checkbox.checked,
                value: checkbox.value,
                skorItemExists: !!skorItem,
                skorItemDisplay: skorItem ? skorItem.style.display : 'N/A'
            });
        });
    });
    console.log('=== DEBUG END ===');
}

// Panggil debug sebelum form submit
document.getElementById('stationForm')?.addEventListener('submit', function(e) {
    console.log('=== DEBUG BEFORE SUBMIT ===');
    debugAllAspek();
});

// Fallback initialization if DOMContentLoaded doesn't fire
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOMContentLoaded event fired');
    });
} else {
    console.log('DOM already loaded, initializing immediately');
    // Trigger initialization manually
    const event = new Event('DOMContentLoaded');
    document.dispatchEvent(event);
}



// Checklist Manager
class ChecklistManager {
    constructor() {
        this.templates = {
            'persiapan_alat': `diagnostik kit
occlusal biterim
occlusal bite plane
sliding caliper
spidol
benang
gunting
spirtus dan korek
lecron
KAPI`,
            'kapi': `Cuci tangan sebelum prosedur
Pakai APD lengkap
Persiapan alat steril
Desinfeksi area kerja
Pembuangan limbah medis`,
            'langkah_prosedur': `Penjelasan prosedur kepada pasien
Posisi pasien yang benar
Penggunaan alat yang tepat
Teknik yang benar
Hasil akhir sesuai standar`
        };
        
        this.init();
    }
    
    init() {
        // Event listener untuk toggle checklist
        document.addEventListener('change', (e) => {
            if (e.target.classList.contains('has-checklist-checkbox')) {
                this.toggleChecklistContainer(e.target);
            }
        });
        
        // Event listener untuk template buttons
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('template-btn')) {
                this.applyTemplate(e.target);
            }
        });
        
        // Initialize existing checklists
        document.querySelectorAll('.has-checklist-checkbox').forEach(checkbox => {
            this.toggleChecklistContainer(checkbox);
        });
    }
    
    toggleChecklistContainer(checkbox) {
        const container = checkbox.closest('.checklist-verifikasi-section')
            .querySelector('.checklist-items-container');
        
        if (checkbox.checked) {
            container.style.display = 'block';
            
            // Jika textarea kosong, isi dengan template default
            const textarea = container.querySelector('.checklist-items-textarea');
            if (textarea && !textarea.value.trim()) {
                textarea.value = this.templates.persiapan_alat;
            }
        } else {
            container.style.display = 'none';
        }
    }
    
    applyTemplate(button) {
        const templateName = button.dataset.template;
        const templateContent = this.templates[templateName];
        
        if (templateContent) {
            const container = button.closest('.checklist-items-container');
            const textarea = container.querySelector('.checklist-items-textarea');
            textarea.value = templateContent;
            
            // Show success message
            this.showToast('Template diterapkan!', 'success');
        }
    }
    
    showToast(message, type = 'success') {
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;
        toast.style.cssText = `
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: ${type === 'success' ? '#28a745' : '#dc3545'};
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            z-index: 9999;
            animation: slideIn 0.3s ease;
        `;
        
        document.body.appendChild(toast);
        
        setTimeout(() => {
            toast.remove();
        }, 3000);
    }
    
    // Method untuk mengambil data checklist
    getChecklistData(aspekId) {
        const container = document.querySelector(`[data-aspek-id="${aspekId}"] .checklist-items-container`);
        if (!container) return [];
        
        const textarea = container.querySelector('.checklist-items-textarea');
        if (!textarea || !textarea.value.trim()) return [];
        
        return textarea.value.split('\n')
            .map(item => item.trim())
            .filter(item => item.length > 0);
    }
}

// Initialize ChecklistManager
document.addEventListener('DOMContentLoaded', () => {
    window.checklistManager = new ChecklistManager();
});

// Di soal.js, tambahkan fungsi untuk toggle item verifikasi
function initItemVerifikasiToggle() {
    document.addEventListener('change', function(e) {
        if (e.target.classList.contains('toggle-item-verifikasi')) {
            const aspekItem = e.target.closest('.aspek-item');
            const verifikasiSection = aspekItem.querySelector('.item-verifikasi-section');
            const previewSection = aspekItem.querySelector('.item-preview');
            const textarea = aspekItem.querySelector('.item-verifikasi-textarea');
            
            if (e.target.checked) {
                verifikasiSection.style.display = 'block';
                textarea.required = true;
            } else {
                verifikasiSection.style.display = 'none';
                textarea.required = false;
                previewSection.style.display = 'none';
            }
        }
    });
    
    // Live preview untuk item verifikasi
    document.addEventListener('input', function(e) {
        if (e.target.classList.contains('item-verifikasi-textarea')) {
            const aspekItem = e.target.closest('.aspek-item');
            const previewSection = aspekItem.querySelector('.item-preview');
            const previewContent = aspekItem.querySelector('.preview-content');
            const textarea = e.target;
            
            if (textarea.value.trim()) {
                previewSection.style.display = 'block';
                
                // Format preview
                const items = textarea.value.split('\n').filter(item => item.trim() !== '');
                let previewHTML = '<div style="display: flex; flex-wrap: wrap; gap: 10px; margin-top: 10px;">';
                
                items.forEach((item, index) => {
                    if (item.trim()) {
                        previewHTML += `
                            <div style="display: flex; align-items: center; gap: 5px; background: white; padding: 5px 10px; border-radius: 4px; border: 1px solid #dee2e6;">
                                <input type="checkbox" disabled>
                                <span>${item.trim()}</span>
                            </div>
                        `;
                    }
                });
                
                previewHTML += '</div>';
                previewContent.innerHTML = previewHTML;
            } else {
                previewSection.style.display = 'none';
            }
        }
    });
}

// Panggil di DOMContentLoaded
document.addEventListener('DOMContentLoaded', function() {
    initItemVerifikasiToggle();
});