<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\Admin;

use APD\I18n\JsTranslationManager;
use APD\I18n\PluginTranslationManager;
use APD\Support\RequestData;

defined('ABSPATH') || exit;

class TranslationsPage
{
    public function render() : void
    {
        if (! current_user_can('manage_asuka_designer')) {
            wp_die(esc_html__('You are not allowed to manage translations.', 'asuka-product-designer'));
        }

        $query = RequestData::query();
        $settings = (new AdminSettings())->all();
        $manager = new JsTranslationManager();
        $currentLocale = JsTranslationManager::normalizeLocale((string) ($query['locale'] ?? determine_locale() ?: get_locale()));
        if ($currentLocale === '') {
            $currentLocale = 'en';
        }

        $availableLocales = $manager->getAvailableLocales();
        if (! isset($availableLocales[$currentLocale]) && $currentLocale !== '') {
            $availableLocales[$currentLocale] = [
                'label' => $manager->getLocaleDisplayName($currentLocale),
                'translations' => [],
                'updated_at' => '',
            ];
        }
        if (! isset($availableLocales[$currentLocale])) {
            $currentLocale = 'en';
        }

        $scope = sanitize_key((string) ($query['scope'] ?? 'designer'));
        if ($scope === 'wordpress') {
            $this->renderPluginEditor($settings, $manager, $availableLocales, $currentLocale);
            return;
        }

        $rows = $manager->getEditorRows($currentLocale);
        $stats = $manager->getLocaleStats($currentLocale);
        $wpLocale = JsTranslationManager::normalizeLocale(determine_locale() ?: get_locale());
        $namespaces = array_values(array_unique(array_map(static fn(array $row) => (string) $row['namespace'], $rows)));
        sort($namespaces, SORT_NATURAL | SORT_FLAG_CASE);
        ?>
        <div class="wrap apd-admin-shell apd-admin-theme-<?php echo esc_attr($settings['admin_theme']); ?> apd-translations-page" data-apd-translations-page>
            <div class="apd-page-heading">
                <div>
                    <span class="apd-badge"><?php esc_html_e('JS runtime i18n', 'asuka-product-designer'); ?></span>
                    <h1><?php esc_html_e('Translations', 'asuka-product-designer'); ?></h1>
                    <p><?php esc_html_e('Manage AsukaDesigner JavaScript translations per locale, while keeping the WordPress plugin strings compatible with gettext tools like Loco Translate.', 'asuka-product-designer'); ?></p>
                </div>
            </div>

            <?php $this->renderScopeTabs('designer', $currentLocale); ?>

            <?php $this->renderNotices(); ?>

            <div class="apd-grid apd-grid-3 apd-translation-kpis">
                <article class="apd-mini-stat">
                    <strong><?php echo esc_html((string) $stats['translated']); ?></strong>
                    <span><?php esc_html_e('Translated keys for this locale', 'asuka-product-designer'); ?></span>
                </article>
                <article class="apd-mini-stat">
                    <strong><?php echo esc_html((string) $stats['missing']); ?></strong>
                    <span><?php esc_html_e('Keys still using fallback English', 'asuka-product-designer'); ?></span>
                </article>
                <article class="apd-mini-stat">
                    <strong><?php echo esc_html($wpLocale ?: 'en'); ?></strong>
                    <span><?php esc_html_e('Current WordPress locale', 'asuka-product-designer'); ?></span>
                </article>
            </div>

            <div class="apd-grid apd-translation-layout apd-translation-layout--main">
                <aside class="apd-card apd-translation-sidebar">
                    <div class="apd-card-head">
                        <h2><?php esc_html_e('Locales', 'asuka-product-designer'); ?></h2>
                        <span class="apd-chip"><?php echo esc_html((string) count($availableLocales)); ?></span>
                    </div>
                    <div class="apd-translation-locale-list">
                        <?php foreach ($availableLocales as $locale => $payload) : ?>
                            <?php $localeStats = $manager->getLocaleStats($locale); ?>
                            <a class="apd-list-item<?php echo $locale === $currentLocale ? ' is-active' : ''; ?>" href="<?php echo esc_url(admin_url('admin.php?page=apd-translations&locale=' . rawurlencode($locale))); ?>">
                                <strong><?php echo esc_html($locale); ?></strong>
                                <span><?php echo esc_html((string) ($payload['label'] ?? $manager->getLocaleDisplayName($locale))); ?></span>
                                <span class="apd-chip apd-chip-soft"><?php echo esc_html(sprintf(/* translators: Placeholder values are populated from the current administration record. */ __('%1$d / %2$d translated', 'asuka-product-designer'), (int) $localeStats['translated'], (int) $localeStats['total'])); ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="apd-form-grid apd-stack-top">
                        <?php wp_nonce_field('apd_create_js_translation_locale'); ?>
                        <input type="hidden" name="action" value="apd_create_js_translation_locale">
                        <input type="hidden" name="scope" value="designer">
                        <label class="apd-field">
                            <span><?php esc_html_e('Add locale', 'asuka-product-designer'); ?></span>
                            <input type="text" name="locale" placeholder="<?php echo esc_attr__('fr_FR', 'asuka-product-designer'); ?>" pattern="[A-Za-z0-9_-]+" required>
                            <small><?php esc_html_e('Examples: fr_FR, fr, es_ES, de_DE.', 'asuka-product-designer'); ?></small>
                        </label>
                        <label class="apd-field">
                            <span><?php esc_html_e('Label', 'asuka-product-designer'); ?></span>
                            <input type="text" name="locale_label" placeholder="<?php echo esc_attr__('French (France)', 'asuka-product-designer'); ?>">
                        </label>
                        <button type="submit" class="button button-primary"><?php esc_html_e('Create locale', 'asuka-product-designer'); ?></button>
                    </form>
                </aside>

                <section class="apd-card apd-translation-editor">
                    <div class="apd-card-head apd-translation-editor-head">
                        <div>
                            <h2><?php echo esc_html(sprintf(/* translators: Placeholder values are populated from the current administration record. */ __('Editing locale: %s', 'asuka-product-designer'), $currentLocale)); ?></h2>
                            <p><?php echo esc_html(sprintf(/* translators: Placeholder values are populated from the current administration record. */ __('The JavaScript runtime uses %s first, then falls back to English. WordPress admin strings still use standard gettext.', 'asuka-product-designer'), $currentLocale)); ?></p>
                        </div>
                        <div class="apd-inline-actions">
                            <?php if ($currentLocale !== 'en') : ?>
                                <a class="button button-secondary" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=apd_export_js_translation_locale&locale=' . rawurlencode($currentLocale)), 'apd_export_js_translation_locale_' . $currentLocale)); ?>"><?php esc_html_e('Export JSON', 'asuka-product-designer'); ?></a>
                                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" onsubmit="return window.confirm('<?php echo esc_js(__('Delete this locale and all its overrides?', 'asuka-product-designer')); ?>');">
                                    <?php wp_nonce_field('apd_delete_js_translation_locale_' . $currentLocale); ?>
                                    <input type="hidden" name="action" value="apd_delete_js_translation_locale">
                                    <input type="hidden" name="locale" value="<?php echo esc_attr($currentLocale); ?>">
                                    <button type="submit" class="button button-secondary"><?php esc_html_e('Delete locale', 'asuka-product-designer'); ?></button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="apd-grid apd-grid-3 apd-translation-tools apd-spacing-bottom">
                        <label class="apd-field">
                            <span><?php esc_html_e('Search keys', 'asuka-product-designer'); ?></span>
                            <input type="search" data-apd-translation-search placeholder="<?php echo esc_attr__('common.save, layers, pricing…', 'asuka-product-designer'); ?>">
                        </label>
                        <label class="apd-field">
                            <span><?php esc_html_e('Namespace', 'asuka-product-designer'); ?></span>
                            <select data-apd-translation-namespace>
                                <option value=""><?php esc_html_e('All namespaces', 'asuka-product-designer'); ?></option>
                                <?php foreach ($namespaces as $namespace) : ?>
                                    <option value="<?php echo esc_attr($namespace); ?>"><?php echo esc_html($namespace); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </label>
                        <div class="apd-field">
                            <span><?php esc_html_e('Visible rows', 'asuka-product-designer'); ?></span>
                            <div class="apd-translation-visible-count" data-apd-translation-visible-count><?php echo esc_html((string) count($rows)); ?></div>
                        </div>
                    </div>

                    <?php if ($currentLocale !== 'en') : ?>
                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="apd-form-grid apd-spacing-bottom">
                            <?php wp_nonce_field('apd_import_js_translation_locale_' . $currentLocale); ?>
                            <input type="hidden" name="action" value="apd_import_js_translation_locale">
                            <input type="hidden" name="locale" value="<?php echo esc_attr($currentLocale); ?>">
                            <label class="apd-field">
                                <span><?php esc_html_e('Import JSON overrides', 'asuka-product-designer'); ?></span>
                                <textarea name="import_json" rows="5" placeholder='<?php echo esc_attr__('{"common.save":"Enregistrer"}', 'asuka-product-designer'); ?>'></textarea>
                                <small><?php esc_html_e('Accepts either a flat key/value object, a nested runtime catalog, or an exported locale payload.', 'asuka-product-designer'); ?></small>
                            </label>
                            <div class="apd-inline-actions">
                                <button type="submit" class="button button-secondary"><?php esc_html_e('Import into this locale', 'asuka-product-designer'); ?></button>
                            </div>
                        </form>
                    <?php endif; ?>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <?php wp_nonce_field('apd_save_js_translations_' . $currentLocale); ?>
                        <input type="hidden" name="action" value="apd_save_js_translations">
                        <input type="hidden" name="locale" value="<?php echo esc_attr($currentLocale); ?>">
                        <label class="apd-field apd-translation-label-field">
                            <span><?php esc_html_e('Locale label', 'asuka-product-designer'); ?></span>
                            <input type="text" name="locale_label" value="<?php echo esc_attr((string) ($availableLocales[$currentLocale]['label'] ?? $manager->getLocaleDisplayName($currentLocale))); ?>" <?php disabled($currentLocale, 'en'); ?>>
                        </label>

                        <div class="apd-translation-table-wrap">
                            <table class="widefat fixed striped apd-translation-table">
                                <thead>
                                    <tr>
                                        <th class="apd-col-key"><?php esc_html_e('Key', 'asuka-product-designer'); ?></th>
                                        <th class="apd-col-namespace"><?php esc_html_e('Namespace', 'asuka-product-designer'); ?></th>
                                        <th><?php esc_html_e('Default English', 'asuka-product-designer'); ?></th>
                                        <th><?php echo esc_html($currentLocale === 'en' ? __('Catalog value', 'asuka-product-designer') : __('Override for this locale', 'asuka-product-designer')); ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($rows as $row) : ?>
                                        <tr data-apd-translation-row data-apd-key="<?php echo esc_attr((string) $row['key']); ?>" data-apd-namespace="<?php echo esc_attr((string) $row['namespace']); ?>" data-apd-default="<?php echo esc_attr((string) $row['default']); ?>" data-apd-translation="<?php echo esc_attr((string) $row['translation']); ?>">
                                            <td>
                                                <code><?php echo esc_html((string) $row['key']); ?></code>
                                            </td>
                                            <td><?php echo esc_html((string) $row['namespace']); ?></td>
                                            <td>
                                                <div class="apd-translation-default"><?php echo esc_html((string) $row['default']); ?></div>
                                            </td>
                                            <td>
                                                <?php if ($currentLocale === 'en') : ?>
                                                    <div class="apd-translation-default"><?php echo esc_html((string) $row['default']); ?></div>
                                                <?php else : ?>
                                                    <textarea class="apd-translation-input" name="translations[<?php echo esc_attr((string) $row['key']); ?>]" rows="2" placeholder="<?php echo esc_attr((string) $row['default']); ?>"><?php echo esc_textarea((string) $row['translation']); ?></textarea>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <?php if ($currentLocale !== 'en') : ?>
                            <div class="apd-inline-actions apd-stack-top">
                                <button type="submit" class="button button-primary button-hero"><?php esc_html_e('Save translations', 'asuka-product-designer'); ?></button>
                            </div>
                        <?php endif; ?>
                    </form>
                </section>
            </div>
        </div>
        <?php
    }

