// Variabel global
let currentContent = '';
let autoSaveTimer = null;
let tabs = [];
let activeTabId = null;
let fontSize = localStorage.getItem('editorFontSize') || '14px';
let fontFamily = localStorage.getItem('editorFontFamily') || 'Courier New, monospace';
let darkModeEnabled = localStorage.getItem('darkMode') === 'true';
let autoSaveEnabled = localStorage.getItem('autoSave') !== 'false'; // Default true
let wordWrapEnabled = localStorage.getItem('wordWrap') !== 'false'; // Default true
let inputDebounceTimer = null;
const INPUT_DEBOUNCE_DELAY = 300; // 300ms
let cursorPositions = {};
let searchMatches = [];
let currentMatchIndex = -1;
let lastSearchTerm = '';

function saveCursorPosition(tabId) {
    const editor = document.getElementById('editor');
    cursorPositions[tabId] = editor.selectionStart;
}

function restoreCursorPosition(tabId) {
    const editor = document.getElementById('editor');
    const position = cursorPositions[tabId] || 0;
    
    // Gunakan setTimeout untuk memastikan editor sudah fokus
    setTimeout(() => {
        editor.selectionStart = position;
        editor.selectionEnd = position;
        editor.focus();
    }, 0);
}

function showToggleNotification(setting, isOn) {
    const settingNames = {
        'darkMode': 'Mode Gelap',
        'autoSave': 'Auto-save',
        'wordWrap': 'Word Wrap'
    };
    const status = isOn ? 'Aktif' : 'Nonaktif';
    showToast(`${settingNames[setting]} ${status}`, isOn ? 'success' : 'warning');
}

function setupEventListeners() {
    document.addEventListener('click', function(e) {
        // Handle tab click
        if (e.target.matches('.nav-link[data-tab-id]')) {
            e.preventDefault();
            setActiveTab(e.target.dataset.tabId);
        }

        // Handle close tab button
        if (e.target.matches('.btn-close-tab, .btn-close-tab *')) {
            const btn = e.target.closest('.btn-close-tab');
            closeTab(btn.dataset.tabId);
        }

        // Handle close all tabs
        if (e.target.matches('#closeAllTabs, #closeAllTabs *')) {
            closeAllTabs();
        }
    });
}

// Fungsi untuk membuka modal find/replace
function openFindReplaceModal() {
    const modal = new bootstrap.Modal(document.getElementById('findReplaceModal'));
    modal.show();
    document.getElementById('findInput').focus();
    
    // Jika ada teks yang diseleksi, masukkan ke find input
    const editor = document.getElementById('editor');
    const selectedText = editor.value.substring(editor.selectionStart, editor.selectionEnd);
    if (selectedText) {
        document.getElementById('findInput').value = selectedText;
        performSearch();
    }
}

// Fungsi untuk melakukan pencarian
function performSearch() {
    const findText = document.getElementById('findInput').value;
    const matchCase = document.getElementById('matchCase').checked;
    const editor = document.getElementById('editor');
    const content = editor.value;
    
    // Reset state pencarian sebelumnya
    clearHighlights();
    searchMatches = [];
    currentMatchIndex = -1;
    
    if (!findText) {
        document.getElementById('matchCount').textContent = '0 matches found';
        return;
    }
    
    // Simpan posisi scroll dan selection
    const scrollPos = editor.scrollTop;
    const selStart = editor.selectionStart;
    
    // Lakukan pencarian
    const flags = matchCase ? 'g' : 'gi';
    const regex = new RegExp(escapeRegExp(findText), flags);
    let match;
    
    while ((match = regex.exec(content)) !== null) {
        searchMatches.push({
            start: match.index,
            end: match.index + match[0].length
        });
    }
    
    // Update UI dengan hasil pencarian
    document.getElementById('matchCount').textContent = `${searchMatches.length} matches found`;
    
    // Highlight semua hasil
    highlightMatches();
    
    // Kembalikan posisi scroll dan selection
    editor.scrollTop = scrollPos;
    editor.selectionStart = selStart;
    editor.selectionEnd = selStart;
    
    lastSearchTerm = findText;
}

// Fungsi untuk escape regex special characters
function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

// Fungsi untuk highlight semua hasil pencarian
function highlightMatches() {
    const editor = document.getElementById('editor');
    const content = editor.value;
    const matchCase = document.getElementById('matchCase').checked;
    const findText = document.getElementById('findInput').value;
    
    if (!findText) return;
    
    const flags = matchCase ? 'g' : 'gi';
    const regex = new RegExp(escapeRegExp(findText), flags);
    
    // Buat HTML dengan highlight
    let highlightedContent = content.replace(regex, match => 
        `<span class="highlight">${match}</span>`
    );
    
    // Simpan posisi scroll dan cursor
    const scrollPos = editor.scrollTop;
    const cursorPos = editor.selectionStart;
    
    // Ganti textarea dengan div yang bisa render HTML
    const editorParent = editor.parentNode;
    const hiddenInput = document.createElement('textarea');
    hiddenInput.className = editor.className;
    hiddenInput.style.display = 'none';
    hiddenInput.id = 'editor';
    hiddenInput.value = content;
    
    const highlightDiv = document.createElement('div');
    highlightDiv.className = 'editor-highlight';
    highlightDiv.style.whiteSpace = 'pre-wrap';
    highlightDiv.style.fontFamily = editor.style.fontFamily;
    highlightDiv.style.fontSize = editor.style.fontSize;
    highlightDiv.style.padding = '15px';
    highlightDiv.style.minHeight = '100%';
    highlightDiv.innerHTML = highlightedContent;
    
    editorParent.appendChild(hiddenInput);
    editorParent.appendChild(highlightDiv);
    
    // Kembalikan posisi scroll
    highlightDiv.scrollTop = scrollPos;
    
    // Set current highlight
    if (currentMatchIndex >= 0 && searchMatches.length > 0) {
        const currentMatch = searchMatches[currentMatchIndex];
        const highlights = highlightDiv.querySelectorAll('.highlight');
        if (highlights[currentMatchIndex]) {
            highlights[currentMatchIndex].classList.add('current-highlight');
            
            // Scroll ke current highlight
            highlights[currentMatchIndex].scrollIntoView({
                block: 'center',
                behavior: 'smooth'
            });
        }
    }
    
    // Ketika editor asli difokuskan, kembalikan ke textarea
    highlightDiv.addEventListener('click', () => {
        hiddenInput.focus();
        restoreEditor();
    });
}

