<x-admin-layout>
    <x-slot name="header">
        <div class="flex items-center justify-between">
            <div>
                <h2 class="font-semibold text-lg text-gray-800 dark:text-gray-200 leading-tight">
                    <i class="fas fa-cog mr-2"></i>{{ __('Setări') }}
                </h2>
                <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">
                    <a href="{{ route('dashboard') }}" class="text-blue-600 dark:text-blue-400 hover:underline">Dashboard</a>
                    <span class="mx-2">/</span>
                    <a href="{{ route('admin.dashboard') }}" class="text-blue-600 dark:text-blue-400 hover:underline">Admin</a>
                    <span class="mx-2">/</span>
                    <span>Setări</span>
                    <span class="mx-2">/</span>
                    <span>Șabloane Email</span>
                </p>
            </div>
        </div>
    </x-slot>

    {{-- Alertă Succes cu Dark Mode --}}
    @if (session('success'))
        <div class="max-w-7xl mx-auto px-6 lg:px-8 mt-4">
            <div class="bg-green-50 dark:bg-green-900/20 border-l-4 border-green-500 text-green-700 dark:text-green-300 p-4 rounded-r-lg" role="alert">
                <div class="flex items-center">
                    <i class="fas fa-check-circle text-green-500 mr-3"></i>
                    <div>
                        <p class="font-bold">Succes!</p>
                        <p class="text-sm">{{ session('success') }}</p>
                    </div>
                </div>
            </div>
        </div>
    @endif

    {{-- Alertă Eroare cu Dark Mode --}}
    @if (session('error'))
        <div class="max-w-7xl mx-auto px-6 lg:px-8 mt-4">
            <div class="bg-red-50 dark:bg-red-900/20 border-l-4 border-red-500 text-red-700 dark:text-red-300 p-4 rounded-r-lg" role="alert">
                <div class="flex items-center">
                    <i class="fas fa-exclamation-circle text-red-500 mr-3"></i>
                    <div>
                        <p class="font-bold">Eroare!</p>
                        <p class="text-sm">{{ session('error') }}</p>
                    </div>
                </div>
            </div>
        </div>
    @endif

    @php
        // Statistici pentru carduri
        $totalTemplates = count($emailTemplates ?? []);
        $activeTemplates = collect($emailTemplates ?? [])->where('is_active', true)->count();
        $inactiveTemplates = $totalTemplates - $activeTemplates;
        $categories = collect($emailTemplates ?? [])->groupBy('category');
    @endphp

    <div class="py-12">
        <div class="px-6 lg:px-8">
            {{-- Carduri Statistici --}}
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                {{-- Total Șabloane --}}
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 border border-gray-100 dark:border-gray-700">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Total Șabloane</p>
                            <p class="mt-2 text-3xl font-bold text-gray-900 dark:text-white">{{ $totalTemplates }}</p>
                            <p class="mt-1 text-xs text-gray-400 dark:text-gray-500">șabloane configurate</p>
                        </div>
                        <div class="w-12 h-12 bg-orange-100 dark:bg-orange-900/30 rounded-lg flex items-center justify-center">
                            <i class="fas fa-file-alt text-xl text-orange-600 dark:text-orange-400"></i>
                        </div>
                    </div>
                </div>

                {{-- Active --}}
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 border border-gray-100 dark:border-gray-700">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Active</p>
                            <p class="mt-2 text-3xl font-bold text-green-600 dark:text-green-400">{{ $activeTemplates }}</p>
                            <p class="mt-1 text-xs text-green-500 dark:text-green-400"><i class="fas fa-check-circle mr-1"></i>funcționale</p>
                        </div>
                        <div class="w-12 h-12 bg-green-100 dark:bg-green-900/30 rounded-lg flex items-center justify-center">
                            <i class="fas fa-toggle-on text-xl text-green-600 dark:text-green-400"></i>
                        </div>
                    </div>
                </div>

                {{-- Inactive --}}
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 border border-gray-100 dark:border-gray-700">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Inactive</p>
                            <p class="mt-2 text-3xl font-bold text-gray-600 dark:text-gray-400">{{ $inactiveTemplates }}</p>
                            <p class="mt-1 text-xs text-gray-400 dark:text-gray-500"><i class="fas fa-pause-circle mr-1"></i>dezactivate</p>
                        </div>
                        <div class="w-12 h-12 bg-gray-100 dark:bg-gray-700 rounded-lg flex items-center justify-center">
                            <i class="fas fa-toggle-off text-xl text-gray-500 dark:text-gray-400"></i>
                        </div>
                    </div>
                </div>

                {{-- Categorii --}}
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 border border-gray-100 dark:border-gray-700">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Categorii</p>
                            <div class="mt-2 flex items-center space-x-3">
                                <span class="inline-flex items-center text-xs text-gray-600 dark:text-gray-300">
                                    <span class="w-2 h-2 bg-blue-500 rounded-full mr-1"></span>
                                    {{ $categories->get('system', collect())->count() }} Sistem
                                </span>
                                <span class="inline-flex items-center text-xs text-gray-600 dark:text-gray-300">
                                    <span class="w-2 h-2 bg-green-500 rounded-full mr-1"></span>
                                    {{ $categories->get('notification', collect())->count() }} Notif.
                                </span>
                                <span class="inline-flex items-center text-xs text-gray-600 dark:text-gray-300">
                                    <span class="w-2 h-2 bg-yellow-500 rounded-full mr-1"></span>
                                    {{ $categories->get('alert', collect())->count() }} Alerte
                                </span>
                            </div>
                            <p class="mt-1 text-xs text-gray-400 dark:text-gray-500">distribuție</p>
                        </div>
                        <div class="w-12 h-12 bg-purple-100 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
                            <i class="fas fa-layer-group text-xl text-purple-600 dark:text-purple-400"></i>
                        </div>
                    </div>
                </div>
            </div>

            {{-- Quick Actions Bar --}}
            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-4 mb-8 border border-gray-100 dark:border-gray-700">
                <div class="flex flex-wrap items-center justify-between gap-4">
                    <div class="flex items-center text-sm text-gray-600 dark:text-gray-400">
                        <i class="fas fa-bolt text-yellow-500 mr-2"></i>
                        <span class="font-medium">Acțiuni Rapide:</span>
                    </div>
                    <div class="flex flex-wrap items-center gap-2">
                        <a href="{{ route('admin.email-templates.create') }}"
                           class="inline-flex items-center px-4 py-2 bg-orange-600 hover:bg-orange-700 text-white text-sm font-medium rounded-lg transition">
                            <i class="fas fa-plus mr-2"></i>Adaugă Șablon
                        </a>
                        <button type="button"
                                onclick="generateDefaultTemplates()"
                                class="inline-flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition">
                            <i class="fas fa-magic mr-2"></i>Generează Default
                        </button>
                        <button type="button"
                                onclick="exportTemplates()"
                                class="inline-flex items-center px-4 py-2 bg-green-600 hover:bg-green-700 text-white text-sm font-medium rounded-lg transition">
                            <i class="fas fa-download mr-2"></i>Export
                        </button>
                        <label class="inline-flex items-center px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white text-sm font-medium rounded-lg transition cursor-pointer">
                            <i class="fas fa-upload mr-2"></i>Import
                            <input type="file" class="hidden" accept=".json" onchange="importTemplates(this)">
                        </label>
                    </div>
                </div>
            </div>

            <div class="flex gap-6">
                {{-- Settings Sidebar Menu --}}
                <x-settings-sidebar />

                {{-- Main Content Area --}}
                <div class="flex-1">
                    <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                        <div class="p-6">
                            {{-- Header cu Search și Filter - Totul pe un singur rând --}}
                            <div class="flex items-center justify-between gap-4 mb-6">
                                <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100 whitespace-nowrap">
                                    <i class="fas fa-file-alt text-orange-600 mr-2"></i>Șabloane Email
                                </h3>

                                <div class="flex items-center gap-3">
                                    {{-- Search --}}
                                    <div class="relative">
                                        <input type="text"
                                               id="searchTemplates"
                                               placeholder="Caută șablon..."
                                               class="w-48 pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:ring-orange-500 focus:border-orange-500">
                                        <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                                    </div>

                                    {{-- Filter Category --}}
                                    <select id="filterCategory"
                                            class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:ring-orange-500 focus:border-orange-500">
                                        <option value="">Toate categoriile</option>
                                        <option value="system">Sistem</option>
                                        <option value="notification">Notificare</option>
                                        <option value="alert">Alertă</option>
                                    </select>
                                </div>
                            </div>

                            {{-- Info Banner --}}
                            <div class="bg-blue-50 dark:bg-blue-900/20 border-l-4 border-blue-500 p-4 rounded-r-lg mb-6">
                                <div class="flex">
                                    <div class="flex-shrink-0">
                                        <i class="fas fa-info-circle text-blue-500 text-xl"></i>
                                    </div>
                                    <div class="ml-3">
                                        <h4 class="text-sm font-medium text-blue-800 dark:text-blue-300">
                                            Despre Șabloanele Email
                                        </h4>
                                        <p class="mt-2 text-sm text-blue-700 dark:text-blue-400">
                                            Șabloanele email sunt folosite pentru toate comunicările automate ale platformei:
                                            înregistrare, verificare cont, resetare parolă, notificări, alerte DNS, etc.
                                            Poți personaliza fiecare șablon cu variabile dinamice.
                                        </p>
                                    </div>
                                </div>
                            </div>

                            {{-- Templates List --}}
                            <div class="bg-white dark:bg-gray-800 shadow-sm rounded-lg overflow-hidden border border-gray-200 dark:border-gray-700">
                                <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700" id="templatesTable">
                                    <thead class="bg-gray-50 dark:bg-gray-700">
                                        <tr>
                                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-600" onclick="sortTable(0)">
                                                Nume Șablon <i class="fas fa-sort ml-1 text-gray-400"></i>
                                            </th>
                                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-600" onclick="sortTable(1)">
                                                Categorie <i class="fas fa-sort ml-1 text-gray-400"></i>
                                            </th>
                                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                                Subiect
                                            </th>
                                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-600" onclick="sortTable(3)">
                                                Status <i class="fas fa-sort ml-1 text-gray-400"></i>
                                            </th>
                                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                                Acțiuni
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                                        @forelse($emailTemplates ?? [] as $template)
                                            <tr class="hover:bg-gray-50 dark:hover:bg-gray-700 transition template-row"
                                                data-name="{{ strtolower($template->name) }}"
                                                data-key="{{ strtolower($template->key) }}"
                                                data-category="{{ $template->category }}"
                                                data-status="{{ $template->is_active ? 'active' : 'inactive' }}">
                                                <td class="px-6 py-4 whitespace-nowrap">
                                                    <div class="flex items-center">
                                                        <i class="fas fa-envelope text-orange-500 mr-3"></i>
                                                        <div>
                                                            <div class="text-sm font-medium text-gray-900 dark:text-gray-100">
                                                                {{ $template->name }}
                                                            </div>
                                                            <div class="text-xs text-gray-500 dark:text-gray-400">
                                                                {{ $template->key }}
                                                            </div>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td class="px-6 py-4 whitespace-nowrap">
                                                    @php
                                                        $categoryLabels = [
                                                            'system' => 'Sistem',
                                                            'notification' => 'Notificare',
                                                            'alert' => 'Alertă'
                                                        ];
                                                    @endphp
                                                    <span class="inline-flex items-center px-2.5 py-1 rounded-lg text-xs font-semibold border
                                                        @if($template->category === 'system') bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 border-blue-200 dark:border-blue-800
                                                        @elseif($template->category === 'notification') bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300 border-green-200 dark:border-green-800
                                                        @else bg-yellow-50 dark:bg-yellow-900/20 text-yellow-700 dark:text-yellow-300 border-yellow-200 dark:border-yellow-800
                                                        @endif">
                                                        {{ $categoryLabels[$template->category] ?? ucfirst($template->category) }}
                                                    </span>
                                                </td>
                                                <td class="px-6 py-4">
                                                    <div class="text-sm text-gray-900 dark:text-gray-100 max-w-xs truncate">
                                                        {{ $template->subject }}
                                                    </div>
                                                </td>
                                                <td class="px-6 py-4 whitespace-nowrap">
                                                    @if($template->is_active)
                                                        <span class="inline-flex items-center px-2.5 py-1 rounded-lg text-xs font-semibold bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300 border border-green-200 dark:border-green-800">
                                                            <i class="fas fa-check-circle mr-1"></i> Activ
                                                        </span>
                                                    @else
                                                        <span class="inline-flex items-center px-2.5 py-1 rounded-lg text-xs font-semibold bg-gray-50 dark:bg-gray-700 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-gray-600">
                                                            <i class="fas fa-times-circle mr-1"></i> Inactiv
                                                        </span>
                                                    @endif
                                                </td>
                                                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                                    <div class="flex items-center justify-end space-x-1.5">
                                                        {{-- Preview --}}
                                                        <button type="button"
                                                                onclick="previewTemplate({{ $template->id }})"
                                                                class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-cyan-50 dark:bg-cyan-900/20 text-cyan-600 dark:text-cyan-400 hover:bg-cyan-100 dark:hover:bg-cyan-900/40 border border-cyan-200 dark:border-cyan-800 transition"
                                                                title="Preview">
                                                            <i class="fas fa-eye"></i>
                                                        </button>
                                                        {{-- Test Email --}}
                                                        <button type="button"
                                                                onclick="testEmail({{ $template->id }})"
                                                                class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-green-50 dark:bg-green-900/20 text-green-600 dark:text-green-400 hover:bg-green-100 dark:hover:bg-green-900/40 border border-green-200 dark:border-green-800 transition"
                                                                title="Trimite Test Email">
                                                            <i class="fas fa-paper-plane"></i>
                                                        </button>
                                                        {{-- Duplicate --}}
                                                        <button type="button"
                                                                onclick="duplicateTemplate({{ $template->id }})"
                                                                class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 hover:bg-purple-100 dark:hover:bg-purple-900/40 border border-purple-200 dark:border-purple-800 transition"
                                                                title="Duplică">
                                                            <i class="fas fa-copy"></i>
                                                        </button>
                                                        {{-- Edit --}}
                                                        <a href="{{ route('admin.email-templates.edit', $template) }}"
                                                           class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-indigo-50 dark:bg-indigo-900/20 text-indigo-600 dark:text-indigo-400 hover:bg-indigo-100 dark:hover:bg-indigo-900/40 border border-indigo-200 dark:border-indigo-800 transition"
                                                           title="Editează">
                                                            <i class="fas fa-edit"></i>
                                                        </a>
                                                        {{-- Delete --}}
                                                        <form action="{{ route('admin.email-templates.destroy', $template) }}"
                                                              method="POST"
                                                              class="inline"
                                                              onsubmit="return confirm('Sigur vrei să ștergi acest șablon?');">
                                                            @csrf
                                                            @method('DELETE')
                                                            <button type="submit"
                                                                    class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 hover:bg-red-100 dark:hover:bg-red-900/40 border border-red-200 dark:border-red-800 transition"
                                                                    title="Șterge">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        </form>
                                                    </div>
                                                </td>
                                            </tr>
                                        @empty
                                            <tr id="emptyRow">
                                                <td colspan="5" class="px-6 py-12 text-center">
                                                    <div class="flex flex-col items-center justify-center">
                                                        <i class="fas fa-inbox text-gray-400 dark:text-gray-500 text-5xl mb-4"></i>
                                                        <p class="text-gray-500 dark:text-gray-400 text-lg mb-2">
                                                            Nu există șabloane email configurate
                                                        </p>
                                                        <p class="text-gray-400 dark:text-gray-500 text-sm mb-4">
                                                            Adaugă primul șablon sau generează șabloanele default
                                                        </p>
                                                        <div class="flex gap-3">
                                                            <a href="{{ route('admin.email-templates.create') }}"
                                                               class="bg-orange-600 hover:bg-orange-700 text-white font-bold py-2 px-4 rounded-lg transition">
                                                                <i class="fas fa-plus mr-2"></i>Adaugă Șablon
                                                            </a>
                                                            <button type="button"
                                                                    onclick="generateDefaultTemplates()"
                                                                    class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg transition">
                                                                <i class="fas fa-magic mr-2"></i>Generează Default
                                                            </button>
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>
                                        @endforelse
                                    </tbody>
                                </table>
                            </div>

                            {{-- Variabile Disponibile --}}
                            <div class="mt-6 bg-gray-50 dark:bg-gray-900 p-6 rounded-lg border border-gray-200 dark:border-gray-700">
                                <h4 class="text-md font-semibold text-gray-900 dark:text-gray-100 mb-3 flex items-center">
                                    <i class="fas fa-code text-orange-600 mr-2"></i>
                                    Variabile Disponibile în Șabloane
                                </h4>
                                <p class="text-sm text-gray-600 dark:text-gray-400 mb-3">
                                    Poți folosi următoarele variabile în șabloanele tale (vor fi înlocuite automat):
                                </p>
                                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                                    <div class="bg-white dark:bg-gray-800 p-3 rounded-lg border border-gray-200 dark:border-gray-700">
                                        <code class="text-sm text-orange-600 dark:text-orange-400 font-mono">{name}</code>
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">Numele utilizatorului</p>
                                    </div>
                                    <div class="bg-white dark:bg-gray-800 p-3 rounded-lg border border-gray-200 dark:border-gray-700">
                                        <code class="text-sm text-orange-600 dark:text-orange-400 font-mono">{email}</code>
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">Email utilizator</p>
                                    </div>
                                    <div class="bg-white dark:bg-gray-800 p-3 rounded-lg border border-gray-200 dark:border-gray-700">
                                        <code class="text-sm text-orange-600 dark:text-orange-400 font-mono">{verification_url}</code>
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">Link verificare cont</p>
                                    </div>
                                    <div class="bg-white dark:bg-gray-800 p-3 rounded-lg border border-gray-200 dark:border-gray-700">
                                        <code class="text-sm text-orange-600 dark:text-orange-400 font-mono">{reset_url}</code>
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">Link resetare parolă</p>
                                    </div>
                                    <div class="bg-white dark:bg-gray-800 p-3 rounded-lg border border-gray-200 dark:border-gray-700">
                                        <code class="text-sm text-orange-600 dark:text-orange-400 font-mono">{app_name}</code>
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">Nume aplicație</p>
                                    </div>
                                    <div class="bg-white dark:bg-gray-800 p-3 rounded-lg border border-gray-200 dark:border-gray-700">
                                        <code class="text-sm text-orange-600 dark:text-orange-400 font-mono">{app_url}</code>
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">URL aplicație</p>
                                    </div>
                                    <div class="bg-white dark:bg-gray-800 p-3 rounded-lg border border-gray-200 dark:border-gray-700">
                                        <code class="text-sm text-orange-600 dark:text-orange-400 font-mono">{domain}</code>
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">Domeniu DNS</p>
                                    </div>
                                    <div class="bg-white dark:bg-gray-800 p-3 rounded-lg border border-gray-200 dark:border-gray-700">
                                        <code class="text-sm text-orange-600 dark:text-orange-400 font-mono">{nameservers}</code>
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">Lista nameserver-e</p>
                                    </div>
                                    <div class="bg-white dark:bg-gray-800 p-3 rounded-lg border border-gray-200 dark:border-gray-700">
                                        <code class="text-sm text-orange-600 dark:text-orange-400 font-mono">{expiry_date}</code>
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">Data expirare plan</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- Preview Modal --}}
    <div id="previewModal" class="fixed inset-0 z-50 hidden overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:p-0">
            <div class="fixed inset-0 transition-opacity bg-black/50 dark:bg-black/60 backdrop-blur-sm" onclick="closePreviewModal()"></div>
            <div class="relative inline-block w-full max-w-4xl p-6 overflow-hidden text-left align-middle transition-all transform bg-white dark:bg-gray-800 rounded-xl shadow-xl">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100">
                        <i class="fas fa-eye text-cyan-600 mr-2"></i>Preview Email
                    </h3>
                    <button type="button" onclick="closePreviewModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                <div class="border-b border-gray-200 dark:border-gray-700 pb-3 mb-4">
                    <p class="text-sm text-gray-600 dark:text-gray-400"><strong>Subiect:</strong> <span id="previewSubject"></span></p>
                </div>
                <div id="previewContent" class="bg-gray-50 dark:bg-gray-900 rounded-lg p-4 max-h-96 overflow-y-auto">
                    {{-- Content loaded via JS --}}
                </div>
                <div class="mt-4 flex justify-end">
                    <button type="button" onclick="closePreviewModal()" class="px-4 py-2 bg-gray-300 dark:bg-gray-600 text-gray-800 dark:text-gray-200 rounded-lg hover:bg-gray-400 dark:hover:bg-gray-500 transition">
                        Închide
                    </button>
                </div>
            </div>
        </div>
    </div>

    {{-- Test Email Modal --}}
    <div id="testEmailModal" class="fixed inset-0 z-50 hidden overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:p-0">
            <div class="fixed inset-0 transition-opacity bg-black/50 dark:bg-black/60 backdrop-blur-sm" onclick="closeTestEmailModal()"></div>
            <div class="relative inline-block w-full max-w-md p-6 overflow-hidden text-left align-middle transition-all transform bg-white dark:bg-gray-800 rounded-xl shadow-xl">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100">
                        <i class="fas fa-paper-plane text-green-600 mr-2"></i>Trimite Email de Test
                    </h3>
                    <button type="button" onclick="closeTestEmailModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                <form id="testEmailForm" onsubmit="sendTestEmail(event)">
                    <input type="hidden" id="testTemplateId" name="template_id">
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Adresă Email Destinatar
                        </label>
                        <input type="email"
                               id="testEmailAddress"
                               name="email"
                               value="{{ auth()->user()->email }}"
                               required
                               class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-green-500 focus:border-green-500">
                    </div>
                    <div class="flex justify-end space-x-3">
                        <button type="button" onclick="closeTestEmailModal()" class="px-4 py-2 bg-gray-300 dark:bg-gray-600 text-gray-800 dark:text-gray-200 rounded-lg hover:bg-gray-400 dark:hover:bg-gray-500 transition">
                            Anulează
                        </button>
                        <button type="submit" id="sendTestBtn" class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                            <i class="fas fa-paper-plane mr-2"></i>Trimite
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        // Search și Filter
        document.getElementById('searchTemplates').addEventListener('input', filterTemplates);
        document.getElementById('filterCategory').addEventListener('change', filterTemplates);

        function filterTemplates() {
            const search = document.getElementById('searchTemplates').value.toLowerCase();
            const category = document.getElementById('filterCategory').value;
            const rows = document.querySelectorAll('.template-row');
            let visibleCount = 0;

            rows.forEach(row => {
                const name = row.dataset.name;
                const key = row.dataset.key;
                const rowCategory = row.dataset.category;

                const matchesSearch = name.includes(search) || key.includes(search);
                const matchesCategory = !category || rowCategory === category;

                if (matchesSearch && matchesCategory) {
                    row.style.display = '';
                    visibleCount++;
                } else {
                    row.style.display = 'none';
                }
            });

            // Afișează mesaj dacă nu sunt rezultate
            const emptyRow = document.getElementById('emptyRow');
            if (emptyRow) {
                emptyRow.style.display = visibleCount === 0 ? '' : 'none';
            }
        }

        // Sort Table
        let sortDirection = {};
        function sortTable(columnIndex) {
            const table = document.getElementById('templatesTable');
            const tbody = table.querySelector('tbody');
            const rows = Array.from(tbody.querySelectorAll('.template-row'));

            sortDirection[columnIndex] = !sortDirection[columnIndex];
            const direction = sortDirection[columnIndex] ? 1 : -1;

            rows.sort((a, b) => {
                const aText = a.cells[columnIndex].textContent.trim().toLowerCase();
                const bText = b.cells[columnIndex].textContent.trim().toLowerCase();
                return aText.localeCompare(bText) * direction;
            });

            rows.forEach(row => tbody.appendChild(row));
        }

        // Preview Template
        function previewTemplate(templateId) {
            fetch(`{{ url('/admin/email-templates') }}/${templateId}/preview`)
                .then(response => response.json())
                .then(data => {
                    document.getElementById('previewSubject').textContent = data.subject;
                    document.getElementById('previewContent').innerHTML = data.body;
                    document.getElementById('previewModal').classList.remove('hidden');
                })
                .catch(error => {
                    alert('Eroare la încărcarea preview-ului');
                    console.error(error);
                });
        }

        function closePreviewModal() {
            document.getElementById('previewModal').classList.add('hidden');
        }

        // Test Email
        function testEmail(templateId) {
            document.getElementById('testTemplateId').value = templateId;
            document.getElementById('testEmailModal').classList.remove('hidden');
        }

        function closeTestEmailModal() {
            document.getElementById('testEmailModal').classList.add('hidden');
        }

        function sendTestEmail(event) {
            event.preventDefault();
            const btn = document.getElementById('sendTestBtn');
            const templateId = document.getElementById('testTemplateId').value;
            const email = document.getElementById('testEmailAddress').value;

            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Se trimite...';

            fetch(`{{ url('/admin/email-templates') }}/${templateId}/test`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify({ email: email })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('✅ ' + data.message);
                    closeTestEmailModal();
                } else {
                    alert('❌ ' + data.message);
                }
            })
            .catch(error => {
                alert('❌ Eroare la trimiterea emailului');
                console.error(error);
            })
            .finally(() => {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-paper-plane mr-2"></i>Trimite';
            });
        }

        // Duplicate Template
        function duplicateTemplate(templateId) {
            if (!confirm('Vrei să duplici acest șablon?')) return;

            fetch(`{{ url('/admin/email-templates') }}/${templateId}/duplicate`, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('✅ ' + data.message);
                    window.location.reload();
                } else {
                    alert('❌ ' + data.message);
                }
            })
            .catch(error => {
                alert('❌ Eroare la duplicare');
                console.error(error);
            });
        }

        // Generate Default Templates
        function generateDefaultTemplates() {
            if (!confirm('Vrei să generezi șabloanele email standard? Acest lucru va crea șabloane pentru: bun venit, verificare email, resetare parolă, expirare plan, alertă DNS.')) return;

            fetch('{{ route("admin.email-templates.generate-defaults") }}', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('✅ ' + data.message);
                    window.location.reload();
                } else {
                    alert('❌ ' + data.message);
                }
            })
            .catch(error => {
                alert('❌ Eroare la generare');
                console.error(error);
            });
        }

        // Export Templates
        function exportTemplates() {
            window.location.href = '{{ route("admin.email-templates.export") }}';
        }

        // Import Templates
        function importTemplates(input) {
            if (!input.files.length) return;

            const formData = new FormData();
            formData.append('file', input.files[0]);

            fetch('{{ route("admin.email-templates.import") }}', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('✅ ' + data.message);
                    window.location.reload();
                } else {
                    alert('❌ ' + data.message);
                }
            })
            .catch(error => {
                alert('❌ Eroare la import');
                console.error(error);
            });

            input.value = '';
        }

        // Escape key closes modals
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closePreviewModal();
                closeTestEmailModal();
            }
        });
    </script>
    @endpush
</x-admin-layout>