    private function renderPluginEditor(array $settings, JsTranslationManager $localeManager, array $availableLocales, string $currentLocale) : void
    {
        $manager = new PluginTranslationManager();
        $rows = $manager->getEditorRows($currentLocale);
        $stats = $manager->getLocaleStats($currentLocale);
        $wpLocale = JsTranslationManager::normalizeLocale(determine_locale() ?: get_locale());
        $namespaces = array_values(array_unique(array_map(static fn(array $row) => (string) $row['namespace'], $rows)));
        sort($namespaces, SORT_NATURAL | SORT_FLAG_CASE);
        ?>
        <div class="wrap apd-admin-shell apd-admin-theme-<?php echo esc_attr($settings['admin_theme']); ?> apd-translations-page" data-apd-translations-page>
            <div class="apd-page-heading">
                <div>
                    <span class="apd-badge"><?php esc_html_e('WordPress gettext', 'asuka-product-designer'); ?></span>
                    <h1><?php esc_html_e('Translations', 'asuka-product-designer'); ?></h1>
                    <p><?php esc_html_e('Translate every string discovered in the plugin. Database overrides take priority, while WordPress language packs and Loco Translate remain the automatic fallback.', 'asuka-product-designer'); ?></p>
                </div>
            </div>

            <?php $this->renderScopeTabs('wordpress', $currentLocale); ?>
            <?php $this->renderNotices(); ?>

            <div class="apd-grid apd-grid-3 apd-translation-kpis">
                <article class="apd-mini-stat">
                    <strong><?php echo esc_html((string) $stats['translated']); ?></strong>
                    <span><?php esc_html_e('Plugin strings translated here', 'asuka-product-designer'); ?></span>
                </article>
                <article class="apd-mini-stat">
                    <strong><?php echo esc_html((string) $stats['missing']); ?></strong>
                    <span><?php esc_html_e('Strings using gettext or English fallback', 'asuka-product-designer'); ?></span>
                </article>
                <article class="apd-mini-stat">
                    <strong><?php echo esc_html($wpLocale ?: 'en'); ?></strong>
                    <span><?php esc_html_e('Current WordPress locale', 'asuka-product-designer'); ?></span>
                </article>
            </div>

            <div class="apd-grid apd-translation-layout apd-translation-layout--main">
                <aside class="apd-card apd-translation-sidebar">
                    <div class="apd-card-head">
                        <h2><?php esc_html_e('Locales', 'asuka-product-designer'); ?></h2>
                        <span class="apd-chip"><?php echo esc_html((string) count($availableLocales)); ?></span>
                    </div>
                    <div class="apd-translation-locale-list">
                        <?php foreach ($availableLocales as $locale => $payload) : ?>
                            <?php $localeStats = $manager->getLocaleStats($locale); ?>
                            <a class="apd-list-item<?php echo $locale === $currentLocale ? ' is-active' : ''; ?>" href="<?php echo esc_url(add_query_arg(['page' => 'apd-translations', 'scope' => 'wordpress', 'locale' => $locale], admin_url('admin.php'))); ?>">
                                <strong><?php echo esc_html($locale); ?></strong>
                                <span><?php echo esc_html((string) ($payload['label'] ?? $localeManager->getLocaleDisplayName($locale))); ?></span>
                                <span class="apd-chip apd-chip-soft"><?php echo esc_html(sprintf(/* translators: Placeholder values are populated from the current administration record. */ __('%1$d / %2$d translated', 'asuka-product-designer'), (int) $localeStats['translated'], (int) $localeStats['total'])); ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="apd-form-grid apd-stack-top">
                        <?php wp_nonce_field('apd_create_js_translation_locale'); ?>
                        <input type="hidden" name="action" value="apd_create_js_translation_locale">
                        <input type="hidden" name="scope" value="wordpress">
                        <label class="apd-field">
                            <span><?php esc_html_e('Add locale', 'asuka-product-designer'); ?></span>
                            <input type="text" name="locale" placeholder="<?php echo esc_attr__('fr_FR', 'asuka-product-designer'); ?>" pattern="[A-Za-z0-9_-]+" required>
                            <small><?php esc_html_e('The same locale is shared with the JavaScript designer.', 'asuka-product-designer'); ?></small>
                        </label>
                        <label class="apd-field">
                            <span><?php esc_html_e('Label', 'asuka-product-designer'); ?></span>
                            <input type="text" name="locale_label" placeholder="<?php echo esc_attr__('French (France)', 'asuka-product-designer'); ?>">
                        </label>
                        <button type="submit" class="button button-primary"><?php esc_html_e('Create locale', 'asuka-product-designer'); ?></button>
                    </form>
                </aside>

                <section class="apd-card apd-translation-editor">
                    <div class="apd-card-head apd-translation-editor-head">
                        <div>
                            <h2><?php echo esc_html(sprintf(/* translators: Placeholder values are populated from the current administration record. */ __('Editing locale: %s', 'asuka-product-designer'), $currentLocale)); ?></h2>
                            <p><?php esc_html_e('The scanner reads translatable PHP calls and keeps a stable identifier even when a string appears in several files.', 'asuka-product-designer'); ?></p>
                        </div>
                        <div class="apd-inline-actions">
                            <?php if ($currentLocale !== 'en') : ?>
                                <a class="button button-secondary" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=apd_export_plugin_translation_locale&locale=' . rawurlencode($currentLocale)), 'apd_export_plugin_translation_locale_' . $currentLocale)); ?>"><?php esc_html_e('Export JSON', 'asuka-product-designer'); ?></a>
                                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" onsubmit="return window.confirm('<?php echo esc_js(__('Delete this locale and all its JavaScript and WordPress overrides?', 'asuka-product-designer')); ?>');">
                                    <?php wp_nonce_field('apd_delete_js_translation_locale_' . $currentLocale); ?>
                                    <input type="hidden" name="action" value="apd_delete_js_translation_locale">
                                    <input type="hidden" name="scope" value="wordpress">
                                    <input type="hidden" name="locale" value="<?php echo esc_attr($currentLocale); ?>">
                                    <button type="submit" class="button button-secondary"><?php esc_html_e('Delete locale', 'asuka-product-designer'); ?></button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="apd-translation-native-note">
                        <strong><?php esc_html_e('Compatible with Loco Translate', 'asuka-product-designer'); ?></strong>
                        <span><?php esc_html_e('Leave a field empty to use the normal WordPress translation. Fill it only when this installation needs a local override.', 'asuka-product-designer'); ?></span>
                    </div>

                    <div class="apd-grid apd-grid-3 apd-translation-tools apd-spacing-bottom">
                        <label class="apd-field">
                            <span><?php esc_html_e('Search strings', 'asuka-product-designer'); ?></span>
                            <input type="search" data-apd-translation-search placeholder="<?php echo esc_attr__('Settings, products, license...', 'asuka-product-designer'); ?>">
                        </label>
                        <label class="apd-field">
                            <span><?php esc_html_e('Area', 'asuka-product-designer'); ?></span>
                            <select data-apd-translation-namespace>
                                <option value=""><?php esc_html_e('All areas', 'asuka-product-designer'); ?></option>
                                <?php foreach ($namespaces as $namespace) : ?>
                                    <option value="<?php echo esc_attr($namespace); ?>"><?php echo esc_html($namespace); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </label>
                        <div class="apd-field">
                            <span><?php esc_html_e('Visible rows', 'asuka-product-designer'); ?></span>
                            <div class="apd-translation-visible-count" data-apd-translation-visible-count><?php echo esc_html((string) count($rows)); ?></div>
                        </div>
                    </div>

                    <?php if ($currentLocale !== 'en') : ?>
                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="apd-form-grid apd-spacing-bottom">
                            <?php wp_nonce_field('apd_import_plugin_translation_locale_' . $currentLocale); ?>
                            <input type="hidden" name="action" value="apd_import_plugin_translation_locale">
                            <input type="hidden" name="locale" value="<?php echo esc_attr($currentLocale); ?>">
                            <label class="apd-field">
                                <span><?php esc_html_e('Import JSON overrides', 'asuka-product-designer'); ?></span>
                                <textarea name="import_json" rows="4" placeholder='{"wp_...":"Translation"}'></textarea>
                            </label>
                            <div class="apd-inline-actions">
                                <button type="submit" class="button button-secondary"><?php esc_html_e('Import into this locale', 'asuka-product-designer'); ?></button>
                            </div>
                        </form>
                    <?php endif; ?>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <?php wp_nonce_field('apd_save_plugin_translations_' . $currentLocale); ?>
                        <input type="hidden" name="action" value="apd_save_plugin_translations">
                        <input type="hidden" name="locale" value="<?php echo esc_attr($currentLocale); ?>">
                        <div class="apd-translation-table-wrap">
                            <table class="widefat fixed striped apd-translation-table apd-translation-table--plugin">
                                <thead>
                                    <tr>
                                        <th class="apd-col-namespace"><?php esc_html_e('Area', 'asuka-product-designer'); ?></th>
                                        <th><?php esc_html_e('Default English and source', 'asuka-product-designer'); ?></th>
                                        <th><?php echo esc_html($currentLocale === 'en' ? __('Catalog value', 'asuka-product-designer') : __('Override for this locale', 'asuka-product-designer')); ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($rows as $row) : ?>
                                        <tr data-apd-translation-row data-apd-key="<?php echo esc_attr((string) $row['key']); ?>" data-apd-namespace="<?php echo esc_attr((string) $row['namespace']); ?>" data-apd-default="<?php echo esc_attr((string) $row['default']); ?>" data-apd-translation="<?php echo esc_attr((string) $row['translation']); ?>">
                                            <td><span class="apd-chip apd-chip-soft"><?php echo esc_html((string) $row['namespace']); ?></span></td>
                                            <td>
                                                <div class="apd-translation-default"><?php echo esc_html((string) $row['default']); ?></div>
                                                <?php if ((string) $row['context'] !== '') : ?><code><?php echo esc_html((string) $row['context']); ?></code><?php endif; ?>
                                                <small class="apd-translation-source"><?php echo esc_html(implode(', ', array_slice((array) $row['files'], 0, 3))); ?></small>
                                            </td>
                                            <td>
                                                <?php if ($currentLocale === 'en') : ?>
                                                    <div class="apd-translation-default"><?php echo esc_html((string) $row['default']); ?></div>
                                                <?php else : ?>
                                                    <textarea class="apd-translation-input" name="translations[<?php echo esc_attr((string) $row['key']); ?>]" rows="2" placeholder="<?php echo esc_attr((string) $row['default']); ?>"><?php echo esc_textarea((string) $row['translation']); ?></textarea>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <?php if ($currentLocale !== 'en') : ?>
                            <div class="apd-inline-actions apd-stack-top">
                                <button type="submit" class="button button-primary button-hero"><?php esc_html_e('Save plugin translations', 'asuka-product-designer'); ?></button>
                            </div>
                        <?php endif; ?>
                    </form>
                </section>
            </div>
        </div>
        <?php
    }