// Fungsi untuk mengembalikan editor ke textarea
function restoreEditor() {
    const editorParent = document.getElementById('editor').parentNode;
    const highlightDiv = editorParent.querySelector('.editor-highlight');
    const hiddenInput = editorParent.querySelector('textarea#editor');
    
    if (highlightDiv) {
        editorParent.removeChild(highlightDiv);
    }
    
    if (hiddenInput) {
        hiddenInput.style.display = 'block';
    }
}

// Fungsi untuk menghapus highlight
function clearHighlights() {
    restoreEditor();
}

// Fungsi untuk navigasi hasil pencarian
function navigateMatch(direction) {
    if (searchMatches.length === 0) return;
    
    if (direction === 'next') {
        currentMatchIndex = (currentMatchIndex + 1) % searchMatches.length;
    } else {
        currentMatchIndex = (currentMatchIndex - 1 + searchMatches.length) % searchMatches.length;
    }
    
    const match = searchMatches[currentMatchIndex];
    const editor = document.getElementById('editor');
    
    // Set selection dan scroll
    editor.selectionStart = match.start;
    editor.selectionEnd = match.end;
    editor.focus();
    
    // Hitung posisi scroll
    const lineHeight = parseInt(getComputedStyle(editor).lineHeight);
    const editorHeight = editor.clientHeight;
    const scrollPos = match.start - (editorHeight / lineHeight / 2) * 100;
    
    // Scroll ke posisi
    editor.scrollTop = scrollPos;
    
    // Update highlight
    highlightMatches();
}

// Fungsi untuk replace
function replaceCurrent() {
    if (currentMatchIndex === -1 || searchMatches.length === 0) return;
    
    const editor = document.getElementById('editor');
    const replaceText = document.getElementById('replaceInput').value;
    const match = searchMatches[currentMatchIndex];
    
    // Lakukan replace
    const content = editor.value;
    const newContent = content.substring(0, match.start) + replaceText + content.substring(match.end);
    
    // Update editor
    editor.value = newContent;
    
    // Update tab content jika ada tab aktif
    if (activeTabId) {
        const tab = tabs.find(t => t.id === activeTabId);
        if (tab) {
            tab.content = newContent;
            if (autoSaveEnabled) {
                saveContentToFile(tab);
            }
        }
    }
    
    // Perbarui pencarian
    performSearch();
    
    // Pindah ke match berikutnya
    if (searchMatches.length > 0) {
        navigateMatch('next');
    }
}

function replaceAll() {
    const editor = document.getElementById('editor');
    const findText = document.getElementById('findInput').value;
    const replaceText = document.getElementById('replaceInput').value;
    const matchCase = document.getElementById('matchCase').checked;
    
    if (!findText) return;
    
    const flags = matchCase ? 'g' : 'gi';
    const regex = new RegExp(escapeRegExp(findText), flags);
    const newContent = editor.value.replace(regex, replaceText);
    
    // Update editor
    editor.value = newContent;
    
    // Update tab content jika ada tab aktif
    if (activeTabId) {
        const tab = tabs.find(t => t.id === activeTabId);
        if (tab) {
            tab.content = newContent;
            if (autoSaveEnabled) {
                saveContentToFile(tab);
            }
        }
    }
    
    // Reset pencarian
    searchMatches = [];
    currentMatchIndex = -1;
    document.getElementById('matchCount').textContent = '0 matches found';
    clearHighlights();
    
    showToast(`Replaced all occurrences of "${findText}"`, 'success');
}


function generateId() {
    return Math.random().toString(36).substr(2, 9);
}
function applyFontSize() {
    document.getElementById('editor').style.fontSize = fontSize;
    localStorage.setItem('editorFontSize', fontSize);
}

// Fungsi untuk menghitung kata
function countWords(text) {
    if (!text.trim()) return 0;
    return text.trim().split(/\s+/).length;
}

let lastWordCount = 0;

function updateWordCount() {
    const text = document.getElementById('editor').value;

    // Hanya hitung jika perubahan signifikan
    if (text.length < 1000 || Math.abs(text.length - lastWordCount) > 50) {
        const count = text.trim() ? text.trim().split(/\s+/).length : 0;
        document.getElementById('wordCount').textContent = `${count} kata`;
        lastWordCount = count;
        return count;
    }
    return lastWordCount;
}

function createTab(novel, series, file, type, content) {
    const id = generateId();
    const title = `${type === 'chapter' ? 'Chapter' : type.charAt(0).toUpperCase() + type.slice(1)}: ${file.replace('.txt', '')}`;

    const newTab = {
        id,
        novel,
        series,
        file,
        type,
        title,
        content,
        savedContent: content
    };

    tabs.push(newTab);
    renderTabs();
    setActiveTab(id);

    return id;
}

