<x-layouts.admin :title="__('Translations')" :subtitle="__('Translate UI strings into any registered language — no FTP required.')">
    <div class="space-y-6" x-data="translationsEditor()" x-init="init()">

        {{-- Top bar: language picker + progress + import/export --}}
        <div class="panel p-5">
            <div class="flex flex-wrap items-center gap-4">
                <div class="flex-1 min-w-[220px]">
                    <label class="block text-xs font-bold text-muted uppercase tracking-wider mb-1.5">{{ __('Language') }}</label>
                    <select onchange="window.location.href='{{ route('admin.translations.index') }}?lang=' + this.value" class="settings-select">
                        @foreach($languages as $lang)
                        <option value="{{ $lang->code }}" {{ $code === $lang->code ? 'selected' : '' }}>
                            {{ $lang->name }} ({{ $lang->code }}){{ $lang->native_name && $lang->native_name !== $lang->name ? ' — ' . $lang->native_name : '' }}
                        </option>
                        @endforeach
                    </select>
                </div>

                <div class="flex-1 min-w-[260px]">
                    <div class="flex items-center justify-between mb-1.5">
                        <span class="text-xs font-bold text-muted uppercase tracking-wider">{{ __('Progress') }}</span>
                        <span class="text-xs font-bold text-ink" x-text="stats.translated + ' / ' + stats.total + ' (' + stats.percent + '%)'"></span>
                    </div>
                    <div class="h-2 rounded-full bg-surface overflow-hidden">
                        <div class="h-full bg-brand transition-all duration-300" :style="'width: ' + stats.percent + '%'"></div>
                    </div>
                </div>

                <div class="flex items-end gap-2">
                    <a href="{{ route('admin.translations.export', ['code' => $code]) }}" class="btn-secondary">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
                        {{ __('Export') }}
                    </a>
                    <button type="button" @click="importOpen = true" class="btn-secondary">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/></svg>
                        {{ __('Import JSON') }}
                    </button>
                </div>
            </div>
        </div>

        {{-- Filters + save bar --}}
        <div class="panel p-4 flex flex-wrap items-center gap-3 sticky top-4 z-20">
            <input type="text" x-model="search" placeholder="{{ __('Search keys or text...') }}"
                   class="settings-input flex-1 min-w-[200px]">

            <div class="inline-flex rounded-xl bg-surface p-1 border border-border">
                <button type="button" @click="filter = 'all'"
                        :class="filter === 'all' ? 'bg-brand text-white' : 'text-muted hover:text-ink'"
                        class="px-3 py-1.5 text-xs font-bold rounded-lg transition">{{ __('All') }}</button>
                <button type="button" @click="filter = 'missing'"
                        :class="filter === 'missing' ? 'bg-brand text-white' : 'text-muted hover:text-ink'"
                        class="px-3 py-1.5 text-xs font-bold rounded-lg transition">{{ __('Missing') }}</button>
                <button type="button" @click="filter = 'translated'"
                        :class="filter === 'translated' ? 'bg-brand text-white' : 'text-muted hover:text-ink'"
                        class="px-3 py-1.5 text-xs font-bold rounded-lg transition">{{ __('Translated') }}</button>
            </div>

            <span class="text-sm text-muted" x-text="visibleCount + ' / ' + rows.length + ' shown'"></span>

            <div class="flex-1"></div>

            <span x-show="dirtyCount > 0" x-cloak class="text-xs font-semibold text-warning" x-text="dirtyCount + ' unsaved'"></span>
            <button type="button" @click="saveAll()" :disabled="saving || dirtyCount === 0"
                    class="settings-save-btn disabled:opacity-50 disabled:cursor-not-allowed">
                <svg class="w-4 h-4" :class="saving ? 'animate-spin' : ''" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path x-show="!saving" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                    <path x-show="saving" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581"/>
                </svg>
                <span x-text="saving ? '{{ __('Saving...') }}' : '{{ __('Save All Changes') }}'"></span>
            </button>
        </div>

        {{-- Strings table --}}
        <div class="panel overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead class="bg-surface text-muted text-xs uppercase tracking-wider">
                        <tr>
                            <th class="px-5 py-3 text-left w-12">#</th>
                            <th class="px-5 py-3 text-left w-2/5">{{ __('English (source)') }}</th>
                            <th class="px-5 py-3 text-left w-2/5">{{ __('Translation') }} ({{ $code }})</th>
                            <th class="px-5 py-3 text-center w-32">{{ __('Status') }}</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-border/40">
                        <template x-for="(row, idx) in visibleRows" :key="row.key">
                            <tr class="hover:bg-surface/40 transition">
                                <td class="px-5 py-3 align-top text-muted text-xs font-mono" x-text="idx + 1 + (page - 1) * pageSize"></td>
                                <td class="px-5 py-3 align-top">
                                    <div class="text-ink text-sm leading-relaxed whitespace-pre-wrap break-words" x-text="row.source"></div>
                                </td>
                                <td class="px-5 py-3 align-top">
                                    <textarea
                                        rows="1"
                                        x-model="row.value"
                                        @input="markDirty(row); autoGrow($event.target)"
                                        @focus="autoGrow($event.target)"
                                        class="w-full px-3 py-2 text-sm bg-surface border border-border rounded-lg focus:ring-2 focus:ring-brand/30 focus:border-brand/40 focus:outline-none resize-none overflow-hidden"
                                        :placeholder="row.source"
                                    ></textarea>
                                </td>
                                <td class="px-5 py-3 align-top text-center">
                                    <span x-show="row._dirty" class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-warning/10 text-warning uppercase tracking-wider">
                                        <span class="w-1.5 h-1.5 rounded-full bg-warning"></span> {{ __('Edited') }}
                                    </span>
                                    <template x-if="!row._dirty">
                                        <span :class="{
                                            'bg-success/10 text-success': row.status === 'translated',
                                            'bg-muted/10 text-muted': row.status === 'missing',
                                            'bg-warning/10 text-warning': row.status === 'same',
                                        }" class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider">
                                            <span x-text="row.status === 'translated' ? '{{ __('Translated') }}' : (row.status === 'missing' ? '{{ __('Missing') }}' : '{{ __('Same as source') }}')"></span>
                                        </span>
                                    </template>
                                </td>
                            </tr>
                        </template>
                        <template x-if="visibleRows.length === 0">
                            <tr>
                                <td colspan="4" class="px-5 py-12 text-center text-muted">
                                    <svg class="w-12 h-12 mx-auto mb-3 text-muted/50" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
                                    <p class="font-medium">{{ __('No strings match your filters.') }}</p>
                                </td>
                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>

            {{-- Pagination --}}
            <div class="flex items-center justify-between px-5 py-3 border-t border-border bg-surface/30" x-show="totalPages > 1">
                <button type="button" @click="page = Math.max(1, page - 1)" :disabled="page === 1"
                        class="px-3 py-1.5 text-xs font-bold text-ink hover:text-brand transition disabled:opacity-40 disabled:cursor-not-allowed">{{ __('← Previous') }}</button>
                <span class="text-xs text-muted">
                    {{ __('Page') }} <span x-text="page"></span> {{ __('of') }} <span x-text="totalPages"></span>
                </span>
                <button type="button" @click="page = Math.min(totalPages, page + 1)" :disabled="page === totalPages"
                        class="px-3 py-1.5 text-xs font-bold text-ink hover:text-brand transition disabled:opacity-40 disabled:cursor-not-allowed">{{ __('Next →') }}</button>
            </div>
        </div>

        {{-- Import modal --}}
        <div x-show="importOpen" x-cloak x-transition.opacity
             @keydown.escape.window="importOpen = false"
             class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm"
             @click.self="importOpen = false">
            <div class="w-full max-w-2xl bg-surface-2 rounded-2xl shadow-2xl border border-border overflow-hidden">
                <div class="flex items-center justify-between px-6 py-4 border-b border-border">
                    <h3 class="text-lg font-bold text-ink">{{ __('Import Translations') }}</h3>
                    <button type="button" @click="importOpen = false" class="p-2 rounded-lg text-muted hover:text-ink hover:bg-surface transition">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                    </button>
                </div>
                <form method="POST" action="{{ route('admin.translations.import') }}" enctype="multipart/form-data" class="p-6 space-y-4">
                    @csrf
                    <input type="hidden" name="code" value="{{ $code }}">

                    <div class="p-4 bg-info/5 border border-info/20 rounded-xl text-sm text-info">
                        {{ __('Upload a JSON file OR paste JSON text below. Only keys that exist in en.json will be imported; orphan keys are silently skipped.') }}
                    </div>

                    <div>
                        <label class="settings-label">{{ __('Upload .json file') }}</label>
                        <input type="file" name="json_file" accept=".json,application/json" class="settings-input">
                    </div>

                    <div class="text-center text-xs text-muted">— {{ __('OR') }} —</div>

                    <div>
                        <label class="settings-label">{{ __('Paste JSON') }}</label>
                        <textarea name="json_text" rows="10" class="settings-input font-mono text-xs" placeholder='{"Hello": "Bonjour", ...}'></textarea>
                    </div>

                    <div class="flex justify-end gap-2 pt-2">
                        <button type="button" @click="importOpen = false" class="btn-secondary">{{ __('Cancel') }}</button>
                        <button type="submit" class="btn-primary">{{ __('Import') }}</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
    function translationsEditor() {
        return {
            rows: @json($rows),
            stats: @json($stats),
            search: '',
            filter: 'all',
            page: 1,
            pageSize: 50,
            saving: false,
            importOpen: false,
            code: @json($code),

            init() {
                // Mark each row with a non-dirty flag we mutate as the
                // user edits — separate from the saved status so it survives
                // filter/page changes.
                this.rows.forEach(r => r._dirty = false);
                this.$nextTick(() => {
                    document.querySelectorAll('textarea').forEach(t => this.autoGrow(t));
                });
            },

            get filteredRows() {
                const q = this.search.trim().toLowerCase();
                return this.rows.filter(r => {
                    if (this.filter === 'missing' && r.status === 'translated' && !r._dirty) return false;
                    if (this.filter === 'translated' && r.status !== 'translated') return false;
                    if (q && !r.source.toLowerCase().includes(q) && !r.value.toLowerCase().includes(q) && !r.key.toLowerCase().includes(q)) return false;
                    return true;
                });
            },

            get visibleCount() { return this.filteredRows.length; },
            get totalPages() { return Math.max(1, Math.ceil(this.filteredRows.length / this.pageSize)); },
            get visibleRows() {
                const start = (this.page - 1) * this.pageSize;
                return this.filteredRows.slice(start, start + this.pageSize);
            },
            get dirtyCount() { return this.rows.filter(r => r._dirty).length; },

            markDirty(row) { row._dirty = true; },

            autoGrow(el) {
                el.style.height = 'auto';
                el.style.height = (el.scrollHeight + 2) + 'px';
            },

            async saveAll() {
                if (this.dirtyCount === 0 || this.saving) return;
                this.saving = true;

                // Build a partial-payload of only the rows the user actually
                // touched — keeps the request small even on a 3500-key file.
                const translations = {};
                this.rows.filter(r => r._dirty).forEach(r => {
                    translations[r.key] = r.value;
                });

                try {
                    const res = await fetch('{{ route('admin.translations.save') }}', {
                        method: 'POST',
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                            'X-Requested-With': 'XMLHttpRequest',
                        },
                        body: JSON.stringify({ code: this.code, translations }),
                    });
                    const data = await res.json();
                    if (data.ok) {
                        // Mark all dirty rows as clean + update their saved value
                        this.rows.forEach(r => {
                            if (r._dirty) {
                                r._dirty = false;
                                // Recompute status based on the new value
                                if (r.value === '' || r.value === null) r.status = 'missing';
                                else if (r.value === r.source) r.status = 'same';
                                else r.status = 'translated';
                            }
                        });
                        this.stats = data.stats;
                        this.toast('{{ __('Saved') }}', 'success');
                    } else {
                        this.toast(data.message || '{{ __('Save failed') }}', 'error');
                    }
                } catch (e) {
                    this.toast(e.message, 'error');
                } finally {
                    this.saving = false;
                }
            },

            toast(msg, type) {
                // Lightweight inline toast — slides down from the top.
                const el = document.createElement('div');
                el.className = 'fixed top-6 right-6 px-4 py-3 rounded-xl text-sm font-bold text-white shadow-lg z-50 ' +
                    (type === 'error' ? 'bg-danger' : 'bg-success');
                el.textContent = msg;
                document.body.appendChild(el);
                setTimeout(() => el.remove(), 2500);
            },
        };
    }
    </script>
</x-layouts.admin>