    private function renderScopeTabs(string $activeScope, string $locale) : void
    {
        $designerUrl = add_query_arg(['page' => 'apd-translations', 'scope' => 'designer', 'locale' => $locale], admin_url('admin.php'));
        $wordpressUrl = add_query_arg(['page' => 'apd-translations', 'scope' => 'wordpress', 'locale' => $locale], admin_url('admin.php'));
        ?>
        <nav class="apd-translation-scope-tabs" aria-label="<?php echo esc_attr__('Translation source', 'asuka-product-designer'); ?>">
            <a class="<?php echo $activeScope === 'designer' ? 'is-active' : ''; ?>" href="<?php echo esc_url($designerUrl); ?>">
                <strong><?php esc_html_e('JavaScript designer', 'asuka-product-designer'); ?></strong>
                <span><?php esc_html_e('Canvas, modules and customer tools', 'asuka-product-designer'); ?></span>
            </a>
            <a class="<?php echo $activeScope === 'wordpress' ? 'is-active' : ''; ?>" href="<?php echo esc_url($wordpressUrl); ?>">
                <strong><?php esc_html_e('WordPress plugin', 'asuka-product-designer'); ?></strong>
                <span><?php esc_html_e('Administration, storefront and WooCommerce', 'asuka-product-designer'); ?></span>
            </a>
        </nav>
        <?php
    }

