<?php
 
 
 
 
 
 
 
 
 
$enabledCount = 0;
foreach ($languages as $lang) {
    if ((int)$lang['is_enabled']) $enabledCount++;
}
$editLangName = '';
if ($editLang) {
    foreach ($enabledLanguages as $el) {
        if ($el['code'] === $editLang) {
            $editLangName = $el['name'] . ' (' . $el['native_name'] . ')';
            break;
        }
    }
}
$totalLangs = count($languages);
?>




<div class="bg-white rounded-lg border border-gray-200 mb-6">
    <form action="/admin/languages" method="POST" id="langForm">
        <?= Router::csrfField() ?>
        <div class="px-4 sm:px-5 py-4 border-b border-gray-200 flex items-center justify-between">
            <div class="flex items-center gap-3">
                <h2 class="text-base font-semibold text-gray-900">Languages</h2>
                <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-gray-100 text-gray-600" id="enabledBadge">
                    <span id="countNum"><?= $enabledCount ?></span> enabled
                </span>
            </div>
            <button type="submit" class="inline-flex items-center gap-1.5 px-3 sm:px-4 py-2 bg-primary-600 text-white text-sm font-medium rounded-lg hover:bg-primary-700 transition-colors">
                <svg viewBox="0 0 24 24" class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
                Save
            </button>
        </div>

        <div id="langGrid" class="p-3 sm:p-4 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-2">
            <?php foreach ($languages as $lang):
                $code = htmlspecialchars($lang['code']);
                $isEnabled = (int)$lang['is_enabled'];
                $isDefault = (int)$lang['is_default'];
                $isEnglish = $lang['code'] === 'en';
                $isRtl = ($lang['direction'] ?? 'ltr') === 'rtl';
            ?>
            <label class="lang-card relative flex items-center gap-2 px-2.5 py-2 rounded-lg border cursor-pointer transition-all duration-150 select-none
                <?= $isEnabled ? 'border-primary-200 bg-primary-50/50' : 'border-gray-200 bg-white hover:border-gray-300' ?>"
                data-lang-card>
                <input type="checkbox" name="enabled[]" value="<?= $code ?>"
                       class="sr-only peer lang-checkbox"
                       <?= $isEnabled ? 'checked' : '' ?>
                       <?= $isEnglish ? 'checked disabled' : '' ?>
                       data-code="<?= $code ?>">
                <?php if ($isEnglish): ?>
                    <input type="hidden" name="enabled[]" value="en">
                <?php endif; ?>

                <div class="w-7 h-4 rounded-full transition-colors duration-150 shrink-0 relative
                    <?= $isEnabled ? 'bg-primary-600' : 'bg-gray-300' ?>" data-toggle>
                    <div class="absolute top-[2px] left-[2px] w-3 h-3 rounded-full bg-white shadow-sm transition-transform duration-150
                        <?= $isEnabled ? 'translate-x-3' : '' ?>"></div>
                </div>

                <span class="fi fi-<?= Translator::flagCode($lang['code']) ?> fis shrink-0" style="width:20px;height:20px;border-radius:3px;box-shadow:0 0 0 1px rgba(0,0,0,0.08);"></span>

                <div class="flex-1 min-w-0">
                    <div class="flex items-center gap-1">
                        <span class="text-xs font-semibold text-gray-900 truncate"><?= htmlspecialchars($lang['name']) ?></span>
                        <?php if ($isRtl): ?>
                            <span class="text-[8px] font-bold text-amber-600 bg-amber-100 px-1 rounded leading-none py-0.5">RTL</span>
                        <?php endif; ?>
                    </div>
                    <div class="flex items-center gap-1">
                        <span class="text-[11px] text-gray-500 truncate"><?= htmlspecialchars($lang['native_name']) ?></span>
                        <span class="text-[10px] text-gray-400 font-mono"><?= $code ?></span>
                    </div>
                </div>

                <div class="shrink-0 flex flex-col items-center" title="Set as default language">
                    <input type="radio" name="default_lang" value="<?= $code ?>"
                           class="w-3.5 h-3.5 text-primary-600 border-gray-300 focus:ring-primary-500 default-radio"
                           <?= $isDefault ? 'checked' : '' ?>
                           <?= !$isEnabled ? 'disabled' : '' ?>>
                    <?php if ($isDefault): ?>
                        <span class="text-[9px] text-primary-600 font-semibold mt-0.5" data-default-label>Default</span>
                    <?php endif; ?>
                </div>
            </label>
            <?php endforeach; ?>
        </div>

        
        <div id="langToggle" class="px-4 pb-3 text-center hidden">
            <button type="button" onclick="toggleLangGrid()" class="inline-flex items-center gap-1.5 text-xs text-gray-500 hover:text-primary-600 transition-colors py-1 px-3 rounded-full border border-gray-200 hover:border-primary-200 hover:bg-primary-50">
                <span id="langToggleText">Show all <?= $totalLangs ?> languages</span>
                <svg id="langToggleArrow" class="w-3.5 h-3.5 transition-transform duration-200" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M19 9l-7 7-7-7"/></svg>
            </button>
        </div>

        
        <div class="px-4 sm:px-5 py-3 border-t border-gray-200">
            <label class="flex items-center justify-between cursor-pointer">
                <div>
                    <span class="text-sm font-medium text-gray-900">Auto-detect browser language</span>
                    <p class="text-xs text-gray-500 mt-0.5">Automatically redirect visitors to their browser's preferred language. When disabled, all visitors see the default language unless they switch manually.</p>
                </div>
                <div class="relative shrink-0 ml-4">
                    <input type="checkbox" name="auto_detect_language" value="1" class="sr-only peer" <?= $autoDetectLanguage ? 'checked' : '' ?>>
                    <div class="w-9 h-5 rounded-full transition-colors duration-150 <?= $autoDetectLanguage ? 'bg-primary-600' : 'bg-gray-300' ?> peer-focus:ring-2 peer-focus:ring-primary-500 peer-focus:ring-offset-1 peer-checked:bg-primary-600" data-auto-detect-toggle>
                        <div class="absolute top-[2px] left-[2px] w-4 h-4 rounded-full bg-white shadow-sm transition-transform duration-150 <?= $autoDetectLanguage ? 'translate-x-4' : '' ?>" data-auto-detect-dot></div>
                    </div>
                </div>
            </label>
        </div>
    </form>