// Fungsi untuk merender semua tab
function renderTabs() {
    const tabsContainer = document.getElementById('editorTabs');
    tabsContainer.innerHTML = '';

    const fragment = document.createDocumentFragment();

    tabs.forEach(tab => {
        const tabEl = document.createElement('li');
        tabEl.className = `nav-item d-flex align-items-center ${tab.id === activeTabId ? 'active-tab' : ''}`;
        tabEl.innerHTML = `
            <a class="nav-link" href="#" data-tab-id="${tab.id}" title="${tab.title}">
                ${tab.title}
            </a>
            <button class="btn btn-sm btn-close-tab" data-tab-id="${tab.id}">
                <i class="bi bi-x"></i>
            </button>
        `;
        fragment.appendChild(tabEl);
    });

    // Tambahkan tombol Close All jika ada lebih dari 1 tab
    if (tabs.length > 1) {
        const closeAllBtn = document.createElement('li');
        closeAllBtn.className = 'nav-item ms-auto';
        closeAllBtn.innerHTML = `
            <button class="btn btn-sm btn-outline-danger" id="closeAllTabs">
                <i class="bi bi-x-circle"></i> Close All
            </button>
        `;
        fragment.appendChild(closeAllBtn);
    }

    // Tambahkan fragment ke container
    tabsContainer.appendChild(fragment);

    // Scroll ke tab aktif jika ada
    if (activeTabId) {
        const activeTab = tabsContainer.querySelector(`.nav-link[data-tab-id="${activeTabId}"]`);
        if (activeTab) {
            // Gunakan setTimeout untuk memastikan DOM sudah di-render
            setTimeout(() => {
                activeTab.scrollIntoView({
                    behavior: 'smooth',
                    block: 'nearest',
                    inline: 'center'
                });
            }, 0);
        }
    }
}
// Fungsi untuk mengatur tab aktif
function setActiveTab(tabId) {
    // Simpan posisi kursor tab sebelumnya
    if (activeTabId) {
        saveCursorPosition(activeTabId);
    }

    const tab = tabs.find(t => t.id === tabId);
    if (!tab) return;

    activeTabId = tabId;
    document.getElementById('editor').value = tab.content;
    currentContent = tab.content;
    updateWordCount();

    // Safely update editorInfo if it exists
    const editorInfo = document.getElementById('editorInfo');
    if (editorInfo) {
        editorInfo.textContent = `${tab.novel}${tab.series ? ' > ' + tab.series : ''} > ${tab.file}`;
    }

    renderTabs();
    
    // Kembalikan posisi kursor
    restoreCursorPosition(tabId);
}

// Fungsi untuk menutup tab
function closeTab(tabId, force = false) {
    const tab = tabs.find(t => t.id === tabId);
    if (!tab) return false;

    // Check for unsaved changes when auto-save is off
    if (!autoSaveEnabled && tab.content !== tab.savedContent && !force) {
        const response = confirm(`Ada perubahan yang belum disimpan di "${tab.title}".\n\nApakah Anda ingin menyimpan sebelum menutup?`);

        if (response === true) {
            // User chose to save
            saveContentToFile(tab);
            tab.savedContent = tab.content;
        } else if (response === null) {
            // User canceled
            return false;
        }
        // If false, continue without saving
    }

    tabs = tabs.filter(t => t.id !== tabId);

    if (tabs.length === 0) {
        document.getElementById('editor').value = '';
        currentContent = '';
        activeTabId = null;
        document.getElementById('editorInfo').textContent = '';
    } else if (activeTabId === tabId) {
        setActiveTab(tabs[tabs.length - 1].id);
    }

    renderTabs();
    return true;
}

function searchNovel(novel, keyword) {
    if (!novel || !keyword) return;

    fetch('', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `action=search&novel=${encodeURIComponent(novel)}&keyword=${encodeURIComponent(keyword)}`
    })
        .then(response => response.json())
        .then(data => {
        if (data.success && data.results.length > 0) {
            const resultsContainer = document.getElementById('searchResults');
            resultsContainer.innerHTML = '';

            data.results.forEach(result => {
                const resultItem = document.createElement('div');
                resultItem.className = 'list-group-item list-group-item-action';
                resultItem.innerHTML = `
                    <div class="d-flex w-100 justify-content-between">
                        <h6 class="mb-1">${result.file}</h6>
                        <small>${result.type}</small>
                    </div>
                    <p class="mb-1">${result.context}</p>
                    <small>${result.path}</small>
                `;

                resultItem.addEventListener('click', () => {
                    // Close the modal first
                    bootstrap.Modal.getInstance(document.getElementById('searchResultsModal')).hide();

                    // Open the file in editor
                    if (result.type === 'chapter') {
                        loadFileContent(novel, result.series, result.filename, 'chapter');
                    } else {
                        loadFileContent(novel, '', result.filename, result.type);
                    }
                });

                resultsContainer.appendChild(resultItem);
            });

            // Show the modal
            const modal = new bootstrap.Modal(document.getElementById('searchResultsModal'));
            modal.show();
        } else {
            showToast('Tidak ditemukan hasil pencarian', 'warning');
        }
    });
}

// Fungsi untuk menutup semua tab
function closeAllTabs() {
    let unsavedTabs = [];

    if (!autoSaveEnabled) {
        unsavedTabs = tabs.filter(tab => tab.content !== tab.savedContent);
    }

    if (unsavedTabs.length > 0) {
        const tabList = unsavedTabs.map(tab => `- ${tab.title}`).join('\n');
        const response = confirm(
            `Ada ${unsavedTabs.length} file dengan perubahan yang belum disimpan:\n\n${tabList}\n\nApakah Anda ingin menyimpan sebelum menutup semua tab?`
        );

        if (response === true) {
            unsavedTabs.forEach(tab => {
                saveContentToFile(tab);
                tab.savedContent = tab.content;
            });
        } else if (response === null) {
            return false; // User canceled
        }
    }

    tabs = [];
    activeTabId = null;
    document.getElementById('editor').value = '';
    currentContent = '';
    document.getElementById('editorInfo').textContent = '';

    renderTabs();
    return true;
}
function showToast(message, type = 'success') {
    const toastEl = document.getElementById('liveToast');
    const toastBody = toastEl.querySelector('.toast-body');

    toastEl.className = `toast show align-items-center text-white bg-${type}`;
    toastBody.textContent = message;

    setTimeout(() => {
        toastEl.classList.remove('show');
    }, 3000);
}