    public function createLocale() : void
    {
        $this->assertCanManage();
        check_admin_referer('apd_create_js_translation_locale');

        $post = RequestData::post();
        $manager = new JsTranslationManager();
        $locale = JsTranslationManager::normalizeLocale((string) ($post['locale'] ?? ''));
        $label = sanitize_text_field((string) ($post['locale_label'] ?? ''));
        $scope = sanitize_key((string) ($post['scope'] ?? 'designer')) === 'wordpress' ? 'wordpress' : 'designer';

        if ($locale === '' || $locale === 'en') {
            $this->redirectWithStatus('invalid_locale', 'en', $scope);
        }

        $manager->ensureLocale($locale, $label);
        $this->redirectWithStatus('locale_created', $locale, $scope);
    }

    public function save() : void
    {
        $this->assertCanManage();
        $post = RequestData::post();
        $locale = JsTranslationManager::normalizeLocale((string) ($post['locale'] ?? ''));
        check_admin_referer('apd_save_js_translations_' . $locale);

        if ($locale === '' || $locale === 'en') {
            $this->redirectWithStatus('invalid_locale', 'en');
        }

        $translations = isset($post['translations']) && is_array($post['translations']) ? $post['translations'] : [];
        $label = sanitize_text_field((string) ($post['locale_label'] ?? ''));
        (new JsTranslationManager())->saveLocale($locale, $translations, $label);

        $this->redirectWithStatus('updated', $locale);
    }

