<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>
    </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: '',
        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;
        },

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