<div x-data="app" class="bg-white rounded-lg shadow">
    <div x-show="loading" class="fixed inset-0 bg-gray-800 bg-opacity-75 flex justify-center items-center z-50">
        <img src="../img/loading.gif" alt="Cargando..." class="w-16 h-16" />
    </div>

    <div class="container mx-auto p-6 w-full max-w-xl">
        <div class="mb-6">
            <h1 class="text-2xl font-bold mb-1">Configuración SMTP</h1>
            <p class="text-sm text-gray-500">Servidor de correo saliente para las notificaciones automáticas</p>
        </div>

        <form @submit.prevent="save()" class="space-y-4 bg-gray-50 rounded-lg p-5 border border-gray-200">
            <div class="grid grid-cols-2 gap-4">
                <div class="col-span-2 md:col-span-1">
                    <label class="text-xs font-medium text-gray-600">Host SMTP *</label>
                    <input x-model="form.host" required placeholder="smtp.gmail.com"
                        class="mt-1 w-full border rounded px-3 py-2 text-sm" />
                </div>
                <div>
                    <label class="text-xs font-medium text-gray-600">Puerto *</label>
                    <input x-model="form.port" type="number" required placeholder="587"
                        class="mt-1 w-full border rounded px-3 py-2 text-sm" />
                </div>
                <div>
                    <label class="text-xs font-medium text-gray-600">Usuario / Email *</label>
                    <input x-model="form.username" type="email" required
                        class="mt-1 w-full border rounded px-3 py-2 text-sm" />
                </div>
                <div>
                    <label class="text-xs font-medium text-gray-600">Contraseña</label>
                    <input x-model="form.password" type="password"
                        placeholder="Dejar vacío para no cambiar"
                        class="mt-1 w-full border rounded px-3 py-2 text-sm" />
                </div>
                <div>
                    <label class="text-xs font-medium text-gray-600">Cifrado</label>
                    <select x-model="form.encryption" class="mt-1 w-full border rounded px-3 py-2 text-sm">
                        <option value="tls">TLS (STARTTLS)</option>
                        <option value="ssl">SSL</option>
                        <option value="none">Sin cifrado</option>
                    </select>
                </div>
                <div>
                    <label class="text-xs font-medium text-gray-600">Nombre remitente</label>
                    <input x-model="form.from_name" class="mt-1 w-full border rounded px-3 py-2 text-sm" />
                </div>
                <div class="col-span-2">
                    <label class="text-xs font-medium text-gray-600">Email remitente *</label>
                    <input x-model="form.from_address" type="email" required
                        class="mt-1 w-full border rounded px-3 py-2 text-sm" />
                </div>
            </div>

            <div class="flex items-center justify-between pt-2 border-t">
                <div class="flex gap-2">
                    <input type="text" x-model="testEmail" placeholder="Email de prueba"
                        class="border rounded px-3 py-1.5 text-sm w-56" />
                    <button type="button" @click="testSMTP()"
                        class="px-3 py-1.5 border border-purple-300 text-purple-700 rounded text-sm hover:bg-purple-50"
                        :disabled="loading">
                        <span x-text="loading ? 'Enviando…' : 'Probar'"></span>
                    </button>
                </div>
                <button type="submit"
                    class="px-5 py-2 bg-[#8eb02f] text-white rounded text-sm font-medium"
                    :disabled="loading">
                    <span x-text="loading ? 'Guardando…' : 'Guardar configuración'"></span>
                </button>
            </div>
        </form>

        <!-- Estado actual -->
        <div class="mt-5 p-4 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-700">
            <strong>Nota:</strong> Al guardar, la configuración se aplica inmediatamente sin necesidad de reiniciar el servidor.
            La contraseña se almacena cifrada con AES-256.
        </div>

        <!-- ─── Diagnóstico del ciclo completo ─────────────────────────────── -->
        <div class="mt-6 border border-gray-200 rounded-lg overflow-hidden">
            <div class="bg-gray-50 px-5 py-3 border-b flex items-center gap-2">
                <svg class="w-4 h-4 text-indigo-500" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M9.75 3.104v5.714a2.25 2.25 0 0 1-.659 1.591L5 14.5M9.75 3.104c-.251.023-.501.05-.75.082m.75-.082a24.301 24.301 0 0 1 4.5 0m0 0v5.714c0 .597.237 1.17.659 1.591L19.8 15.3M14.25 3.104c.251.023.501.05.75.082M19.8 15.3l-1.57.393A9.065 9.065 0 0 1 12 15a9.065 9.065 0 0 1-6.23-.693L5 14.5m14.8.8 1.402 1.402c1.232 1.232.65 3.318-1.067 3.611A48.309 48.309 0 0 1 12 21c-2.773 0-5.491-.235-8.135-.687-1.718-.293-2.3-2.379-1.067-3.61L5 14.5" />
                </svg>
                <h2 class="text-sm font-semibold text-gray-700">Diagnóstico — ciclo completo de notificaciones</h2>
            </div>
            <div class="p-5 space-y-4">
                <p class="text-xs text-gray-500">Crea datos temporales, ejecuta el ciclo completo (bienvenida → pago recibido → idempotencia) usando tu SMTP real y los destruye al finalizar.</p>
                <div class="flex gap-2">
                    <input type="email" x-model="diagEmail" placeholder="Email donde recibirás los correos de prueba"
                        class="border rounded px-3 py-1.5 text-sm flex-1" />
                    <button @click="runDiag()"
                        :disabled="diagLoading || !diagEmail"
                        class="px-4 py-1.5 bg-indigo-600 text-white rounded text-sm font-medium disabled:opacity-40 flex items-center gap-1.5">
                        <svg x-show="!diagLoading" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 0 1 0 1.972l-11.54 6.347a1.125 1.125 0 0 1-1.667-.986V5.653Z"/></svg>
                        <svg x-show="diagLoading" class="w-3.5 h-3.5 animate-spin" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/></svg>
                        <span x-text="diagLoading ? 'Ejecutando…' : 'Ejecutar test'"></span>
                    </button>
                </div>

                <!-- Resultado -->
                <div x-show="diagPasos.length > 0">
                    <!-- Resumen -->
                    <div class="flex items-center gap-2 mb-3 px-3 py-2 rounded text-sm font-medium"
                        :class="diagOK ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'">
                        <svg x-show="diagOK" class="w-4 h-4 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"/></svg>
                        <svg x-show="!diagOK" class="w-4 h-4 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m9-.75a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 3.75h.008v.008H12v-.008Z"/></svg>
                        <span x-text="diagResumen"></span>
                    </div>
                    <!-- Pasos -->
                    <div class="border rounded divide-y text-xs">
                        <template x-for="(p, i) in diagPasos" :key="i">
                            <div class="flex items-start gap-2 px-3 py-2"
                                :class="p.ok ? 'bg-white' : 'bg-red-50'">
                                <svg x-show="p.ok" class="w-3.5 h-3.5 text-green-500 mt-0.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m4.5 12.75 6 6 9-13.5"/></svg>
                                <svg x-show="!p.ok" class="w-3.5 h-3.5 text-red-500 mt-0.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"/></svg>
                                <div class="flex-1 min-w-0">
                                    <span class="font-medium" x-text="p.paso"></span>
                                    <span x-show="!p.ok" class="block text-red-600 mt-0.5" x-text="p.mensaje"></span>
                                </div>
                                <span class="text-gray-400 flex-shrink-0" x-text="p.ms + 'ms'"></span>
                            </div>
                        </template>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div x-show="toast.show" x-cloak x-transition
        class="fixed bottom-4 right-4 z-[100] px-4 py-3 rounded shadow-lg text-sm text-white"
        :class="toast.type==='error' ? 'bg-red-500' : 'bg-[#8eb02f]'"
        x-text="toast.msg"></div>