</div>




<div class="bg-white rounded-lg border border-gray-200">
    <div class="px-4 sm:px-5 py-4 border-b border-gray-200">
        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2">
            <div>
                <h2 class="text-base font-semibold text-gray-900">Edit Translations</h2>
                <p class="text-xs text-gray-500 mt-0.5">Customize frontend text. Changes override built-in files.</p>
            </div>
        </div>
        
        <?php if (!empty($enabledLanguages)): ?>
            <div class="flex items-center gap-1.5 mt-3 overflow-x-auto pb-1 -mb-1 scrollbar-hide">
                <?php foreach ($enabledLanguages as $el): ?>
                    <a href="/admin/languages?edit=<?= htmlspecialchars($el['code']) ?>"
                       class="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all duration-150 border whitespace-nowrap shrink-0
                        <?= $editLang === $el['code'] ? 'bg-primary-600 text-white border-primary-600' : 'bg-white text-gray-600 border-gray-200 hover:border-primary-300 hover:text-primary-700' ?>">
                        <span class="fi fi-<?= Translator::flagCode($el['code']) ?> fis" style="width:14px;height:14px;border-radius:2px;box-shadow:0 0 0 1px rgba(0,0,0,0.08);"></span>
                        <?= htmlspecialchars($el['name']) ?>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <?php if (!$editLang): ?>
        <div class="px-5 py-12 text-center">
            <svg class="mx-auto w-10 h-10 text-gray-300 mb-3" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
            <p class="text-sm text-gray-500">Select a language above to edit its translations.</p>
        </div>
    <?php else: ?>
        
        <div class="px-4 sm:px-5 py-3 border-b border-gray-100 bg-gray-50/50">
            <div class="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-2">
                <div class="flex items-center gap-3">
                    <div class="relative flex-1 sm:flex-initial">
                        <input type="text" id="translationSearch" placeholder="Filter keys..."
                               class="w-full sm:w-48 pl-8 pr-3 py-1.5 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 bg-white">
                        <svg class="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                    </div>
                    <span class="text-xs text-gray-400 whitespace-nowrap">
                        <?= $totalKeys ?> keys<?= $overrideCount > 0 ? " &middot; <span class='text-amber-600 font-medium'>$overrideCount custom</span>" : '' ?><?php if ($untranslatedCount > 0): ?>
                        &middot; <button type="button" id="filterUntranslated" onclick="toggleUntranslatedFilter()" class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-700 hover:bg-red-200 transition-colors cursor-pointer border-0">
                            <svg class="w-3 h-3" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
                            <?= $untranslatedCount ?> untranslated
                        </button><?php endif; ?>
                    </span>
                </div>
                <div class="flex items-center gap-1">
                    <button type="button" onclick="expandAllSections()" class="text-[11px] text-gray-400 hover:text-primary-600 px-1.5 py-0.5 rounded hover:bg-primary-50 transition-colors whitespace-nowrap">Expand all</button>
                    <span class="text-gray-300">|</span>
                    <button type="button" onclick="collapseAllSections()" class="text-[11px] text-gray-400 hover:text-primary-600 px-1.5 py-0.5 rounded hover:bg-primary-50 transition-colors whitespace-nowrap">Collapse all</button>
                </div>
            </div>
        </div>

        
        <form method="post" action="/admin/translations/save" id="translationForm">
            <?= Router::csrfField() ?>
            <input type="hidden" name="lang" value="<?= htmlspecialchars($editLang) ?>">

            <div class="divide-y divide-gray-100">
                <?php $sectionIdx = 0; foreach ($sections as $sectionName => $rows):
                    $sectionOverrides = 0;
                    foreach ($rows as $r) { if ($r['is_overridden']) $sectionOverrides++; }
                ?>
                    <div class="translation-section" id="section-<?= $sectionIdx ?>" data-section="<?= htmlspecialchars(strtolower($sectionName)) ?>">
                        
                        <button type="button" onclick="toggleSection(<?= $sectionIdx ?>)"
                                class="section-header w-full px-4 sm:px-5 py-3 flex items-center justify-between hover:bg-gray-50 transition-colors cursor-pointer text-left">
                            <div class="flex items-center gap-2">
                                <svg class="section-chevron w-4 h-4 text-gray-400 transition-transform duration-200 <?= $sectionIdx === 0 ? 'rotate-90' : '' ?>" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M9 18l6-6-6-6"/></svg>
                                <h3 class="text-xs font-semibold text-gray-600 uppercase tracking-wider"><?= htmlspecialchars($sectionName) ?></h3>
                                <?php if (!empty($registeredSectionNames[$sectionName])): ?>
                                    <span class="text-[9px] font-semibold px-1.5 py-0.5 rounded-full bg-violet-100 text-violet-600">Theme</span>
                                <?php endif; ?>
                                <span class="text-[11px] text-gray-400 font-normal"><?= count($rows) ?></span>
                            </div>
                            <?php if ($sectionOverrides > 0): ?>
                                <span class="text-[10px] font-medium text-amber-600 bg-amber-50 px-1.5 py-0.5 rounded-full"><?= $sectionOverrides ?> custom</span>
                            <?php endif; ?>
                        </button>

                        
                        <div class="section-body" id="sectionBody-<?= $sectionIdx ?>" <?= $sectionIdx !== 0 ? 'style="display:none"' : '' ?>>
                            <?php foreach ($rows as $row): ?>
                                <div class="translation-row px-4 sm:px-5 py-2 hover:bg-gray-50/50 transition-colors border-t border-gray-50"
                                     data-key="<?= htmlspecialchars($row['key']) ?>"
                                     data-search="<?= htmlspecialchars(strtolower($row['key'] . ' ' . $row['english'] . ' ' . $row['current'])) ?>"
                                     <?= $row['current'] === '' ? 'data-untranslated="1"' : '' ?>>

                                    <div class="flex flex-col sm:flex-row sm:items-start gap-1.5 sm:gap-3">
                                        
                                        <div class="sm:w-36 shrink-0 sm:pt-1.5 flex items-center justify-between sm:block">
                                            <code class="text-[11px] text-gray-500 font-mono leading-tight break-all"><?= htmlspecialchars($row['key']) ?></code>
                                            <?php if ($row['is_overridden']): ?>
                                                <span class="inline-block ml-1 w-1.5 h-1.5 rounded-full bg-amber-500 custom-dot shrink-0" title="Custom override"></span>
                                            <?php endif; ?>
                                        </div>

                                        
                                        <?php if ($editLang !== 'en'): ?>
                                            <div class="sm:w-1/4 shrink-0 sm:pt-1.5">
                                                <p class="text-xs text-gray-400 leading-snug"><?= htmlspecialchars($row['english']) ?></p>
                                            </div>
                                        <?php endif; ?>

                                        
                                        <div class="flex-1 flex items-start gap-1.5">
                                            <textarea name="translations[<?= htmlspecialchars($row['key']) ?>]"
                                                      rows="1"
                                                      data-original="<?= htmlspecialchars($row['current']) ?>"
                                                      <?php if (!empty($row['hint'])): ?>placeholder="Default: <?= htmlspecialchars($row['hint']) ?>"<?php endif; ?>
                                                      class="translation-input flex-1 px-2.5 py-1.5 border border-gray-200 rounded text-sm resize-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 transition-colors leading-snug"
                                                      oninput="autoResize(this); trackChange(this)"><?= htmlspecialchars($row['current']) ?></textarea>
                                            <?php if ($row['is_overridden']): ?>
                                                <button type="button"
                                                        onclick="resetKey('<?= htmlspecialchars($row['key']) ?>', this)"
                                                        class="reset-btn shrink-0 mt-1 p-1 text-gray-400 hover:text-red-500 transition-colors rounded hover:bg-red-50"
                                                        title="Reset to default">
                                                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php $sectionIdx++; endforeach; ?>
            </div>

            
            <div id="saveBar" class="sticky bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-4 sm:px-5 py-3 flex items-center justify-between translate-y-full transition-transform duration-200" style="box-shadow: 0 -2px 10px rgba(0,0,0,0.06);">
                <span class="text-sm text-gray-600"><span id="changeCount" class="font-semibold text-primary-600">0</span> unsaved</span>
                <div class="flex items-center gap-2">
                    <button type="button" onclick="discardChanges()" class="px-3 py-1.5 text-sm text-gray-500 hover:text-gray-700 transition-colors">Discard</button>
                    <button type="submit" class="px-4 py-1.5 bg-primary-600 text-white text-sm font-medium rounded-lg hover:bg-primary-700 transition-colors">Save</button>
                </div>
            </div>
        </form>
    <?php endif; ?>
