<div x-data="websmsApp()" x-init="init()" class="p-6 max-w-3xl mx-auto">

  <div class="flex items-center justify-between mb-6">
    <div>
      <h1 class="text-2xl font-bold text-slate-800">WebSMS (LabsMobile)</h1>
      <p class="text-sm text-slate-500 mt-1">Integración de SMS para notificaciones</p>
    </div>
  </div>

  <!-- Configuración -->
  <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-6 mb-6">
    <h2 class="text-lg font-bold text-slate-800 mb-4">Configuración API</h2>
    <form @submit.prevent="save()">
      <div class="grid grid-cols-2 gap-4">
        <div class="col-span-2">
          <label class="label">Usuario (email)</label>
          <input x-model="form.username" class="input-field w-full" required placeholder="lizandro.guarnizo@u-site.app">
        </div>
        <div class="col-span-2">
          <label class="label">API Token</label>
          <div class="relative">
            <input x-model="form.api_token" type="password" class="input-field w-full pr-10" required>
            <button type="button" @click="showToken=!showToken; $el.previousElementSibling.type=showToken?'text':'password'" class="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600">
              <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><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>
          </div>
        </div>
        <div>
          <label class="label">Remitente (TPOA)</label>
          <input x-model="form.sender" class="input-field w-full" placeholder="U-SITE">
        </div>
        <div>
          <label class="label">Notas</label>
          <input x-model="form.notas" class="input-field w-full" placeholder="Opcional">
        </div>
      </div>
      <p x-show="error" x-text="error" class="text-red-500 text-sm mt-3"></p>
      <div class="flex justify-end mt-5">
        <button type="submit" :disabled="saving" class="btn-primary" x-text="saving?'Guardando...':'Guardar configuración'"></button>
      </div>
    </form>
  </div>

  <!-- API Key -->
  <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-6 mb-6">
    <h2 class="text-lg font-bold text-slate-800 mb-1">API Key (envío externo)</h2>
    <p class="text-sm text-slate-500 mb-4">Usa este token en <code class="bg-slate-100 px-1 rounded">Authorization: Bearer &lt;key&gt;</code> para llamar a <code class="bg-slate-100 px-1 rounded">POST /api/sms/send</code> desde sistemas externos.</p>
    <div x-show="secretKey" class="flex items-center gap-2">
      <code class="flex-1 text-xs bg-slate-50 p-2 rounded border border-slate-200 text-slate-700 break-all font-mono" x-text="secretKey"></code>
      <button type="button" @click="copy(secretKey)" class="btn-icon text-slate-400 hover:text-slate-600 flex-shrink-0" title="Copiar">
        <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><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 x-show="!secretKey" class="text-sm text-slate-400">Guarda la configuración para generar la API Key.</p>
  </div>

  <!-- Probar envío -->
  <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-6 mb-6">
    <h2 class="text-lg font-bold text-slate-800 mb-4">Probar envío</h2>
    <form @submit.prevent="test()">
      <div class="grid grid-cols-2 gap-4">
        <div>
          <label class="label">Número destino</label>
          <input x-model="testPara" class="input-field w-full" placeholder="57300xxxxxx" required>
        </div>
        <div>
          <label class="label">Mensaje (opcional)</label>
          <input x-model="testMsg" class="input-field w-full" placeholder="Texto de prueba">
        </div>
      </div>
      <p x-show="testResult" x-text="testResult" class="text-sm mt-3" :class="testOk?'text-green-600':'text-red-500'"></p>
      <div class="flex justify-end mt-4">
        <button type="submit" :disabled="saving" class="btn-primary" x-text="saving?'Enviando...':'Enviar SMS de prueba'"></button>
      </div>
    </form>
  </div>

  <!-- Webhooks URLs -->
  <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-6 mb-6">
    <h2 class="text-lg font-bold text-slate-800 mb-4">Webhooks</h2>
    <p class="text-sm text-slate-500 mb-4">Configura estas URLs en el panel de WebSMS para recibir notificaciones:</p>
    <div class="space-y-3">
      <div>
        <label class="label">Confirmaciones de entrega (ACK)</label>
        <div class="flex items-center gap-2">
          <code class="flex-1 text-xs bg-slate-50 p-2 rounded border border-slate-200 text-slate-700 break-all">https://admin.u-site.app/webhooks/websms/delivery</code>
          <button type="button" @click="copy('https://admin.u-site.app/webhooks/websms/delivery')" class="btn-icon text-slate-400 hover:text-slate-600 flex-shrink-0" title="Copiar">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><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>
        <label class="label">Clics en shortlinks</label>
        <div class="flex items-center gap-2">
          <code class="flex-1 text-xs bg-slate-50 p-2 rounded border border-slate-200 text-slate-700 break-all">https://admin.u-site.app/webhooks/websms/click</code>
          <button type="button" @click="copy('https://admin.u-site.app/webhooks/websms/click')" class="btn-icon text-slate-400 hover:text-slate-600 flex-shrink-0" title="Copiar">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><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>
        <label class="label">Mensajes entrantes</label>
        <div class="flex items-center gap-2">
          <code class="flex-1 text-xs bg-slate-50 p-2 rounded border border-slate-200 text-slate-700 break-all">https://admin.u-site.app/webhooks/websms/incoming</code>
          <button type="button" @click="copy('https://admin.u-site.app/webhooks/websms/incoming')" class="btn-icon text-slate-400 hover:text-slate-600 flex-shrink-0" title="Copiar">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><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>
    <p x-show="copied" x-text="copied" class="text-green-600 text-xs mt-3"></p>
  </div>

  <!-- Documentación de integración -->
  <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-6 mb-6" x-data="{ tab: 'curl' }">
    <div class="flex items-center justify-between mb-5">
      <div>
        <h2 class="text-lg font-bold text-slate-800">Documentación de integración</h2>
        <p class="text-sm text-slate-500 mt-0.5">Cómo enviar SMS desde tu propio sistema</p>
      </div>
      <span class="text-xs px-2 py-1 bg-green-100 text-green-700 rounded-full font-bold">REST API</span>
    </div>

    <!-- Endpoint -->
    <div class="mb-5">
      <p class="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Endpoint</p>
      <div class="flex items-center gap-2 bg-slate-50 border border-slate-200 rounded-lg px-3 py-2">
        <span class="text-xs font-bold bg-blue-600 text-white px-2 py-0.5 rounded font-mono">POST</span>
        <code class="text-sm font-mono text-slate-700 flex-1">https://admin.u-site.app/api/sms/send</code>
        <button type="button" @click="copy('https://admin.u-site.app/api/sms/send')" class="btn-icon text-slate-400 hover:text-slate-600" title="Copiar">
          <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><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>

    <!-- Auth -->
    <div class="mb-5">
      <p class="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Autenticación</p>
      <div class="bg-amber-50 border border-amber-200 rounded-lg p-3 text-sm text-amber-800">
        Incluye tu API Key en el header <code class="bg-amber-100 px-1 rounded font-mono text-xs">Authorization: Bearer {API_KEY}</code>.<br>
        Encuentra tu API Key en la sección <strong>API Key (envío externo)</strong> de esta página.
      </div>
    </div>

    <!-- Request/Response -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-5">
      <div>
        <p class="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Body (JSON)</p>
        <div class="bg-slate-900 rounded-lg p-4">
          <pre class="text-green-400 text-xs font-mono leading-relaxed">{
  "numero":  "573001234567",
  "mensaje": "Hola, este es tu código: 9821"
}</pre>
        </div>
        <div class="mt-2 space-y-1">
          <div class="flex gap-2 text-xs"><code class="text-blue-600 font-mono font-bold w-16">numero</code><span class="text-slate-500">Teléfono en formato internacional sin <code class="bg-slate-100 px-1 rounded">+</code> (ej: <code class="bg-slate-100 px-1 rounded">573001234567</code>)</span></div>
          <div class="flex gap-2 text-xs"><code class="text-blue-600 font-mono font-bold w-16">mensaje</code><span class="text-slate-500">Texto del SMS. Máx 160 caracteres para un crédito.</span></div>
        </div>
      </div>
      <div>
        <p class="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Respuestas</p>
        <div class="space-y-2">
          <div>
            <span class="text-xs font-bold text-green-700">200 — Enviado</span>
            <div class="bg-slate-900 rounded-lg p-3 mt-1">
              <pre class="text-green-400 text-xs font-mono">{ "ok": true, "id": "6a3d4f155..." }</pre>
            </div>
          </div>
          <div>
            <span class="text-xs font-bold text-red-600">401 — No autenticado</span>
            <div class="bg-slate-900 rounded-lg p-3 mt-1">
              <pre class="text-red-400 text-xs font-mono">{ "error": "token requerido" }</pre>
            </div>
          </div>
          <div>
            <span class="text-xs font-bold text-red-600">400 — Datos inválidos</span>
            <div class="bg-slate-900 rounded-lg p-3 mt-1">
              <pre class="text-red-400 text-xs font-mono">{ "error": "numero y mensaje son requeridos" }</pre>
            </div>
          </div>
          <div>
            <span class="text-xs font-bold text-red-600">500 — Error LabsMobile</span>
            <div class="bg-slate-900 rounded-lg p-3 mt-1">
              <pre class="text-red-400 text-xs font-mono">{ "error": "descripción del error" }</pre>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Code examples -->
    <div>
      <p class="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Ejemplos de código</p>
      <!-- Tabs -->
      <div class="flex gap-1 mb-3 border-b border-slate-200">
        <template x-for="t in [{id:'curl',label:'cURL'},{id:'js',label:'JavaScript'},{id:'php',label:'PHP'},{id:'python',label:'Python'}]" :key="t.id">
          <button type="button" @click="tab=t.id"
            :class="tab===t.id ? 'border-b-2 border-green-600 text-green-700 font-bold' : 'text-slate-500 hover:text-slate-700'"
            class="px-3 py-1.5 text-xs transition-colors -mb-px"
            x-text="t.label"></button>
        </template>
      </div>

      <!-- Bloque de código único — el contenido lo genera JS -->
      <div class="relative group">
        <div class="bg-slate-900 rounded-lg p-4">
          <pre class="text-green-400 text-xs font-mono leading-relaxed whitespace-pre-wrap" x-text="getCodeExample(tab)"></pre>
        </div>
        <button type="button" @click="copy(getCodeExample(tab))"
          class="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity bg-slate-700 hover:bg-slate-600 text-slate-300 rounded px-2 py-1 text-xs">
          Copiar
        </button>
      </div>
    </div>

    <p x-show="copied" x-text="copied" class="text-green-600 text-xs mt-3"></p>
  </div>

  <!-- Logs -->
  <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
    <h2 class="text-lg font-bold text-slate-800 mb-4">Últimos envíos</h2>
    <div class="overflow-x-auto">
      <table class="w-full text-sm">
        <thead class="bg-slate-50 text-slate-500 text-xs uppercase tracking-wide">
          <tr>
            <th class="px-3 py-2 text-left">Fecha</th>
            <th class="px-3 py-2 text-left">Para</th>
            <th class="px-3 py-2 text-left">Mensaje</th>
            <th class="px-3 py-2 text-left">Estado</th>
            <th class="px-3 py-2 text-left">ID</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-slate-100">
          <template x-for="l in logs" :key="l.ID">
            <tr class="hover:bg-slate-50">
              <td class="px-3 py-2 text-xs text-slate-500" x-text="formatDate(l.CreatedAt)"></td>
              <td class="px-3 py-2 text-slate-700" x-text="l.para"></td>
              <td class="px-3 py-2 text-slate-600 max-w-xs truncate" x-text="l.mensaje"></td>
              <td class="px-3 py-2">
                <span class="badge" :class="l.status==='0'?'badge-green':'badge-red'" x-text="l.status==='0'?'Enviado':'Error'"></span>
              </td>
              <td class="px-3 py-2 text-xs font-mono text-slate-500" x-text="l.msg_id||'-'"></td>
            </tr>
          </template>
          <template x-if="!logs.length">
            <tr><td colspan="5" class="text-center py-6 text-slate-400">Sin envíos aún</td></tr>
          </template>
        </tbody>
      </table>
    </div>
  </div>