function applyFontSettings() {
    const editor = document.getElementById('editor');
    editor.style.fontSize = fontSize;
    editor.style.fontFamily = fontFamily;
    localStorage.setItem('editorFontSize', fontSize);
    localStorage.setItem('editorFontFamily', fontFamily);
}

// Fungsi untuk menyimpan konten tab
function saveTabContent(tabId) {
    const tab = tabs.find(t => t.id === tabId);
    if (!tab) return;

    const editorContent = document.getElementById('editor').value;
    if (tab.id === activeTabId) {
        tab.content = editorContent;
    }

    // Jika konten berubah, simpan ke file
    if (tab.content !== tab.savedContent) {
        saveContentToFile(tab);
        tab.savedContent = tab.content;
    }
}

// Fungsi untuk menyimpan konten ke file
function saveContentToFile(tab) {
    fetch('', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `action=save&novel=${encodeURIComponent(tab.novel)}&series=${encodeURIComponent(tab.series)}&file=${encodeURIComponent(tab.file)}&content=${encodeURIComponent(tab.content)}&type=${tab.type}`
    })
        .then(response => response.json())
        .then(data => {
        if (data.success) {
            tab.savedContent = tab.content;
            if (tab.id === activeTabId) {
                showToast('Berhasil disimpan');
            }
        } else {
            showToast('Gagal menyimpan', 'danger');
        }
    });
}
function loadFileContent(novel, series, file, type) {
    // Cek apakah file sudah dibuka di tab
    const existingTab = tabs.find(tab => 
                                  tab.novel === novel && 
                                  (tab.type !== 'chapter' || tab.series === series) && 
                                  tab.file === file && 
                                  tab.type === type
                                 );

    if (existingTab) {
        setActiveTab(existingTab.id);
        return;
    }

    fetch('', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `action=get_content&novel=${encodeURIComponent(novel)}&series=${encodeURIComponent(series)}&file=${encodeURIComponent(file)}&type=${type}`
    })
        .then(response => response.json())
        .then(data => {
        if (data.success) {
            createTab(novel, series, file, type, data.content);

            // Mulai auto-save jika aktif
            if (autoSaveEnabled) {
                startAutoSave();
            }
        }
    });
}
// Fungsi untuk menyimpan konten
// Fungsi untuk menyimpan konten
function saveContent() {
    if (!activeTabId) return;

    const tab = tabs.find(t => t.id === activeTabId);
    if (!tab) return;

    const editor = document.getElementById('editor');
    const content = editor.value;

    if (content !== tab.savedContent) {
        fetch('', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `action=save&novel=${encodeURIComponent(tab.novel)}&series=${encodeURIComponent(tab.series)}&file=${encodeURIComponent(tab.file)}&content=${encodeURIComponent(content)}&type=${tab.type}`
        })
            .then(response => response.json())
            .then(data => {
            if (data.success) {
                tab.savedContent = content;
                showToast('Berhasil disimpan');
            } else {
                showToast('Gagal menyimpan', 'danger');
            }
        });
    }
}

// Fungsi untuk memulai auto-save
function startAutoSave() {
    if (autoSaveTimer) clearInterval(autoSaveTimer);
    if (!autoSaveEnabled) return;

    autoSaveTimer = setInterval(() => {
        if (!activeTabId) return;

        const tab = tabs.find(t => t.id === activeTabId);
        if (!tab || tab.content === tab.savedContent) return;

        // Gunakan requestIdleCallback jika tersedia
        if ('requestIdleCallback' in window) {
            window.requestIdleCallback(() => {
                saveContentToFile(tab);
            }, { timeout: 1000 });
        } else {
            saveContentToFile(tab);
        }
    }, 30000); // Tetap 30 detik tapi dengan optimasi
}

// Fungsi untuk menampilkan toast notifikasi
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type} border-0 position-fixed bottom-0 end-0 m-3`;
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');

    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">${message}</div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    `;

    document.body.appendChild(toast);
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();

    // Hapus toast setelah ditutup
    toast.addEventListener('hidden.bs.toast', () => {
        toast.remove();
    });
}

// Fungsi untuk memuat daftar seri
function loadSeries(novel) {
    fetch('', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `action=get_series&novel=${encodeURIComponent(novel)}`
    })
        .then(response => response.json())
        .then(data => {
        if (data.success) {
            const seriesList = document.getElementById('seriesList');
            seriesList.innerHTML = '';

            if (data.series.length > 0) {
                data.series.forEach(series => {
                    const seriesItem = document.createElement('div');
                    seriesItem.className = 'list-group-item list-group-item-action d-flex justify-content-between align-items-center';
                    seriesItem.innerHTML = `
                        <span>${series}</span>
                        <div>
                            <button class="btn btn-sm btn-outline-primary new-chapter-btn" data-series="${series}">
                                <i class="bi bi-plus"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-danger delete-btn" data-type="series" data-name="${series}">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    `;

                    seriesItem.addEventListener('click', (e) => {
                        if (!e.target.classList.contains('btn')) {
                            loadChapters(novel, series);
                        }
                    });

                    seriesList.appendChild(seriesItem);
                });
            } else {
                seriesList.innerHTML = '<div class="list-group-item text-muted">Tidak ada seri</div>';
            }

            // Aktifkan tombol new chapter jika ada seri
            document.getElementById('newSeriesBtn').disabled = false;
        }
    });
}

