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() {
        // Create toolbar
        const toolbar = document.createElement('div');
        toolbar.className = 'editor-toolbar';
        toolbar.innerHTML = `
            <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"><i class="fas fa-image"></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 {
                    document.execCommand(command, false, null);
                }
                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();
        });
    }

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

// Mini Rich Text Editor untuk aspek penilaian
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
        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() {
        // Create mini toolbar
        const toolbar = document.createElement('div');
        toolbar.className = 'mini-toolbar';
        toolbar.innerHTML = `
            <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>
        `;

        // Create editable div
        const editable = document.createElement('div');
        editable.className = 'editor-content mini-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');
                document.execCommand(command, false, null);
                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();
        });
    }

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

// Aspek Penilaian Management
class AspekManager {
    constructor() {
        this.container = document.getElementById('aspekContainer');
        this.template = document.getElementById('aspekTemplate');
        this.aspekCount = 0;
        this.maxAspek = 20;
        this.init();
    }

    init() {
        console.log('AspekManager initialized'); // 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); // Debug log
        
        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
            this.initRichTextEditorsForAspek(aspekElement);

            // Setup skor checkbox event listeners
            this.setupSkorCheckboxes(aspekElement);

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

    createAspekElement() {
        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 aspekElement = tempDiv.firstElementChild;
        
        if (!aspekElement) {
            console.error('Gagal membuat elemen aspek dari template!');
            return null;
        }
        
        // Set nomor urut
        const nomorUrutInput = aspekElement.querySelector('.nomor-urut');
        if (nomorUrutInput) {
            nomorUrutInput.value = this.container.children.length + 1;
        }
        
        // 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);
            });
        }

        return aspekElement;
    }

    initRichTextEditorsForAspek(aspekElement) {
    // Inisialisasi rich text editor untuk nama aspek
    const namaAspekEditor = aspekElement.querySelector('.nama-aspek-editor');
    if (namaAspekEditor) {
        new MiniRichTextEditor(namaAspekEditor);
    }

    // Inisialisasi rich text editor untuk deskripsi skor
    const skorEditors = aspekElement.querySelectorAll('.mini-editor:not(.nama-aspek-editor)');
    skorEditors.forEach(editor => {
        new MiniRichTextEditor(editor);
    });
}

    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
            this.initRichTextEditorsForAspek(duplicatedElement);

            // Setup skor checkbox event listeners
            this.setupSkorCheckboxes(duplicatedElement);

            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.container.children.length + 1;
        }
        
        // Copy nama aspek content
        if (dupAspekNamaEditor && sourceAspekNamaEditor) {
            dupAspekNamaEditor.innerHTML = sourceAspekNamaEditor.innerHTML + " (Salinan)";
        }
        
        // Copy checkbox states
        if (sourceCheckboxes && dupCheckboxes) {
            sourceCheckboxes.forEach((checkbox, index) => {
                if (dupCheckboxes[index]) {
                    dupCheckboxes[index].checked = checkbox.checked;
                }
            });
        }
        
        // 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 => {
            checkbox.addEventListener('change', (e) => {
                const skorText = e.target.parentElement.textContent.trim();
                const skorMatch = skorText.match(/Skor (\d+)/);
                
                if (skorMatch) {
                    const skorValue = skorMatch[1];
                    const skorItem = aspekElement.querySelector(`.skor-${skorValue}`);
                    
                    if (skorItem) {
                        if (e.target.checked) {
                            skorItem.style.display = 'block';
                        } else {
                            skorItem.style.display = 'none';
                        }
                    }
                }
            });

            // Initialize visibility based on checked state
            const skorText = checkbox.parentElement.textContent.trim();
            const skorMatch = skorText.match(/Skor (\d+)/);
            
            if (skorMatch) {
                const skorValue = skorMatch[1];
                const skorItem = aspekElement.querySelector(`.skor-${skorValue}`);
                
                if (skorItem && !checkbox.checked) {
                    skorItem.style.display = 'none';
                }
            }
        });
    }

    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
    const stationForm = document.getElementById('stationForm');
    if (stationForm) {
        stationForm.addEventListener('submit', function(e) {
            console.log('Form submission started'); // Debug log
            
            // Sync all rich text editors sebelum submit
            syncAllRichTextEditors();
            
            // 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;
aspekItems.forEach((item, index) => {
    // Cari textarea untuk nama aspek (bukan editor content)
    const aspekNamaTextarea = item.querySelector('textarea[name="aspek_nama[]"]');
    const skorCheckboxes = item.querySelectorAll('input[type="checkbox"][name^="skor_"]:checked');
    
    if (!aspekNamaTextarea || !aspekNamaTextarea.value.trim()) {
        valid = false;
        // Focus ke editor nama aspek
        const namaAspekEditor = item.querySelector('.nama-aspek-editor .editor-content');
        if (namaAspekEditor) {
            namaAspekEditor.focus();
        }
        alert(`Aspek penilaian ${index + 1} harus memiliki nama!`);
        return;
    }
    
    if (skorCheckboxes.length === 0) {
        valid = false;
        alert(`Aspek penilaian ${index + 1} harus memiliki minimal satu skor yang dipilih!`);
        return;
    }
});

            if (!valid) {
                e.preventDefault();
            } else {
                console.log('Form validation passed'); // Debug log
            }
        });
    }

    // Function untuk sync semua rich text editors
    function syncAllRichTextEditors() {
        // Sync main editors
        document.querySelectorAll('.rich-text-editor').forEach(editor => {
            const contentDiv = editor.querySelector('.editor-content');
            const targetName = editor.getAttribute('data-target');
            const textarea = document.querySelector(`textarea[name="${targetName}"]`);
            
            if (contentDiv && textarea) {
                textarea.value = contentDiv.innerHTML;
                console.log(`Synced ${targetName}:`, textarea.value.substring(0, 50) + '...'); // Debug log
            }
        });

        // Sync mini editors untuk aspek
        document.querySelectorAll('.mini-editor').forEach(editor => {
            const contentDiv = editor.querySelector('.editor-content');
            const targetName = editor.getAttribute('data-target');
            const textareas = document.querySelectorAll(`textarea[name="${targetName}"]`);
            const lastTextarea = textareas[textareas.length - 1];
            
            if (contentDiv && lastTextarea) {
                lastTextarea.value = contentDiv.innerHTML;
                console.log(`Synced ${targetName}:`, lastTextarea.value.substring(0, 50) + '...'); // Debug log
            }
        });
    }

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

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