</div>

<script>
function websmsApp() {
  return {
    form:{ username:'', api_token:'', sender:'', notas:'' },
    showToken:false, secretKey:'',
    logs:[],
    testPara:'', testMsg:'', testResult:'', testOk:false,
    saving:false, error:'', copied:'',

    async init(){
      await this.loadConfig();
      await this.loadLogs();
    },

    async loadConfig(){
      try {
        const r=await axios.get('/app/websms/config');
        if(r.data.data){
          this.form={id:r.data.data.ID, username:r.data.data.username, api_token:r.data.data.api_token, sender:r.data.data.sender||'', notas:r.data.data.notas||''};
          this.secretKey=r.data.data.secret_key||'';
        }
      } catch(e){}
    },

    async loadLogs(){
      try { const r=await axios.get('/app/websms/logs'); this.logs=r.data; } catch(e){}
    },

    async save(){
      this.saving=true; this.error='';
      try {
        await axios.post('/app/websms/save', this.form);
        await this.loadConfig();
      } catch(e){ this.error=e.response?.data?.error||'Error al guardar'; }
      finally{ this.saving=false; }
    },

    async test(){
      this.saving=true; this.testResult=''; this.testOk=false;
      try {
        const r=await axios.post('/app/websms/test', {para:this.testPara, mensaje:this.testMsg});
        this.testResult='SMS enviado correctamente. Código: '+r.data.response.code;
        this.testOk=true;
        await this.loadLogs();
      } catch(e){ this.testResult=e.response?.data?.error||'Error al enviar'; this.testOk=false; }
      finally{ this.saving=false; }
    },

    formatDate(d){ if(!d) return ''; return new Date(d).toLocaleDateString('es-CO',{day:'2-digit',month:'short',year:'numeric',hour:'2-digit',minute:'2-digit'}); },
    copy(text){ navigator.clipboard.writeText(text); this.copied='Copiado'; setTimeout(()=>this.copied='', 2000); },

    getCodeExample(tab) {
      const key = this.secretKey || '{API_KEY}';
      const url = 'https://admin.u-site.app/api/sms/send';
      if (tab === 'curl') {
        return [
          "curl -X POST " + url + " \\",
          "  -H 'Authorization: Bearer " + key + "' \\",
          "  -H 'Content-Type: application/json' \\",
          "  -d '{",
          '    "numero":  "573001234567",',
          '    "mensaje": "Hola, este es tu código: 9821"',
          "  }'"
        ].join('\n');
      }
      if (tab === 'js') {
        return [
          "const response = await fetch('" + url + "', {",
          "  method: 'POST',",
          "  headers: {",
          "    'Authorization': 'Bearer " + key + "',",
          "    'Content-Type': 'application/json',",
          "  },",
          "  body: JSON.stringify({",
          "    numero:  '573001234567',",
          "    mensaje: 'Hola, este es tu código: 9821',",
          "  }),",
          "});",
          "",
          "const data = await response.json();",
          "console.log(data); // { ok: true, id: '6a3d...' }"
        ].join('\n');
      }
      if (tab === 'php') {
        return [
          "<?php",
          "$ch = curl_init('" + url + "');",
          "curl_setopt_array($ch, [",
          "  CURLOPT_RETURNTRANSFER => true,",
          "  CURLOPT_POST           => true,",
          "  CURLOPT_HTTPHEADER     => [",
          "    'Authorization: Bearer " + key + "',",
          "    'Content-Type: application/json',",
          "  ],",
          '  CURLOPT_POSTFIELDS => json_encode([',
          "    'numero'  => '573001234567',",
          "    'mensaje' => 'Hola, este es tu código: 9821',",
          "  ]),",
          "]);",
          "$response = json_decode(curl_exec($ch), true);",
          "curl_close($ch);",
          "// $response['ok'] === true"
        ].join('\n');
      }
      if (tab === 'python') {
        return [
          "import requests",
          "",
          "response = requests.post(",
          "    '" + url + "',",
          "    headers={",
          "        'Authorization': 'Bearer " + key + "',",
          "        'Content-Type': 'application/json',",
          "    },",
          "    json={",
          "        'numero':  '573001234567',",
          "        'mensaje': 'Hola, este es tu código: 9821',",
          "    },",
          ")",
          "",
          "data = response.json()",
          "print(data)  # {'ok': True, 'id': '6a3d...'}"
        ].join('\n');
      }
      return '';
    },
  }
}
</script>

