<div x-data="hostingerApp" 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">Hostinger API</h1>
                <p class="text-xs text-slate-500 mt-0.5">Conexión con tu cuenta de Hostinger para visualizar VPS, dominios, DNS, hosting y facturación.</p>
            </div>
            <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>

        <!-- 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 Hostinger.
            Puedes generarlo en <strong>hpanel.hostinger.com → Cuenta → API</strong>.
        </div>

        <!-- Tabs de navegación -->
        <div class="border-b border-gray-200 mb-6">
            <nav class="-mb-px flex gap-6 text-sm">
                <button @click="activeTab='vps'" :class="activeTab==='vps' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-500 hover:text-gray-700'" class="pb-2 transition-colors">VPS / Servidores</button>
                <button @click="activeTab='domains'" :class="activeTab==='domains' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-500 hover:text-gray-700'" class="pb-2 transition-colors">Dominios</button>
                <button @click="activeTab='hosting'" :class="activeTab==='hosting' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-500 hover:text-gray-700'" class="pb-2 transition-colors">Hosting</button>
                <button @click="activeTab='orders'" :class="activeTab==='orders' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-500 hover:text-gray-700'" class="pb-2 transition-colors">Facturación</button>
            </nav>
        </div>

        <!-- Botón Cargar datos -->
        <div 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 datos'"></span>
            </button>
            <span class="text-xs text-gray-400" x-show="lastFetch" x-text="'Actualizado: ' + lastFetch"></span>
        </div>

        <!-- ─── TAB: VPS ─── -->
        <div x-show="activeTab==='vps'">
            <div x-show="vps.length === 0 && !loading" class="text-sm text-gray-400 py-8 text-center">Sin datos. Haz clic en "Actualizar datos".</div>
            <div x-show="vps.length > 0" class="mb-4">
                <input x-model="vpsSearch" type="text" placeholder="Buscar por hostname, IP, plan, datacenter..."
                    class="w-full border rounded-lg px-3 py-2 text-sm" />
            </div>
            <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                <template x-for="v in filteredVPS" :key="v.id">
                    <div class="border rounded-xl p-4 bg-white shadow-sm hover:shadow-md transition">
                        <div class="flex items-center justify-between mb-3">
                            <span class="font-semibold text-sm truncate" x-text="v.hostname"></span>
                            <span class="px-2 py-0.5 rounded-full text-xs font-medium"
                                :class="v.state === 'running' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'"
                                x-text="v.state"></span>
                        </div>
                        <div class="space-y-1 text-xs text-gray-500">
                            <div class="flex justify-between"><span>IPv4</span><span class="font-mono" x-text="(v.ipv4 && v.ipv4.length) ? v.ipv4.map(ip => ip.address).join(', ') : '—'"></span></div>
                            <div class="flex justify-between"><span>Plan</span><span x-text="v.plan || '—'"></span></div>
                            <div class="flex justify-between"><span>Datacenter</span><span x-text="v.data_center || '—'"></span></div>
                            <div class="flex justify-between"><span>CPU</span><span x-text="(v.cpus || v.cpu || '—') + ' vCPU'"></span></div>
                            <div class="flex justify-between"><span>RAM</span><span x-text="formatBytes(v.memory) + ' RAM'"></span></div>
                            <div class="flex justify-between"><span>Disco</span><span x-text="formatBytes(v.disk)"></span></div>
                        </div>
                        <button @click="loadDNSForDomain(v.hostname)"
                            class="mt-3 w-full text-center text-xs py-1.5 rounded border border-[#8eb02f] text-[#6d8c24] hover:bg-green-50 transition">
                            Ver DNS del hostname
                        </button>
                        <!-- Acciones de estado -->
                        <div class="mt-2 flex gap-1.5">
                            <button x-show="v.state !== 'running'"
                                @click="vpsAction(v.id, 'start')"
                                :disabled="vpsActionLoading[v.id]"
                                class="flex-1 text-xs py-1.5 rounded bg-green-500 text-white hover:bg-green-600 disabled:opacity-40 transition">
                                <span x-text="vpsActionLoading[v.id]==='start' ? '...' : '▶ Start'"></span>
                            </button>
                            <button x-show="v.state === 'running'"
                                @click="vpsAction(v.id, 'stop')"
                                :disabled="vpsActionLoading[v.id]"
                                class="flex-1 text-xs py-1.5 rounded bg-red-500 text-white hover:bg-red-600 disabled:opacity-40 transition">
                                <span x-text="vpsActionLoading[v.id]==='stop' ? '...' : '■ Stop'"></span>
                            </button>
                            <button x-show="v.state === 'running'"
                                @click="vpsAction(v.id, 'restart')"
                                :disabled="vpsActionLoading[v.id]"
                                class="flex-1 text-xs py-1.5 rounded bg-yellow-500 text-white hover:bg-yellow-600 disabled:opacity-40 transition">
                                <span x-text="vpsActionLoading[v.id]==='restart' ? '...' : '↺ Restart'"></span>
                            </button>
                        </div>
                        <!-- Configuración avanzada -->
                        <div class="mt-1.5 flex gap-1.5">
                            <button @click="vpsPasswordForm={id:v.id,password:''}; vpsPasswordModal=true"
                                class="flex-1 text-xs py-1.5 rounded border border-gray-300 text-gray-600 hover:bg-gray-50 transition">
                                🔑 Password
                            </button>
                            <button @click="vpsHostnameForm={id:v.id,hostname:v.hostname}; vpsHostnameModal=true"
                                class="flex-1 text-xs py-1.5 rounded border border-gray-300 text-gray-600 hover:bg-gray-50 transition">
                                ✏️ Hostname
                            </button>
                            <button @click="openMetrics(v)"
                                class="flex-1 text-xs py-1.5 rounded border border-blue-200 text-blue-600 hover:bg-blue-50 transition">
                                📊 Métricas
                            </button>
                        </div>
                    </div>
                </template>
            </div>
        </div>

        <!-- ─── TAB: Dominios ─── -->
        <div x-show="activeTab==='domains'">
            <div x-show="domains.length === 0 && !loading" class="text-sm text-gray-400 py-8 text-center">Sin datos. Haz clic en "Actualizar datos".</div>
            <div x-show="domains.length > 0" class="mb-4">
                <input x-model="domainsSearch" type="text" placeholder="Buscar dominio o estado..."
                    class="w-full border rounded-lg px-3 py-2 text-sm" />
            </div>
            <div class="overflow-x-auto">
                <table class="table-auto w-full text-sm">
                    <thead>
                        <tr class="text-left border-b text-xs text-gray-500 font-semibold">
                            <th class="py-2 px-3">Dominio</th>
                            <th class="py-2 px-3">Estado</th>
                            <th class="py-2 px-3">Registrado</th>
                            <th class="py-2 px-3">Vence</th>
                            <th class="py-2 px-3"></th>
                        </tr>
                    </thead>
                    <tbody>
                        <template x-for="(d, dIdx) in filteredDomains" :key="d.domain + '_' + dIdx">
                            <tr class="border-b hover:bg-gray-50">
                                <td class="py-2 px-3 font-mono text-xs" x-text="d.domain"></td>
                                <td class="py-2 px-3">
                                    <span class="px-2 py-0.5 rounded-full text-xs"
                                        :class="d.status === 'active' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'"
                                        x-text="d.status"></span>
                                </td>
                                <td class="py-2 px-3 text-xs text-gray-500" x-text="d.registered_at || '—'"></td>
                                <td class="py-2 px-3 text-xs text-gray-500" x-text="d.expires_at || '—'"></td>
                                <td class="py-2 px-3">
                                    <div class="flex flex-wrap gap-1">
                                        <button @click="loadDNSForDomain(d.domain)"
                                            class="text-xs px-2 py-1 rounded border border-[#8eb02f] text-[#6d8c24] hover:bg-green-50 transition">
                                            DNS
                                        </button>
                                        <button @click="nsForm={domain:d.domain,ns1:'',ns2:'',ns3:'',ns4:''}; nsModal=true"
                                            class="text-xs px-2 py-1 rounded border border-blue-400 text-blue-600 hover:bg-blue-50 transition">
                                            NS
                                        </button>
                                        <button @click="toggleDomainLock(d.domain, true)"
                                            class="text-xs px-2 py-1 rounded border border-gray-300 text-gray-500 hover:bg-gray-50 transition"
                                            title="Bloquear dominio">
                                            🔒
                                        </button>
                                        <button @click="toggleDomainLock(d.domain, false)"
                                            class="text-xs px-2 py-1 rounded border border-gray-300 text-gray-500 hover:bg-gray-50 transition"
                                            title="Desbloquear dominio">
                                            🔓
                                        </button>
                                        <button @click="togglePrivacy(d.domain, true)"
                                            class="text-xs px-2 py-1 rounded border border-purple-300 text-purple-600 hover:bg-purple-50 transition"
                                            title="Activar privacy WHOIS">
                                            👁
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- ─── TAB: Hosting ─── -->
        <div x-show="activeTab==='hosting'">
            <div x-show="hosting.length === 0 && !loading" class="text-sm text-gray-400 py-8 text-center">Sin datos. Haz clic en "Actualizar datos".</div>
            <div x-show="hosting.length > 0" class="mb-4">
                <input x-model="hostingSearch" type="text" placeholder="Buscar por dominio, tipo o usuario..."
                    class="w-full border rounded-lg px-3 py-2 text-sm" />
            </div>
            <div class="overflow-x-auto">
                <table class="table-auto w-full text-sm">
                    <thead>
                        <tr class="text-left border-b text-xs text-gray-500 font-semibold">
                            <th class="py-2 px-3">Dominio</th>
                            <th class="py-2 px-3">Tipo</th>
                            <th class="py-2 px-3">Estado</th>
                            <th class="py-2 px-3">Usuario</th>
                            <th class="py-2 px-3">Creado</th>
                        </tr>
                    </thead>
                    <tbody>
                        <template x-for="(h, hIdx) in filteredHosting" :key="h.domain + '_' + hIdx">
                            <tr class="border-b hover:bg-gray-50">
                                <td class="py-2 px-3 font-mono text-xs" x-text="h.domain || '—'"></td>
                                <td class="py-2 px-3 text-xs" x-text="h.vhost_type || '—'"></td>
                                <td class="py-2 px-3">
                                    <span class="px-2 py-0.5 rounded-full text-xs"
                                        :class="h.is_enabled ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'"
                                        x-text="h.is_enabled ? 'activo' : 'inactivo'"></span>
                                </td>
                                <td class="py-2 px-3 text-xs" x-text="h.username || '—'"></td>
                                <td class="py-2 px-3 text-xs text-gray-500" x-text="h.created_at || '—'"></td>
                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- ─── TAB: Facturación ─── -->
        <div x-show="activeTab==='orders'">
            <div x-show="orders.length === 0 && !loading" class="text-sm text-gray-400 py-8 text-center">Sin datos. Haz clic en "Actualizar datos".</div>
            <div x-show="orders.length > 0" class="mb-4">
                <input x-model="ordersSearch" type="text" placeholder="Buscar por nombre, ID o estado..."
                    class="w-full border rounded-lg px-3 py-2 text-sm" />
            </div>
            <div class="overflow-x-auto">
                <table class="table-auto w-full text-sm">
                    <thead>
                        <tr class="text-left border-b text-xs text-gray-500 font-semibold">
                            <th class="py-2 px-3">Nombre</th>
                            <th class="py-2 px-3">Estado</th>
                            <th class="py-2 px-3">Precio</th>
                            <th class="py-2 px-3">Período</th>
                            <th class="py-2 px-3">Vence / Próximo cobro</th>
                            <th class="py-2 px-3">Auto-renovar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <template x-for="o in filteredOrders" :key="o.id">
                            <tr class="border-b hover:bg-gray-50">
                                <td class="py-2 px-3 text-xs" x-text="o.name || '—'"></td>
                                <td class="py-2 px-3">
                                    <span class="px-2 py-0.5 rounded-full text-xs"
                                        :class="o.status === 'active' ? 'bg-green-100 text-green-700' : o.status === 'in_trial' ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-500'"
                                        x-text="o.status"></span>
                                </td>
                                <td class="py-2 px-3 text-xs font-semibold font-mono" x-text="o.total_price ? o.currency_code + '\u00a0' + new Intl.NumberFormat('es-CO').format(o.total_price / 100) : '—'"></td>
                                <td class="py-2 px-3 text-xs text-gray-500" x-text="o.billing_period + '\u00a0' + (o.billing_period_unit === 'year' ? (o.billing_period === 1 ? 'año' : 'años') : (o.billing_period === 1 ? 'mes' : 'meses'))"></td>
                                <td class="py-2 px-3 text-xs text-gray-500" x-text="o.expires_at || o.next_billing_at || '—'"></td>
                                <td class="py-2 px-3">
                                    <button x-show="!o.is_auto_renewed" @click="toggleAutoRenewal(o.id, true)"
                                        class="text-xs px-2 py-1 rounded border border-green-400 text-green-600 hover:bg-green-50 transition">
                                        Activar
                                    </button>
                                    <button x-show="o.is_auto_renewed" @click="toggleAutoRenewal(o.id, false)"
                                        class="text-xs px-2 py-1 rounded border border-red-300 text-red-500 hover:bg-red-50 transition">
                                        Desactivar
                                    </button>
                                </td>
                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>
        </div>

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

    <!-- ─── Modal: VPS Root Password ─── -->
    <div x-show="vpsPasswordModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4"
        @click.self="vpsPasswordModal=false">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-sm">
            <div class="flex items-center justify-between px-5 py-4 border-b">
                <h3 class="font-semibold text-sm">Cambiar contraseña root</h3>
                <button @click="vpsPasswordModal=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 space-y-4">
                <div>
                    <label class="text-xs font-medium text-gray-600">Nueva contraseña *</label>
                    <input x-model="vpsPasswordForm.password" type="password" required autocomplete="new-password"
                        class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono"
                        placeholder="Mín. 8 caracteres, letras y números" />
                </div>
                <div class="flex gap-3 justify-end">
                    <button @click="vpsPasswordModal=false" class="px-4 py-2 rounded border text-sm text-gray-600 hover:bg-gray-50">Cancelar</button>
                    <button @click="setRootPassword()" :disabled="loading || !vpsPasswordForm.password"
                        class="px-4 py-2 rounded text-sm bg-[#8eb02f] text-white hover:bg-[#6d8c24] disabled:opacity-40 transition">
                        Guardar
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- ─── Modal: VPS Hostname ─── -->
    <div x-show="vpsHostnameModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4"
        @click.self="vpsHostnameModal=false">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-sm">
            <div class="flex items-center justify-between px-5 py-4 border-b">
                <h3 class="font-semibold text-sm">Cambiar Hostname</h3>
                <button @click="vpsHostnameModal=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 space-y-4">
                <div>
                    <label class="text-xs font-medium text-gray-600">Hostname *</label>
                    <input x-model="vpsHostnameForm.hostname" type="text" required
                        class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono"
                        placeholder="servidor.ejemplo.com" />
                </div>
                <div class="flex gap-3 justify-end">
                    <button @click="vpsHostnameModal=false" class="px-4 py-2 rounded border text-sm text-gray-600 hover:bg-gray-50">Cancelar</button>
                    <button @click="setHostname()" :disabled="loading || !vpsHostnameForm.hostname"
                        class="px-4 py-2 rounded text-sm bg-[#8eb02f] text-white hover:bg-[#6d8c24] disabled:opacity-40 transition">
                        Guardar
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- ─── Modal: VPS Métricas ─── -->
    <div x-show="metricsModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4"
        @click.self="metricsModal=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" x-text="'Métricas: ' + (metricsVPS?.hostname || '')"></h3>
                <button @click="metricsModal=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">
                <div x-show="metricsLoading" class="text-center text-sm text-gray-400 py-8">Cargando métricas...</div>
                <div x-show="!metricsLoading && metricsData" class="space-y-4">
                    <!-- CPU -->
                    <div>
                        <div class="flex justify-between text-xs mb-1">
                            <span class="font-medium text-gray-700">CPU</span>
                            <span class="text-gray-500" x-text="avgMetricVal(metricsData?.cpu_usage?.usage).toFixed(1) + '%'"></span>
                        </div>
                        <div class="w-full bg-gray-100 rounded-full h-2">
                            <div class="h-2 rounded-full transition-all duration-500"
                                :class="avgMetricVal(metricsData?.cpu_usage?.usage) > 80 ? 'bg-red-500' : avgMetricVal(metricsData?.cpu_usage?.usage) > 50 ? 'bg-yellow-500' : 'bg-green-500'"
                                :style="'width:' + Math.min(avgMetricVal(metricsData?.cpu_usage?.usage), 100) + '%'">
                            </div>
                        </div>
                    </div>
                    <!-- RAM -->
                    <div>
                        <div class="flex justify-between text-xs mb-1">
                            <span class="font-medium text-gray-700">RAM</span>
                            <span class="text-gray-500" x-text="formatBytesRaw(latestMetricVal(metricsData?.ram_usage?.usage)) + ' / ' + formatBytes(metricsVPS?.memory)"></span>
                        </div>
                        <div class="w-full bg-gray-100 rounded-full h-2">
                            <div class="h-2 rounded-full bg-blue-500 transition-all duration-500"
                                :style="'width:' + Math.min((latestMetricVal(metricsData?.ram_usage?.usage) / ((metricsVPS?.memory || 1) * 1024 * 1024)) * 100, 100) + '%'">
                            </div>
                        </div>
                    </div>
                    <!-- Disco -->
                    <div>
                        <div class="flex justify-between text-xs mb-1">
                            <span class="font-medium text-gray-700">Disco</span>
                            <span class="text-gray-500" x-text="formatBytesRaw(latestMetricVal(metricsData?.disk_space?.usage)) + ' / ' + formatBytes(metricsVPS?.disk)"></span>
                        </div>
                        <div class="w-full bg-gray-100 rounded-full h-2">
                            <div class="h-2 rounded-full bg-purple-500 transition-all duration-500"
                                :style="'width:' + Math.min((latestMetricVal(metricsData?.disk_space?.usage) / ((metricsVPS?.disk || 1) * 1024 * 1024)) * 100, 100) + '%'">
                            </div>
                        </div>
                    </div>
                    <!-- Red -->
                    <div class="grid grid-cols-2 gap-3">
                        <div class="bg-gray-50 rounded-lg p-2.5 text-xs">
                            <div class="font-medium text-gray-700 mb-0.5">↓ Entrante</div>
                            <div class="text-gray-500" x-text="formatBytesRaw(sumMetricVal(metricsData?.incoming_traffic?.usage))"></div>
                        </div>
                        <div class="bg-gray-50 rounded-lg p-2.5 text-xs">
                            <div class="font-medium text-gray-700 mb-0.5">↑ Saliente</div>
                            <div class="text-gray-500" x-text="formatBytesRaw(sumMetricVal(metricsData?.outgoing_traffic?.usage))"></div>
                        </div>
                    </div>
                    <!-- Uptime -->
                    <div class="flex justify-between text-xs">
                        <span class="font-medium text-gray-700">Uptime</span>
                        <span class="text-gray-500" x-text="formatUptime(latestMetricVal(metricsData?.uptime?.usage))"></span>
                    </div>
                    <div class="text-xs text-gray-400 text-center pt-1">Promedio últimas 24 horas</div>
                </div>
            </div>
        </div>
    </div>

    <!-- ─── Modal: Nameservers ─── -->
    <div x-show="nsModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4"
        @click.self="nsModal=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">Editar Nameservers — <span class="font-mono text-[#6d8c24]" x-text="nsForm.domain"></span></h3>
                <button @click="nsModal=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 space-y-3">
                <div>
                    <label class="text-xs font-medium text-gray-600 uppercase">NS1</label>
                    <input x-model="nsForm.ns1" type="text" class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono" placeholder="ns1.hostinger.com" />
                </div>
                <div>
                    <label class="text-xs font-medium text-gray-600 uppercase">NS2</label>
                    <input x-model="nsForm.ns2" type="text" class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono" placeholder="ns2.hostinger.com" />
                </div>
                <div>
                    <label class="text-xs font-medium text-gray-600 uppercase">NS3</label>
                    <input x-model="nsForm.ns3" type="text" class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono" placeholder="ns3.hostinger.com" />
                </div>
                <div>
                    <label class="text-xs font-medium text-gray-600 uppercase">NS4</label>
                    <input x-model="nsForm.ns4" type="text" class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono" placeholder="ns4.hostinger.com" />
                </div>
                <div class="flex gap-3 justify-end pt-2">
                    <button @click="nsModal=false" class="px-4 py-2 rounded border text-sm text-gray-600 hover:bg-gray-50">Cancelar</button>
                    <button @click="updateNameservers()" :disabled="loading"
                        class="px-4 py-2 rounded text-sm bg-[#8eb02f] text-white hover:bg-[#6d8c24] disabled:opacity-40 transition">
                        Guardar
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- ─── Modal: DNS Records ─── -->
    <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-2xl max-h-[80vh] flex flex-col">
            <div class="flex items-center justify-between px-5 py-4 border-b">
                <h3 class="font-semibold text-sm">DNS Records — <span class="font-mono text-[#6d8c24]" x-text="dnsDomain"></span></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>
            <div class="overflow-y-auto p-5">
                <!-- Nameservers -->
                <div x-show="dnsNameServers" class="mb-4 p-3 bg-gray-50 rounded-lg border">
                    <p class="text-xs font-semibold text-gray-500 mb-2">Nameservers</p>
                    <div class="flex flex-wrap gap-2">
                        <template x-for="(ns, i) in [dnsNameServers?.ns1, dnsNameServers?.ns2, dnsNameServers?.ns3, dnsNameServers?.ns4].filter(Boolean)" :key="i">
                            <span class="px-2 py-1 bg-white border rounded text-xs font-mono text-gray-700" x-text="ns"></span>
                        </template>
                    </div>
                </div>
                <div x-show="dnsRecords.length === 0" class="text-sm text-gray-400 text-center py-8">Sin registros DNS encontrados.</div>
                <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-1 px-2">Tipo</th>
                            <th class="py-1 px-2">Nombre</th>
                            <th class="py-1 px-2">Contenido</th>
                            <th class="py-1 px-2">TTL</th>
                        </tr>
                    </thead>
                    <tbody>
                        <template x-for="(r, rIdx) in dnsRecords" :key="rIdx">
                            <tr class="border-b hover:bg-gray-50">
                                <td class="py-1.5 px-2"><span class="px-1.5 py-0.5 bg-blue-100 text-blue-700 rounded text-xs font-mono" x-text="r.type"></span></td>
                                <td class="py-1.5 px-2 font-mono" x-text="r.name"></td>
                                <td class="py-1.5 px-2 font-mono truncate max-w-xs" x-text="r.content"></td>
                                <td class="py-1.5 px-2" x-text="r.ttl"></td>
                            </tr>
                        </template>
                    </tbody>
                </table>

                <!-- Agregar registro DNS -->
                <div class="mt-5 border-t pt-4">
                    <p class="text-xs font-semibold text-gray-500 mb-2">Agregar registro</p>
                    <div class="grid grid-cols-2 gap-2 mb-2">
                        <div>
                            <label class="text-xs text-gray-500">Tipo</label>
                            <select x-model="dnsAddForm.type" class="w-full border rounded px-2 py-1 text-xs">
                                <option>A</option><option>AAAA</option><option>CNAME</option>
                                <option>MX</option><option>TXT</option><option>NS</option>
                                <option>SRV</option><option>CAA</option>
                            </select>
                        </div>
                        <div>
                            <label class="text-xs text-gray-500">TTL</label>
                            <input x-model.number="dnsAddForm.ttl" type="number" class="w-full border rounded px-2 py-1 text-xs" placeholder="14400" />
                        </div>
                        <div>
                            <label class="text-xs text-gray-500">Nombre</label>
                            <input x-model="dnsAddForm.name" type="text" class="w-full border rounded px-2 py-1 text-xs font-mono" placeholder="@ o subdominio" />
                        </div>
                        <div>
                            <label class="text-xs text-gray-500">Contenido</label>
                            <input x-model="dnsAddForm.content" type="text" class="w-full border rounded px-2 py-1 text-xs font-mono" placeholder="IP, hostname..." />
                        </div>
                    </div>
                    <div class="flex gap-2">
                        <button @click="addDNSRecord()" :disabled="loading || !dnsAddForm.content"
                            class="flex-1 py-1.5 rounded text-xs bg-[#8eb02f] text-white hover:bg-[#6d8c24] disabled:opacity-40 transition">
                            + Agregar registro
                        </button>
                        <button @click="resetDNS()" :disabled="loading"
                            class="px-3 py-1.5 rounded text-xs bg-red-100 text-red-600 hover:bg-red-200 disabled:opacity-40 transition">
                            Reset DNS
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <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 — Hostinger</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">
                <div>
                    <label class="text-xs font-medium text-gray-600">API Token *</label>
                    <input x-model="cfgForm.token" type="password" required
                        placeholder="Pega aquí tu Bearer token de Hostinger"
                        class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono" />
                    <p class="mt-1 text-xs text-gray-400">Genera el token en hpanel.hostinger.com → Cuenta → API</p>
                </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="submit" class="px-5 py-2 text-white text-sm rounded"
                        style="background-color:#8eb02f"
                        :disabled="loading">
                        <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('hostingerApp', () => ({
        loading: false,
        hasConfig: false,
        activeTab: 'vps',
        lastFetch: '',
        vps: [],
        domains: [],
        hosting: [],
        orders: [],
        vpsSearch: '',
        domainsSearch: '',
        hostingSearch: '',
        ordersSearch: '',
        dnsRecords: [],
        dnsDomain: '',
        dnsNameServers: null,
        dnsAddForm: { name: '', type: 'A', content: '', ttl: 14400 },
        dnsModal: false,
        configModal: false,
        cfgForm: { id: 0, token: '', nota: '' },
        // VPS actions
        vpsActionLoading: {},
        vpsPasswordModal: false,
        vpsPasswordForm: { id: 0, password: '' },
        vpsHostnameModal: false,
        vpsHostnameForm: { id: 0, hostname: '' },
        // Nameservers
        nsModal: false,
        nsForm: { domain: '', ns1: '', ns2: '', ns3: '', ns4: '' },
        // Métricas VPS
        metricsModal: false,
        metricsData: null,
        metricsVPS: null,
        metricsLoading: false,
        toast: { show: false, msg: '', type: 'ok' },

        async init() {
            try {
                const res = await axios.get('/app/hostinger/vps');
                this.hasConfig = true;
                this.vps = res.data.data || [];
                this.lastFetch = new Date().toLocaleTimeString();
            } catch (e) {
                if (e.response?.status === 503) this.hasConfig = false;
                else this.hasConfig = true;
            }
        },

        get filteredVPS() {
            if (!this.vpsSearch) return this.vps;
            const q = this.vpsSearch.toLowerCase();
            return this.vps.filter(v =>
                (v.hostname && v.hostname.toLowerCase().includes(q)) ||
                (v.plan && v.plan.toLowerCase().includes(q)) ||
                (v.data_center && v.data_center.toLowerCase().includes(q)) ||
                (v.state && v.state.toLowerCase().includes(q)) ||
                (v.ipv4 && v.ipv4.some(ip => ip.address && ip.address.includes(q)))
            );
        },
        get filteredDomains() {
            if (!this.domainsSearch) return this.domains;
            const q = this.domainsSearch.toLowerCase();
            return this.domains.filter(d =>
                (d.domain && d.domain.toLowerCase().includes(q)) ||
                (d.status && d.status.toLowerCase().includes(q))
            );
        },
        get filteredHosting() {
            if (!this.hostingSearch) return this.hosting;
            const q = this.hostingSearch.toLowerCase();
            return this.hosting.filter(h =>
                (h.domain && h.domain.toLowerCase().includes(q)) ||
                (h.vhost_type && h.vhost_type.toLowerCase().includes(q)) ||
                (h.username && h.username.toLowerCase().includes(q))
            );
        },
        get filteredOrders() {
            if (!this.ordersSearch) return this.orders;
            const q = this.ordersSearch.toLowerCase();
            return this.orders.filter(o =>
                (o.name && o.name.toLowerCase().includes(q)) ||
                (o.status && o.status.toLowerCase().includes(q)) ||
                (o.id && o.id.toLowerCase().includes(q))
            );
        },

        async loadTab() {
            this.loading = true;
            try {
                let res;
                if (this.activeTab === 'vps') {
                    res = await axios.get('/app/hostinger/vps');
                    this.vps = res.data.data || [];
                } else if (this.activeTab === 'domains') {
                    res = await axios.get('/app/hostinger/domains');
                    this.domains = res.data.data || [];
                } else if (this.activeTab === 'hosting') {
                    res = await axios.get('/app/hostinger/hosting');
                    this.hosting = res.data.data || [];
                } else if (this.activeTab === 'orders') {
                    res = await axios.get('/app/hostinger/orders');
                    this.orders = res.data.data || [];
                }
                this.lastFetch = new Date().toLocaleTimeString();
                this.hasConfig = true;
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error al cargar datos', 'error');
            }
            this.loading = false;
        },

        async loadDNSForDomain(domain) {
            this.loading = true;
            this.dnsDomain = domain;
            this.dnsRecords = [];
            this.dnsNameServers = null;
            try {
                const res = await axios.get('/app/hostinger/dns/' + encodeURIComponent(domain));
                this.dnsRecords = res.data.data || [];
                this.dnsNameServers = res.data.name_servers || null;
                this.dnsModal = true;
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error al cargar DNS', 'error');
            }
            this.loading = false;
        },

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

        formatBytes(mb) {
            if (!mb || mb === 0) return '—';
            const gb = mb / 1024;
            if (gb >= 1) return gb.toFixed(1) + ' GB';
            return mb.toFixed(0) + ' MB';
        },

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

        async vpsAction(id, action) {
            this.vpsActionLoading = { ...this.vpsActionLoading, [id]: action };
            try {
                await axios.post(`/app/hostinger/vps/${id}/${action}`);
                this.showToast(`${action.charAt(0).toUpperCase()+action.slice(1)} enviado`);
                setTimeout(() => this.loadTab(), 1500);
            } catch (e) {
                this.showToast(e.response?.data?.error || `Error: ${action}`, 'error');
            }
            const updated = { ...this.vpsActionLoading };
            delete updated[id];
            this.vpsActionLoading = updated;
        },

        async setRootPassword() {
            this.loading = true;
            try {
                await axios.put(`/app/hostinger/vps/${this.vpsPasswordForm.id}/root-password`,
                    { password: this.vpsPasswordForm.password });
                this.showToast('Contraseña cambiada correctamente');
                this.vpsPasswordModal = false;
                this.vpsPasswordForm = { id: 0, password: '' };
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error al cambiar contraseña', 'error');
            }
            this.loading = false;
        },

        async setHostname() {
            this.loading = true;
            try {
                await axios.put(`/app/hostinger/vps/${this.vpsHostnameForm.id}/hostname`,
                    { hostname: this.vpsHostnameForm.hostname });
                this.showToast('Hostname actualizado');
                this.vpsHostnameModal = false;
                this.vpsHostnameForm = { id: 0, hostname: '' };
                await this.loadTab();
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error al cambiar hostname', 'error');
            }
            this.loading = false;
        },

        async openMetrics(v) {
            this.metricsVPS = v;
            this.metricsData = null;
            this.metricsModal = true;
            this.metricsLoading = true;
            try {
                const res = await axios.get(`/app/hostinger/vps/${v.id}/metrics`);
                this.metricsData = res.data;
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error al cargar métricas', 'error');
                this.metricsModal = false;
            }
            this.metricsLoading = false;
        },

        latestMetricVal(usage) {
            if (!usage) return 0;
            const keys = Object.keys(usage).sort();
            if (!keys.length) return 0;
            return usage[keys[keys.length - 1]] || 0;
        },

        avgMetricVal(usage) {
            if (!usage) return 0;
            const vals = Object.values(usage);
            if (!vals.length) return 0;
            return vals.reduce((a, b) => a + b, 0) / vals.length;
        },

        sumMetricVal(usage) {
            if (!usage) return 0;
            return Object.values(usage).reduce((a, b) => a + b, 0);
        },

        formatBytesRaw(bytes) {
            if (!bytes || bytes === 0) return '—';
            const gb = bytes / (1024 ** 3);
            if (gb >= 1) return gb.toFixed(1) + ' GB';
            return (bytes / (1024 ** 2)).toFixed(0) + ' MB';
        },

        formatUptime(ms) {
            if (!ms) return '—';
            const s = Math.floor(ms / 1000);
            const h = Math.floor(s / 3600);
            const m = Math.floor((s % 3600) / 60);
            if (h >= 24) return `${Math.floor(h / 24)}d ${h % 24}h`;
            return `${h}h ${m}m`;
        },

        async updateNameservers() {
            this.loading = true;
            try {
                await axios.put(`/app/hostinger/domains/${encodeURIComponent(this.nsForm.domain)}/nameservers`,
                    { ns1: this.nsForm.ns1, ns2: this.nsForm.ns2, ns3: this.nsForm.ns3, ns4: this.nsForm.ns4 });
                this.showToast('Nameservers actualizados');
                this.nsModal = false;
                await this.loadTab();
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error al actualizar nameservers', 'error');
            }
            this.loading = false;
        },

        async toggleDomainLock(domain, enable) {
            try {
                if (enable) await axios.put(`/app/hostinger/domains/${encodeURIComponent(domain)}/domain-lock`);
                else await axios.delete(`/app/hostinger/domains/${encodeURIComponent(domain)}/domain-lock`);
                this.showToast(enable ? 'Dominio bloqueado' : 'Dominio desbloqueado');
                await this.loadTab();
            } catch (e) { this.showToast(e.response?.data?.error || 'Error', 'error'); }
        },

        async togglePrivacy(domain, enable) {
            try {
                if (enable) await axios.put(`/app/hostinger/domains/${encodeURIComponent(domain)}/privacy`);
                else await axios.delete(`/app/hostinger/domains/${encodeURIComponent(domain)}/privacy`);
                this.showToast(enable ? 'Privacy activada' : 'Privacy desactivada');
                await this.loadTab();
            } catch (e) { this.showToast(e.response?.data?.error || 'Error', 'error'); }
        },

        async toggleAutoRenewal(id, enable) {
            try {
                if (enable) await axios.patch(`/app/hostinger/billing/${id}/auto-renewal/enable`);
                else await axios.delete(`/app/hostinger/billing/${id}/auto-renewal/disable`);
                this.showToast(enable ? 'Autorenovación activada' : 'Autorenovación desactivada');
                await this.loadTab();
            } catch (e) { this.showToast(e.response?.data?.error || 'Error', 'error'); }
        },

        async addDNSRecord() {
            this.loading = true;
            try {
                await axios.put(`/app/hostinger/dns/${encodeURIComponent(this.dnsDomain)}`, {
                    overwrite: false,
                    zone: [{ name: this.dnsAddForm.name, type: this.dnsAddForm.type,
                             ttl: this.dnsAddForm.ttl,
                             records: [{ content: this.dnsAddForm.content }] }]
                });
                this.showToast('Registro DNS agregado');
                this.dnsAddForm = { name: '', type: 'A', content: '', ttl: 14400 };
                await this.loadDNSForDomain(this.dnsDomain);
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error al agregar registro', 'error');
            }
            this.loading = false;
        },

        async resetDNS() {
            if (!confirm(`¿Resetear la zona DNS de ${this.dnsDomain}? Se restaurarán los valores por defecto.`)) return;
            this.loading = true;
            try {
                await axios.post(`/app/hostinger/dns/${encodeURIComponent(this.dnsDomain)}/reset`);
                this.showToast('Zona DNS reseteada');
                await this.loadDNSForDomain(this.dnsDomain);
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error al resetear DNS', 'error');
            }
            this.loading = false;
        }
    }));
});
</script>
