<div x-data="cloudflareApp" class="bg-white rounded-lg shadow">

    <!-- Overlay de carga -->
    <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">

        <!-- Header -->
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
            <div>
                <h1 class="text-2xl font-bold">Cloudflare API</h1>
                <p class="text-xs text-slate-500 mt-0.5">Conexión con tu cuenta de Cloudflare para visualizar zonas, DNS, SSL y reglas de firewall.</p>
            </div>
            <div class="flex items-center gap-2">
            <button @click="diagnosModal = true; diagnosToken()"
                class="flex items-center gap-2 border border-gray-300 text-gray-600 text-sm font-medium px-4 py-2 rounded-lg hover:bg-gray-50"
                title="Ver permisos reales del token">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z"/>
                </svg>
                Diagnosticar
            </button>
            <button @click="configModal = true"
                class="flex items-center gap-2 text-white text-sm font-medium px-4 py-2 rounded-lg"
                style="background-color:#8eb02f"
                onmouseover="this.style.backgroundColor='#6d8c24'"
                onmouseout="this.style.backgroundColor='#8eb02f'">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 0 1 1.37.49l1.296 2.247a1.125 1.125 0 0 1-.26 1.431l-1.003.827c-.293.241-.438.613-.43.992a7.723 7.723 0 0 1 0 .255c-.008.378.137.75.43.991l1.004.827c.424.35.534.955.26 1.43l-1.298 2.247a1.125 1.125 0 0 1-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 0 1-.22.128c-.331.183-.581.495-.644.869l-.213 1.281c-.09.543-.56.94-1.11.94h-2.594c-.55 0-1.019-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 0 1-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 0 1-1.369-.49l-1.297-2.247a1.125 1.125 0 0 1 .26-1.431l1.004-.827c.292-.24.437-.613.43-.991a6.932 6.932 0 0 1 0-.255c.007-.38-.138-.751-.43-.992l-1.004-.827a1.125 1.125 0 0 1-.26-1.43l1.297-2.247a1.125 1.125 0 0 1 1.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.086.22-.128.332-.183.582-.495.644-.869l.214-1.28Z"/>
                    <path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"/>
                </svg>
                Configurar Token
            </button>
            </div>
        </div>

        <!-- Alerta sin config -->
        <div x-show="!hasConfig" class="mb-6 p-4 bg-yellow-50 border border-yellow-200 rounded-lg text-sm text-yellow-700">
            <strong>Sin configuración activa.</strong> Haz clic en "Configurar Token" para ingresar tu API Token de Cloudflare.
            Puedes generarlo en <strong>dash.cloudflare.com → Perfil → API Tokens</strong>.
        </div>

        <!-- Info de usuario -->
        <div x-show="user && user.email" class="mb-5 flex items-center gap-3 p-3 bg-orange-50 border border-orange-200 rounded-lg">
            <div class="h-9 w-9 rounded-full bg-orange-500 flex items-center justify-center text-white font-bold text-sm" x-text="(user.email||'?').charAt(0).toUpperCase()"></div>
            <div>
                <p class="text-sm font-semibold" x-text="user.email"></p>
                <p class="text-xs text-gray-500" x-text="'ID: ' + (user.id || '—')"></p>
            </div>
        </div>

        <!-- Tabs -->
        <div class="border-b border-gray-200 mb-6">
            <nav class="-mb-px flex flex-wrap gap-6 text-sm">
                <button @click="setTab('zones')" :class="activeTab==='zones' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-500 hover:text-gray-700'" class="pb-2 transition-colors">Zonas / Dominios</button>
                <button @click="setTab('dns')" :class="activeTab==='dns' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-500 hover:text-gray-700'" class="pb-2 transition-colors">DNS Records</button>
                <button @click="setTab('ssl')" :class="activeTab==='ssl' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-500 hover:text-gray-700'" class="pb-2 transition-colors">SSL / Certificados</button>
                <button @click="setTab('firewall')" :class="activeTab==='firewall' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-500 hover:text-gray-700'" class="pb-2 transition-colors">Firewall</button>
            </nav>
        </div>

        <!-- Selector de zona (para tabs que requieren zone_id) -->
        <div x-show="['dns','ssl','firewall'].includes(activeTab)" class="flex items-center gap-3 mb-4">
            <label class="text-xs font-medium text-gray-600 shrink-0">Zona:</label>
            <select x-model="selectedZoneId" class="border rounded px-3 py-1.5 text-sm">
                <option value="">— Selecciona una zona —</option>
                <template x-for="z in zones" :key="z.id">
                    <option :value="z.id" x-text="z.name"></option>
                </template>
            </select>
            <button @click="loadTab()" :disabled="!selectedZoneId || loading"
                class="flex items-center gap-1 px-3 py-1.5 rounded border border-gray-300 text-xs hover:bg-gray-50 transition disabled:opacity-40">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" :class="loading && 'animate-spin'" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99"/>
                </svg>
                Cargar
            </button>
        </div>

        <!-- Botón cargar para tabs sin zona -->
        <div x-show="activeTab==='zones'" class="flex items-center gap-3 mb-4">
            <button @click="loadTab()" :disabled="loading"
                class="flex items-center gap-2 px-4 py-2 rounded-lg border border-gray-300 text-sm hover:bg-gray-50 transition">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" :class="loading && 'animate-spin'" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99"/>
                </svg>
                <span x-text="loading ? 'Cargando...' : 'Actualizar zonas'"></span>
            </button>
            <span class="text-xs text-gray-400" x-show="lastFetch" x-text="'Actualizado: ' + lastFetch"></span>
        </div>

        <!-- ─── TAB: Zonas ─── -->
        <div x-show="activeTab==='zones'">
            <div x-show="zones.length === 0 && !loading" class="text-sm text-gray-400 py-8 text-center">Sin datos. Haz clic en "Actualizar zonas".</div>
            <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                <template x-for="z in zones" :key="z.id">
                    <div class="border rounded-xl p-4 bg-white shadow-sm hover:shadow-md transition cursor-pointer"
                        @click="selectZone(z)">
                        <div class="flex items-center justify-between mb-2">
                            <span class="font-semibold text-sm" x-text="z.name"></span>
                            <span class="px-2 py-0.5 rounded-full text-xs font-medium"
                                :class="z.status === 'active' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'"
                                x-text="z.status"></span>
                        </div>
                        <div class="space-y-1 text-xs text-gray-500">
                            <div class="flex justify-between"><span>Plan</span><span x-text="z.plan?.name || z.plan || '—'"></span></div>
                            <div class="flex justify-between"><span>Tipo</span><span x-text="z.type || '—'"></span></div>
                            <div class="flex justify-between"><span>ID</span><span class="font-mono truncate max-w-[100px]" x-text="z.id"></span></div>
                        </div>
                        <div class="mt-3 flex gap-2">
                            <button @click.stop="selectedZoneId = z.id; setTab('dns'); loadTab()"
                                class="flex-1 text-xs py-1.5 rounded border border-[#8eb02f] text-[#6d8c24] hover:bg-green-50 transition">DNS</button>
                            <button @click.stop="selectedZoneId = z.id; setTab('ssl'); loadTab()"
                                class="flex-1 text-xs py-1.5 rounded border border-blue-300 text-blue-600 hover:bg-blue-50 transition">SSL</button>
                            <button @click.stop="selectedZoneId = z.id; setTab('firewall'); loadTab()"
                                class="flex-1 text-xs py-1.5 rounded border border-red-300 text-red-600 hover:bg-red-50 transition">Firewall</button>
                        </div>
                    </div>
                </template>
            </div>
        </div>

        <!-- ─── TAB: DNS ─── -->
        <div x-show="activeTab==='dns'">
            <!-- Toolbar -->
            <div class="flex items-center justify-between gap-3 mb-3">
                <input x-model="dnsSearch" type="search" placeholder="Filtrar por nombre, tipo o contenido…"
                    class="border rounded px-3 py-1.5 text-xs w-full max-w-sm" />
                <button @click="openDnsModal()"
                    class="flex items-center gap-1.5 px-3 py-1.5 text-white text-xs rounded shrink-0"
                    style="background-color:#8eb02f"
                    onmouseover="this.style.backgroundColor='#6d8c24'"
                    onmouseout="this.style.backgroundColor='#8eb02f'">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/></svg>
                    Nuevo registro
                </button>
            </div>
            <div x-show="dnsRecords.length === 0 && !loading" class="text-sm text-gray-400 py-8 text-center">Selecciona una zona y haz clic en "Cargar".</div>
            <div class="overflow-x-auto">
                <table class="table-auto w-full text-xs" x-show="dnsRecords.length > 0">
                    <thead>
                        <tr class="text-left border-b font-semibold text-gray-500">
                            <th class="py-2 px-3">Tipo</th>
                            <th class="py-2 px-3">Nombre</th>
                            <th class="py-2 px-3">Contenido</th>
                            <th class="py-2 px-3">Proxy</th>
                            <th class="py-2 px-3">TTL</th>
                            <th class="py-2 px-3">Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <template x-for="r in dnsFiltered" :key="r.id">
                            <tr class="border-b hover:bg-gray-50">
                                <td class="py-2 px-3"><span class="px-1.5 py-0.5 bg-blue-100 text-blue-700 rounded font-mono text-xs" x-text="r.type"></span></td>
                                <td class="py-2 px-3 font-mono" x-text="r.name"></td>
                                <td class="py-2 px-3 font-mono truncate max-w-xs" x-text="r.content"></td>
                                <td class="py-2 px-3">
                                    <span :class="r.proxied ? 'bg-orange-100 text-orange-700' : 'bg-gray-100 text-gray-500'" class="px-1.5 py-0.5 rounded text-xs">
                                        <span x-text="r.proxied ? 'Proxied' : 'DNS only'"></span>
                                    </span>
                                </td>
                                <td class="py-2 px-3" x-text="r.ttl === 1 ? 'Auto' : r.ttl"></td>
                                <td class="py-2 px-3">
                                    <div class="flex items-center gap-2">
                                        <button @click="openDnsModal(r)" title="Editar"
                                            class="text-blue-500 hover:text-blue-700 transition">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125"/></svg>
                                        </button>
                                        <button @click="deleteDns(r)" title="Eliminar"
                                            class="text-red-400 hover:text-red-600 transition">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"/></svg>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- ─── TAB: SSL ─── -->
        <div x-show="activeTab==='ssl'">
            <div x-show="sslCerts.length === 0 && !sslUniversal && !loading" class="text-sm text-gray-400 py-8 text-center">Selecciona una zona y haz clic en "Cargar".</div>
            <!-- Fallback: Universal SSL -->
            <div x-show="sslUniversal" class="mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-800">
                <p class="font-medium mb-1">Universal SSL</p>
                <p x-text="sslUniversal?.note || (sslUniversal?.enabled ? 'Universal SSL activo' : 'Universal SSL inactivo')"></p>
            </div>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <template x-for="c in sslCerts" :key="c.id">
                    <div class="border rounded-xl p-4 bg-white shadow-sm">
                        <div class="flex items-center justify-between mb-2">
                            <span class="font-semibold text-sm capitalize" x-text="c.type || 'Certificado'"></span>
                            <span class="px-2 py-0.5 rounded-full text-xs font-medium"
                                :class="c.status === 'active' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'"
                                x-text="c.status"></span>
                        </div>
                        <div class="space-y-1 text-xs text-gray-500">
                            <div class="flex justify-between"><span>Hosts cubiertos</span><span class="text-right truncate max-w-[14rem]" x-text="(c.hosts||[]).join(', ')"></span></div>
                            <div class="flex justify-between" x-show="c.certificate_authority"><span>CA</span><span x-text="c.certificate_authority || '—'"></span></div>
                            <div class="flex justify-between" x-show="c.validity_days"><span>Vigencia</span><span x-text="c.validity_days ? c.validity_days + ' días' : '—'"></span></div>
                            <div class="flex justify-between"><span>ID</span><span class="font-mono" x-text="c.id || '—'"></span></div>
                        </div>
                    </div>
                </template>
            </div>
        </div>

        <!-- ─── TAB: Firewall ─── -->
        <div x-show="activeTab==='firewall'">
            <div x-show="fwRules.length === 0 && !loading" class="text-sm text-gray-400 py-8 text-center">Selecciona una zona y haz clic en "Cargar".</div>
            <div class="overflow-x-auto">
                <table class="table-auto w-full text-xs" x-show="fwRules.length > 0">
                    <thead>
                        <tr class="text-left border-b font-semibold text-gray-500">
                            <th class="py-2 px-3">Modo</th>
                            <th class="py-2 px-3">IP / Rango</th>
                            <th class="py-2 px-3">País</th>
                            <th class="py-2 px-3">Notas</th>
                            <th class="py-2 px-3">Creado</th>
                        </tr>
                    </thead>
                    <tbody>
                        <template x-for="r in fwRules" :key="r.id">
                            <tr class="border-b hover:bg-gray-50">
                                <td class="py-2 px-3">
                                    <span class="px-2 py-0.5 rounded text-xs font-medium"
                                        :class="r.mode === 'block' ? 'bg-red-100 text-red-700' : (r.mode === 'challenge' ? 'bg-yellow-100 text-yellow-700' : 'bg-green-100 text-green-700')"
                                        x-text="r.mode"></span>
                                </td>
                                <td class="py-2 px-3 font-mono" x-text="r.configuration?.value || '—'"></td>
                                <td class="py-2 px-3" x-text="r.configuration?.country || '—'"></td>
                                <td class="py-2 px-3 truncate max-w-[12rem]" x-text="r.notes || '—'"></td>
                                <td class="py-2 px-3 text-gray-500" x-text="r.created_on ? new Date(r.created_on).toLocaleDateString() : '—'"></td>
                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>
        </div>

    </div><!-- /container -->

    <!-- ─── Modal: DNS Crear / Editar ─── -->
    <div x-show="dnsModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4"
        @click.self="dnsModal=false">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-lg">
            <div class="flex items-center justify-between px-5 py-4 border-b">
                <h3 class="font-semibold text-sm" x-text="dnsForm.id ? 'Editar registro DNS' : 'Nuevo registro DNS'"></h3>
                <button @click="dnsModal=false" class="text-gray-400 hover:text-gray-600">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"/></svg>
                </button>
            </div>
            <form @submit.prevent="saveDns()" class="p-5 space-y-3">
                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="text-xs font-medium text-gray-600">Tipo *</label>
                        <select x-model="dnsForm.type" required class="mt-1 w-full border rounded px-3 py-2 text-sm">
                            <template x-for="t in ['A','AAAA','CNAME','TXT','MX','NS','SRV','CAA','PTR']" :key="t">
                                <option :value="t" x-text="t"></option>
                            </template>
                        </select>
                    </div>
                    <div>
                        <label class="text-xs font-medium text-gray-600">TTL</label>
                        <select x-model.number="dnsForm.ttl" class="mt-1 w-full border rounded px-3 py-2 text-sm">
                            <option value="1">Auto</option>
                            <option value="60">1 min</option>
                            <option value="300">5 min</option>
                            <option value="600">10 min</option>
                            <option value="1800">30 min</option>
                            <option value="3600">1 hora</option>
                            <option value="86400">1 día</option>
                        </select>
                    </div>
                </div>
                <div>
                    <label class="text-xs font-medium text-gray-600">Nombre *</label>
                    <input x-model="dnsForm.name" required placeholder="@ o subdominio (ej: www)" class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono" />
                </div>
                <div>
                    <label class="text-xs font-medium text-gray-600">Contenido *</label>
                    <input x-model="dnsForm.content" required :placeholder="dnsForm.type === 'A' ? '1.2.3.4' : dnsForm.type === 'MX' ? 'mail.ejemplo.com' : 'valor'" class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono" />
                </div>
                <div x-show="dnsForm.type === 'MX' || dnsForm.type === 'SRV'">
                    <label class="text-xs font-medium text-gray-600">Prioridad</label>
                    <input x-model.number="dnsForm.priority" type="number" min="0" class="mt-1 w-full border rounded px-3 py-2 text-sm" />
                </div>
                <div class="flex items-center gap-2">
                    <label class="relative inline-flex items-center cursor-pointer">
                        <input type="checkbox" x-model="dnsForm.proxied" class="sr-only peer" />
                        <div class="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:bg-orange-500 after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-4"></div>
                    </label>
                    <span class="text-xs" x-text="dnsForm.proxied ? 'Proxied (nube naranja)' : 'DNS only'"></span>
                </div>
                <div>
                    <label class="text-xs font-medium text-gray-600">Comentario <span class="font-normal text-gray-400">(opcional)</span></label>
                    <input x-model="dnsForm.comment" placeholder="Descripción del registro" class="mt-1 w-full border rounded px-3 py-2 text-sm" />
                </div>
                <div class="flex justify-end gap-3 pt-2 border-t">
                    <button type="button" @click="dnsModal=false" class="px-4 py-2 border rounded text-sm">Cancelar</button>
                    <button type="submit" :disabled="loading" class="px-5 py-2 text-white text-sm rounded" style="background-color:#8eb02f">
                        <span x-text="loading ? 'Guardando…' : (dnsForm.id ? 'Actualizar' : 'Crear')"></span>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- ─── Modal: Diagnóstico de Token ─── -->
    <div x-show="diagnosModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4"
        @click.self="diagnosModal=false">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col">
            <div class="flex items-center justify-between px-5 py-4 border-b shrink-0">
                <h3 class="font-semibold text-sm">Diagnóstico del Token</h3>
                <button @click="diagnosModal=false" class="text-gray-400 hover:text-gray-600">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>
            <div class="p-5 overflow-y-auto flex-1">
                <!-- Cargando -->
                <div x-show="diagnosLoading" class="flex items-center gap-2 text-sm text-gray-500">
                    <svg class="animate-spin h-4 w-4" 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-8v8H4z"/>
                    </svg>
                    Consultando Cloudflare API…
                </div>
                <!-- Resultado resumen -->
                <template x-if="diagnosData && !diagnosLoading">
                    <div class="space-y-4">
                        <!-- Hint destacado -->
                        <div :class="diagnosData.hint && diagnosData.hint.startsWith('Token válido') ? 'bg-green-50 border-green-300 text-green-800' : 'bg-amber-50 border-amber-300 text-amber-800'"
                            class="border rounded-lg p-3 text-sm font-medium">
                            <span x-text="diagnosData.hint || diagnosData.error || 'Sin datos'"></span>
                        </div>
                        <!-- Tarjetas de permisos -->
                        <div class="grid grid-cols-2 gap-3" x-show="diagnosData.permissions_test">
                            <div class="border rounded-lg p-3">
                                <p class="text-xs font-medium text-gray-500 mb-1">Zone:Zone:Read</p>
                                <div class="flex items-center gap-1.5">
                                    <span :class="diagnosData.permissions_test?.zone_read?.ok ? 'bg-green-500' : 'bg-red-500'" class="h-2.5 w-2.5 rounded-full shrink-0"></span>
                                    <span class="text-xs" x-text="diagnosData.permissions_test?.zone_read?.ok ? 'OK' : (diagnosData.permissions_test?.zone_read?.error || 'Error')"></span>
                                </div>
                            </div>
                            <div class="border rounded-lg p-3">
                                <p class="text-xs font-medium text-gray-500 mb-1">Zone:DNS:Read</p>
                                <div class="flex items-center gap-1.5">
                                    <span :class="diagnosData.permissions_test?.dns_read?.ok ? 'bg-green-500' : 'bg-red-500'" class="h-2.5 w-2.5 rounded-full shrink-0"></span>
                                    <span class="text-xs" x-text="diagnosData.permissions_test?.dns_read?.ok ? 'OK' : (diagnosData.permissions_test?.dns_read?.error || 'Error')"></span>
                                </div>
                                <p class="text-xs text-gray-400 mt-1 font-mono truncate" x-show="diagnosData.permissions_test?.dns_read?.zone_tested"
                                    x-text="'Zona: ' + diagnosData.permissions_test?.dns_read?.zone_tested"></p>
                            </div>
                        </div>
                        <!-- Info del token -->
                        <div class="grid grid-cols-2 gap-2 text-xs text-gray-600">
                            <div><span class="font-medium">Tipo auth:</span> <span x-text="diagnosData.auth_type || diagnosData.token?.auth_type || '—'"></span></div>
                            <div><span class="font-medium">Estado:</span> <span x-text="diagnosData.token_status || '—'"></span></div>
                            <div><span class="font-medium">Token ID:</span> <span class="font-mono" x-text="diagnosData.token_id || '—'"></span></div>
                            <div><span class="font-medium">Longitud:</span> <span x-text="(diagnosData.token_len || diagnosData.token?.length || '—') + ' chars'"></span></div>
                            <div x-show="diagnosData.user_email"><span class="font-medium">Email:</span> <span x-text="diagnosData.user_email"></span></div>
                            <div><span class="font-medium">Tenía chars sucios:</span> <span x-text="diagnosData.was_dirty || diagnosData.token?.was_sanitized ? 'SÍ (saneado)' : 'No'"></span></div>
                            <div x-show="diagnosData.token?.hint_format" class="col-span-2 text-amber-700 font-medium" x-text="diagnosData.token?.hint_format"></div>
                        </div>
                        <!-- Políticas raw -->
                        <div x-show="diagnosData.policies">
                            <p class="text-xs font-medium text-gray-500 mb-1">Políticas registradas en Cloudflare:</p>
                            <pre class="bg-gray-50 border rounded p-3 text-xs overflow-x-auto whitespace-pre-wrap break-all"
                                x-text="JSON.stringify(diagnosData.policies, null, 2)"></pre>
                        </div>
                        <!-- JSON completo -->
                        <details class="text-xs">
                            <summary class="cursor-pointer text-gray-400 hover:text-gray-600">Ver JSON completo</summary>
                            <pre class="mt-2 bg-gray-50 border rounded p-3 overflow-x-auto whitespace-pre-wrap break-all"
                                x-text="JSON.stringify(diagnosData, null, 2)"></pre>
                        </details>
                    </div>
                </template>
                <!-- Error de conexión -->
                <div x-show="diagnosError && !diagnosLoading" class="bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-700" x-text="diagnosError"></div>
            </div>
            <div class="px-5 py-3 border-t shrink-0 flex justify-between items-center">
                <button @click="diagnosToken()" :disabled="diagnosLoading"
                    class="px-4 py-2 border rounded text-sm hover:bg-gray-50 disabled:opacity-40">Reintentar</button>
                <button @click="diagnosModal=false" class="px-4 py-2 text-white text-sm rounded" style="background-color:#8eb02f">Cerrar</button>
            </div>
        </div>
    </div>

    <!-- ─── Modal: Configurar Token ─── -->
    <div x-show="configModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4"
        @click.self="configModal=false">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md">
            <div class="flex items-center justify-between px-5 py-4 border-b">
                <h3 class="font-semibold text-sm">Configurar API Token — Cloudflare</h3>
                <button @click="configModal=false" class="text-gray-400 hover:text-gray-600">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>
            <form @submit.prevent="saveConfig()" class="p-5 space-y-4">
                <!-- Tipo de autenticación -->
                <div>
                    <label class="text-xs font-medium text-gray-600">Tipo de credencial *</label>
                    <div class="mt-2 flex gap-4">
                        <label class="flex items-center gap-2 text-sm cursor-pointer">
                            <input type="radio" x-model="cfgForm.auth_type" value="token" class="accent-[#8eb02f]" />
                            <span>API Token <span class="text-xs text-gray-400">(recomendado, 40 chars)</span></span>
                        </label>
                        <label class="flex items-center gap-2 text-sm cursor-pointer">
                            <input type="radio" x-model="cfgForm.auth_type" value="global_key" class="accent-[#8eb02f]" />
                            <span>Global API Key <span class="text-xs text-gray-400">(API de cuenta, 37 chars)</span></span>
                        </label>
                    </div>
                </div>
                <!-- Email (solo Global API Key) -->
                <div x-show="cfgForm.auth_type === 'global_key'">
                    <label class="text-xs font-medium text-gray-600">Email de la cuenta *</label>
                    <input x-model="cfgForm.email" type="email"
                        :required="cfgForm.auth_type === 'global_key'"
                        placeholder="tucuenta@ejemplo.com"
                        class="mt-1 w-full border rounded px-3 py-2 text-sm" />
                    <p class="mt-1 text-xs text-gray-400">El email con el que accedes a dash.cloudflare.com</p>
                </div>
                <!-- API Token / Global API Key -->
                <div>
                    <label class="text-xs font-medium text-gray-600">
                        <span x-text="cfgForm.auth_type === 'global_key' ? 'Global API Key *' : 'API Token *'"></span>
                    </label>
                    <input x-model="cfgForm.api_token" type="password" required
                        :placeholder="cfgForm.auth_type === 'global_key' ? 'Global API Key (37 chars hexadecimales)' : 'API Token (40 chars)'"
                        class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono" />
                    <p x-show="cfgForm.auth_type === 'token'" class="mt-1 text-xs text-gray-400">
                        dash.cloudflare.com → Mi perfil → API Tokens → Crear token
                    </p>
                    <p x-show="cfgForm.auth_type === 'global_key'" class="mt-1 text-xs text-gray-400">
                        dash.cloudflare.com → Mi perfil → API Tokens → Global API Key → View
                    </p>
                </div>
                <div>
                    <label class="text-xs font-medium text-gray-600">Account ID (opcional)</label>
                    <input x-model="cfgForm.account_id" class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono"
                        placeholder="ID de cuenta (visible en el panel)" />
                </div>
                <div>
                    <label class="text-xs font-medium text-gray-600">Nota (opcional)</label>
                    <input x-model="cfgForm.nota" class="mt-1 w-full border rounded px-3 py-2 text-sm" placeholder="Ej: producción" />
                </div>
                <div class="flex justify-end gap-3 pt-2 border-t">
                    <button type="button" @click="configModal=false" class="px-4 py-2 border rounded text-sm">Cancelar</button>
                    <button type="button" @click="verifyToken()" :disabled="loading"
                        class="px-4 py-2 border border-orange-400 text-orange-600 rounded text-sm hover:bg-orange-50">
                        Verificar token
                    </button>
                    <button type="submit" :disabled="loading" class="px-5 py-2 text-white text-sm rounded"
                        style="background-color:#8eb02f">
                        <span x-text="loading ? 'Guardando…' : 'Guardar'"></span>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Toast -->
    <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('cloudflareApp', () => ({
        loading: false,
        hasConfig: false,
        activeTab: 'zones',
        lastFetch: '',
        user: {},
        zones: [],
        dnsRecords: [],
        sslCerts: [],
        sslUniversal: null,
        fwRules: [],
        selectedZoneId: '',
        dnsSearch: '',
        dnsModal: false,
        dnsForm: { id: '', type: 'A', name: '', content: '', ttl: 1, proxied: false, priority: 0, comment: '' },
        diagnosModal: false,
        diagnosLoading: false,
        diagnosData: null,
        diagnosError: '',
        cfgForm: {
            id:         {{ if .Config }}{{ .Config.ID }}{{ else }}0{{ end }},
            auth_type:  '{{ if .Config }}{{ .Config.AuthType }}{{ else }}token{{ end }}',
            api_token:  '',
            email:      '{{ if .Config }}{{ .Config.Email }}{{ else }}{{ end }}',
            account_id: '{{ if .Config }}{{ .Config.AccountID }}{{ else }}{{ end }}',
            nota:       '{{ if .Config }}{{ .Config.Nota }}{{ else }}{{ end }}',
        },
        toast: { show: false, msg: '', type: 'ok' },

        async init() {
            try {
                const zRes = await axios.get('/app/cloudflare/zones');
                this.zones = zRes.data.data || [];
                this.hasConfig = true;
                this.lastFetch = new Date().toLocaleTimeString();
            } catch (e) {
                if (e.response?.status === 503) this.hasConfig = false;
                else this.hasConfig = true;
                return;
            }
            // /user puede fallar para tokens de zona → no bloquea la carga
            try {
                const uRes = await axios.get('/app/cloudflare/user');
                this.user = uRes.data.data || {};
            } catch (_) {}
        },

        get dnsFiltered() {
            const q = this.dnsSearch.toLowerCase();
            if (!q) return this.dnsRecords;
            return this.dnsRecords.filter(r =>
                (r.name||'').toLowerCase().includes(q) ||
                (r.type||'').toLowerCase().includes(q) ||
                (r.content||'').toLowerCase().includes(q)
            );
        },

        setTab(tab) {
            this.activeTab = tab;
        },

        selectZone(z) {
            this.selectedZoneId = z.id;
        },

        async loadTab() {
            this.loading = true;
            try {
                if (this.activeTab === 'zones') {
                    const res = await axios.get('/app/cloudflare/zones');
                    this.zones = res.data.data || [];
                    this.lastFetch = new Date().toLocaleTimeString();
                } else if (this.activeTab === 'dns' && this.selectedZoneId) {
                    const res = await axios.get('/app/cloudflare/zones/' + this.selectedZoneId + '/dns');
                    this.dnsRecords = res.data.data || [];
                } else if (this.activeTab === 'ssl' && this.selectedZoneId) {
                    const res = await axios.get('/app/cloudflare/zones/' + this.selectedZoneId + '/ssl');
                    this.sslCerts = res.data.data || [];
                    this.sslUniversal = res.data.universal_ssl || null;
                } else if (this.activeTab === 'firewall' && this.selectedZoneId) {
                    const res = await axios.get('/app/cloudflare/zones/' + this.selectedZoneId + '/firewall');
                    this.fwRules = res.data.data || [];
                }
                this.hasConfig = true;
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error al cargar datos', 'error');
            }
            this.loading = false;
        },

        openDnsModal(record = null) {
            if (record) {
                this.dnsForm = {
                    id:       record.id,
                    type:     record.type,
                    name:     record.name,
                    content:  record.content,
                    ttl:      record.ttl ?? 1,
                    proxied:  record.proxied ?? false,
                    priority: record.priority ?? 0,
                    comment:  record.comment ?? '',
                };
            } else {
                this.dnsForm = { id: '', type: 'A', name: '', content: '', ttl: 1, proxied: false, priority: 0, comment: '' };
            }
            this.dnsModal = true;
        },

        async saveDns() {
            if (!this.selectedZoneId) return;
            this.loading = true;
            const payload = {
                type:     this.dnsForm.type,
                name:     this.dnsForm.name,
                content:  this.dnsForm.content,
                ttl:      this.dnsForm.ttl,
                proxied:  this.dnsForm.proxied,
                priority: this.dnsForm.priority || 0,
                comment:  this.dnsForm.comment,
            };
            try {
                if (this.dnsForm.id) {
                    await axios.put(`/app/cloudflare/zones/${this.selectedZoneId}/dns/${this.dnsForm.id}`, payload);
                    this.showToast('Registro actualizado');
                } else {
                    await axios.post(`/app/cloudflare/zones/${this.selectedZoneId}/dns`, payload);
                    this.showToast('Registro creado');
                }
                this.dnsModal = false;
                await this.loadTab();
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error al guardar registro', 'error');
            }
            this.loading = false;
        },

        async deleteDns(record) {
            if (!confirm(`¿Eliminar ${record.type} ${record.name}?`)) return;
            this.loading = true;
            try {
                await axios.delete(`/app/cloudflare/zones/${this.selectedZoneId}/dns/${record.id}`);
                this.showToast('Registro eliminado');
                await this.loadTab();
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error al eliminar', 'error');
            }
            this.loading = false;
        },

        async saveConfig() {
            this.loading = true;
            try {
                await axios.post('/app/cloudflare/config', this.cfgForm);
                this.showToast('Token guardado correctamente');
                this.configModal = false;
                this.hasConfig = true;
                await this.init();
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error al guardar', 'error');
            }
            this.loading = false;
        },

        async verifyToken() {
            this.loading = true;
            try {
                const res = await axios.get('/app/cloudflare/verify');
                const status = res.data?.data?.status || res.data?.token_status || 'active';
                this.showToast('Token válido — estado: ' + status);
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Token inválido o sin permisos', 'error');
            }
            this.loading = false;
        },

        async diagnosToken() {
            this.diagnosLoading = true;
            this.diagnosData = null;
            this.diagnosError = '';
            try {
                const res = await axios.get('/app/cloudflare/verify');
                this.diagnosData = res.data;
            } catch (e) {
                this.diagnosError = e.response?.data?.error || e.message || 'Error al consultar';
                this.diagnosData = e.response?.data || null;
            }
            this.diagnosLoading = false;
        },

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