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

    <div class="container mx-auto p-6 w-full">
        <div class="justify-between items-center w-full md:flex">
            <div>
                <h1 class="text-2xl font-bold mb-2">Lista de servidores</h1>
                <p class="mb-4 text-sm">Gestión de servidores.</p>
            </div>

            <div class="mb-4 md:mb-0 relative">
                <input type="text" placeholder="Buscar..." class="border border-gray-300 rounded p-2 w-full"
                    x-model="search" @input.debounce.500ms="loadData()" />
            </div>

            <div class="flex items-center justify-end mb-4 gap-2 md:mb-0">
                <button @click="addModal = true"
                    class="bg-[#8eb02f] text-white px-4 py-2 rounded text-sm">Nuevo</button>
            </div>
        </div>

        <div class="overflow-x-auto">
            <table class="table-auto w-full">
                <thead class="text-sm text-left py-4 border-b border-gray-300">
                    <tr class="text-left font-semibold border-collapse">
                        <th class="py-2 px-3 border-b">Nombre</th>
                        <th class="py-2 px-3 border-b">IP Servidor</th>
                        <th class="py-2 px-3 border-b">SO</th>
                        <th class="py-2 px-3 border-b">Vencimiento</th>
                        <th class="py-2 px-3 border-b">Ram</th>
                        <th class="py-2 px-3 border-b">Nucleo</th>
                        <th class="py-2 px-3 border-b">Disco</th>
                        <th class="py-2 px-3 border-b">Ultimo ping</th>
                        <th class="py-2 px-3 border-b">Proveedor</th>
                        <th class="py-2 px-3 border-b">Tipo servidor</th>
                        <th class="py-2 px-3 border-b"></th>
                    </tr>
                </thead>
                <tbody class="text-gray-500 select-none text-sm">
                    <template x-for="data in datos" :key="data.id">
                        <tr class="hover:bg-gray-100">

                            <td class="py-3 text-xs px-3 border-b" x-text="data.nombre"></td>
                            <td class="py-3 text-xs px-3 border-b" x-text="data.ip_servidor"></td>
                            <td class="py-3 text-xs px-3 border-b" x-text="data.so"></td>
                            <td class="py-3 text-xs px-3 border-b" x-text="data.vencimiento"></td>
                            <td class="py-3 text-xs px-3 border-b" x-text="data.ram"></td>
                            <td class="py-3 text-xs px-3 border-b" x-text="data.nucleos"></td>
                            <td class="py-3 text-xs px-3 border-b" x-text="data.disco"></td>
                            <td class="py-3 text-xs px-3 border-b" x-text="data.ultimo_ping"></td>
                            <td class="py-3 text-xs px-3 border-b"
                                x-text="proveedores.find(prov => prov.ID == data.prov_servidor_id).nombre"></td>
                            <td class="py-3 text-xs px-3 border-b"
                                x-text="tipos.find(ts => ts.ID == data.tipo_servidor_id).nombre"></td>
                            <td class="py-3 text-xs px-3 border-b w-24">
                                <div class="flex items-center gap-2">
                                    <button @click="openViewModal(data)" title="Ver">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                                            stroke-width="1.5" stroke="currentColor" class="w-5 text-[#8eb02f]">
                                            <path stroke-linecap="round" stroke-linejoin="round"
                                                d="M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z" />
                                            <path stroke-linecap="round" stroke-linejoin="round"
                                                d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
                                        </svg>
                                    </button>
                                    <button @click="openEditModal(data)" title="Editar">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                                            stroke-width="1.5" stroke="currentColor" class="w-5">
                                            <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.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10" />
                                        </svg>
                                    </button>
                                    <button @click="openDeleteModal(data)" title="Eliminar">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                                            stroke-width="1.5" stroke="currentColor" class="w-5 text-red-500">
                                            <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>
                                    <button x-show="data.hostinger_vps_id" @click="syncHostinger(data.id)"
                                        :disabled="syncCargando[data.id]" title="Sincronizar desde Hostinger"
                                        class="text-orange-500 hover:text-orange-700 disabled:opacity-40">
                                        <svg :class="syncCargando[data.id] ? 'animate-spin' : ''" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
                                        </svg>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>

        <div class="flex justify-start items-center gap-2 p-4 text-sm">
            <button @click="page = Math.max(1, page - 1); loadData()" :disabled="page === 1"
                class="px-4 py-2 text-black bg-gray-200 rounded-l-md opacity-50 disabled:cursor-not-allowed">
                Anterior
            </button>
            <template x-for="pageNum in paginatedPages" :key="pageNum">
                <button @click="goToPage(pageNum)"
                    class="px-4 py-2 text-black bg-gray-200 bg-black text-gray-50 rounded-md hover:bg-gray-300"
                    :class="{ 'bg-black text-white': pageNum === page }" x-text="pageNum"></button>
            </template>
            <button @click="page += 1; loadData()" :disabled="datos.length < limit" :disabled="page === totalPages"
                class="px-4 py-2 text-black bg-gray-200 rounded-r-md opacity-50 disabled:cursor-not-allowed">
                Siguiente
            </button>
        </div>
    </div>

    <!-- Modales -->
    <div x-show="viewModal"
        class="fixed inset-0 overflow-auto bg-gray-800 bg-opacity-75 flex justify-center items-center text-sm z-40">
        <div class="bg-white rounded-lg shadow-lg p-6 w-11/12 max-w-lg">
            <h2 class="text-xl font-bold mb-4">Ver servidor</h2>

            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Nombre:</label>
                    <input type="text" x-model="selectedItem.nombre" disabled
                        class="border border-gray-300 rounded p-2 w-full" placeholder="Nombre" />
                </div>
                <div class="w-full">
                    <label class="block mb-2">IP Servidor:</label>
                    <input type="text" x-model="selectedItem.ip_servidor" disabled
                        class="border border-gray-300 rounded p-2 w-full" placeholder="IP Servidor" />
                </div>
            </div>
            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Sistema Operativo:</label>
                    <input type="text" x-model="selectedItem.so" disabled
                        class="border border-gray-300 rounded p-2 w-full" placeholder="Sistema Operativo" />
                </div>
                <div class="w-full">
                    <label class="block mb-2">Vencimiento:</label>
                    <input type="date" x-model="selectedItem.vencimiento" disabled
                        class="border border-gray-300 rounded p-2 w-full" placeholder="Vencimiento" />
                </div>
            </div>
            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">RAM:</label>
                    <input type="text" x-model="selectedItem.ram" disabled
                        class="border border-gray-300 rounded p-2 w-full" placeholder="Ingresa la ram" />
                </div>
                <div class="w-full">
                    <label class="block mb-2">Nucleos:</label>
                    <input type="text" x-model="selectedItem.nucleos" disabled
                        class="border border-gray-300 rounded p-2 w-full" placeholder="Ingresa los nucleos" />
                </div>
            </div>
            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Disco:</label>
                    <input type="text" x-model="selectedItem.disco" disabled
                        class="border border-gray-300 rounded p-2 w-full" placeholder="Ingresa el disco" />
                </div>
                <div class="w-full">
                    <label class="block mb-2">Ultimo ping:</label>
                    <input type="text" x-model="selectedItem.ultimo_ping" disabled
                        class="border border-gray-300 rounded p-2 w-full" placeholder="Ingresa el ultimo ping" />
                </div>
            </div>
            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Proveedor:</label>
                    <select x-model="selectedItem.prov_servidor_id" disabled
                        class="border border-gray-300 rounded p-2 w-full">
                        <option value="">Selecciona un proveedor</option>
                        <template x-for="provedor in proveedores" :key="provedor.ID">
                            <option :value="provedor.ID" x-text="provedor.nombre"></option>
                        </template>
                    </select>
                </div>
                <div class="w-full">
                    <label class="block mb-2">Tipo de Servidor:</label>
                    <select x-model="selectedItem.tipo_servidor_id" disabled
                        class="border border-gray-300 rounded p-2 w-full">
                        <option value="">Selecciona un tipo de servidor</option>
                        <template x-for="tipo in tipos" :key="tipo.ID">
                            <option :value="tipo.ID" x-text="tipo.nombre"></option>
                        </template>
                    </select>
                </div>
            </div>

            <div class="flex justify-end gap-2 text-sm">
                <button @click="viewModal = false" class="px-4 py-2 bg-gray-600 text-white rounded">Cerrar</button>
            </div>
        </div>
    </div>

    <div x-show="editModal"
        class="fixed inset-0 overflow-auto bg-gray-800 bg-opacity-75 flex justify-center items-center text-sm z-40">
        <div class="bg-white rounded-lg shadow-lg p-6 w-11/12 max-w-lg">
            <h2 class="text-xl font-bold mb-4">Editar servidor</h2>

            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Nombre:</label>
                    <input type="text" x-model="selectedItem.nombre" class="border border-gray-300 rounded p-2 w-full"
                        placeholder="Nombre" />
                </div>
                <div class="w-full">
                    <label class="block mb-2">IP Servidor:</label>
                    <input type="text" x-model="selectedItem.ip_servidor"
                        class="border border-gray-300 rounded p-2 w-full" placeholder="IP Servidor" />
                </div>
            </div>
            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Sistema Operativo:</label>
                    <input type="text" x-model="selectedItem.so" class="border border-gray-300 rounded p-2 w-full"
                        placeholder="Sistema Operativo" />
                </div>
                <div class="w-full">
                    <label class="block mb-2">Vencimiento:</label>
                    <input type="date" x-model="selectedItem.vencimiento"
                        class="border border-gray-300 rounded p-2 w-full" placeholder="Vencimiento" />
                </div>
            </div>
            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">RAM:</label>
                    <input type="text" x-model="selectedItem.ram" class="border border-gray-300 rounded p-2 w-full"
                        placeholder="Ingresa la ram" />
                </div>
                <div class="w-full">
                    <label class="block mb-2">Nucleos:</label>
                    <input type="text" x-model="selectedItem.nucleos" class="border border-gray-300 rounded p-2 w-full"
                        placeholder="Ingresa los nucleos" />
                </div>
            </div>
            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Disco:</label>
                    <input type="text" x-model="selectedItem.disco" class="border border-gray-300 rounded p-2 w-full"
                        placeholder="Ingresa el disco" />
                    <p x-show="errors.disco" x-text="errors.disco" class="text-red-500 text-sm"></p>
                </div>
                <div class="w-full">
                    <label class="block mb-2">Ultimo ping:</label>
                    <input type="text" x-model="selectedItem.ultimo_ping"
                        class="border border-gray-300 rounded p-2 w-full" placeholder="Ingresa el ultimo ping" />
                </div>
            </div>
            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Proveedor:</label>
                    <select x-model="selectedItem.prov_servidor_id" class="border border-gray-300 rounded p-2 w-full">
                        <option value="">Selecciona un proveedor</option>
                        <template x-for="provedor in proveedores" :key="provedor.ID">
                            <option :value="provedor.ID" x-text="provedor.nombre"></option>
                        </template>
                    </select>
                </div>
                <div class="w-full">
                    <label class="block mb-2">Tipo de Servidor:</label>
                    <select x-model="selectedItem.tipo_servidor_id" class="border border-gray-300 rounded p-2 w-full">
                        <option value="">Selecciona un tipo de servidor</option>
                        <template x-for="tipo in tipos" :key="tipo.ID">
                            <option :value="tipo.ID" x-text="tipo.nombre"></option>
                        </template>
                    </select>
                </div>
            </div>

            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Hostinger VPS ID <span class="text-xs text-gray-400">(opcional)</span>:</label>
                    <input type="number" x-model="selectedItem.hostinger_vps_id"
                        class="border border-gray-300 rounded p-2 w-full" placeholder="ID del VPS en Hostinger" />
                </div>
                <div class="w-full">
                    <label class="block mb-2">Hostinger Subscription ID <span class="text-xs text-gray-400">(billing)</span>:</label>
                    <input type="text" x-model="selectedItem.hostinger_subscription_id"
                        class="border border-gray-300 rounded p-2 w-full font-mono text-xs" placeholder="Auto-detectado al sincronizar" />
                </div>
            </div>

            <div class="w-full mb-4" x-show="selectedItem.id && selectedItem.hostinger_vps_id">
                <button @click="syncHostinger(selectedItem.id)" :disabled="syncCargando[selectedItem.id]"
                    class="w-full px-4 py-2 bg-orange-500 text-white rounded text-sm flex items-center justify-center gap-2 hover:bg-orange-600 disabled:opacity-50">
                    <svg :class="syncCargando[selectedItem.id] ? 'animate-spin' : ''" class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
                    <span x-text="syncCargando[selectedItem.id] ? 'Sincronizando...' : 'Sync desde Hostinger (IP, RAM, CPU, Disco, Vencimiento)'"></span>
                </button>
            </div>

            <div class="flex justify-between gap-2 text-sm">
                <button @click="updateItem()" class="px-4 py-2 bg-[#8eb02f] text-white rounded">Actualizar</button>
                <button @click="closeModals()" class="px-4 py-2 bg-gray-600 text-white rounded">Cerrar</button>
            </div>
        </div>
    </div>

    <div x-show="addModal"
        class="fixed inset-0 overflow-auto bg-gray-800 bg-opacity-75 flex justify-center items-center text-sm z-40">
        <div class="bg-white rounded-lg shadow-lg p-6 w-11/12 max-w-lg">
            <h2 class="text-xl font-bold mb-4">Añadir servidor</h2>

            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Nombre:</label>
                    <input type="text" x-model="selectedItem.nombre" class="border border-gray-300 rounded p-2 w-full"
                        placeholder="Nombre" />
                </div>
                <div class="w-full">
                    <label class="block mb-2">IP Servidor:</label>
                    <input type="text" x-model="selectedItem.ip_servidor"
                        class="border border-gray-300 rounded p-2 w-full" placeholder="IP Servidor" />
                </div>
            </div>
            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Sistema Operativo:</label>
                    <input type="text" x-model="selectedItem.so" class="border border-gray-300 rounded p-2 w-full"
                        placeholder="Sistema Operativo" />
                </div>
                <div class="w-full">
                    <label class="block mb-2">Vencimiento:</label>
                    <input type="date" x-model="selectedItem.vencimiento"
                        class="border border-gray-300 rounded p-2 w-full" placeholder="Vencimiento" />
                </div>
            </div>
            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">RAM:</label>
                    <input type="text" x-model="selectedItem.ram" class="border border-gray-300 rounded p-2 w-full"
                        placeholder="Ingresa la ram" />
                </div>
                <div class="w-full">
                    <label class="block mb-2">Nucleos:</label>
                    <input type="text" x-model="selectedItem.nucleos" class="border border-gray-300 rounded p-2 w-full"
                        placeholder="Ingresa los nucleos" />
                </div>
            </div>
            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Disco:</label>
                    <input type="text" x-model="selectedItem.disco" class="border border-gray-300 rounded p-2 w-full"
                        placeholder="Ingresa el disco" />
                    <p x-show="errors.disco" x-text="errors.disco" class="text-red-500 text-sm"></p>
                </div>
                <div class="w-full">
                    <label class="block mb-2">Ultimo ping:</label>
                    <input type="text" x-model="selectedItem.ultimo_ping"
                        class="border border-gray-300 rounded p-2 w-full" placeholder="Ingresa el ultimo ping" />
                </div>
            </div>
            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Proveedor:</label>
                    <select x-model="selectedItem.prov_servidor_id" class="border border-gray-300 rounded p-2 w-full">
                        <option value="">Selecciona un proveedor</option>
                        <template x-for="provedor in proveedores" :key="provedor.ID">
                            <option :value="provedor.ID" x-text="provedor.nombre"></option>
                        </template>
                    </select>
                </div>
                <div class="w-full">
                    <label class="block mb-2">Tipo de Servidor:</label>
                    <select x-model="selectedItem.tipo_servidor_id" class="border border-gray-300 rounded p-2 w-full">
                        <option value="">Selecciona un tipo de servidor</option>
                        <template x-for="tipo in tipos" :key="tipo.ID">
                            <option :value="tipo.ID" x-text="tipo.nombre"></option>
                        </template>
                    </select>
                </div>
            </div>

            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Hostinger VPS ID <span class="text-xs text-gray-400">(opcional)</span>:</label>
                    <input type="number" x-model="selectedItem.hostinger_vps_id"
                        class="border border-gray-300 rounded p-2 w-full" placeholder="ID del VPS en Hostinger" />
                </div>
            </div>

            <div class="flex justify-between gap-2 text-sm">
                <button @click="addItem()" class="px-4 py-2 bg-[#8eb02f] text-white rounded">Guardar</button>
                <button @click="addModal = false" class="px-4 py-2 bg-gray-600 text-white rounded">Cancelar</button>
            </div>
        </div>
    </div>

    <div x-show="deleteModal"
        class="fixed inset-0 overflow-auto bg-gray-800 bg-opacity-75 flex justify-center items-center z-40">
        <div class="bg-white rounded-lg shadow-lg p-6 w-11/12 max-w-lg text-sm">
            <h2 class="text-xl font-bold mb-4">Confirmar Eliminación</h2>

            <p>¿Estás seguro de que deseas eliminar este registro?</p>


            <div class="flex mt-4 justify-end gap-2 text-sm">
                <button @click="deleteItem()" class="px-4 py-2 bg-red-500 text-white rounded">Eliminar</button>
                <button @click="closeModals()" class="bg-gray-600 text-white px-4 py-2 rounded">Cancelar</button>
            </div>
        </div>
    </div>
