<div x-data="pasarelasApp()" 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>

    <!-- Toast de notificación -->
    <div x-show="toast.show" x-transition
        :class="toast.type === 'error' ? 'bg-red-600' : 'bg-green-600'"
        class="fixed bottom-5 right-5 z-50 text-white text-sm px-5 py-3 rounded-xl shadow-lg flex items-center gap-2">
        <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="M5 13l4 4L19 7"/>
        </svg>
        <span x-text="toast.msg"></span>
    </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">Pasarelas de Pago</h1>
                <p class="text-xs text-slate-500 mt-0.5">Configura las credenciales de cada pasarela y selecciona el entorno activo.</p>
            </div>
            <!-- Indicador de modo activo por pasarela -->
            <div class="flex gap-2 flex-wrap">
                <span class="px-3 py-1 rounded-full text-xs font-semibold flex items-center gap-1"
                    :class="boldModo === 'production' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'">
                    <span class="w-2 h-2 rounded-full inline-block"
                        :class="boldModo === 'production' ? 'bg-green-500' : 'bg-yellow-500'"></span>
                    Bold — <span x-text="boldModo === 'production' ? 'Producción' : 'Test'"></span>
                </span>
                <span class="px-3 py-1 rounded-full text-xs font-semibold flex items-center gap-1"
                    :class="dlocalModo === 'prod' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'">
                    <span class="w-2 h-2 rounded-full inline-block"
                        :class="dlocalModo === 'prod' ? 'bg-green-500' : 'bg-yellow-500'"></span>
                    dLocal — <span x-text="dlocalModo === 'prod' ? 'Producción' : 'Desarrollo'"></span>
                </span>
                <span class="px-3 py-1 rounded-full text-xs font-semibold flex items-center gap-1"
                    :class="paypalModo === 'live' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'">
                    <span class="w-2 h-2 rounded-full inline-block"
                        :class="paypalModo === 'live' ? 'bg-green-500' : 'bg-yellow-500'"></span>
                    PayPal — <span x-text="paypalModo === 'live' ? 'Producción' : 'Sandbox'"></span>
                </span>
            </div>
        </div>

        <!-- Tabs -->
        <div class="border-b border-gray-200 mb-6">
            <nav class="-mb-px flex gap-6 text-sm">
                <button @click="activeTab = 'bold'"
                    :class="activeTab === 'bold' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-500 hover:text-gray-700'"
                    class="pb-2 transition-colors flex items-center gap-2">
                    <!-- Bold icon -->
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M6 3h7a5 5 0 0 1 5 5 5 5 0 0 1-2.5 4.33A5.5 5.5 0 0 1 13 22H6V3zm3 3v4h4a2 2 0 0 0 0-4H9zm0 7v4h4.5a2.5 2.5 0 0 0 0-5H9z"/>
                    </svg>
                    Bold
                </button>
                <button @click="activeTab = 'dlocal'"
                    :class="activeTab === 'dlocal' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-500 hover:text-gray-700'"
                    class="pb-2 transition-colors flex items-center gap-2">
                    <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="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"/>
                    </svg>
                    dLocal
                </button>
                <button @click="activeTab = 'paypal'"
                    :class="activeTab === 'paypal' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-500 hover:text-gray-700'"
                    class="pb-2 transition-colors flex items-center gap-2">
                    <!-- PayPal icon -->
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M7.076 21.337H2.47a.641.641 0 0 1-.633-.74L4.944.901C5.026.382 5.474 0 5.998 0h7.46c2.57 0 4.578.543 5.69 1.81 1.01 1.15 1.304 2.42 1.012 4.287-.023.143-.047.288-.077.437-.983 5.05-4.349 6.797-8.647 6.797h-2.19c-.524 0-.968.382-1.05.9l-1.12 7.106zm14.146-14.42a3.35 3.35 0 0 0-.607-.541c-.013.076-.026.175-.041.254-.93 4.778-4.005 7.201-9.138 7.201h-2.19a.563.563 0 0 0-.556.479l-1.187 7.527h-.506l-.24 1.516a.56.56 0 0 0 .554.647h3.882c.46 0 .85-.334.922-.788.06-.26.76-4.852.816-5.09a.932.932 0 0 1 .923-.788h.58c3.76 0 6.705-1.528 7.566-5.946.36-1.847.174-3.388-.778-4.471z"/>
                    </svg>
                    PayPal
                </button>
            </nav>
        </div>

        <!-- ═══════════════════════════════════════════════════════════════════ -->
        <!-- TAB: BOLD                                                          -->
        <!-- ═══════════════════════════════════════════════════════════════════ -->
        <div x-show="activeTab === 'bold'" x-transition>

            <!-- Sub-tabs Bold -->
            <div class="border-b border-gray-100 mb-5">
                <nav class="-mb-px flex gap-5 text-xs">
                    <button @click="boldTab = 'config'"
                        :class="boldTab==='config' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-400 hover:text-gray-600'"
                        class="pb-2 transition-colors">Configuración</button>
                    <button @click="boldTab = 'notificaciones'; loadBoldLogs()"
                        :class="boldTab==='notificaciones' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-400 hover:text-gray-600'"
                        class="pb-2 transition-colors flex items-center gap-1">
                        Notificaciones
                        <span x-show="boldLogsTotal > 0"
                            class="bg-[#8eb02f] text-white text-[10px] px-1.5 py-0.5 rounded-full"
                            x-text="boldLogsTotal"></span>
                    </button>
                    <button @click="boldTab = 'intentos'; loadBoldCallbacks()"
                        :class="boldTab==='intentos' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-400 hover:text-gray-600'"
                        class="pb-2 transition-colors flex items-center gap-1">
                        Intentos de pago
                        <span x-show="boldCallbacksTotal > 0"
                            class="bg-orange-400 text-white text-[10px] px-1.5 py-0.5 rounded-full"
                            x-text="boldCallbacksTotal"></span>
                    </button>
                </nav>
            </div>

            <!-- ── Sub-tab: Configuración ─────────────────────────────────── -->
            <div x-show="boldTab === 'config'">
            <div class="grid lg:grid-cols-2 gap-6">

                <!-- Formulario de credenciales Bold -->
                <div class="border border-gray-200 rounded-xl p-5">
                    <h2 class="text-base font-semibold mb-1 flex items-center gap-2">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-[#8eb02f]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"/>
                        </svg>
                        Credenciales Bold
                    </h2>
                    <p class="text-xs text-gray-500 mb-4">Panel Bold → Configuración → Integraciones → API</p>

                    <!-- Selector de entorno -->
                    <div class="mb-5">
                        <label class="block text-xs font-medium text-gray-600 mb-1.5">Entorno activo</label>
                        <div class="flex gap-3">
                            <label class="flex items-center gap-2 cursor-pointer">
                                <input type="radio" x-model="boldModo" value="test" class="accent-[#8eb02f]"/>
                                <span class="text-sm px-2 py-0.5 rounded bg-yellow-50 text-yellow-700 font-medium">Test / Sandbox</span>
                            </label>
                            <label class="flex items-center gap-2 cursor-pointer">
                                <input type="radio" x-model="boldModo" value="production" class="accent-[#8eb02f]"/>
                                <span class="text-sm px-2 py-0.5 rounded bg-green-50 text-green-700 font-medium">Producción</span>
                            </label>
                        </div>
                    </div>

                    <!-- Sección Test -->
                    <div class="mb-5 p-4 rounded-lg bg-yellow-50 border border-yellow-200">
                        <p class="text-xs font-semibold text-yellow-700 mb-3 flex items-center gap-1">
                            <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="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"/>
                            </svg>
                            Entorno de prueba
                        </p>
                        <div class="space-y-3">
                            <div>
                                <label class="block text-xs font-medium text-gray-600 mb-1">API Key (test)</label>
                                <input x-model="bold.api_key_test" type="text" placeholder="pk_test_..." class="ui-input text-xs font-mono" autocomplete="off"/>
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-gray-600 mb-1">
                                    Secret Key (test)
                                    <span class="text-gray-400 font-normal">(puede quedar vacía en sandbox)</span>
                                </label>
                                <input x-model="bold.secret_key_test" type="password" placeholder="Dejar vacío para test" class="ui-input text-xs font-mono" autocomplete="off"/>
                            </div>
                        </div>
                    </div>

                    <!-- Sección Producción -->
                    <div class="mb-5 p-4 rounded-lg bg-green-50 border border-green-200">
                        <p class="text-xs font-semibold text-green-700 mb-3 flex items-center gap-1">
                            <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="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/>
                            </svg>
                            Producción
                        </p>
                        <div class="space-y-3">
                            <div>
                                <label class="block text-xs font-medium text-gray-600 mb-1">API Key (producción)</label>
                                <input x-model="bold.api_key_prod" type="text" placeholder="pk_live_..." class="ui-input text-xs font-mono" autocomplete="off"/>
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-gray-600 mb-1">Secret Key (producción)</label>
                                <input x-model="bold.secret_key_prod" type="password" placeholder="sk_live_..." class="ui-input text-xs font-mono" autocomplete="off"/>
                            </div>
                        </div>
                    </div>

                    <!-- Callback URL -->
                    <div class="mb-5">
                        <label class="block text-xs font-medium text-gray-600 mb-1">
                            Callback URL
                            <span class="text-gray-400 font-normal">(Bold redirige aquí al usuario tras el pago)</span>
                        </label>
                        <input x-model="bold.callback_url" type="url" placeholder="https://tudominio.com/pago-exitoso" class="ui-input text-xs"/>
                    </div>

                    <!-- Nota -->
                    <div class="mb-5">
                        <label class="block text-xs font-medium text-gray-600 mb-1">Nota interna</label>
                        <input x-model="bold.nota" type="text" placeholder="Opcional" class="ui-input text-xs"/>
                    </div>

                    <button @click="saveBold()"
                        class="w-full py-2.5 rounded-xl text-sm font-semibold text-white transition-all"
                        style="background-color:#8eb02f"
                        onmouseover="this.style.backgroundColor='#6d8c24'"
                        onmouseout="this.style.backgroundColor='#8eb02f'">
                        Guardar configuración Bold
                    </button>
                </div>

                <!-- Info / Guía Bold -->
                <div class="space-y-4">

                    <!-- Estado actual -->
                    <div class="border border-gray-200 rounded-xl p-5">
                        <h3 class="text-sm font-semibold mb-3 text-gray-700">Estado actual</h3>
                        <div class="space-y-2 text-xs">
                            <div class="flex justify-between">
                                <span class="text-gray-500">Entorno</span>
                                <span class="font-semibold"
                                    :class="boldModo === 'production' ? 'text-green-600' : 'text-yellow-600'"
                                    x-text="boldModo === 'production' ? 'Producción 🟢' : 'Test / Sandbox 🟡'"></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-500">API Key (activa)</span>
                                <span class="font-mono text-gray-700"
                                    x-text="boldModo === 'production'
                                        ? (bold.api_key_prod ? bold.api_key_prod.slice(0,8)+'...' : '—')
                                        : (bold.api_key_test ? bold.api_key_test.slice(0,8)+'...' : '—')"></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-500">Callback URL</span>
                                <span class="font-mono text-gray-700 truncate max-w-[180px]" x-text="bold.callback_url || '—'"></span>
                            </div>
                        </div>
                    </div>

                    <!-- URL del Webhook -->
                    <div class="border border-gray-200 rounded-xl p-5">
                        <h3 class="text-sm font-semibold mb-2 flex items-center gap-2 text-gray-700">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-[#8eb02f]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"/>
                            </svg>
                            URL del Webhook
                        </h3>
                        <p class="text-xs text-gray-500 mb-3">Registra esta URL en el panel Bold → Configuración → Webhooks</p>
                        <div class="flex items-center gap-2 bg-gray-50 border border-gray-200 rounded-lg px-3 py-2">
                            <span class="text-xs font-mono text-gray-700 flex-1 truncate">/webhooks/bold</span>
                            <button @click="copyWebhook()" title="Copiar URL"
                                class="text-[#8eb02f] hover:text-[#6d8c24] flex-shrink-0">
                                <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="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                                </svg>
                            </button>
                        </div>
                        <p class="text-xs text-gray-400 mt-2">La firma se verifica con HMAC-SHA256. En modo test la secret key puede ser vacía.</p>
                    </div>

                    <!-- Eventos soportados -->
                    <div class="border border-gray-200 rounded-xl p-5">
                        <h3 class="text-sm font-semibold mb-3 text-gray-700">Eventos del webhook</h3>
                        <div class="space-y-2">
                            <div class="flex items-center justify-between text-xs">
                                <span class="font-mono bg-green-50 text-green-700 px-2 py-0.5 rounded">SALE_APPROVED</span>
                                <span class="text-gray-500">Pago aprobado ✅</span>
                            </div>
                            <div class="flex items-center justify-between text-xs">
                                <span class="font-mono bg-red-50 text-red-600 px-2 py-0.5 rounded">SALE_REJECTED</span>
                                <span class="text-gray-500">Pago rechazado ❌</span>
                            </div>
                            <div class="flex items-center justify-between text-xs">
                                <span class="font-mono bg-orange-50 text-orange-600 px-2 py-0.5 rounded">SALE_REVERSED</span>
                                <span class="text-gray-500">Reverso / devolución 🔄</span>
                            </div>
                            <div class="flex items-center justify-between text-xs">
                                <span class="font-mono bg-purple-50 text-purple-600 px-2 py-0.5 rounded">CHARGEBACK</span>
                                <span class="text-gray-500">Contracargo iniciado ⚠️</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            </div><!-- /sub-tab config -->

            <!-- ── Sub-tab: Notificaciones ────────────────────────────────── -->
            <div x-show="boldTab === 'notificaciones'">
                <!-- Filtros + estadísticas rápidas -->
                <div class="flex flex-wrap items-center gap-3 mb-4">
                    <!-- Contadores por tipo -->
                    <template x-for="stat in boldLogsStats" :key="stat.tipo">
                        <button @click="boldLogsFilter = stat.tipo; boldLogsPage = 1; loadBoldLogs()"
                            class="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-xs font-medium transition-all"
                            :class="boldLogsFilter === stat.tipo
                                ? 'border-[#8eb02f] bg-[#f2f9e6] text-[#6d8c24]'
                                : 'border-gray-200 bg-white text-gray-600 hover:border-gray-300'">
                            <span :class="stat.color" class="w-2 h-2 rounded-full inline-block"></span>
                            <span x-text="stat.label"></span>
                            <span class="font-bold" x-text="stat.count"></span>
                        </button>
                    </template>
                    <button @click="loadBoldLogs()" class="ml-auto text-xs text-[#8eb02f] hover:underline flex items-center gap-1">
                        <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="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>
                        Refrescar
                    </button>
                </div>

                <!-- Tabla notificaciones -->
                <div class="border border-gray-200 rounded-xl overflow-hidden">
                    <div x-show="boldLogs.length === 0" class="py-12 text-center text-gray-400 text-sm">
                        Sin notificaciones recibidas aún.
                    </div>
                    <div x-show="boldLogs.length > 0">
                        <table class="w-full text-xs table-auto">
                            <thead>
                                <tr class="bg-gray-50 text-left border-b">
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Evento</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Payment ID</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Referencia</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Email pagador</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Monto</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Estado</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Fecha</th>
                                    <th class="py-3 px-4"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <template x-for="log in boldLogs" :key="log.ID">
                                    <tr class="border-b last:border-0 hover:bg-gray-50 transition-colors">
                                        <td class="py-3 px-4">
                                            <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase"
                                                :class="{
                                                    'bg-green-50 text-green-700': log.tipo === 'SALE_APPROVED',
                                                    'bg-red-50 text-red-600':    log.tipo === 'SALE_REJECTED',
                                                    'bg-orange-50 text-orange-600': log.tipo === 'SALE_REVERSED',
                                                    'bg-purple-50 text-purple-600': log.tipo === 'CHARGEBACK',
                                                    'bg-blue-50 text-blue-600':  !['SALE_APPROVED','SALE_REJECTED','SALE_REVERSED','CHARGEBACK'].includes(log.tipo)
                                                }"
                                                x-text="log.tipo || '—'"></span>
                                        </td>
                                        <td class="py-3 px-4 font-mono text-gray-500" x-text="(log.payment_id||'—').slice(0,16) + ((log.payment_id||'').length > 16 ? '…' : '')"></td>
                                        <td class="py-3 px-4 font-mono text-gray-600" x-text="log.referencia || '—'"></td>
                                        <td class="py-3 px-4 text-gray-600" x-text="log.payer_email || '—'"></td>
                                        <td class="py-3 px-4 font-semibold text-gray-800" x-text="log.monto ? '$' + Number(log.monto).toLocaleString('es-CO') : '—'"></td>
                                        <td class="py-3 px-4">
                                            <span class="px-2 py-0.5 rounded text-[10px] font-semibold"
                                                :class="log.procesado ? 'bg-green-50 text-green-600' : 'bg-yellow-50 text-yellow-600'"
                                                x-text="log.procesado ? 'Procesado' : 'Pendiente'"></span>
                                        </td>
                                        <td class="py-3 px-4 text-gray-400" x-text="log.CreatedAt ? new Date(log.CreatedAt).toLocaleString('es-CO',{dateStyle:'short',timeStyle:'short'}) : '—'"></td>
                        <td class="py-3 px-4">
                                            <div class="flex items-center gap-2">
                                            <button @click="selectedLog = log; showLogModal = true" title="Ver detalle"
                                                class="text-gray-400 hover:text-[#8eb02f] transition-colors">
                                                <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="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                                                    <path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                                                </svg>
                                            </button>
                                            <!-- Botón Validar: en API_CHECK con datos incompletos, o en cualquier log si contrato no confirmado -->
                                            <button x-show="log.tipo === 'API_CHECK' && (!log.payer_email || !log.monto)"
                                                @click="validarLog(log)"
                                                :disabled="validandoLogID === log.ID"
                                                title="Verificar pago en todas las fuentes (Bold API, dLocal, logs)"
                                                class="flex items-center gap-1 text-[10px] px-2 py-0.5 rounded border border-indigo-300 text-indigo-600 hover:bg-indigo-50 disabled:opacity-40 transition-colors">
                                                <svg x-show="validandoLogID !== log.ID" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><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>
                                                <svg x-show="validandoLogID === log.ID" class="w-3 h-3 animate-spin" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/></svg>
                                                Validar
                                            </button>
                                            </div>
                                        </td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                        <!-- Paginación -->
                        <div class="flex items-center justify-between px-4 py-3 border-t bg-gray-50 text-xs text-gray-500">
                            <span>Mostrando <strong x-text="boldLogs.length"></strong> de <strong x-text="boldLogsTotal"></strong> registros</span>
                            <div class="flex gap-2">
                                <button :disabled="boldLogsPage <= 1" @click="boldLogsPage--; loadBoldLogs()"
                                    class="px-3 py-1 rounded border border-gray-200 disabled:opacity-40 hover:bg-white">← Ant</button>
                                <span class="px-2 py-1">Pág <strong x-text="boldLogsPage"></strong></span>
                                <button :disabled="boldLogs.length < boldLogsLimit" @click="boldLogsPage++; loadBoldLogs()"
                                    class="px-3 py-1 rounded border border-gray-200 disabled:opacity-40 hover:bg-white">Sig →</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div><!-- /sub-tab notificaciones -->

            <!-- ── Sub-tab: Intentos de pago ──────────────────────────────── -->
            <div x-show="boldTab === 'intentos'">
                <div class="mb-4 p-3 bg-amber-50 border border-amber-200 rounded-lg text-xs text-amber-700">
                    <strong>¿Qué es este registro?</strong> Cada vez que un usuario llega a la página de retorno
                    de Bold (callback URL) se registra un intento. Si el webhook posterior confirma el pago,
                    el estado cambia a <em>pagado</em>. Si el usuario abandonó antes de pagar queda en <em>pendiente</em>.
                </div>

                <!-- Filtros -->
                <div class="flex flex-wrap items-center gap-2 mb-4">
                    <template x-for="s in [{v:'',l:'Todos'},{v:'pendiente',l:'Pendientes'},{v:'pagado',l:'Pagados'},{v:'fallido',l:'Fallidos'},{v:'revertido',l:'Revertidos'}]" :key="s.v">
                        <button @click="boldCallbacksFilter = s.v; boldCallbacksPage = 1; loadBoldCallbacks()"
                            class="px-3 py-1.5 rounded-lg border text-xs font-medium transition-all"
                            :class="boldCallbacksFilter === s.v
                                ? 'border-[#8eb02f] bg-[#f2f9e6] text-[#6d8c24]'
                                : 'border-gray-200 bg-white text-gray-500 hover:border-gray-300'"
                            x-text="s.l">
                        </button>
                    </template>
                    <button @click="loadBoldCallbacks()" class="ml-auto text-xs text-[#8eb02f] hover:underline flex items-center gap-1">
                        <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="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>
                        Refrescar
                    </button>
                </div>

                <!-- Tabla intentos -->
                <div class="border border-gray-200 rounded-xl overflow-hidden">
                    <div x-show="boldCallbacks.length === 0" class="py-12 text-center text-gray-400 text-sm">
                        Sin intentos registrados aún. Los intentos aparecen cuando un usuario llega al checkout de Bold.
                    </div>
                    <div x-show="boldCallbacks.length > 0">
                        <table class="w-full text-xs table-auto">
                            <thead>
                                <tr class="bg-gray-50 text-left border-b">
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Estado</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Referencia</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Monto</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Email</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">IP</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Fecha intento</th>
                                    <th class="py-3 px-4"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <template x-for="cb in boldCallbacks" :key="cb.ID">
                                    <tr class="border-b last:border-0 hover:bg-gray-50 transition-colors">
                                        <td class="py-3 px-4">
                                            <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase"
                                                :class="{
                                                    'bg-yellow-50 text-yellow-700': cb.estado === 'pendiente',
                                                    'bg-green-50 text-green-700':  cb.estado === 'pagado',
                                                    'bg-red-50 text-red-600':      cb.estado === 'fallido',
                                                    'bg-orange-50 text-orange-600':cb.estado === 'revertido'
                                                }"
                                                x-text="cb.estado || 'pendiente'"></span>
                                        </td>
                                        <td class="py-3 px-4 font-mono text-gray-600" x-text="cb.referencia || '—'"></td>
                                        <td class="py-3 px-4 font-semibold text-gray-800" x-text="cb.monto ? '$ ' + Number(cb.monto).toLocaleString('es-CO') : '—'"></td>
                                        <td class="py-3 px-4 text-gray-600" x-text="cb.payer_email || '—'"></td>
                                        <td class="py-3 px-4 font-mono text-gray-400" x-text="cb.ip || '—'"></td>
                                        <td class="py-3 px-4 text-gray-400" x-text="cb.CreatedAt ? new Date(cb.CreatedAt).toLocaleString('es-CO',{dateStyle:'short',timeStyle:'short'}) : '—'"></td>
                                        <td class="py-3 px-4">
                                            <div class="flex items-center gap-2">
                                            <button @click="selectedCallback = cb; showCallbackModal = true" title="Ver parámetros recibidos"
                                                class="text-gray-400 hover:text-[#8eb02f] transition-colors">
                                                <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="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                                                    <path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                                                </svg>
                                            </button>
                                            <!-- Validar: solo en intentos pendientes -->
                                            <button x-show="cb.estado === 'pendiente'"
                                                @click="validarCallback(cb)"
                                                :disabled="validandoCallbackID === cb.ID"
                                                title="Verificar si el pago realmente se realizó"
                                                class="flex items-center gap-1 text-[10px] px-2 py-0.5 rounded border border-indigo-300 text-indigo-600 hover:bg-indigo-50 disabled:opacity-40 transition-colors">
                                                <svg x-show="validandoCallbackID !== cb.ID" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><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>
                                                <svg x-show="validandoCallbackID === cb.ID" class="w-3 h-3 animate-spin" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/></svg>
                                                Validar
                                            </button>
                                            </div>
                                        </td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                        <!-- Paginación -->
                        <div class="flex items-center justify-between px-4 py-3 border-t bg-gray-50 text-xs text-gray-500">
                            <span>Mostrando <strong x-text="boldCallbacks.length"></strong> de <strong x-text="boldCallbacksTotal"></strong> intentos</span>
                            <div class="flex gap-2">
                                <button :disabled="boldCallbacksPage <= 1" @click="boldCallbacksPage--; loadBoldCallbacks()"
                                    class="px-3 py-1 rounded border border-gray-200 disabled:opacity-40 hover:bg-white">← Ant</button>
                                <span class="px-2 py-1">Pág <strong x-text="boldCallbacksPage"></strong></span>
                                <button :disabled="boldCallbacks.length < boldCallbacksLimit" @click="boldCallbacksPage++; loadBoldCallbacks()"
                                    class="px-3 py-1 rounded border border-gray-200 disabled:opacity-40 hover:bg-white">Sig →</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div><!-- /sub-tab intentos -->

        </div><!-- /TAB BOLD -->

        <!-- ═══════════════════════════════════════════════════════════════════ -->
        <!-- TAB: PAYPAL                                                        -->
        <!-- ═══════════════════════════════════════════════════════════════════ -->
        <div x-show="activeTab === 'paypal'" x-transition>
            <div class="grid lg:grid-cols-2 gap-6">

                <!-- Formulario de credenciales PayPal -->
                <div class="border border-gray-200 rounded-xl p-5">
                    <h2 class="text-base font-semibold mb-1 flex items-center gap-2">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-[#003087]" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M7.076 21.337H2.47a.641.641 0 0 1-.633-.74L4.944.901C5.026.382 5.474 0 5.998 0h7.46c2.57 0 4.578.543 5.69 1.81 1.01 1.15 1.304 2.42 1.012 4.287-.023.143-.047.288-.077.437-.983 5.05-4.349 6.797-8.647 6.797h-2.19c-.524 0-.968.382-1.05.9l-1.12 7.106zm14.146-14.42a3.35 3.35 0 0 0-.607-.541c-.013.076-.026.175-.041.254-.93 4.778-4.005 7.201-9.138 7.201h-2.19a.563.563 0 0 0-.556.479l-1.187 7.527h-.506l-.24 1.516a.56.56 0 0 0 .554.647h3.882c.46 0 .85-.334.922-.788.06-.26.76-4.852.816-5.09a.932.932 0 0 1 .923-.788h.58c3.76 0 6.705-1.528 7.566-5.946.36-1.847.174-3.388-.778-4.471z"/>
                        </svg>
                        Credenciales PayPal
                    </h2>
                    <p class="text-xs text-gray-500 mb-4">Panel PayPal → Apps &amp; Credentials → Create App</p>

                    <!-- Selector de entorno -->
                    <div class="mb-5">
                        <label class="block text-xs font-medium text-gray-600 mb-1.5">Entorno activo</label>
                        <div class="flex gap-3">
                            <label class="flex items-center gap-2 cursor-pointer">
                                <input type="radio" x-model="paypalModo" value="sandbox" class="accent-[#8eb02f]"/>
                                <span class="text-sm px-2 py-0.5 rounded bg-yellow-50 text-yellow-700 font-medium">Sandbox</span>
                            </label>
                            <label class="flex items-center gap-2 cursor-pointer">
                                <input type="radio" x-model="paypalModo" value="live" class="accent-[#8eb02f]"/>
                                <span class="text-sm px-2 py-0.5 rounded bg-green-50 text-green-700 font-medium">Producción (Live)</span>
                            </label>
                        </div>
                    </div>

                    <!-- Sandbox -->
                    <div class="mb-5 p-4 rounded-lg bg-yellow-50 border border-yellow-200">
                        <p class="text-xs font-semibold text-yellow-700 mb-3 flex items-center gap-1">
                            <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="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"/>
                            </svg>
                            Sandbox
                        </p>
                        <div class="space-y-3">
                            <div>
                                <label class="block text-xs font-medium text-gray-600 mb-1">Client ID (sandbox)</label>
                                <input x-model="paypal.client_id_sandbox" type="text" placeholder="AXxx..." class="ui-input text-xs font-mono" autocomplete="off"/>
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-gray-600 mb-1">Client Secret (sandbox)</label>
                                <input x-model="paypal.client_secret_sandbox" type="password" placeholder="EHxx..." class="ui-input text-xs font-mono" autocomplete="off"/>
                            </div>
                        </div>
                    </div>

                    <!-- Producción -->
                    <div class="mb-5 p-4 rounded-lg bg-green-50 border border-green-200">
                        <p class="text-xs font-semibold text-green-700 mb-3 flex items-center gap-1">
                            <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="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/>
                            </svg>
                            Producción
                        </p>
                        <div class="space-y-3">
                            <div>
                                <label class="block text-xs font-medium text-gray-600 mb-1">Client ID (producción)</label>
                                <input x-model="paypal.client_id_prod" type="text" placeholder="AXxx..." class="ui-input text-xs font-mono" autocomplete="off"/>
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-gray-600 mb-1">Client Secret (producción)</label>
                                <input x-model="paypal.client_secret_prod" type="password" placeholder="EHxx..." class="ui-input text-xs font-mono" autocomplete="off"/>
                            </div>
                        </div>
                    </div>

                    <!-- Webhook ID -->
                    <div class="mb-4">
                        <label class="block text-xs font-medium text-gray-600 mb-1">
                            Webhook ID
                            <span class="text-gray-400 font-normal">(para verificación de firma)</span>
                        </label>
                        <input x-model="paypal.webhook_id" type="text" placeholder="Ej: 8PT597110X687430N" class="ui-input text-xs font-mono" autocomplete="off"/>
                    </div>

                    <!-- URLs -->
                    <div class="mb-4">
                        <label class="block text-xs font-medium text-gray-600 mb-1">Return URL</label>
                        <input x-model="paypal.return_url" type="url" placeholder="https://tudominio.com/pago-exitoso" class="ui-input text-xs"/>
                    </div>
                    <div class="mb-5">
                        <label class="block text-xs font-medium text-gray-600 mb-1">Cancel URL</label>
                        <input x-model="paypal.cancel_url" type="url" placeholder="https://tudominio.com/pago-cancelado" class="ui-input text-xs"/>
                    </div>

                    <!-- Nota -->
                    <div class="mb-5">
                        <label class="block text-xs font-medium text-gray-600 mb-1">Nota interna</label>
                        <input x-model="paypal.nota" type="text" placeholder="Opcional" class="ui-input text-xs"/>
                    </div>

                    <button @click="savePaypal()"
                        class="w-full py-2.5 rounded-xl text-sm font-semibold text-white transition-all"
                        style="background-color:#003087"
                        onmouseover="this.style.backgroundColor='#001f5c'"
                        onmouseout="this.style.backgroundColor='#003087'">
                        Guardar configuración PayPal
                    </button>
                </div>

                <!-- Info / Guía PayPal -->
                <div class="space-y-4">

                    <!-- Estado actual -->
                    <div class="border border-gray-200 rounded-xl p-5">
                        <h3 class="text-sm font-semibold mb-3 text-gray-700">Estado actual</h3>
                        <div class="space-y-2 text-xs">
                            <div class="flex justify-between">
                                <span class="text-gray-500">Entorno</span>
                                <span class="font-semibold"
                                    :class="paypalModo === 'live' ? 'text-green-600' : 'text-yellow-600'"
                                    x-text="paypalModo === 'live' ? 'Producción 🟢' : 'Sandbox 🟡'"></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-500">Client ID (activo)</span>
                                <span class="font-mono text-gray-700"
                                    x-text="paypalModo === 'live'
                                        ? (paypal.client_id_prod ? paypal.client_id_prod.slice(0,8)+'...' : '—')
                                        : (paypal.client_id_sandbox ? paypal.client_id_sandbox.slice(0,8)+'...' : '—')"></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-500">Webhook ID</span>
                                <span class="font-mono text-gray-700 truncate max-w-[180px]" x-text="paypal.webhook_id || '—'"></span>
                            </div>
                        </div>
                    </div>

                    <!-- Webhook URL -->
                    <div class="border border-gray-200 rounded-xl p-5">
                        <h3 class="text-sm font-semibold mb-2 flex items-center gap-2 text-gray-700">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-[#8eb02f]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"/>
                            </svg>
                            URL del Webhook
                        </h3>
                        <p class="text-xs text-gray-500 mb-3">Registra esta URL en PayPal → Apps → Webhooks</p>
                        <div class="flex items-center gap-2 bg-gray-50 border border-gray-200 rounded-lg px-3 py-2">
                            <span class="text-xs font-mono text-gray-700 flex-1 truncate">/webhooks/paypal</span>
                            <button @click="copyPaypalWebhook()" title="Copiar URL"
                                class="text-[#8eb02f] hover:text-[#6d8c24] flex-shrink-0">
                                <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="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                                </svg>
                            </button>
                        </div>
                    </div>

                    <!-- Eventos soportados -->
                    <div class="border border-gray-200 rounded-xl p-5">
                        <h3 class="text-sm font-semibold mb-3 text-gray-700">Eventos del webhook</h3>
                        <div class="space-y-2">
                            <div class="flex items-center justify-between text-xs">
                                <span class="font-mono bg-green-50 text-green-700 px-2 py-0.5 rounded">PAYMENT.CAPTURE.COMPLETED</span>
                                <span class="text-gray-500">Pago completado ✅</span>
                            </div>
                            <div class="flex items-center justify-between text-xs">
                                <span class="font-mono bg-red-50 text-red-600 px-2 py-0.5 rounded">PAYMENT.CAPTURE.DENIED</span>
                                <span class="text-gray-500">Pago denegado ❌</span>
                            </div>
                            <div class="flex items-center justify-between text-xs">
                                <span class="font-mono bg-orange-50 text-orange-600 px-2 py-0.5 rounded">PAYMENT.CAPTURE.REFUNDED</span>
                                <span class="text-gray-500">Devolución 🔄</span>
                            </div>
                            <div class="flex items-center justify-between text-xs">
                                <span class="font-mono bg-purple-50 text-purple-600 px-2 py-0.5 rounded">CUSTOMER.DISPUTE.CREATED</span>
                                <span class="text-gray-500">Disputa iniciada ⚠️</span>
                            </div>
                        </div>
                    </div>

                    <!-- Guía rápida -->
                    <div class="border border-gray-200 rounded-xl p-5">
                        <h3 class="text-sm font-semibold mb-3 text-gray-700">Guía rápida</h3>
                        <ol class="space-y-2 text-xs text-gray-600 list-decimal list-inside">
                            <li>Entra a <span class="font-mono">developer.paypal.com</span> → <strong>Apps &amp; Credentials</strong>.</li>
                            <li>Crea o selecciona una app y copia el <strong>Client ID</strong> y <strong>Secret</strong>.</li>
                            <li>En la misma app activa <strong>Webhooks</strong> y pega la URL de arriba.</li>
                            <li>Copia el <strong>Webhook ID</strong> generado y pégalo en este formulario.</li>
                            <li>Cuando estés listo para producción cambia a <strong>Live</strong> y repite con las credenciales de producción.</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div><!-- /TAB PAYPAL -->

        <!-- Modal detalle de notificación webhook -->
        <div x-show="showLogModal" x-transition class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
            <div @click.outside="showLogModal = false" class="bg-white rounded-2xl shadow-2xl w-full max-w-lg p-6 relative">
                <button @click="showLogModal = false" class="absolute top-4 right-4 text-gray-400 hover:text-gray-700">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
                <h3 class="text-sm font-semibold mb-4 flex items-center gap-2">
                    <span class="px-2 py-0.5 rounded-full text-[10px] font-bold"
                        :class="{
                            'bg-green-50 text-green-700': selectedLog?.tipo === 'SALE_APPROVED',
                            'bg-red-50 text-red-600':    selectedLog?.tipo === 'SALE_REJECTED',
                            'bg-orange-50 text-orange-600': selectedLog?.tipo === 'SALE_REVERSED',
                            'bg-purple-50 text-purple-600': selectedLog?.tipo === 'CHARGEBACK',
                        }"
                        x-text="selectedLog?.tipo || ''"></span>
                    Detalle de notificación
                </h3>
                <div class="space-y-2 text-xs mb-4">
                    <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Notification ID</span><span class="font-mono text-gray-700 text-right" x-text="selectedLog?.notification_id || '—'"></span></div>
                    <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Payment ID</span><span class="font-mono text-gray-700" x-text="selectedLog?.payment_id || '—'"></span></div>
                    <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Referencia</span><span class="font-mono text-gray-700" x-text="selectedLog?.referencia || '—'"></span></div>
                    <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Email pagador</span><span class="text-gray-700" x-text="selectedLog?.payer_email || '—'"></span></div>
                    <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Monto</span><span class="font-semibold text-gray-800" x-text="selectedLog?.monto ? '$' + Number(selectedLog.monto).toLocaleString('es-CO') : '—'"></span></div>
                    <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Procesado</span><span :class="selectedLog?.procesado ? 'text-green-600' : 'text-yellow-600'" x-text="selectedLog?.procesado ? 'Sí' : 'No'"></span></div>
                    <div class="flex justify-between py-1.5"><span class="text-gray-500">Fecha</span><span class="text-gray-600" x-text="selectedLog?.CreatedAt ? new Date(selectedLog.CreatedAt).toLocaleString('es-CO') : '—'"></span></div>
                </div>
                <!-- Body raw -->
                <div x-show="selectedLog?.raw">
                    <p class="text-[10px] font-semibold text-gray-400 uppercase mb-1">Payload RAW</p>
                    <pre class="bg-gray-50 border rounded-lg p-3 text-[10px] font-mono text-gray-600 overflow-x-auto max-h-40"
                        x-text="tryPrettyJson(selectedLog?.raw)"></pre>
                </div>
            </div>
        </div>

        <!-- Modal detalle de intento de pago -->
        <div x-show="showCallbackModal" x-transition class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
            <div @click.outside="showCallbackModal = false" class="bg-white rounded-2xl shadow-2xl w-full max-w-lg p-6 relative">
                <button @click="showCallbackModal = false" class="absolute top-4 right-4 text-gray-400 hover:text-gray-700">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
                <h3 class="text-sm font-semibold mb-4">Detalle de intento de pago</h3>
                <div class="space-y-2 text-xs mb-4">
                    <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Estado</span>
                        <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase"
                            :class="{
                                'bg-yellow-50 text-yellow-700': selectedCallback?.estado === 'pendiente',
                                'bg-green-50 text-green-700':  selectedCallback?.estado === 'pagado',
                                'bg-red-50 text-red-600':      selectedCallback?.estado === 'fallido',
                                'bg-orange-50 text-orange-600':selectedCallback?.estado === 'revertido'
                            }"
                            x-text="selectedCallback?.estado || '—'"></span></div>
                    <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Referencia</span><span class="font-mono text-gray-700" x-text="selectedCallback?.referencia || '—'"></span></div>
                    <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Payment Link</span><span class="font-mono text-gray-700" x-text="selectedCallback?.payment_link || '—'"></span></div>
                    <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Email</span><span class="text-gray-700" x-text="selectedCallback?.payer_email || '—'"></span></div>
                    <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">IP</span><span class="font-mono text-gray-600" x-text="selectedCallback?.ip || '—'"></span></div>
                    <div class="flex justify-between py-1.5"><span class="text-gray-500">Fecha</span><span class="text-gray-600" x-text="selectedCallback?.CreatedAt ? new Date(selectedCallback.CreatedAt).toLocaleString('es-CO') : '—'"></span></div>
                </div>
                <div x-show="selectedCallback?.params">
                    <p class="text-[10px] font-semibold text-gray-400 uppercase mb-1">Parámetros recibidos de Bold</p>
                    <pre class="bg-gray-50 border rounded-lg p-3 text-[10px] font-mono text-gray-600 overflow-x-auto max-h-40"
                        x-text="tryPrettyJson(selectedCallback?.params)"></pre>
                </div>
                <div x-show="selectedCallback?.user_agent" class="mt-3">
                    <p class="text-[10px] font-semibold text-gray-400 uppercase mb-1">User Agent</p>
                    <p class="text-[10px] font-mono text-gray-500 break-all" x-text="selectedCallback?.user_agent"></p>
                </div>
            </div>
        </div>

        <!-- ═══════════════════════════════════════════════════════════════════ -->
        <!-- TAB: dLOCAL                                                        -->
        <!-- ═══════════════════════════════════════════════════════════════════ -->
        <div x-show="activeTab === 'dlocal'" x-transition>

            <!-- Sub-tabs dLocal -->
            <div class="border-b border-gray-100 mb-5">
                <nav class="-mb-px flex gap-5 text-xs">
                    <button @click="dlocalTab = 'config'"
                        :class="dlocalTab==='config' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-400 hover:text-gray-600'"
                        class="pb-2 transition-colors">Configuración</button>
                    <button @click="dlocalTab = 'notificaciones'; loadDlocalLogs()"
                        :class="dlocalTab==='notificaciones' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-400 hover:text-gray-600'"
                        class="pb-2 transition-colors flex items-center gap-1">
                        Notificaciones
                        <span x-show="dlocalLogsTotal > 0"
                            class="bg-[#8eb02f] text-white text-[10px] px-1.5 py-0.5 rounded-full"
                            x-text="dlocalLogsTotal"></span>
                    </button>
                    <button @click="dlocalTab = 'planes'; loadDlocalPlanes()"
                        :class="dlocalTab==='planes' ? 'border-b-2 border-[#8eb02f] text-[#6d8c24] font-semibold' : 'text-gray-400 hover:text-gray-600'"
                        class="pb-2 transition-colors">Planes de suscripción</button>
                </nav>
            </div>

            <!-- ── Sub-tab: Configuración ─────────────────────────────────── -->
            <div x-show="dlocalTab === 'config'">
            <div class="grid lg:grid-cols-2 gap-6">

                <!-- Formulario dLocal -->
                <div class="border border-gray-200 rounded-xl p-5">
                    <h2 class="text-base font-semibold mb-1 flex items-center gap-2">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-[#8eb02f]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"/>
                        </svg>
                        Credenciales dLocal
                    </h2>
                    <p class="text-xs text-gray-500 mb-4">Panel dLocal → API Credentials</p>

                    <!-- Selector de entorno -->
                    <div class="mb-5">
                        <label class="block text-xs font-medium text-gray-600 mb-1.5">Entorno activo</label>
                        <div class="flex gap-3">
                            <label class="flex items-center gap-2 cursor-pointer">
                                <input type="radio" x-model="dlocalModo" value="dev" class="accent-[#8eb02f]"/>
                                <span class="text-sm px-2 py-0.5 rounded bg-yellow-50 text-yellow-700 font-medium">Desarrollo</span>
                            </label>
                            <label class="flex items-center gap-2 cursor-pointer">
                                <input type="radio" x-model="dlocalModo" value="prod" class="accent-[#8eb02f]"/>
                                <span class="text-sm px-2 py-0.5 rounded bg-green-50 text-green-700 font-medium">Producción</span>
                            </label>
                        </div>
                    </div>

                    <!-- URLs -->
                    <div class="grid grid-cols-2 gap-3 mb-4">
                        <div>
                            <label class="block text-xs font-medium text-gray-600 mb-1">URL Producción</label>
                            <input x-model="dlocal.url_prod" type="url" placeholder="https://api.dlocal.com" class="ui-input text-xs"/>
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-gray-600 mb-1">URL Desarrollo</label>
                            <input x-model="dlocal.url_dev" type="url" placeholder="https://sandbox.dlocal.com" class="ui-input text-xs"/>
                        </div>
                    </div>

                    <!-- Producción -->
                    <div class="mb-4 p-4 rounded-lg bg-green-50 border border-green-200">
                        <p class="text-xs font-semibold text-green-700 mb-3">Producción</p>
                        <div class="space-y-3">
                            <div>
                                <label class="block text-xs font-medium text-gray-600 mb-1">Access Key ID</label>
                                <input x-model="dlocal.access_key_id" type="text" placeholder="xkey_..." class="ui-input text-xs font-mono" autocomplete="off"/>
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-gray-600 mb-1">Access Key Secret</label>
                                <input x-model="dlocal.access_key_secret" type="password" placeholder="•••••••" class="ui-input text-xs font-mono" autocomplete="off"/>
                            </div>
                        </div>
                    </div>

                    <!-- Desarrollo -->
                    <div class="mb-5 p-4 rounded-lg bg-yellow-50 border border-yellow-200">
                        <p class="text-xs font-semibold text-yellow-700 mb-3">Desarrollo / Sandbox</p>
                        <div class="space-y-3">
                            <div>
                                <label class="block text-xs font-medium text-gray-600 mb-1">Access Key ID (dev)</label>
                                <input x-model="dlocal.access_key_id_dev" type="text" placeholder="xkey_dev_..." class="ui-input text-xs font-mono" autocomplete="off"/>
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-gray-600 mb-1">Access Key Secret (dev)</label>
                                <input x-model="dlocal.access_key_secret_dev" type="password" placeholder="•••••••" class="ui-input text-xs font-mono" autocomplete="off"/>
                            </div>
                        </div>
                    </div>

                    <button @click="saveDlocal()"
                        class="w-full py-2.5 rounded-xl text-sm font-semibold text-white transition-all"
                        style="background-color:#8eb02f"
                        onmouseover="this.style.backgroundColor='#6d8c24'"
                        onmouseout="this.style.backgroundColor='#8eb02f'">
                        Guardar configuración dLocal
                    </button>
                </div>

                <!-- Info dLocal -->
                <div class="space-y-4">
                    <div class="border border-gray-200 rounded-xl p-5">
                        <h3 class="text-sm font-semibold mb-3 text-gray-700">Estado actual</h3>
                        <div class="space-y-2 text-xs">
                            <div class="flex justify-between">
                                <span class="text-gray-500">Entorno</span>
                                <span class="font-semibold"
                                    :class="dlocalModo === 'prod' ? 'text-green-600' : 'text-yellow-600'"
                                    x-text="dlocalModo === 'prod' ? 'Producción 🟢' : 'Desarrollo 🟡'"></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-500">Access Key (activa)</span>
                                <span class="font-mono text-gray-700"
                                    x-text="dlocalModo === 'prod'
                                        ? (dlocal.access_key_id ? dlocal.access_key_id.slice(0,8)+'...' : '—')
                                        : (dlocal.access_key_id_dev ? dlocal.access_key_id_dev.slice(0,8)+'...' : '—')"></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-500">URL activa</span>
                                <span class="font-mono text-gray-700 truncate max-w-[180px]"
                                    x-text="dlocalModo === 'prod' ? (dlocal.url_prod || '—') : (dlocal.url_dev || '—')"></span>
                            </div>
                        </div>
                    </div>

                    <div class="border border-gray-200 rounded-xl p-5">
                        <h3 class="text-sm font-semibold mb-2 flex items-center gap-2 text-gray-700">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-[#8eb02f]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"/>
                            </svg>
                            URL del Webhook
                        </h3>
                        <p class="text-xs text-gray-500 mb-3">Registra esta URL en el panel dLocal → Integraciones → Webhook</p>
                        <div class="flex items-center gap-2 bg-gray-50 border border-gray-200 rounded-lg px-3 py-2">
                            <span class="text-xs font-mono text-gray-700 flex-1 truncate">/webhooks/dlocal</span>
                            <button @click="copyDlocalWebhook()" title="Copiar URL" class="text-[#8eb02f] hover:text-[#6d8c24] flex-shrink-0">
                                <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="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            </div><!-- /sub-tab config -->

            <!-- ── Sub-tab: Planes de suscripción ─────────────────────────── -->
            <div x-show="dlocalTab === 'planes'">

                <div class="flex justify-between items-center mb-4">
                    <p class="text-xs text-gray-500">Planes almacenados en dLocal directamente. Los cambios se reflejan en tiempo real.</p>
                    <button @click="openPlanAdd()" class="bg-[#8eb02f] text-white px-4 py-2 rounded text-sm">+ Nuevo plan</button>
                </div>

                <!-- Loading planes -->
                <div x-show="dlocalPlanesLoading" class="py-8 text-center text-gray-400 text-sm">Consultando planes en dLocal…</div>
                <div x-show="dlocalPlanesError" class="py-4 px-4 bg-red-50 text-red-600 rounded text-sm" x-text="dlocalPlanesError"></div>

                <!-- Tabla de planes -->
                <div x-show="!dlocalPlanesLoading && !dlocalPlanesError" class="border border-gray-200 rounded-xl overflow-hidden">
                    <div x-show="dlocalPlanes.length === 0" class="py-12 text-center text-gray-400 text-sm">
                        Sin planes creados en dLocal aún.
                    </div>
                    <div x-show="dlocalPlanes.length > 0">
                        <table class="w-full text-xs table-auto">
                            <thead>
                                <tr class="bg-gray-50 text-left border-b">
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">ID</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Nombre</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Monto</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Frecuencia</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Estado</th>
                                    <th class="py-3 px-4"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <template x-for="plan in dlocalPlanes" :key="plan.id">
                                    <tr class="border-b last:border-0 hover:bg-gray-50 transition-colors">
                                        <td class="py-3 px-4 font-mono text-gray-400 text-[10px]" x-text="(plan.id||'—').slice(0,12)+'…'"></td>
                                        <td class="py-3 px-4">
                                            <div class="font-medium text-gray-800" x-text="plan.name || '—'"></div>
                                            <div class="text-gray-400 text-[10px] mt-0.5" x-text="plan.description || ''"></div>
                                        </td>
                                        <td class="py-3 px-4 font-semibold text-gray-800">
                                            <span x-text="plan.currency + ' ' + (plan.amount || 0).toLocaleString('es-CO')"></span>
                                        </td>
                                        <td class="py-3 px-4 text-gray-600">
                                            <span x-text="plan.frequency_type || '—'"></span>
                                            <span x-show="plan.frequency_value" x-text="' x' + plan.frequency_value" class="text-gray-400"></span>
                                            <span x-show="plan.day_of_month" x-text="' (día ' + plan.day_of_month + ')'" class="text-gray-400"></span>
                                        </td>
                                        <td class="py-3 px-4">
                                            <span x-text="plan.status || 'active'"
                                                :class="(plan.status === 'inactive' || plan.status === 'INACTIVE') ? 'bg-red-50 text-red-600' : 'bg-green-50 text-green-700'"
                                                class="px-2 py-0.5 rounded-full text-[10px] font-semibold capitalize"></span>
                                        </td>
                                        <td class="py-3 px-4">
                                            <button @click="openPlanEdit(plan)" title="Editar" class="text-blue-500 hover:text-blue-700 mr-2">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                                    <path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
                                                </svg>
                                            </button>
                                        </td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Modal crear / editar plan -->
                <div x-show="showPlanModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm" style="display:none">
                    <div class="bg-white rounded-lg shadow-xl w-full max-w-xl mx-4 max-h-screen overflow-y-auto">
                        <div class="flex justify-between items-center p-5 border-b">
                            <h2 class="text-lg font-semibold" x-text="planEditMode ? 'Editar plan dLocal' : 'Nuevo plan dLocal'"></h2>
                            <button @click="showPlanModal = false" class="text-gray-400 hover:text-gray-600 text-xl">✕</button>
                        </div>
                        <div class="p-5 space-y-3">
                            <div class="grid grid-cols-2 gap-4">
                                <div class="col-span-2">
                                    <label class="block text-xs font-medium text-gray-700 mb-1">Nombre <span class="text-red-500">*</span></label>
                                    <input type="text" x-model="planForm.name" class="border rounded w-full p-2 text-sm" placeholder="Ej: Plan mensual VCard">
                                </div>
                                <div class="col-span-2">
                                    <label class="block text-xs font-medium text-gray-700 mb-1">Descripción</label>
                                    <input type="text" x-model="planForm.description" class="border rounded w-full p-2 text-sm" placeholder="Descripción breve">
                                </div>
                                <div>
                                    <label class="block text-xs font-medium text-gray-700 mb-1">Moneda <span class="text-red-500">*</span></label>
                                    <input type="text" x-model="planForm.currency" class="border rounded w-full p-2 text-sm font-mono" placeholder="COP / USD">
                                </div>
                                <div>
                                    <label class="block text-xs font-medium text-gray-700 mb-1">Monto <span class="text-red-500">*</span></label>
                                    <input type="number" x-model.number="planForm.amount" class="border rounded w-full p-2 text-sm" placeholder="50000">
                                </div>
                                <div>
                                    <label class="block text-xs font-medium text-gray-700 mb-1">Tipo de frecuencia <span class="text-red-500">*</span></label>
                                    <select x-model="planForm.frequency_type" class="border rounded w-full p-2 text-sm">
                                        <option value="MONTHLY">Mensual</option>
                                        <option value="WEEKLY">Semanal</option>
                                        <option value="DAILY">Diario</option>
                                        <option value="YEARLY">Anual</option>
                                    </select>
                                </div>
                                <div>
                                    <label class="block text-xs font-medium text-gray-700 mb-1">Valor frecuencia <span class="text-gray-400 font-normal">(ej: 1)</span></label>
                                    <input type="number" x-model.number="planForm.frequency_value" class="border rounded w-full p-2 text-sm" min="1">
                                </div>
                                <div>
                                    <label class="block text-xs font-medium text-gray-700 mb-1">Día del mes <span class="text-gray-400 font-normal">(opcional)</span></label>
                                    <input type="number" x-model.number="planForm.day_of_month" class="border rounded w-full p-2 text-sm" min="1" max="31">
                                </div>
                                <div>
                                    <label class="block text-xs font-medium text-gray-700 mb-1">País <span class="text-gray-400 font-normal">(opcional)</span></label>
                                    <input type="text" x-model="planForm.country" class="border rounded w-full p-2 text-sm font-mono" placeholder="CO">
                                </div>
                                <div class="col-span-2">
                                    <label class="block text-xs font-medium text-gray-700 mb-1">URL de notificación (webhook)</label>
                                    <input type="url" x-model="planForm.notification_url" class="border rounded w-full p-2 text-sm font-mono" placeholder="https://…/webhooks/dlocal">
                                </div>
                                <div>
                                    <label class="block text-xs font-medium text-gray-700 mb-1">URL éxito</label>
                                    <input type="url" x-model="planForm.success_url" class="border rounded w-full p-2 text-sm font-mono">
                                </div>
                                <div>
                                    <label class="block text-xs font-medium text-gray-700 mb-1">URL retorno</label>
                                    <input type="url" x-model="planForm.back_url" class="border rounded w-full p-2 text-sm font-mono">
                                </div>
                                <div class="col-span-2">
                                    <label class="block text-xs font-medium text-gray-700 mb-1">URL error</label>
                                    <input type="url" x-model="planForm.error_url" class="border rounded w-full p-2 text-sm font-mono">
                                </div>
                            </div>
                            <p x-show="planError" x-text="planError" class="text-red-500 text-sm"></p>
                        </div>
                        <div class="flex justify-end gap-3 p-5 border-t">
                            <button @click="showPlanModal = false" class="px-4 py-2 border rounded text-sm">Cancelar</button>
                            <button @click="savePlan()" :disabled="planSaving" class="bg-[#8eb02f] text-white px-4 py-2 rounded text-sm disabled:opacity-50">
                                <span x-show="!planSaving">Guardar en dLocal</span>
                                <span x-show="planSaving">Guardando…</span>
                            </button>
                        </div>
                    </div>
                </div>

            </div><!-- /sub-tab planes -->

            <!-- ── Sub-tab: Notificaciones dLocal ───────────────────────────── -->
            <div x-show="dlocalTab === 'notificaciones'">

                <!-- Filtros rápidos -->
                <div class="flex flex-wrap items-center gap-3 mb-4">
                    <template x-for="stat in dlocalLogsStats" :key="stat.estado">
                        <button @click="dlocalLogsFilter = stat.estado; dlocalLogsPage = 1; loadDlocalLogs()"
                            class="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-xs font-medium transition-all"
                            :class="dlocalLogsFilter === stat.estado
                                ? 'border-[#8eb02f] bg-[#f2f9e6] text-[#6d8c24]'
                                : 'border-gray-200 bg-white text-gray-600 hover:border-gray-300'">
                            <span :class="stat.color" class="w-2 h-2 rounded-full inline-block"></span>
                            <span x-text="stat.label"></span>
                            <span class="font-bold" x-text="stat.count"></span>
                        </button>
                    </template>
                    <button @click="loadDlocalLogs()" class="ml-auto text-xs text-[#8eb02f] hover:underline flex items-center gap-1">
                        <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="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>
                        Refrescar
                    </button>
                </div>

                <!-- Tabla -->
                <div class="border border-gray-200 rounded-xl overflow-hidden">
                    <div x-show="dlocalLogs.length === 0" class="py-12 text-center text-gray-400 text-sm">
                        Sin notificaciones de dLocal registradas aún.
                    </div>
                    <div x-show="dlocalLogs.length > 0">
                        <table class="w-full text-xs table-auto">
                            <thead>
                                <tr class="bg-gray-50 text-left border-b">
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Tipo / Fuente</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Payment ID</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Referencia</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Email pagador</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Monto</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Estado</th>
                                    <th class="py-3 px-4 font-semibold text-gray-500 uppercase tracking-wide text-[10px]">Fecha</th>
                                    <th class="py-3 px-4"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <template x-for="log in dlocalLogs" :key="log.ID">
                                    <tr class="border-b last:border-0 hover:bg-gray-50 transition-colors">
                                        <td class="py-3 px-4">
                                            <div class="flex flex-col gap-0.5">
                                                <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase w-fit"
                                                    :class="{
                                                        'bg-green-50 text-green-700': log.estado === 'PAID' || log.estado === 'AUTHORIZED',
                                                        'bg-red-50 text-red-600':    log.estado === 'REJECTED' || log.estado === 'CANCELLED',
                                                        'bg-yellow-50 text-yellow-700': log.estado === 'PENDING',
                                                        'bg-gray-50 text-gray-500':  !['PAID','AUTHORIZED','REJECTED','CANCELLED','PENDING'].includes(log.estado)
                                                    }"
                                                    x-text="log.estado || '—'"></span>
                                                <span class="text-[10px] text-gray-400" x-text="log.tipo || log.fuente || ''"></span>
                                            </div>
                                        </td>
                                        <td class="py-3 px-4 font-mono text-gray-500" x-text="(log.payment_id||'—').slice(0,16) + ((log.payment_id||'').length > 16 ? '…' : '')"></td>
                                        <td class="py-3 px-4 font-mono text-gray-600" x-text="log.referencia || log.order_id || '—'"></td>
                                        <td class="py-3 px-4 text-gray-600" x-text="log.payer_email || '—'"></td>
                                        <td class="py-3 px-4 font-semibold text-gray-800" x-text="log.monto ? (log.moneda||'$') + ' ' + Number(log.monto).toLocaleString('es-CO') : '—'"></td>
                                        <td class="py-3 px-4">
                                            <span class="px-2 py-0.5 rounded text-[10px] font-semibold"
                                                :class="log.procesado ? 'bg-green-50 text-green-600' : 'bg-yellow-50 text-yellow-600'"
                                                x-text="log.procesado ? 'Procesado' : 'Pendiente'"></span>
                                        </td>
                                        <td class="py-3 px-4 text-gray-400" x-text="log.CreatedAt ? new Date(log.CreatedAt).toLocaleString('es-CO',{dateStyle:'short',timeStyle:'short'}) : '—'"></td>
                                        <td class="py-3 px-4">
                                            <div class="flex items-center gap-2">
                                                <button @click="selectedDlocalLog = log; showDlocalLogModal = true" title="Ver detalle"
                                                    class="text-gray-400 hover:text-[#8eb02f] transition-colors">
                                                    <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="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                                                        <path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                                                    </svg>
                                                </button>
                                                <!-- Botón Validar: en logs sin estado PAID o con datos incompletos -->
                                                <button x-show="log.estado !== 'PAID' && log.estado !== 'AUTHORIZED' || (!log.payer_email || !log.monto)"
                                                    @click="validarDlocalLog(log)"
                                                    :disabled="validandoDlocalLogID === log.ID"
                                                    title="Verificar pago en todas las fuentes"
                                                    class="flex items-center gap-1 text-[10px] px-2 py-0.5 rounded border border-indigo-300 text-indigo-600 hover:bg-indigo-50 disabled:opacity-40 transition-colors">
                                                    <svg x-show="validandoDlocalLogID !== log.ID" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><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>
                                                    <svg x-show="validandoDlocalLogID === log.ID" class="w-3 h-3 animate-spin" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/></svg>
                                                    Validar
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                        <!-- Paginación -->
                        <div class="flex items-center justify-between px-4 py-3 border-t bg-gray-50 text-xs text-gray-500">
                            <span>Mostrando <strong x-text="dlocalLogs.length"></strong> de <strong x-text="dlocalLogsTotal"></strong> registros</span>
                            <div class="flex gap-2">
                                <button :disabled="dlocalLogsPage <= 1" @click="dlocalLogsPage--; loadDlocalLogs()"
                                    class="px-3 py-1 rounded border border-gray-200 disabled:opacity-40 hover:bg-white">← Ant</button>
                                <span class="px-2 py-1">Pág <strong x-text="dlocalLogsPage"></strong></span>
                                <button :disabled="dlocalLogs.length < dlocalLogsLimit" @click="dlocalLogsPage++; loadDlocalLogs()"
                                    class="px-3 py-1 rounded border border-gray-200 disabled:opacity-40 hover:bg-white">Sig →</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div><!-- /sub-tab notificaciones dlocal -->

            <!-- Modal detalle log dLocal -->
            <div x-show="showDlocalLogModal" x-transition class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
                <div @click.outside="showDlocalLogModal = false" class="bg-white rounded-2xl shadow-2xl w-full max-w-lg p-6 relative">
                    <button @click="showDlocalLogModal = false" class="absolute top-4 right-4 text-gray-400 hover:text-gray-700">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>
                        </svg>
                    </button>
                    <h3 class="text-sm font-semibold mb-4 flex items-center gap-2">
                        <span class="px-2 py-0.5 rounded-full text-[10px] font-bold"
                            :class="{
                                'bg-green-50 text-green-700': selectedDlocalLog?.estado === 'PAID' || selectedDlocalLog?.estado === 'AUTHORIZED',
                                'bg-red-50 text-red-600':    selectedDlocalLog?.estado === 'REJECTED',
                                'bg-yellow-50 text-yellow-700': selectedDlocalLog?.estado === 'PENDING',
                            }"
                            x-text="selectedDlocalLog?.estado || ''"></span>
                        Detalle de notificación dLocal
                    </h3>
                    <div class="space-y-2 text-xs mb-4">
                        <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Notification ID</span><span class="font-mono text-gray-700 text-right truncate max-w-[220px]" x-text="selectedDlocalLog?.notification_id || '—'"></span></div>
                        <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Payment ID</span><span class="font-mono text-gray-700" x-text="selectedDlocalLog?.payment_id || '—'"></span></div>
                        <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Order ID</span><span class="font-mono text-gray-700" x-text="selectedDlocalLog?.order_id || '—'"></span></div>
                        <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Referencia</span><span class="font-mono text-gray-700" x-text="selectedDlocalLog?.referencia || '—'"></span></div>
                        <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Tipo</span><span class="text-gray-700" x-text="selectedDlocalLog?.tipo || selectedDlocalLog?.fuente || '—'"></span></div>
                        <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Email pagador</span><span class="text-gray-700" x-text="selectedDlocalLog?.payer_email || '—'"></span></div>
                        <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Monto</span><span class="font-semibold text-gray-800" x-text="selectedDlocalLog?.monto ? (selectedDlocalLog?.moneda||'') + ' ' + Number(selectedDlocalLog.monto).toLocaleString('es-CO') : '—'"></span></div>
                        <div class="flex justify-between py-1.5 border-b"><span class="text-gray-500">Procesado</span><span :class="selectedDlocalLog?.procesado ? 'text-green-600' : 'text-yellow-600'" x-text="selectedDlocalLog?.procesado ? 'Sí' : 'No'"></span></div>
                        <div class="flex justify-between py-1.5"><span class="text-gray-500">Fecha</span><span class="text-gray-600" x-text="selectedDlocalLog?.CreatedAt ? new Date(selectedDlocalLog.CreatedAt).toLocaleString('es-CO') : '—'"></span></div>
                    </div>
                    <div x-show="selectedDlocalLog?.raw">
                        <p class="text-[10px] font-semibold text-gray-400 uppercase mb-1">Payload RAW</p>
                        <pre class="bg-gray-50 border rounded-lg p-3 text-[10px] font-mono text-gray-600 overflow-x-auto max-h-40"
                            x-text="tryPrettyJson(selectedDlocalLog?.raw)"></pre>
                    </div>
                </div>
            </div>

        </div>

    </div><!-- /container -->