</div>




<script>



(function() {
    const grid = document.getElementById('langGrid');
    const cards = [...grid.querySelectorAll('.lang-card')];
    const toggle = document.getElementById('langToggle');
    const total = cards.length;
    let expanded = false;

    function getColsPerRow() {
        const w = window.innerWidth;
        if (w >= 1024) return 5;
        if (w >= 768) return 4;
        if (w >= 640) return 3;
        return 2;
    }

    function updateGrid() {
        const cols = getColsPerRow();
        const maxVisible = cols * 3;

        if (total <= maxVisible) {
            cards.forEach(c => c.classList.remove('hidden'));
            toggle.classList.add('hidden');
            return;
        }

        toggle.classList.remove('hidden');

        if (expanded) {
            cards.forEach(c => c.classList.remove('hidden'));
            document.getElementById('langToggleText').textContent = 'Show less';
            document.getElementById('langToggleArrow').style.transform = 'rotate(180deg)';
        } else {
            cards.forEach((c, i) => {
                c.classList.toggle('hidden', i >= maxVisible);
            });
            document.getElementById('langToggleText').textContent = 'Show all ' + total + ' languages';
            document.getElementById('langToggleArrow').style.transform = '';
        }
    }

    window.toggleLangGrid = function() {
        expanded = !expanded;
        updateGrid();
    };

    let resizeTimer;
    window.addEventListener('resize', function() {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(updateGrid, 100);
    });
    updateGrid();
})();




