<?php
$page_title  = 'Languages';
$page_active = 'languages';
require __DIR__ . '/includes/page_header.php';

// Built-in 8 languages we ship with the APK (English is the default and
// can't be removed). Custom codes the operator adds get appended to this
// list from `webview_settings.lang_codes`.
$builtin_languages = [
    ['code' => 'en',    'name' => 'English',    'native' => 'English'],
    ['code' => 'ar',    'name' => 'Arabic',     'native' => 'العربية'],
    ['code' => 'fr',    'name' => 'French',     'native' => 'Français'],
    ['code' => 'es',    'name' => 'Spanish',    'native' => 'Español'],
    ['code' => 'pt',    'name' => 'Portuguese', 'native' => 'Português'],
    ['code' => 'tr',    'name' => 'Turkish',    'native' => 'Türkçe'],
    ['code' => 'de',    'name' => 'German',     'native' => 'Deutsch'],
    ['code' => 'zh-cn', 'name' => 'Chinese',    'native' => '中文'],
    ['code' => 'pl',    'name' => 'Polish',     'native' => 'Polski'],
];
$builtin_codes = array_column($builtin_languages, 'code');

// Custom codes the operator has added (stored as a CSV in webview_settings).
$row = db_one('SELECT value FROM webview_settings WHERE key = ?', ['lang_codes']);
$custom_codes = $row && $row['value'] !== ''
    ? array_values(array_filter(array_map('trim', explode(',', $row['value']))))
    : [];
$custom_languages = [];
foreach ($custom_codes as $c) {
    if (in_array($c, $builtin_codes, true)) continue;
    $custom_languages[] = ['code' => $c, 'name' => strtoupper($c), 'native' => strtoupper($c)];
}

$languages = array_merge(
    array_map(function ($l) {
        $l['is_default'] = ($l['code'] === 'en');
        return $l;
    }, $builtin_languages),
    array_map(function ($l) { $l['is_default'] = false; return $l; }, $custom_languages)
);

// Full 217-key English catalog — sourced from the reference JSON bundled with
// the panel. Historical note: this used to be a hardcoded 32-key stub, which
// meant the editor UI only rendered 32 rows and every "Save" wiped the other
// 185 seeded translations. Loading the full catalog fixes both.
$strings = [];
$ref_path = __DIR__ . '/includes/_languages_reference.json';
if (is_file($ref_path)) {
    $ref = @json_decode((string)@file_get_contents($ref_path), true);
    if (is_array($ref)) {
        foreach ($ref as $entry) {
            if (($entry['code'] ?? '') === 'en' && !empty($entry['words']) && is_array($entry['words'])) {
                $strings = $entry['words'];
                break;
            }
        }
    }
}
// Absolute-fallback stub so the page still renders if the reference file is
// missing. Should only fire on a broken install.
if (!$strings) {
    $strings = [
        'account'  => 'Account', 'cancel'   => 'Cancel',   'delete' => 'Delete',
        'password' => 'Password','settings' => 'Settings', 'search' => 'Search',
    ];
}
?>

<!-- Header band -->
<div class="-mx-6 -mt-6 px-6 py-5 mb-6 border-b border-dark-700" style="background:#111;">
    <p class="text-xs font-semibold text-primary-400 uppercase tracking-wider mb-1">
        <span class="text-dark-400">Master Panel</span> / IBO Ultra / Languages
    </p>
    <h2 class="text-2xl font-bold text-white flex items-center gap-3">
        <i class="ph ph-translate text-primary-400"></i> Languages
    </h2>
</div>

<div class="grid grid-cols-1 lg:grid-cols-[320px_1fr] gap-5" x-data="{ active: 'en' }">
    <!-- ============ Languages list ============ -->
    <div class="card">
        <div class="card-head">
            <h3><i class="ph ph-translate"></i> Languages</h3>
            <button onclick="promptAddLang()" class="lang-add-btn"><i class="ph ph-plus"></i></button>
        </div>
        <div class="p-3 space-y-1.5">
            <?php foreach ($languages as $lang): ?>
                <button type="button"
                        @click="active='<?php echo h($lang['code']); ?>'"
                        :class="active==='<?php echo h($lang['code']); ?>' ? 'lang-active' : ''"
                        class="lang-row group"
                        data-code="<?php echo h($lang['code']); ?>">
                    <span class="flex items-center gap-3 min-w-0">
                        <span class="lang-icon"><i class="ph ph-translate"></i></span>
                        <span class="min-w-0">
                            <span class="block text-sm font-semibold text-white truncate"><?php echo h($lang['native']); ?></span>
                            <span class="block text-[10px] text-dark-400 uppercase tracking-wider"><?php echo h($lang['code']); ?></span>
                        </span>
                    </span>
                    <?php if ($lang['is_default']): ?>
                        <span class="pill pill-on text-[10px]">DEFAULT</span>
                    <?php else: ?>
                        <button onclick="event.stopPropagation(); deleteLang('<?php echo h($lang['code']); ?>')" class="icon-btn danger opacity-0 group-hover:opacity-100">
                            <i class="ph ph-trash text-red-400"></i>
                        </button>
                    <?php endif; ?>
                </button>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- ============ Edit Translations ============ -->
    <div class="card">
        <div class="card-head">
            <h3>
                <i class="ph ph-pencil-simple"></i> Edit Translations
                <span class="ml-2 text-xs text-dark-400">[<span x-text="active"></span>]</span>
            </h3>
            <div class="search">
                <i class="ph ph-magnifying-glass"></i>
                <input type="text" id="lang-search" placeholder="Search…">
            </div>
        </div>
        <div class="overflow-x-auto">
            <table class="compact">
                <thead><tr>
                    <th class="text-primary-400 uppercase tracking-wider">String name</th>
                    <th class="text-primary-400 uppercase tracking-wider">Original value</th>
                    <th class="text-primary-400 uppercase tracking-wider">Edited string</th>
                </tr></thead>
                <tbody id="lang-rows">
                    <?php foreach ($strings as $key => $value): ?>
                        <tr data-key="<?php echo h($key); ?>">
                            <td class="mono text-dark-300"><?php echo h($key); ?></td>
                            <td class="text-dark-200"><?php echo h($value); ?></td>
                            <td><input class="form-input mono text-xs lang-edit"
                                       data-key="<?php echo h($key); ?>"
                                       value="<?php echo h($value); ?>"></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <div class="flex justify-end gap-2 px-5 py-3 border-t border-dark-700">
            <span class="text-xs text-dark-500 self-center">Edits are saved per language. The app picks them up next time it opens.</span>
            <button onclick="saveLanguage()" class="btn-primary text-xs"><i class="ph ph-floppy-disk"></i> Save</button>
        </div>
    </div>
