// ── Languages Manager ──────────────────────────────────────────────────
let projectLanguages = [{ code: 'en', name: 'English' }];

function initLanguages() {
    // 1. Try server data
    let saved = currentConfig.languages || [];
    // 2. If empty, try localStorage
    if (saved.length === 0) {
        const local = localStorage.getItem('pp_misc_languages');
        if (local) {
            try { saved = JSON.parse(local); } catch (e) { saved = []; }
        }
    }
    // 3. Fallback to English
    projectLanguages = saved.length > 0 ? saved : [{ code: 'en', name: 'English' }];
    renderLanguagesList();
    updateLanguagesDisplay();
}

function renderLanguagesList() {
    const list = document.getElementById('languagesList');
    if (!list) return;
    list.innerHTML = '';
    projectLanguages.forEach(lang => {
        const li = document.createElement('li');
        li.className = 'list-group-item d-flex justify-content-between align-items-center py-1 px-2';
        li.innerHTML = `<span><strong>${lang.code}</strong> – ${lang.name}</span>
            ${lang.code !== 'en' ? '<button class="btn btn-sm btn-outline-danger remove-lang-btn" data-code="' + lang.code + '"><i class="bi bi-x"></i></button>' : ''}`;
        list.appendChild(li);
    });
}

function updateLanguagesDisplay() {
    const display = document.getElementById('projLanguagesDisplay');
    if (display) {
        const names = projectLanguages.map(l => l.name).join(', ');
        display.textContent = names || 'English';
    }
    syncLangSelectorVisibility();
}

// The "Show language selector" toggle is only meaningful with 2+ languages: it is
// auto-revealed AND auto-checked when a second language is added (unless the owner
// has explicitly turned it off), and hidden again when back to a single language.
function syncLangSelectorVisibility() {
    const wrap = document.getElementById('langSelectorWrap');
    const cb = document.getElementById('projShowLangSelector');
    if (!wrap) return;
    const multi = (projectLanguages || []).length >= 2;
    wrap.style.display = multi ? '' : 'none';
    const proj = (typeof currentConfig !== 'undefined' && currentConfig.project) || {};
    if (multi && cb) {
        // Auto-check the first time we reach 2+ languages (flag never set yet).
        if (proj.showLanguageSelector === undefined && !cb.checked) cb.checked = true;
    }
    // Live-translation toggle is only relevant with 2+ languages — reveal it there
    // (opt-in: revealed but NOT auto-checked, since it ships a DB table + editor).
    const liveWrap = document.getElementById('liveTransWrap');
    const liveCb = document.getElementById('projLiveTranslations');
    if (liveWrap) liveWrap.style.display = multi ? '' : 'none';
    if (multi && liveCb && proj.liveTranslations === true) liveCb.checked = true;
}
window.syncLangSelectorVisibility = syncLangSelectorVisibility;

async function saveLanguages() {
    // Always keep a local backup
    localStorage.setItem('pp_misc_languages', JSON.stringify(projectLanguages));
    currentConfig.languages = projectLanguages;

    await saveSection('languages', { languages: projectLanguages });
}

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('btnManageLanguages')?.addEventListener('click', () => {
        new bootstrap.Modal(document.getElementById('languagesModal')).show();
    });

    document.getElementById('btnAddLanguage')?.addEventListener('click', async () => {
        const code = document.getElementById('newLangCode').value.trim();
        const name = document.getElementById('newLangName').value.trim();
        if (!code || !name) { pp.dialog.toast('error', 'Code and name required.'); return; }
        if (projectLanguages.some(l => l.code === code)) { pp.dialog.toast('warning', 'Language already added.'); return; }

        projectLanguages.push({ code, name });
        document.getElementById('newLangCode').value = '';
        document.getElementById('newLangName').value = '';
        renderLanguagesList();
        updateLanguagesDisplay();
        await saveLanguages();

        try {
            await fetch(`${baseUrl}/project/${projectSlug}/misc/labels/init`, {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ langCode: code })
            });
        } catch (err) { console.warn('Failed to init labels for', code); }
    });


    document.getElementById('languagesList')?.addEventListener('click', async (e) => {
        if (e.target.closest('.remove-lang-btn')) {
            const code = e.target.closest('.remove-lang-btn').dataset.code;
            if (code === 'en') return; // never delete English

            const confirmed = await pp.dialog.confirm(
                'Delete language?',
                'All labels for this language will be permanently removed.'
            );
            if (!confirmed) return;

            projectLanguages = projectLanguages.filter(l => l.code !== code);
            renderLanguagesList();
            updateLanguagesDisplay();
            saveLanguages();
        }
    });

});