</div><!-- /x-data -->

<script>
function pasarelasApp() {
    return {
        activeTab: 'bold',
        loading: false,
        toast: { show: false, msg: '', type: 'success' },

        // ─── Bold ───────────────────────────────────────────────────────
        boldModo: 'test',
        bold: {
            id: 0,
            api_key_prod: '',
            secret_key_prod: '',
            api_key_test: '',
            secret_key_test: '',
            callback_url: '',
            nota: '',
        },

        // Sub-tabs Bold
        boldTab: 'config',

        // Notificaciones webhook
        boldLogs: [],
        boldLogsTotal: 0,
        boldLogsPage: 1,
        boldLogsLimit: 25,
        boldLogsFilter: '',
        boldLogsStats: [
            { tipo: '',           label: 'Todos',        color: 'bg-gray-400',   count: 0 },
            { tipo: 'APROBADOS',  label: 'Aprobados',    color: 'bg-green-400',  count: 0 },
            { tipo: 'SALE_REJECTED',  label: 'Rechazados',    color: 'bg-red-400',    count: 0 },
            { tipo: 'SALE_REVERSED',  label: 'Revertidos',    color: 'bg-orange-400', count: 0 },
            { tipo: 'CHARGEBACK',     label: 'Contracargos',  color: 'bg-purple-400', count: 0 },
        ],

        // Intentos de pago (callbacks)
        boldCallbacks: [],
        boldCallbacksTotal: 0,
        boldCallbacksPage: 1,
        boldCallbacksLimit: 25,
        boldCallbacksFilter: '',

        // Modales detalle
        showLogModal: false,
        selectedLog: null,
        showCallbackModal: false,
        selectedCallback: null,
        validandoLogID: 0,
        validandoCallbackID: 0,

        // ─── PayPal ──────────────────────────────────────────────────────
        paypalModo: 'sandbox',
        paypal: {
            id: 0,
            client_id_sandbox:     '',
            client_secret_sandbox: '',
            client_id_prod:        '',
            client_secret_prod:    '',
            webhook_id:            '',
            return_url:            '',
            cancel_url:            '',
            nota:                  '',
        },

        // ─── dLocal ─────────────────────────────────────────────────────
        dlocalModo: 'dev',
        dlocal: {
            id: 0,
            access_key_id: '',
            access_key_secret: '',
            access_key_id_dev: '',
            access_key_secret_dev: '',
            url_prod: '',
            url_dev: '',
        },

        // Sub-tabs dLocal
        dlocalTab: 'config',

        // Notificaciones dLocal
        dlocalLogs: [],
        dlocalLogsTotal: 0,
        dlocalLogsPage: 1,
        dlocalLogsLimit: 25,
        dlocalLogsFilter: '',
        dlocalLogsStats: [
            { estado: '',          label: 'Todos',      color: 'bg-gray-400',   count: 0 },
            { estado: 'APROBADOS', label: 'Aprobados',  color: 'bg-green-400',  count: 0 },
            { estado: 'PENDING',   label: 'Pendientes', color: 'bg-yellow-400', count: 0 },
            { estado: 'REJECTED',  label: 'Rechazados', color: 'bg-red-400',    count: 0 },
        ],
        showDlocalLogModal: false,
        selectedDlocalLog: null,
        validandoDlocalLogID: 0,

        // Planes dLocal
        dlocalPlanes: [],
        dlocalPlanesLoading: false,
        dlocalPlanesError: '',
        showPlanModal: false,
        planEditMode: false,
        planSaving: false,
        planError: '',
        planEditID: '',
        planForm: {},
        defaultPlanForm() {
            return { name:'', description:'', currency:'COP', amount:0, frequency_type:'MONTHLY', frequency_value:1, day_of_month:0, country:'CO', notification_url:'', success_url:'', back_url:'', error_url:'' };
        },

        // ─── Init ───────────────────────────────────────────────────────
        init() {
            this.loadBold();
            this.loadDlocal();
            this.loadPaypal();
            // Carga perezosa: se carga cuando el usuario abre esos sub-tabs
            this.loadBoldLogs();
        },

        // ─── Bold helpers ────────────────────────────────────────────────
        async loadBold() {
            try {
                const r = await axios.get('/app/pasarelas/bold/config');
                if (r.data.data) {
                    const d = r.data.data;
                    this.bold = {
                        id:              d.ID || 0,
                        api_key_prod:    d.api_key_prod    || '',
                        secret_key_prod: d.secret_key_prod || '',
                        api_key_test:    d.api_key_test    || '',
                        secret_key_test: d.secret_key_test || '',
                        callback_url:    d.callback_url    || '',
                        nota:            d.nota            || '',
                    };
                    this.boldModo = d.modo || 'test';
                }
            } catch (_) {}
        },

        async saveBold() {
            this.loading = true;
            try {
                const payload = { ...this.bold, modo: this.boldModo };
                await axios.post('/app/pasarelas/bold/save', payload);
                this.showToast('Configuración Bold guardada ✓');
                this.loadBold();
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error guardando Bold', 'error');
            } finally {
                this.loading = false;
            }
        },

        async loadBoldLogs() {
            try {
                const params = new URLSearchParams({
                    page:  this.boldLogsPage,
                    limit: this.boldLogsLimit,
                });
                if (this.boldLogsFilter) params.set('tipo', this.boldLogsFilter);
                const r = await axios.get('/app/pasarelas/bold/logs?' + params.toString());
                this.boldLogs = r.data.data || [];
                this.boldLogsTotal = r.data.total || 0;
                // Actualizar contadores rápidos (solo cuando carga sin filtro)
                if (!this.boldLogsFilter) {
                    const all = r.data.total || 0;
                    this.boldLogsStats[0].count = all;
                    // Cargar contadores por tipo en paralelo
                    ['APROBADOS','SALE_REJECTED','SALE_REVERSED','CHARGEBACK'].forEach((tipo, i) => {
                        axios.get(`/app/pasarelas/bold/logs?page=1&limit=1&tipo=${tipo}`)
                            .then(res => { this.boldLogsStats[i+1].count = res.data.total || 0; })
                            .catch(() => {});
                    });
                }
            } catch (_) {}
        },

        async loadBoldCallbacks() {
            try {
                const params = new URLSearchParams({
                    page:  this.boldCallbacksPage,
                    limit: this.boldCallbacksLimit,
                });
                if (this.boldCallbacksFilter) params.set('estado', this.boldCallbacksFilter);
                const r = await axios.get('/app/pasarelas/bold/callbacks?' + params.toString());
                this.boldCallbacks = r.data.data || [];
                this.boldCallbacksTotal = r.data.total || 0;
            } catch (_) {}
        },

        async validarCallback(cb) {
            this.validandoCallbackID = cb.ID;
            try {
                const { data } = await axios.post(`/app/pasarelas/bold/callbacks/${cb.ID}/validar`);
                if (data.ok && data.data) {
                    const idx = this.boldCallbacks.findIndex(c => c.ID === cb.ID);
                    if (idx !== -1) this.boldCallbacks[idx] = data.data;
                }
                const msg = data.mensaje || (data.confirmado ? 'Pago confirmado ✓' : 'Pago aún no confirmado');
                this.showToast(msg, data.confirmado ? 'success' : 'error');
                if (data.confirmado) this.loadBoldCallbacks();
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error al validar', 'error');
            } finally {
                this.validandoCallbackID = 0;
            }
        },

        copyWebhook() {
            const base = window.location.origin;
            const url = base + '/webhooks/bold';
            navigator.clipboard.writeText(url).then(() => {
                this.showToast('URL copiada: ' + url);
            });
        },

        async validarLog(log) {
            this.validandoLogID = log.ID;
            try {
                const { data } = await axios.post(`/app/pasarelas/bold/logs/${log.ID}/validar`);
                if (data.ok && data.data) {
                    // Actualizar la fila en memoria
                    const idx = this.boldLogs.findIndex(l => l.ID === log.ID);
                    if (idx !== -1) this.boldLogs[idx] = data.data;
                }
                const msg = data.mensaje || (data.confirmado ? 'Pago confirmado ✓' : 'Datos actualizados');
                const tipo = data.confirmado ? 'success' : 'info';
                this.showToast(msg, data.confirmado ? 'success' : 'error');
                // Recargar stats si el pago se confirmó ahora
                if (data.confirmado) this.loadBoldLogs();
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error al validar', 'error');
            } finally {
                this.validandoLogID = 0;
            }
        },

        tryPrettyJson(raw) {
            if (!raw) return '';
            try { return JSON.stringify(JSON.parse(raw), null, 2); } catch (_) { return raw; }
        },

        // ─── dLocal helpers ──────────────────────────────────────────────
        async loadDlocal() {
            try {
                const r = await axios.get('/app/pasarelas/dlocal/config');
                if (r.data.data) {
                    const d = r.data.data;
                    this.dlocal = {
                        id:                    d.ID || 0,
                        access_key_id:         d.access_key_id           || '',
                        access_key_secret:     d.access_key_secret       || '',
                        access_key_id_dev:     d.access_key_id_dev       || '',
                        access_key_secret_dev: d.access_key_secret_dev   || '',
                        url_prod:              d.url_prod                 || '',
                        url_dev:               d.url_dev                  || '',
                    };
                    this.dlocalModo = d.modo || 'dev';
                }
            } catch (_) {}
        },

        async saveDlocal() {
            this.loading = true;
            try {
                const payload = { ...this.dlocal, modo: this.dlocalModo };
                await axios.post('/app/pasarelas/dlocal/save', payload);
                this.showToast('Configuración dLocal guardada ✓');
                this.loadDlocal();
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error guardando dLocal', 'error');
            } finally {
                this.loading = false;
            }
        },

        async loadDlocalPlanes() {
            this.dlocalPlanesLoading = true;
            this.dlocalPlanesError = '';
            try {
                const r = await axios.get('/app/dlocal/planes');
                // dLocal devuelve { message, response } donde response es el JSON raw
                const raw = r.data.response;
                const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
                // La API de dLocal devuelve { plans: [...] } o directamente un array
                this.dlocalPlanes = Array.isArray(parsed) ? parsed : (parsed.plans || parsed.data || []);
            } catch (e) {
                this.dlocalPlanesError = e.response?.data?.error || 'No se pudo obtener los planes de dLocal.';
            } finally {
                this.dlocalPlanesLoading = false;
            }
        },

        openPlanAdd() {
            this.planEditMode = false;
            this.planEditID = '';
            this.planForm = this.defaultPlanForm();
            this.planError = '';
            this.showPlanModal = true;
        },

        openPlanEdit(plan) {
            this.planEditMode = true;
            this.planEditID = plan.id;
            this.planForm = {
                name:             plan.name || '',
                description:      plan.description || '',
                currency:         plan.currency || 'COP',
                amount:           plan.amount || 0,
                frequency_type:   plan.frequency_type || 'MONTHLY',
                frequency_value:  plan.frequency_value || 1,
                day_of_month:     plan.day_of_month || 0,
                country:          plan.country || '',
                notification_url: plan.notification_url || '',
                success_url:      plan.success_url || '',
                back_url:         plan.back_url || '',
                error_url:        plan.error_url || '',
            };
            this.planError = '';
            this.showPlanModal = true;
        },

        async savePlan() {
            this.planError = '';
            if (!this.planForm.name)     { this.planError = 'El nombre es requerido.'; return; }
            if (!this.planForm.currency) { this.planError = 'La moneda es requerida.'; return; }
            if (!this.planForm.amount)   { this.planError = 'El monto es requerido.'; return; }
            this.planSaving = true;
            try {
                if (this.planEditMode) {
                    // Solo campos editables en PATCH
                    const patch = {
                        name:             this.planForm.name,
                        description:      this.planForm.description,
                        amount:           this.planForm.amount,
                        notification_url: this.planForm.notification_url,
                        back_url:         this.planForm.back_url,
                        success_url:      this.planForm.success_url,
                        error_url:        this.planForm.error_url,
                    };
                    await axios.patch(`/app/dlocal/planes/${this.planEditID}`, patch);
                    this.showToast('Plan actualizado en dLocal ✓');
                } else {
                    await axios.post('/app/dlocal/planes', this.planForm);
                    this.showToast('Plan creado en dLocal ✓');
                }
                this.showPlanModal = false;
                await this.loadDlocalPlanes();
            } catch (e) {
                this.planError = e.response?.data?.error || 'Error al guardar el plan.';
            } finally {
                this.planSaving = false;
            }
        },

        copyDlocalWebhook() {
            const url = window.location.origin + '/webhooks/dlocal';
            navigator.clipboard.writeText(url).then(() => this.showToast('URL copiada: ' + url));
        },

        async loadDlocalLogs() {
            try {
                const params = new URLSearchParams({ page: this.dlocalLogsPage, limit: this.dlocalLogsLimit });
                if (this.dlocalLogsFilter) params.set('estado', this.dlocalLogsFilter);
                const r = await axios.get('/app/pasarelas/dlocal/logs?' + params.toString());
                this.dlocalLogs = r.data.data || [];
                this.dlocalLogsTotal = r.data.total || 0;
                if (!this.dlocalLogsFilter) {
                    this.dlocalLogsStats[0].count = r.data.total || 0;
                    ['APROBADOS','PENDING','REJECTED'].forEach((e, i) => {
                        axios.get(`/app/pasarelas/dlocal/logs?page=1&limit=1&estado=${e}`)
                            .then(res => { this.dlocalLogsStats[i+1].count = res.data.total || 0; })
                            .catch(() => {});
                    });
                }
            } catch (_) {}
        },

        async validarDlocalLog(log) {
            this.validandoDlocalLogID = log.ID;
            try {
                const { data } = await axios.post(`/app/pasarelas/dlocal/logs/${log.ID}/validar`);
                if (data.ok && data.data) {
                    const idx = this.dlocalLogs.findIndex(l => l.ID === log.ID);
                    if (idx !== -1) this.dlocalLogs[idx] = data.data;
                }
                const msg = data.mensaje || (data.confirmado ? 'Pago confirmado ✓' : 'Datos actualizados');
                this.showToast(msg, data.confirmado ? 'success' : 'error');
                if (data.confirmado) this.loadDlocalLogs();
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error al validar', 'error');
            } finally {
                this.validandoDlocalLogID = 0;
            }
        },

        // ─── PayPal helpers ──────────────────────────────────────────────
        async loadPaypal() {
            try {
                const r = await axios.get('/app/pasarelas/paypal/config');
                if (r.data.data) {
                    const d = r.data.data;
                    this.paypal = {
                        id:                    d.ID || 0,
                        client_id_sandbox:     d.client_id_sandbox     || '',
                        client_secret_sandbox: d.client_secret_sandbox || '',
                        client_id_prod:        d.client_id_prod        || '',
                        client_secret_prod:    d.client_secret_prod    || '',
                        webhook_id:            d.webhook_id            || '',
                        return_url:            d.return_url            || '',
                        cancel_url:            d.cancel_url            || '',
                        nota:                  d.nota                  || '',
                    };
                    this.paypalModo = d.modo || 'sandbox';
                }
            } catch (_) {}
        },

        async savePaypal() {
            this.loading = true;
            try {
                const payload = { ...this.paypal, modo: this.paypalModo };
                await axios.post('/app/pasarelas/paypal/save', payload);
                this.showToast('Configuración PayPal guardada ✓');
                this.loadPaypal();
            } catch (e) {
                this.showToast(e.response?.data?.error || 'Error guardando PayPal', 'error');
            } finally {
                this.loading = false;
            }
        },

        copyPaypalWebhook() {
            const url = window.location.origin + '/webhooks/paypal';
            navigator.clipboard.writeText(url).then(() => this.showToast('URL copiada: ' + url));
        },

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