document.querySelectorAll('[data-lang-card]').forEach(card => {
    card.addEventListener('click', function(e) {
        if (e.target.type === 'radio') return;
        const cb = this.querySelector('.lang-checkbox');
        if (cb.disabled) return;
        cb.checked = !cb.checked;
        cb.dispatchEvent(new Event('change'));
    });
});

(function() {
    const checkboxes = document.querySelectorAll('.lang-checkbox');
    const countEl = document.getElementById('countNum');
    const badge = document.getElementById('enabledBadge');

    function updateCards() {
        let count = 0;
        checkboxes.forEach(cb => { if (cb.checked) count++; });
        countEl.textContent = count;

        checkboxes.forEach(cb => {
            const card = cb.closest('[data-lang-card]');
            const toggle = card.querySelector('[data-toggle]');
            const dot = toggle.querySelector('div');
            const radio = card.querySelector('.default-radio');

            if (cb.checked) {
                card.classList.remove('border-gray-200', 'bg-white');
                card.classList.add('border-primary-200', 'bg-primary-50/50');
                toggle.classList.remove('bg-gray-300');
                toggle.classList.add('bg-primary-600');
                dot.classList.add('translate-x-3');
                if (radio) radio.disabled = false;
            } else {
                card.classList.add('border-gray-200', 'bg-white');
                card.classList.remove('border-primary-200', 'bg-primary-50/50');
                toggle.classList.add('bg-gray-300');
                toggle.classList.remove('bg-primary-600');
                dot.classList.remove('translate-x-3');
                if (radio) {
                    radio.disabled = true;
                    if (radio.checked) {
                        document.querySelector('.default-radio[value="en"]').checked = true;
                    }
                }
            }

            if (cb.dataset.code !== 'en') {
                card.style.opacity = '';
                card.style.pointerEvents = '';
            }
        });
    }

    checkboxes.forEach(cb => cb.addEventListener('change', updateCards));
    updateCards();
})();