// Fungsi untuk memuat daftar chapter
function loadChapters(novel, series) {
    fetch('', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `action=get_chapters&novel=${encodeURIComponent(novel)}&series=${encodeURIComponent(series)}`
    })
        .then(response => response.json())
        .then(data => {
        if (data.success) {
            const chapterList = document.getElementById('chapterList');
            chapterList.innerHTML = '';

            if (data.chapters.length > 0) {
                // Buat salinan array sebelum sorting
                const chaptersToSort = [...data.chapters];

                const sortedChapters = chaptersToSort.sort((a, b) => {
                    // Ekstrak angka dari string (cari semua digit di string)
                    const numA = parseInt(a.match(/\d+/)?.at(0) || 0);
                    const numB = parseInt(b.match(/\d+/)?.at(0) || 0);
                    return numA - numB;
                });

                sortedChapters.forEach(chapter => {
                    const chapterItem = document.createElement('div');
                    chapterItem.className = 'list-group-item list-group-item-action d-flex justify-content-between align-items-center';
                    chapterItem.innerHTML = `
                        <span>${chapter.replace('.txt', '')}</span>
                        <button class="btn btn-sm btn-outline-danger delete-btn" data-type="chapter" data-name="${chapter}">
                            <i class="bi bi-trash"></i>
                        </button>
                    `;

                    chapterItem.addEventListener('click', () => {
                        loadFileContent(novel, series, chapter, 'chapter');
                    });

                    chapterList.appendChild(chapterItem);
                });
            } else {
                chapterList.innerHTML = '<div class="list-group-item text-muted">Tidak ada chapter</div>';
            }
        }
    });
}

// Fungsi untuk memuat daftar karakter
function loadCharacters(novel) {
    fetch('', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `action=get_characters&novel=${encodeURIComponent(novel)}`
    })
        .then(response => response.json())
        .then(data => {
        if (data.success) {
            const characterList = document.getElementById('characterList');
            characterList.innerHTML = '';

            if (data.characters.length > 0) {
                data.characters.forEach(character => {
                    const characterItem = document.createElement('div');
                    characterItem.className = 'list-group-item list-group-item-action d-flex justify-content-between align-items-center';
                    characterItem.innerHTML = `
                        <span>${character}</span>
                        <button class="btn btn-sm btn-outline-danger delete-btn" data-type="character" data-name="${character}">
                            <i class="bi bi-trash"></i>
                        </button>
                    `;

                    characterItem.addEventListener('click', () => {
                        loadFileContent(novel, '', character, 'character');
                    });

                    characterList.appendChild(characterItem);
                });
            } else {
                characterList.innerHTML = '<div class="list-group-item text-muted">Tidak ada karakter</div>';
            }
        }
    });
}

// Fungsi untuk memuat daftar lokasi
function loadLocations(novel) {
    fetch('', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `action=get_locations&novel=${encodeURIComponent(novel)}`
    })
        .then(response => response.json())
        .then(data => {
        if (data.success) {
            const locationList = document.getElementById('locationList');
            locationList.innerHTML = '';

            if (data.locations.length > 0) {
                data.locations.forEach(location => {
                    const locationItem = document.createElement('div');
                    locationItem.className = 'list-group-item list-group-item-action d-flex justify-content-between align-items-center';
                    locationItem.innerHTML = `
                        <span>${location}</span>
                        <button class="btn btn-sm btn-outline-danger delete-btn" data-type="location" data-name="${location}">
                            <i class="bi bi-trash"></i>
                        </button>
                    `;

                    locationItem.addEventListener('click', () => {
                        loadFileContent(novel, '', location, 'location');
                    });

                    locationList.appendChild(locationItem);
                });
            } else {
                locationList.innerHTML = '<div class="list-group-item text-muted">Tidak ada lokasi</div>';
            }
        }
    });
}

// Fungsi untuk memuat daftar catatan
function loadNotes(novel) {
    fetch('', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `action=get_notes&novel=${encodeURIComponent(novel)}`
    })
        .then(response => response.json())
        .then(data => {
        if (data.success) {
            const noteList = document.getElementById('noteList');
            noteList.innerHTML = '';

            if (data.notes.length > 0) {
                data.notes.forEach(note => {
                    const noteItem = document.createElement('div');
                    noteItem.className = 'list-group-item list-group-item-action d-flex justify-content-between align-items-center';
                    noteItem.innerHTML = `
                        <span>${note}</span>
                        <button class="btn btn-sm btn-outline-danger delete-btn" data-type="note" data-name="${note}">
                            <i class="bi bi-trash"></i>
                        </button>
                    `;

                    noteItem.addEventListener('click', () => {
                        loadFileContent(novel, '', note, 'note');
                    });

                    noteList.appendChild(noteItem);
                });
            } else {
                noteList.innerHTML = '<div class="list-group-item text-muted">Tidak ada catatan</div>';
            }
        }
    });
}