</div>

<style>
.lang-row {
    display: flex; align-items: center; justify-content: space-between;
    width: 100%; padding: 10px 12px;
    background: transparent; border: 1px solid transparent; border-radius: 8px;
    cursor: pointer; text-align: left; transition: background .15s, border-color .15s;
}
.lang-row:hover { background: rgba(243,156,18,0.05); border-color: #2a2a2a; }
.lang-active {
    background: rgba(243,156,18,0.10) !important;
    border-color: rgba(243,156,18,0.35) !important;
}
.lang-icon {
    width: 36px; height: 36px; flex-shrink: 0;
    background: rgba(243,156,18,0.10); color: #f39c12;
    border-radius: 6px; display: flex; align-items: center; justify-content: center;
    font-size: 18px;
}
.lang-add-btn {
    width: 30px; height: 30px; background: #f39c12; color: #161616;
    border-radius: 6px; display: inline-flex; align-items: center; justify-content: center;
    cursor: pointer;
}
.lang-add-btn:hover { background: #ffb240; }
</style>

<script>
document.getElementById('lang-search').addEventListener('input', (e) => {
    const q = e.target.value.toLowerCase();
    document.querySelectorAll('#lang-rows tr').forEach(row => {
        const key = (row.dataset.key || '').toLowerCase();
        const val = row.querySelector('td:nth-child(2)').textContent.toLowerCase();
        row.style.display = (!q || key.includes(q) || val.includes(q)) ? '' : 'none';
    });
});

async function promptAddLang() {
    const code = (prompt('Two-letter language code (e.g. ja, ko, ru):', '') || '').trim().toLowerCase();
    if (!code) return;
    if (!/^[a-z]{2,3}(-[a-z]{2})?$/.test(code)) { toast('Invalid code', 'error'); return; }
    try {
        await api.post('api/languages.php', { action: 'add_lang', code });
        toast('Added ' + code.toUpperCase(), 'success');
        location.reload();   // simplest way to re-render the languages sidebar
    } catch (e) { toast(e.message, 'error'); }
}

async function deleteLang(code) {
    if (code === 'en') { toast('Cannot remove the default language', 'warn'); return; }
    if (!(await confirmDanger('Remove the ' + code.toUpperCase() + ' language?'))) return;
    try { await api.post('api/languages.php', { action: 'delete_lang', code }); toast('Removed', 'success'); location.reload(); }
    catch (e) { toast(e.message, 'error'); }
}

let currentLangCode = 'en';
async function loadLangStrings(code) {
    currentLangCode = code;
    try {
        const r = await api.get('api/languages.php?code=' + encodeURIComponent(code));
        document.querySelectorAll('.lang-edit').forEach(inp => {
            const k = inp.dataset.key;
            if (r.strings && r.strings[k] !== undefined) inp.value = r.strings[k];
        });
    } catch (e) { /* may be a fresh language */ }
}

async function saveLanguage() {
    const strings = {};
    document.querySelectorAll('.lang-edit').forEach(inp => { strings[inp.dataset.key] = inp.value; });
    try {
        const r = await api.post('api/languages.php', { action: 'save_lang', code: currentLangCode, strings });
        toast('Saved ' + r.count + ' string' + (r.count === 1 ? '' : 's') + ' for ' + currentLangCode.toUpperCase(), 'success');
    } catch (e) { toast(e.message, 'error'); }
}

// Reload strings whenever the active language changes. Uses data-code so we
// aren't regexing the Alpine `@click` attribute.
document.querySelectorAll('.lang-row[data-code]').forEach(btn => {
    btn.addEventListener('click', () => {
        const code = btn.getAttribute('data-code');
        if (code) loadLangStrings(code);
    });
});
// Kick off with whatever Alpine's default is (the built-in 'en').
loadLangStrings('en');
</script>

<?php require __DIR__ . '/includes/page_footer.php'; ?>