(function() {
    const cb = document.querySelector('input[name="auto_detect_language"]');
    if (!cb) return;
    const toggle = document.querySelector('[data-auto-detect-toggle]');
    const dot = document.querySelector('[data-auto-detect-dot]');
    cb.addEventListener('change', function() {
        if (this.checked) {
            toggle.classList.remove('bg-gray-300');
            toggle.classList.add('bg-primary-600');
            dot.classList.add('translate-x-4');
        } else {
            toggle.classList.add('bg-gray-300');
            toggle.classList.remove('bg-primary-600');
            dot.classList.remove('translate-x-4');
        }
    });
    cb.closest('label').addEventListener('click', function(e) {
        if (e.target === cb) return;
        e.preventDefault();
        cb.checked = !cb.checked;
        cb.dispatchEvent(new Event('change'));
    });
})();




<?php if ($editLang): ?>
const sectionCount = <?= $sectionIdx ?>;
const openSections = new Set([0]); 

function toggleSection(idx) {
    const body = document.getElementById('sectionBody-' + idx);
    const chevron = document.querySelectorAll('.section-chevron')[idx];
    if (!body) return;

    if (openSections.has(idx)) {
        body.style.display = 'none';
        chevron.classList.remove('rotate-90');
        openSections.delete(idx);
    } else {
        body.style.display = '';
        chevron.classList.add('rotate-90');
        openSections.add(idx);
        
        body.querySelectorAll('.translation-input').forEach(autoResize);
    }
}