<style>
.btn-primary { background:#8eb02f; color:#fff; padding:0.5rem 1rem; border-radius:0.5rem; font-weight:600; font-size:.875rem; transition:background .15s; }
.btn-primary:hover { background:#6d8c24; }
.btn-secondary { background:#f1f5f9; color:#475569; padding:0.5rem 1rem; border-radius:0.5rem; font-weight:500; font-size:.875rem; border:1px solid #e2e8f0; }
.btn-icon { display:inline-flex; align-items:center; padding:0.25rem; border-radius:0.375rem; }
.btn-icon:hover { background:#f1f5f9; }
.input-field { border:1px solid #e2e8f0; border-radius:0.5rem; padding:0.5rem 0.75rem; font-size:.875rem; outline:none; transition:border-color .15s; }
.input-field:focus { border-color:#8eb02f; }
.label { display:block; font-size:.75rem; font-weight:600; color:#475569; margin-bottom:.25rem; text-transform:uppercase; letter-spacing:.05em; }
.badge { display:inline-block; padding:.15rem .6rem; border-radius:9999px; font-size:.7rem; font-weight:600; text-transform:capitalize; }
.badge-green { background:#dcfce7; color:#15803d; }
.badge-yellow { background:#fef9c3; color:#854d0e; }
.badge-red { background:#fee2e2; color:#991b1b; }
.badge-slate { background:#f1f5f9; color:#475569; }
.text-primary { color:#8eb02f; }
</style>