    public function deleteLocale() : void
    {
        $this->assertCanManage();
        $post = RequestData::post();
        $locale = JsTranslationManager::normalizeLocale((string) ($post['locale'] ?? ''));
        $scope = sanitize_key((string) ($post['scope'] ?? 'designer')) === 'wordpress' ? 'wordpress' : 'designer';
        check_admin_referer('apd_delete_js_translation_locale_' . $locale);
        (new JsTranslationManager())->deleteLocale($locale);
        (new PluginTranslationManager())->deleteLocale($locale);
        $this->redirectWithStatus('locale_deleted', 'en', $scope);
    }

    public function exportLocale() : void
    {
        $this->assertCanManage();
        $query = RequestData::query();
        $locale = JsTranslationManager::normalizeLocale((string) ($query['locale'] ?? ''));
        check_admin_referer('apd_export_js_translation_locale_' . $locale);

        $manager = new JsTranslationManager();
        $payload = [
            'locale' => $locale,
            'label' => $manager->getLocaleDisplayName($locale),
            'translations' => $manager->getLocaleTranslations($locale),
        ];

        nocache_headers();
        header('Content-Type: application/json; charset=' . get_option('blog_charset'));
        header('Content-Disposition: attachment; filename=apd-js-translations-' . $locale . '.json');
        echo wp_json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    public function importLocale() : void
    {
        $this->assertCanManage();
        $post = RequestData::post();
        $locale = JsTranslationManager::normalizeLocale((string) ($post['locale'] ?? ''));
        check_admin_referer('apd_import_js_translation_locale_' . $locale);

        $raw = trim((string) ($post['import_json'] ?? ''));
        if ($locale === '' || $locale === 'en' || $raw === '') {
            $this->redirectWithStatus('import_error', $locale ?: 'en');
        }

        $decoded = json_decode($raw, true);
        if (! is_array($decoded)) {
            $this->redirectWithStatus('import_error', $locale);
        }

        $manager = new JsTranslationManager();
        $payload = $decoded['translations'] ?? $decoded;
        if (! is_array($payload)) {
            $this->redirectWithStatus('import_error', $locale);
        }

        $hasDottedKey = false;
        foreach (array_keys($payload) as $key) {
            if (is_string($key) && str_contains($key, '.')) {
                $hasDottedKey = true;
                break;
            }
        }

        $flat = $hasDottedKey ? $payload : $manager->flattenCatalog($payload);
        $label = sanitize_text_field((string) ($decoded['label'] ?? ''));
        $manager->saveLocale($locale, $flat, $label);

        $this->redirectWithStatus('imported', $locale);
    }

    public function savePluginTranslations() : void
    {
        $this->assertCanManage();
        $post = RequestData::post();
        $locale = JsTranslationManager::normalizeLocale((string) ($post['locale'] ?? ''));
        check_admin_referer('apd_save_plugin_translations_' . $locale);
        if ($locale === '' || $locale === 'en') {
            $this->redirectWithStatus('invalid_locale', 'en', 'wordpress');
        }

        $translations = isset($post['translations']) && is_array($post['translations']) ? $post['translations'] : [];
        (new PluginTranslationManager())->saveLocale($locale, $translations);
        $this->redirectWithStatus('updated', $locale, 'wordpress');
    }

    public function exportPluginLocale() : void
    {
        $this->assertCanManage();
        $query = RequestData::query();
        $locale = JsTranslationManager::normalizeLocale((string) ($query['locale'] ?? ''));
        check_admin_referer('apd_export_plugin_translation_locale_' . $locale);
        $payload = [
            'scope' => 'wordpress',
            'locale' => $locale,
            'translations' => (new PluginTranslationManager())->getLocaleTranslations($locale),
        ];

        nocache_headers();
        header('Content-Type: application/json; charset=' . get_option('blog_charset'));
        header('Content-Disposition: attachment; filename=apd-wordpress-translations-' . $locale . '.json');
        echo wp_json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    public function importPluginLocale() : void
    {
        $this->assertCanManage();
        $post = RequestData::post();
        $locale = JsTranslationManager::normalizeLocale((string) ($post['locale'] ?? ''));
        check_admin_referer('apd_import_plugin_translation_locale_' . $locale);
        $raw = trim((string) ($post['import_json'] ?? ''));
        $decoded = $raw !== '' ? json_decode($raw, true) : null;
        $translations = is_array($decoded['translations'] ?? null)
            ? $decoded['translations']
            : (is_array($decoded) ? $decoded : null);
        if ($locale === '' || $locale === 'en' || ! is_array($translations)) {
            $this->redirectWithStatus('import_error', $locale ?: 'en', 'wordpress');
        }

        (new PluginTranslationManager())->saveLocale($locale, $translations);
        $this->redirectWithStatus('imported', $locale, 'wordpress');
    }

    private function renderNotices() : void
    {
        $messages = [
            'updated' => __('Translations saved.', 'asuka-product-designer'),
            'locale_created' => __('Locale created.', 'asuka-product-designer'),
            'locale_deleted' => __('Locale deleted.', 'asuka-product-designer'),
            'imported' => __('Translations imported.', 'asuka-product-designer'),
            'import_error' => __('Import failed. Please provide valid JSON.', 'asuka-product-designer'),
            'invalid_locale' => __('Please provide a valid locale code.', 'asuka-product-designer'),
        ];

        $query = RequestData::query();
        $status = sanitize_key((string) ($query['apd_notice'] ?? ''));
        if ($status === '' || ! isset($messages[$status])) {
            return;
        }

        $class = in_array($status, ['import_error', 'invalid_locale'], true) ? 'notice-error' : 'notice-success';
        echo '<div class="notice ' . esc_attr($class) . ' is-dismissible"><p>' . esc_html($messages[$status]) . '</p></div>';
    }

    private function redirectWithStatus(string $status, string $locale, string $scope = 'designer') : never
    {
        $url = add_query_arg([
            'page' => 'apd-translations',
            'scope' => $scope,
            'locale' => $locale,
            'apd_notice' => $status,
        ], admin_url('admin.php'));
        wp_safe_redirect($url);
        exit;
    }

    private function assertCanManage() : void
    {
        if (! current_user_can('manage_asuka_designer')) {
            wp_die(esc_html__('You are not allowed to manage translations.', 'asuka-product-designer'));
        }
    }
}