function expandAllSections() {
    for (let i = 0; i < sectionCount; i++) {
        const body = document.getElementById('sectionBody-' + i);
        const chevron = document.querySelectorAll('.section-chevron')[i];
        if (body) {
            body.style.display = '';
            openSections.add(i);
            body.querySelectorAll('.translation-input').forEach(autoResize);
        }
        if (chevron) chevron.classList.add('rotate-90');
    }
}

function collapseAllSections() {
    for (let i = 0; i < sectionCount; i++) {
        const body = document.getElementById('sectionBody-' + i);
        const chevron = document.querySelectorAll('.section-chevron')[i];
        if (body) { body.style.display = 'none'; openSections.delete(i); }
        if (chevron) chevron.classList.remove('rotate-90');
    }
}




const csrfToken = '<?= htmlspecialchars($_SESSION['csrf_token'] ?? '') ?>';
const selectedLang = '<?= htmlspecialchars($editLang) ?>';
let changedKeys = new Set();

function autoResize(el) {
    el.style.height = 'auto';
    el.style.height = el.scrollHeight + 'px';
}
document.querySelectorAll('.translation-input').forEach(autoResize);

function trackChange(el) {
    const key = el.name.replace('translations[', '').replace(']', '');
    if (el.value !== el.getAttribute('data-original')) {
        changedKeys.add(key);
        el.classList.add('border-amber-400', 'bg-amber-50/50');
        el.classList.remove('border-gray-200');
    } else {
        changedKeys.delete(key);
        el.classList.remove('border-amber-400', 'bg-amber-50/50');
        el.classList.add('border-gray-200');
    }
    updateSaveBar();
}

function updateSaveBar() {
    const bar = document.getElementById('saveBar');
    document.getElementById('changeCount').textContent = changedKeys.size;
    bar.classList.toggle('translate-y-full', changedKeys.size === 0);
}

function discardChanges() {
    document.querySelectorAll('.translation-input').forEach(el => {
        el.value = el.getAttribute('data-original');
        el.classList.remove('border-amber-400', 'bg-amber-50/50');
        el.classList.add('border-gray-200');
        autoResize(el);
    });
    changedKeys.clear();
    updateSaveBar();
}

function resetKey(key, btn) {
    if (!confirm('Reset to default?')) return;
    fetch('/admin/translations/reset', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken },
        body: JSON.stringify({ lang: selectedLang, key: key }),
    })
    .then(r => r.json())
    .then(data => {
        if (!data.success) { alert(data.error || 'Error'); return; }
        const row = document.querySelector('[data-key="' + key + '"]');
        if (!row) return;
        const textarea = row.querySelector('.translation-input');
        textarea.value = data.default_value;
        textarea.setAttribute('data-original', data.default_value);
        textarea.classList.remove('border-amber-400', 'bg-amber-50/50');
        textarea.classList.add('border-gray-200');
        autoResize(textarea);
        row.querySelectorAll('.custom-dot').forEach(d => d.remove());
        row.querySelectorAll('.reset-btn').forEach(b => b.remove());
        changedKeys.delete(key);
        updateSaveBar();
    })
    .catch(() => alert('Network error.'));
}