</div>

<script>
    function app() {
        return {
            datos: [],
            proveedores: [],
            tipos: [],
            loading: false,
            limit: 10,
            page: 1,
            search: '',
            totalPages: 0,
            paginatedPages: [],
            // modales 
            viewModal: false,
            addModal: false,
            editModal: false,
            deleteModal: false,
            selectedItem: {},
            errors: {},
            syncCargando: {},
            init() {
                this.loadData();
                this.loadProvServidor();
                this.loadTipoServidor();
            },
            loadData() {
                if (this.search !== '') {
                    this.page = 1;
                    this.limit = 100;
                } else {
                    this.limit = 10;
                }
                this.setLoading(true);
                console.log('🔄 Cargando servidores desde:', '/app/loadservidor', {page: this.page, limit: this.limit, search: this.search});
                axios.get('/app/loadservidor', {
                    params: {
                        page: this.page,
                        limit: this.limit,
                        search: this.search
                    }
                }).then(response => {
                    console.log('✅ Respuesta recibida:', response.data);
                    if (response.data.registros && response.data.registros.length > 0) {
                        this.datos = response.data.registros.map(data => ({
                            id: data.ID,
                            nombre: data.nombre,
                            ip_servidor: data.ip_servidor,
                            so: data.so,
                            vencimiento: data.vencimiento,
                            ram: data.ram,
                            nucleos: data.nucleos,
                            disco: data.disco,
                            ultimo_ping: data.ultimo_ping,
                            prov_servidor_id: data.prov_servidor_id,
                            tipo_servidor_id: data.tipo_servidor_id,
                            hostinger_vps_id: data.hostinger_vps_id,
                            hostinger_state: data.hostinger_state,
                            hostinger_subscription_id: data.hostinger_subscription_id,
                            created_at: data.CreatedAt,
                        }));
                        console.log('📊 Servidores procesados:', this.datos.length);
                    } else {
                        console.warn('⚠️ No se encontraron servidores');
                        this.datos = [];
                    }

                    this.totalPages = response.data.totalPages;
                    this.calculatePaginatedPages();
                }).catch(error => {
                    console.error('❌ Error al obtener datos:', error);
                    alert('Error cargando servidores: ' + (error.response?.data?.message || error.message));
                }).finally(() => {
                    this.setLoading(false);
                });
            },
            loadProvServidor() {
                axios.get('/app/loadprovservidor')
                    .then(response => {
                        console.log('✅ Proveedores cargados:', response.data.registros?.length || 0);
                        this.proveedores = response.data.registros;
                    })
                    .catch(error => {
                        console.error('❌ Error al cargar proveedores:', error);
                    });
            },
            loadTipoServidor() {
                axios.get('/app/loadtiposervidor')
                    .then(response => {
                        console.log('✅ Tipos de servidor cargados:', response.data.registros?.length || 0);
                        this.tipos = response.data.registros;
                    })
                    .catch(error => {
                        console.error('❌ Error al cargar tipos de servidor:', error);
                    });
            },
            setSelectedItem(data) {
                this.selectedItem = { ...data };
                this.errors = {};
            },
            resetSelectedItem() {
                this.selectedItem = {};
                this.errors = {};
            },
            calculatePaginatedPages() {
                const maxVisiblePages = 5;
                const startPage = Math.max(1, this.page - Math.floor(maxVisiblePages / 2));
                const endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);
                this.paginatedPages = Array.from({ length: endPage - startPage + 1 }, (_, i) => i + startPage);
            },
            goToPage(page) {
                this.page = page;
                this.loadData();
            },
            setLoading(value) {
                this.loading = value;
            },
            // validateFields(fields) {
            //     this.errors = {};
            //     fields.forEach(field => {
            //         if (!this.selectedItem[field]) {
            //             this.errors[field] = 'Este campo es obligatorio';
            //         }
            //     });
            //     return Object.keys(this.errors).length === 0;
            // },

            openViewModal(data) {
                this.setSelectedItem(data);
                this.viewModal = true;
            },
            openEditModal(data) {
                this.setSelectedItem(data);
                this.editModal = true;
            },

            deleteItem() {
                this.setLoading(true);
                axios.delete(`/app/servidor/${this.selectedItem.id}`)
                    .then(() => {
                        alert("Registro eliminado exitosamente.");
                        this.resetSelectedItem();
                        this.deleteModal = false;
                        this.loadData();
                    })
                    .catch(error => console.error("Error al eliminar el registro:", error))
                    .finally(() => this.setLoading(false));
            },
            openDeleteModal(data) {
                this.selectedItem.id = data.id;

                this.deleteModal = true;
            },
            closeModals() {
                this.viewModal = false;
                this.addModal = false;
                this.editModal = false;
                this.deleteModal = false;

                this.resetSelectedItem();
            },
            addItem() {
                if (this.selectedItem.prov_servidor_id) {
                    this.selectedItem.prov_servidor_id = parseInt(this.selectedItem.prov_servidor_id);
                } else {
                    this.selectedItem.prov_servidor_id = null;
                }
                if (this.selectedItem.tipo_servidor_id) {
                    this.selectedItem.tipo_servidor_id = parseInt(this.selectedItem.tipo_servidor_id);
                } else {
                    this.selectedItem.tipo_servidor_id = null;
                }

                this.setLoading(true);

                axios.post('/app/servidor', this.selectedItem)
                    .then(response => {
                        alert("Servidor añadido exitosamente.");
                        this.resetSelectedItem();
                        this.addModal = false;
                        this.loadData();
                    })
                    .catch(error => {
                        console.error("Error al añadir el servidor:", error);
                    })
                    .finally(() => {
                        this.setLoading(false);
                    });
            },

            async syncHostinger(id) {
                if (!id || this.syncCargando[id]) return;
                this.syncCargando[id] = true;
                try {
                    const r = await axios.post(`/app/servidor/${id}/sync-hostinger`);
                    if (r.data?.ok) {
                        await this.loadData();
                        alert('Sincronizado desde Hostinger correctamente.');
                    }
                } catch (e) {
                    alert('Error al sincronizar: ' + (e.response?.data?.error || e.message));
                } finally {
                    this.syncCargando[id] = false;
                }
            },

            updateItem() {
                if (this.selectedItem.prov_servidor_id) {
                    this.selectedItem.prov_servidor_id = parseInt(this.selectedItem.prov_servidor_id);
                } else {
                    this.selectedItem.prov_servidor_id = null;
                }
                if (this.selectedItem.tipo_servidor_id) {
                    this.selectedItem.tipo_servidor_id = parseInt(this.selectedItem.tipo_servidor_id);
                } else {
                    this.selectedItem.tipo_servidor_id = null;
                }

                const dataToSend = {
                    nombre: this.selectedItem.nombre,
                    ip_servidor: this.selectedItem.ip_servidor,
                    so: this.selectedItem.so,
                    vencimiento: this.selectedItem.vencimiento,
                    ram: this.selectedItem.ram,
                    nucleos: this.selectedItem.nucleos,
                    disco: this.selectedItem.disco,
                    ultimo_ping: this.selectedItem.ultimo_ping,
                    prov_servidor_id: this.selectedItem.prov_servidor_id,
                    tipo_servidor_id: this.selectedItem.tipo_servidor_id,
                    hostinger_vps_id: this.selectedItem.hostinger_vps_id ? parseInt(this.selectedItem.hostinger_vps_id) : null,
                    hostinger_subscription_id: this.selectedItem.hostinger_subscription_id || '',
                };

                this.setLoading(true);

                axios.put(`/app/servidor/${this.selectedItem.id}`, dataToSend)
                    .then(response => {
                        alert("Servidor actualizado exitosamente.");
                        this.resetSelectedItem();
                        this.editModal = false;
                        this.loadData();
                    })
                    .catch(error => {
                        console.error("Error al actualizar el servidor:", error);
                    })
                    .finally(() => {
                        this.setLoading(false);
                    });
            }
        }
    }
</script>