// Event listeners
document.addEventListener('DOMContentLoaded', function() {
    // Toggle dark mode
    document.getElementById('darkModeToggle').checked = darkModeEnabled;
    document.body.classList.toggle('dark-mode', darkModeEnabled);


    document.getElementById('darkModeToggle').addEventListener('change', function() {
        darkModeEnabled = this.checked;


        document.body.classList.toggle('dark-mode', darkModeEnabled);
        localStorage.setItem('darkMode', darkModeEnabled);
        showToggleNotification('darkMode', darkModeEnabled);
    });

    document.getElementById('autoSaveToggle').checked = autoSaveEnabled;
    if (autoSaveEnabled) {
        startAutoSave();
    }

    document.getElementById('wordWrapToggle').checked = wordWrapEnabled;
    document.getElementById('editor').style.whiteSpace = wordWrapEnabled ? 'pre-wrap' : 'pre';

    // Toggle auto-save
    document.getElementById('autoSaveToggle').addEventListener('change', function() {
        autoSaveEnabled = this.checked;
        localStorage.setItem('autoSave', autoSaveEnabled);
        if (autoSaveEnabled) {
            startAutoSave();
        } else if (autoSaveTimer) {
            clearInterval(autoSaveTimer);
            autoSaveTimer = null;
        }
        showToggleNotification('autoSave', autoSaveEnabled);
    });

    applyFontSize();
    applyFontSettings();

    document.getElementById('fontSizeSelect').value = fontSize;
    document.getElementById('fontFamilySelect').value = fontFamily;

    // Font size control
    document.getElementById('fontSizeSelect').addEventListener('change', function() {
        fontSize = this.value;
        applyFontSettings();
    });

document.getElementById('editor').addEventListener('blur', function() {
    if (activeTabId) {
        saveCursorPosition(activeTabId);
    }
});

    // Font family control
    document.getElementById('fontFamilySelect').addEventListener('change', function() {
        fontFamily = this.value;
        applyFontSettings();
    });

    // Manual save button
    document.getElementById('manualSaveBtn').addEventListener('click', function() {
        if (activeTabId) {
            const tab = tabs.find(t => t.id === activeTabId);
            if (tab) {
                tab.content = document.getElementById('editor').value;
                saveContentToFile(tab);
            }
        } else {
            showToast('Tidak ada file yang aktif untuk disimpan', 'warning');
        }
    });

document.addEventListener('click', function(e) {
    // Handle tab click
    if (e.target.matches('.nav-link[data-tab-id]')) {
        e.preventDefault();
        setActiveTab(e.target.dataset.tabId);
    }

    // Handle close tab button
    if (e.target.matches('.btn-close-tab, .btn-close-tab *')) {
        const btn = e.target.closest('.btn-close-tab');
        closeTab(btn.dataset.tabId);
    }

    // Handle close all tabs
    if (e.target.matches('#closeAllTabs, #closeAllTabs *')) {
        closeAllTabs();
    }
});


    document.getElementById('searchBtn').addEventListener('click', function() {
        const novel = document.getElementById('novelSelect').value;
        const keyword = document.getElementById('searchInput').value.trim();

        if (!novel) {
            showToast('Pilih novel terlebih dahulu', 'warning');
            return;
        }

        if (!keyword) {
            showToast('Masukkan kata kunci pencarian', 'warning');
            return;
        }

        searchNovel(novel, keyword);
    });

    // Also allow searching with Enter key
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            document.getElementById('searchBtn').click();
        }
    });


    document.getElementById('editor').addEventListener('input', function() {
        // Update konten tab segera (tanpa debounce)
        if (activeTabId) {
            const tab = tabs.find(t => t.id === activeTabId);
            if (tab) {
                tab.content = this.value;
            }
        }

        // Debounce hanya untuk operasi berat seperti word count
        clearTimeout(inputDebounceTimer);
        inputDebounceTimer = setTimeout(updateWordCount, INPUT_DEBOUNCE_DELAY);
    });

    document.getElementById('editor').addEventListener('blur', function() {
        if (activeTabId && autoSaveEnabled) {
            const tab = tabs.find(t => t.id === activeTabId);
            if (tab && tab.content !== tab.savedContent) {
                saveContentToFile(tab);
            }
        }
    });
    