document.getElementById('translationSearch').addEventListener('input', function() {
    const q = this.value.toLowerCase().trim();

    
    if (q && untranslatedFilterActive) {
        untranslatedFilterActive = false;
        const btn = document.getElementById('filterUntranslated');
        if (btn) {
            btn.classList.add('bg-red-100', 'text-red-700', 'hover:bg-red-200');
            btn.classList.remove('bg-red-600', 'text-white', 'hover:bg-red-700');
        }
    }

    document.querySelectorAll('.translation-section').forEach((section, idx) => {
        let visible = 0;
        section.querySelectorAll('.translation-row').forEach(row => {
            const match = !q || row.getAttribute('data-search').includes(q);
            row.style.display = match ? '' : 'none';
            if (match) visible++;
        });
        section.style.display = visible > 0 ? '' : 'none';

        
        if (q && visible > 0) {
            const body = document.getElementById('sectionBody-' + idx);
            const chevron = document.querySelectorAll('.section-chevron')[idx];
            if (body) {
                body.style.display = '';
                body.querySelectorAll('.translation-input').forEach(autoResize);
            }
            if (chevron) chevron.classList.add('rotate-90');
            openSections.add(idx);
        }
    });

    
    if (!q) {
        for (let i = 0; i < sectionCount; i++) {
            const body = document.getElementById('sectionBody-' + i);
            const chevron = document.querySelectorAll('.section-chevron')[i];
            if (!openSections.has(i)) {
                if (body) body.style.display = 'none';
                if (chevron) chevron.classList.remove('rotate-90');
            }
        }
    }
});




let untranslatedFilterActive = false;

function toggleUntranslatedFilter() {
    untranslatedFilterActive = !untranslatedFilterActive;
    const btn = document.getElementById('filterUntranslated');
    const searchInput = document.getElementById('translationSearch');

    if (untranslatedFilterActive) {
        
        searchInput.value = '';
        btn.classList.remove('bg-red-100', 'text-red-700', 'hover:bg-red-200');
        btn.classList.add('bg-red-600', 'text-white', 'hover:bg-red-700');

        document.querySelectorAll('.translation-section').forEach((section, idx) => {
            let visible = 0;
            section.querySelectorAll('.translation-row').forEach(row => {
                const isUntranslated = row.hasAttribute('data-untranslated');
                row.style.display = isUntranslated ? '' : 'none';
                if (isUntranslated) visible++;
            });
            section.style.display = visible > 0 ? '' : 'none';
            
            if (visible > 0) {
                const body = document.getElementById('sectionBody-' + idx);
                const chevron = document.querySelectorAll('.section-chevron')[idx];
                if (body) {
                    body.style.display = '';
                    body.querySelectorAll('.translation-input').forEach(autoResize);
                }
                if (chevron) chevron.classList.add('rotate-90');
                openSections.add(idx);
            }
        });
    } else {
        btn.classList.add('bg-red-100', 'text-red-700', 'hover:bg-red-200');
        btn.classList.remove('bg-red-600', 'text-white', 'hover:bg-red-700');

        
        document.querySelectorAll('.translation-section').forEach((section, idx) => {
            section.style.display = '';
            section.querySelectorAll('.translation-row').forEach(row => {
                row.style.display = '';
            });
        });
        for (let i = 0; i < sectionCount; i++) {
            const body = document.getElementById('sectionBody-' + i);
            const chevron = document.querySelectorAll('.section-chevron')[i];
            if (!openSections.has(i)) {
                if (body) body.style.display = 'none';
                if (chevron) chevron.classList.remove('rotate-90');
            }
        }
    }
}

window.addEventListener('beforeunload', e => {
    if (changedKeys.size > 0) { e.preventDefault(); e.returnValue = ''; }
});
document.getElementById('translationForm').addEventListener('submit', () => { changedKeys.clear(); });
<?php endif; ?>
</script>

<style>
    .translation-input:focus { outline: none; }
    [data-lang-card] { user-select: none; }
</style>