</div>

<script>
document.addEventListener('alpine:init', () => {
    Alpine.data('app', () => ({
        loading: false,
        testEmail: '',
        diagEmail: '', diagLoading: false, diagPasos: [], diagOK: false, diagResumen: '',
        form: { host:'', port:587, username:'', password:'', encryption:'tls', from_name:'', from_address:'' },
        toast: { show:false, msg:'', type:'ok' },

        async init() {
            const { data } = await axios.get('/app/api/smtp-config');
            if (data.ok && data.config) {
                this.form = {
                    host: data.config.host || '',
                    port: data.config.port || 587,
                    username: data.config.username || '',
                    password: '***',
                    encryption: data.config.encryption || 'tls',
                    from_name: data.config.from_name || '',
                    from_address: data.config.from_address || ''
                };
            }
        },

        async save() {
            this.loading = true;
            try {
                await axios.post('/app/api/smtp-config', this.form);
                this.showToast('Configuración guardada correctamente');
            } catch(e) { this.showToast(e.response?.data?.error||'Error al guardar', 'error'); }
            this.loading = false;
        },

        async testSMTP() {
            if (!this.testEmail) { this.showToast('Ingresa un email de prueba', 'error'); return; }
            this.loading = true;
            try {
                await axios.post('/app/api/smtp-config/test', { email: this.testEmail });
                this.showToast('Correo de prueba enviado a ' + this.testEmail);
            } catch(e) { this.showToast(e.response?.data?.error||'Error SMTP', 'error'); }
            this.loading = false;
        },

        async runDiag() {
            if (!this.diagEmail) { this.showToast('Ingresa un email para el diagnóstico', 'error'); return; }
            this.diagLoading = true;
            this.diagPasos = [];
            this.diagResumen = '';
            try {
                const { data } = await axios.post('/app/api/diagnostico/ciclo-notificaciones', { test_email: this.diagEmail });
                this.diagPasos = data.pasos || [];
                this.diagOK = data.ok;
                this.diagResumen = data.resumen || (data.ok ? 'Ciclo completado sin errores' : 'Ciclo con errores');
                if (data.ok) this.showToast('✓ Test del ciclo completado exitosamente');
                else this.showToast('Test completado con errores — ver detalle', 'error');
            } catch(e) {
                this.diagPasos = [];
                this.diagOK = false;
                this.diagResumen = e.response?.data?.error || 'Error al ejecutar el test';
                this.showToast(this.diagResumen, 'error');
            }
            this.diagLoading = false;
        },

        showToast(msg, type='ok') {
            this.toast = { show:true, msg, type };
            setTimeout(() => this.toast.show = false, 3500);
        }
    }));
});
</script>