document.addEventListener('keydown', function(e) {
    // Ctrl+S untuk save
    if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        if (activeTabId) {
            const tab = tabs.find(t => t.id === activeTabId);
            if (tab) {
                tab.content = document.getElementById('editor').value;
                saveContentToFile(tab);
            }
        }
    }
    

    // Ctrl+H atau Ctrl+R untuk find/replace
    else if ((e.ctrlKey || e.metaKey) && (e.key === 'h' || e.key === 'f')) {
        e.preventDefault();
        openFindReplaceModal();
    }
    
    // Shortcut dalam modal find/replace
    else if (document.getElementById('findReplaceModal').classList.contains('show')) {
        if (e.key === 'Enter' && e.shiftKey) {
            e.preventDefault();
            navigateMatch('prev');
        } 
        else if (e.key === 'Enter') {
            e.preventDefault();
            navigateMatch('next');
        }
    }
});
        
        // Jika modal find/replace terbuka, tambahkan shortcut Enter untuk next
        if (document.getElementById('findReplaceModal').classList.contains('show')) {
            if (e.key === 'Enter' && e.shiftKey) {
                e.preventDefault();
                navigateMatch('prev');
            } else if (e.key === 'Enter') {
                e.preventDefault();
                navigateMatch('next');
            }
        }
    });
    
     document.getElementById('findInput').addEventListener('input', performSearch);
    document.getElementById('matchCase').addEventListener('change', performSearch);
    
    document.getElementById('findPrevBtn').addEventListener('click', () => navigateMatch('prev'));
    document.getElementById('findNextBtn').addEventListener('click', () => navigateMatch('next'));
    document.getElementById('replaceBtn').addEventListener('click', replaceCurrent);
    document.getElementById('replaceAllBtn').addEventListener('click', replaceAll);
    
    // Tutup highlight saat modal ditutup
    document.getElementById('findReplaceModal').addEventListener('hidden.bs.modal', clearHighlights);
    
    // Toggle word wrap
    document.getElementById('wordWrapToggle').addEventListener('change', function() {
        wordWrapEnabled = this.checked;
        localStorage.setItem('wordWrap', wordWrapEnabled);
        const editor = document.getElementById('editor');
        editor.style.whiteSpace = wordWrapEnabled ? 'pre-wrap' : 'pre';
        showToggleNotification('wordWrap', wordWrapEnabled);
    });

    // Word count update
    document.getElementById('editor').addEventListener('input', updateWordCount);

    // Pilih novel
    document.getElementById('novelSelect').addEventListener('change', function() {
        const novel = this.value;

        // Check if there are open tabs
        if (tabs.length > 0) {
            const confirmChange = confirm('Anda memiliki file yang terbuka. Jika melanjutkan, semua tab akan ditutup. Lanjutkan?');
            if (!confirmChange) {
                this.value = activeTabId ? tabs.find(t => t.id === activeTabId).novel : '';
                return;
            }

            // Close all tabs if confirmed
            closeAllTabs();
        }

        if (novel) {
            loadSeries(novel);
            loadCharacters(novel);
            loadLocations(novel);
            loadNotes(novel);
            loadChapters(novel);
            // Aktifkan tombol-tombol yang membutuhkan novel
            document.getElementById('newSeriesBtn').disabled = false;
            document.getElementById('addCharacterBtn').disabled = false;
            document.getElementById('addLocationBtn').disabled = false;
            document.getElementById('addNoteBtn').disabled = false;
        } else {
            // Kosongkan semua daftar
            document.getElementById('seriesList').innerHTML = '';
            document.getElementById('chapterList').innerHTML = '';
            document.getElementById('characterList').innerHTML = '';
            document.getElementById('locationList').innerHTML = '';
            document.getElementById('noteList').innerHTML = '';

            // Nonaktifkan tombol-tombol
            document.getElementById('newSeriesBtn').disabled = true;
            document.getElementById('addCharacterBtn').disabled = true;
            document.getElementById('addLocationBtn').disabled = true;
            document.getElementById('addNoteBtn').disabled = true;
        }
    });

    // Tombol novel baru
    document.getElementById('newNovelBtn').addEventListener('click', function() {
        const modal = new bootstrap.Modal(document.getElementById('newNovelModal'));
        document.getElementById('novelName').value = '';
        modal.show();
    });

    // Konfirmasi novel baru
    document.getElementById('confirmNewNovel').addEventListener('click', function() {
        const name = document.getElementById('novelName').value.trim();
        if (name) {
            fetch('', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=create_novel&name=${encodeURIComponent(name)}`
            })
                .then(response => response.json())
                .then(data => {
                if (data.success) {
                    const novelSelect = document.getElementById('novelSelect');
                    novelSelect.innerHTML = '<option value="">Pilih Novel</option>';
                    data.novels.forEach(novel => {
                        const option = document.createElement('option');
                        option.value = novel;
                        option.textContent = novel;
                        novelSelect.appendChild(option);
                    });
                    novelSelect.value = name;
                    novelSelect.dispatchEvent(new Event('change'));

                    showToast('Novel berhasil dibuat');
                    bootstrap.Modal.getInstance(document.getElementById('newNovelModal')).hide();
                } else {
                    showToast(data.message || 'Gagal membuat novel', 'danger');
                }
            });
        }
    });

    // Tombol seri baru
    document.getElementById('newSeriesBtn').addEventListener('click', function() {
        const novel = document.getElementById('novelSelect').value;
        if (novel) {
            const modal = new bootstrap.Modal(document.getElementById('newSeriesModal'));
            document.getElementById('seriesName').value = '';
            modal.show();
        }
    });

    // Konfirmasi seri baru
    document.getElementById('confirmNewSeries').addEventListener('click', function() {
        const novel = document.getElementById('novelSelect').value;
        const name = document.getElementById('seriesName').value.trim();

        if (novel && name) {
            fetch('', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=create_series&novel=${encodeURIComponent(novel)}&name=${encodeURIComponent(name)}`
            })
                .then(response => response.json())
                .then(data => {
                if (data.success) {
                    loadSeries(novel);
                    showToast('Seri berhasil dibuat');
                    bootstrap.Modal.getInstance(document.getElementById('newSeriesModal')).hide();
                } else {
                    showToast(data.message || 'Gagal membuat seri', 'danger');
                }
            });
        }
    });

    // Tombol chapter baru (akan ditambahkan secara dinamis saat seri dimuat)
    // Perbaikan untuk tombol chapter baru
    // Perbaikan untuk tombol chapter baru
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('new-chapter-btn') || e.target.closest('.new-chapter-btn')) {
            const btn = e.target.classList.contains('new-chapter-btn') ? e.target : e.target.closest('.new-chapter-btn');
            const novel = document.getElementById('novelSelect').value;
            const series = btn.getAttribute('data-series');

            if (novel && series) {
                const modal = new bootstrap.Modal(document.getElementById('newChapterModal'));
                document.getElementById('chapterName').value = '';

                // Fungsi untuk menangani konfirmasi
                function handleConfirmNewChapter() {
                    const name = document.getElementById('chapterName').value.trim();
                    if (name) {
                        fetch('', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded',
                            },
                            body: `action=create_chapter&novel=${encodeURIComponent(novel)}&series=${encodeURIComponent(series)}&name=${encodeURIComponent(name)}`
                        })
                            .then(response => response.json())
                            .then(data => {
                            if (data.success) {
                                loadChapters(novel, series);
                                showToast('Chapter berhasil dibuat');
                                bootstrap.Modal.getInstance(document.getElementById('newChapterModal')).hide();

                                // Buka chapter baru
                                const filename = name + '.txt';
                                loadFileContent(novel, series, filename, 'chapter');

                                // Hapus event listener setelah selesai
                                document.getElementById('confirmNewChapter').removeEventListener('click', handleConfirmNewChapter);
                            } else {
                                showToast(data.message || 'Gagal membuat chapter', 'danger');
                            }
                        });
                    }
                }

                // Tambahkan event listener baru
                document.getElementById('confirmNewChapter').addEventListener('click', handleConfirmNewChapter);

                // Bersihkan event listener saat modal ditutup
                modal._element.addEventListener('hidden.bs.modal', function() {
                    document.getElementById('confirmNewChapter').removeEventListener('click', handleConfirmNewChapter);
                });

                modal.show();
            }
        }
    });

    // Tombol tambah karakter
    document.getElementById('addCharacterBtn').addEventListener('click', function() {
        const novel = document.getElementById('novelSelect').value;
        const name = document.getElementById('newCharacterName').value.trim();

        if (novel && name) {
            fetch('', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=create_character&novel=${encodeURIComponent(novel)}&name=${encodeURIComponent(name)}`
            })
                .then(response => response.json())
                .then(data => {
                if (data.success) {
                    loadCharacters(novel);
                    document.getElementById('newCharacterName').value = '';
                    showToast('Karakter berhasil dibuat');

                    // Buka file karakter baru
                    loadFileContent(novel, '', name, 'character');
                } else {
                    showToast(data.message || 'Gagal membuat karakter', 'danger');
                }
            });
        }
    });

    // Tombol tambah lokasi
    document.getElementById('addLocationBtn').addEventListener('click', function() {
        const novel = document.getElementById('novelSelect').value;
        const name = document.getElementById('newLocationName').value.trim();

        if (novel && name) {
            fetch('', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=create_location&novel=${encodeURIComponent(novel)}&name=${encodeURIComponent(name)}`
            })
                .then(response => response.json())
                .then(data => {
                if (data.success) {
                    loadLocations(novel);
                    document.getElementById('newLocationName').value = '';
                    showToast('Lokasi berhasil dibuat');

                    // Buka file lokasi baru
                    loadFileContent(novel, '', name, 'location');
                } else {
                    showToast(data.message || 'Gagal membuat lokasi', 'danger');
                }
            });
        }
    });

    // Tombol tambah catatan
    document.getElementById('addNoteBtn').addEventListener('click', function() {
        const novel = document.getElementById('novelSelect').value;
        const title = document.getElementById('newNoteTitle').value.trim();

        if (novel && title) {
            fetch('', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=create_note&novel=${encodeURIComponent(novel)}&title=${encodeURIComponent(title)}`
            })
                .then(response => response.json())
                .then(data => {
                if (data.success) {
                    loadNotes(novel);
                    document.getElementById('newNoteTitle').value = '';
                    showToast('Catatan berhasil dibuat');

                    // Buka file catatan baru
                    loadFileContent(novel, '', title, 'note');
                } else {
                    showToast(data.message || 'Gagal membuat catatan', 'danger');
                }
            });
        }
    });

    // Tombol hapus (ditambahkan secara dinamis)
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('delete-btn') || e.target.closest('.delete-btn')) {
            const btn = e.target.classList.contains('delete-btn') ? e.target : e.target.closest('.delete-btn');
            const type = btn.getAttribute('data-type');
            const name = btn.getAttribute('data-name');
            const novel = document.getElementById('novelSelect').value;

            let series = '';
            if (type === 'chapter') {
                // Cari seri dari parent element
                const seriesItem = btn.closest('.list-group-item');
                if (seriesItem) {
                    series = seriesItem.querySelector('span').textContent;
                }
            }

            const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
            const deleteMessage = document.getElementById('deleteMessage');

            let itemType = '';
            switch (type) {
                case 'novel': itemType = 'novel'; break;
                case 'series': itemType = 'seri'; break;
                case 'chapter': itemType = 'chapter'; break;
                case 'character': itemType = 'karakter'; break;
                case 'location': itemType = 'lokasi'; break;
                case 'note': itemType = 'catatan'; break;
            }

            deleteMessage.textContent = `Apakah Anda yakin ingin menghapus ${itemType} "${name}"?`;
            modal.show();

            // Set handler untuk konfirmasi hapus
            document.getElementById('confirmDelete').onclick = function() {
                fetch('', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `action=delete&novel=${encodeURIComponent(novel)}&series=${encodeURIComponent(series)}&name=${encodeURIComponent(name)}&type=${type}`
                })
                    .then(response => response.json())
                    .then(data => {
                    if (data.success) {
                        showToast(`${itemType.charAt(0).toUpperCase() + itemType.slice(1)} berhasil dihapus`);

                        // Refresh daftar yang sesuai
                        if (type === 'novel') {
                            // Update dropdown novel
                            const novelSelect = document.getElementById('novelSelect');
                            novelSelect.innerHTML = '<option value="">Pilih Novel</option>';
                            data.novels.forEach(novel => {
                                const option = document.createElement('option');
                                option.value = novel;
                                option.textContent = novel;
                                novelSelect.appendChild(option);
                            });
                            novelSelect.value = '';
                            novelSelect.dispatchEvent(new Event('change'));
                        } else if (type === 'series') {
                            loadSeries(novel);
                        } else if (type === 'chapter') {
                            loadChapters(novel, series);
                        } else if (type === 'character') {
                            loadCharacters(novel);
                        } else if (type === 'location') {
                            loadLocations(novel);
                        } else if (type === 'note') {
                            loadNotes(novel);
                        }

                        // Jika yang dihapus adalah file yang sedang dibuka, kosongkan editor
                        if (currentTab.file === name || currentTab.file === name + '.txt') {
                            document.getElementById('editor').value = '';
                            currentContent = '';
                            updateWordCount();
                            document.getElementById('editorInfo').textContent = '';
                        }
                    } else {
                        showToast(data.message || `Gagal menghapus ${itemType}`, 'danger');
                    }

                    bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
                });
            };
        }
    });

    // Simpan saat editor kehilangan fokus
    document.getElementById('editor').addEventListener('blur', function() {
        if (autoSaveEnabled) {
            saveContent();
        }
    });

  

    // Inisialisasi word wrap
    document.getElementById('editor').style.whiteSpace = 'pre-wrap';

    // Inisialisasi auto-save
    startAutoSave();
});