<div x-data="portalUsuariosApp()" x-init="init()" class="p-6">

  <div class="flex items-center justify-between mb-6">
    <div>
      <h1 class="text-2xl font-bold text-slate-800">Usuarios del Portal</h1>
      <p class="text-sm text-slate-500 mt-1">Accesos del portal de clientes</p>
    </div>
    <button @click="openCreate()" class="btn-primary flex items-center gap-2">
      <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="M12 4v16m8-8H4"/></svg>
      Nuevo usuario
    </button>
  </div>

  <!-- Tabla -->
  <div class="bg-white rounded-xl shadow-sm border border-slate-200 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-4 py-3 text-left">Nombre</th>
          <th class="px-4 py-3 text-left">Email</th>
          <th class="px-4 py-3 text-left">Rol</th>
          <th class="px-4 py-3 text-left">Cliente / Accesos</th>
          <th class="px-4 py-3 text-left">Estado</th>
          <th class="px-4 py-3 text-left">Telegram</th>
          <th class="px-4 py-3 text-left">Acciones</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-slate-100">
        <template x-if="loading">
          <tr><td colspan="6" class="text-center py-10 text-slate-400">Cargando...</td></tr>
        </template>
        <template x-for="u in items" :key="u.ID">
          <tr class="hover:bg-slate-50">
            <td class="px-4 py-3 font-medium text-slate-800" x-text="u.nombre"></td>
            <td class="px-4 py-3 text-slate-600" x-text="u.email"></td>
            <td class="px-4 py-3">
              <span class="badge" :class="u.rol==='partner' ? 'badge-blue' : 'badge-green'" x-text="u.rol"></span>
            </td>
            <td class="px-4 py-3 text-slate-500 text-xs">
              <template x-if="u.rol==='cliente' && u.cliente">
                <span x-text="u.cliente?.empresa || u.cliente?.nombre"></span>
              </template>
              <template x-if="u.rol==='partner'">
                <div class="flex flex-wrap gap-1">
                  <template x-for="acc in (u.portal_accesos||[])" :key="acc.ID">
                    <span class="bg-slate-100 px-2 py-0.5 rounded text-xs flex items-center gap-1">
                      <span x-text="acc.cliente?.empresa || acc.cliente?.nombre || acc.cliente_id"></span>
                      <button @click="removeAcceso(u, acc.cliente_id)" class="text-red-400 hover:text-red-600 ml-1">&times;</button>
                    </span>
                  </template>
                  <button @click="openAddAcceso(u)" class="text-primary text-xs hover:underline">+ Agregar</button>
                </div>
              </template>
            </td>
            <td class="px-4 py-3">
              <span :class="u.activo ? 'badge-green' : 'badge-slate'" class="badge" x-text="u.activo ? 'Activo' : 'Inactivo'"></span>
            </td>
            <td class="px-4 py-3 text-slate-500 text-xs">
              <span x-show="u.telegram_chat_id" x-text="u.telegram_chat_id" class="font-mono"></span>
              <span x-show="!u.telegram_chat_id" class="text-slate-300">—</span>
            </td>
            <td class="px-4 py-3 flex gap-2">
              <button @click="openDetail(u)" class="btn-icon text-blue-500" title="Ver detalle">
                <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>
              <button @click="openEdit(u)" class="btn-icon text-yellow-500" title="Editar">
                <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="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>
              <button @click="confirmDelete(u)" class="btn-icon text-red-500" title="Eliminar">
                <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
              </button>
            </td>
          </tr>
        </template>
      </tbody>
    </table>
  </div>

  <!-- Modal crear/editar -->
  <div x-show="showModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
    <div @click.outside="showModal=false" class="bg-white rounded-2xl shadow-2xl w-full max-w-md mx-4 p-6">
      <h2 class="text-lg font-bold mb-4" x-text="editId ? 'Editar usuario' : 'Nuevo usuario'"></h2>
      <form @submit.prevent="save()">
        <div class="space-y-3">
          <div><label class="label">Nombre</label><input x-model="form.nombre" class="input-field w-full" required></div>
          <div><label class="label">Email</label><input x-model="form.email" type="email" class="input-field w-full" required></div>
          <div>
            <label class="label">Contraseña <span class="normal-case font-normal text-slate-400" x-show="editId">(dejar vacío para no cambiar)</span></label>
            <input x-model="form.password" type="password" class="input-field w-full" :required="!editId">
          </div>
          <div>
            <label class="label">Rol</label>
            <select x-model="form.rol" class="input-field w-full">
              <option value="cliente">Cliente</option>
              <option value="partner">Partner</option>
            </select>
          </div>
          <div x-show="form.rol==='cliente'">
            <label class="label">Cliente asignado</label>
            <select x-model.number="form.cliente_id" class="input-field w-full">
              <option value="">Sin asignar</option>
              <template x-for="c in clientes" :key="c.ID">
                <option :value="c.ID" x-text="c.empresa || c.nombre"></option>
              </template>
            </select>
          </div>
          <div>
            <label class="label">Activo</label>
            <input type="checkbox" x-model="form.activo" class="w-4 h-4">
          </div>
          <div><label class="label">Notas</label><textarea x-model="form.notas" class="input-field w-full" rows="2"></textarea></div>
          <div><label class="label">Chat ID de Telegram</label><input x-model="form.telegram_chat_id" class="input-field w-full font-mono" placeholder="Ej: 123456789"><p class="text-xs text-slate-400 mt-1">Se usa para enviar notificaciones al usuario vía Telegram.</p></div>
          <div><label class="label">Sitio Web</label><input x-model="form.sitio_web" class="input-field w-full" type="url" placeholder="https://ejemplo.com"><p class="text-xs text-slate-400 mt-1">Sitio web del partner o cliente.</p></div>
          <!-- Contacto -->
          <div>
            <label class="label">Teléfono</label>
            <div class="flex gap-2">
              <select x-model="form.indicativo" class="input-field w-28">
                <option value="">Indicativo</option>
                <option value="+57">🇨🇴 +57</option>
                <option value="+1">🇺🇸 +1</option>
                <option value="+52">🇲🇽 +52</option>
                <option value="+54">🇦🇷 +54</option>
                <option value="+56">🇨🇱 +56</option>
                <option value="+51">🇵🇪 +51</option>
                <option value="+58">🇻🇪 +58</option>
                <option value="+593">🇪🇨 +593</option>
                <option value="+34">🇪🇸 +34</option>
                <option value="+55">🇧🇷 +55</option>
                <option value="+44">🇬🇧 +44</option>
                <option value="+1-other">Otro +1</option>
              </select>
              <input x-model="form.telefono" type="tel" class="input-field flex-1" placeholder="Número de teléfono">
            </div>
          </div>
          <div class="grid grid-cols-2 gap-3">
            <div><label class="label">País</label><input x-model="form.pais" class="input-field w-full" placeholder="Ej: Colombia"></div>
            <div><label class="label">Ciudad</label><input x-model="form.ciudad" class="input-field w-full" placeholder="Ej: Bogotá"></div>
          </div>
        </div>
        <p x-show="error" x-text="error" class="text-red-500 text-sm mt-3"></p>
        <div class="flex justify-end gap-3 mt-5">
          <button type="button" @click="showModal=false" class="btn-secondary">Cancelar</button>
          <button type="submit" :disabled="saving" class="btn-primary" x-text="saving?'Guardando...':'Guardar'"></button>
        </div>
      </form>
    </div>
  </div>

  <!-- Modal agregar acceso (partner) -->
  <div x-show="showAccesoModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
    <div @click.outside="showAccesoModal=false" class="bg-white rounded-2xl shadow-2xl w-full max-w-sm mx-4 p-6">
      <h2 class="text-lg font-bold mb-4">Agregar acceso a cliente</h2>
      <label class="label">Cliente</label>
      <select x-model.number="accesoClienteId" class="input-field w-full mb-4">
        <option value="">Seleccionar...</option>
        <template x-for="c in clientes" :key="c.ID">
          <option :value="c.ID" x-text="c.empresa || c.nombre"></option>
        </template>
      </select>
      <div class="flex justify-end gap-3">
        <button @click="showAccesoModal=false" class="btn-secondary">Cancelar</button>
        <button @click="addAcceso()" :disabled="!accesoClienteId" class="btn-primary">Agregar</button>
      </div>
    </div>
  </div>

  <!-- Modal eliminar -->
  <div x-show="showDelete" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
    <div @click.outside="showDelete=false" class="bg-white rounded-2xl shadow-2xl w-full max-w-sm mx-4 p-6">
      <h2 class="text-lg font-bold mb-2">¿Eliminar usuario?</h2>
      <p class="text-slate-500 text-sm mb-5">Se revocará el acceso al portal.</p>
      <div class="flex justify-end gap-3">
        <button @click="showDelete=false" class="btn-secondary">Cancelar</button>
        <button @click="doDelete()" :disabled="saving" class="btn-danger" x-text="saving?'Eliminando...':'Eliminar'"></button>
      </div>
    </div>
  </div>

  <!-- Modal enviar credenciales -->
  <div x-show="showCredModal" x-cloak class="fixed inset-0 z-[60] flex items-center justify-center bg-black/40">
    <div @click.outside="showCredModal=false" class="bg-white rounded-2xl shadow-2xl w-full max-w-sm mx-4 p-6">
      <div class="flex items-center gap-3 mb-4">
        <div class="w-10 h-10 rounded-full bg-[#8eb02f]/15 flex items-center justify-center flex-shrink-0">
          <svg class="w-5 h-5 text-[#6d8c24]" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
        </div>
        <div>
          <h2 class="text-base font-bold text-slate-800">Enviar credenciales de acceso</h2>
          <p class="text-xs text-slate-500" x-text="credEmail"></p>
        </div>
      </div>
      <p class="text-sm text-slate-600 mb-4">Se enviará un correo de bienvenida a <strong x-text="credNombre"></strong> con el enlace al portal y sus datos de inicio de sesión.</p>
      <div class="mb-4">
        <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1">Contraseña a incluir en el correo</label>
        <input x-model="credPassword" type="text" placeholder="Déjalo vacío para omitirla"
          class="input-field w-full font-mono">
        <p class="text-xs text-slate-400 mt-1">Si la dejas vacía se indicará al usuario que use la contraseña que configuraste.</p>
      </div>
      <p x-show="credMsg" x-text="credMsg"
         :class="credOk ? 'text-green-600 bg-green-50 border border-green-200' : 'text-red-600 bg-red-50 border border-red-200'"
         class="text-sm rounded-lg px-3 py-2 mb-3"></p>
      <div class="flex justify-end gap-3">
        <button @click="showCredModal=false" class="btn-secondary">Cancelar</button>
        <button @click="enviarCredenciales()" :disabled="credSending"
          class="btn-primary flex items-center gap-2"
          x-text="credSending ? 'Enviando...' : 'Enviar correo'"></button>
      </div>
    </div>
  </div>

  <!-- Panel detalle usuario (slide derecho) -->
  <div x-show="showDetail" x-cloak class="fixed inset-0 z-50 flex justify-end">
    <div class="absolute inset-0 bg-black/40" @click="showDetail=false"></div>
    <div class="relative w-full max-w-md bg-white shadow-2xl flex flex-col overflow-hidden"
         x-transition:enter="transition ease-out duration-300"
         x-transition:enter-start="translate-x-full opacity-0"
         x-transition:enter-end="translate-x-0 opacity-100"
         x-transition:leave="transition ease-in duration-200"
         x-transition:leave-start="translate-x-0 opacity-100"
         x-transition:leave-end="translate-x-full opacity-0">

      <!-- Header -->
      <div class="flex items-center justify-between px-5 py-4 border-b border-slate-200 flex-shrink-0">
        <h2 class="text-base font-bold text-slate-800">Detalle del usuario</h2>
        <button @click="showDetail=false" class="p-1.5 rounded-lg hover:bg-slate-100 text-slate-400 hover:text-slate-600">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
        </button>
      </div>

      <!-- Loading -->
      <div x-show="loadingDetail" class="flex-1 flex items-center justify-center">
        <p class="text-slate-400 text-sm">Cargando…</p>
      </div>

      <!-- Contenido -->
      <div x-show="detailUser && !loadingDetail" class="flex-1 overflow-y-auto px-5 py-5 space-y-4">

        <!-- Avatar + nombre -->
        <div class="flex items-center gap-3 pb-4 border-b border-slate-100">
          <div class="w-12 h-12 rounded-full bg-primary/20 flex items-center justify-center text-[#8eb02f] font-bold text-xl flex-shrink-0"
               x-text="detailUser?.nombre?.charAt(0)?.toUpperCase()"></div>
          <div>
            <p class="font-semibold text-slate-800 text-base" x-text="detailUser?.nombre"></p>
            <p class="text-sm text-slate-500" x-text="detailUser?.email"></p>
          </div>
        </div>

        <!-- Badges -->
        <div class="flex items-center gap-2 flex-wrap">
          <span class="badge" :class="detailUser?.rol==='partner' ? 'badge-blue' : 'badge-green'" x-text="detailUser?.rol"></span>
          <span class="badge" :class="detailUser?.activo ? 'badge-green' : 'badge-slate'" x-text="detailUser?.activo ? 'Activo' : 'Inactivo'"></span>
          <span x-show="detailUser?.role" class="badge badge-slate" x-text="detailUser?.role?.display_name || detailUser?.role?.name"></span>
        </div>

        <!-- Sección: Contacto -->
        <div class="pt-2">
          <p class="text-xs font-bold text-slate-400 uppercase tracking-widest mb-2">Contacto</p>
          <div class="grid grid-cols-2 gap-x-4 gap-y-3">
            <div class="col-span-2">
              <p class="label">Teléfono</p>
              <p class="text-sm text-slate-700"
                 x-text="(detailUser?.indicativo || '') + ' ' + (detailUser?.telefono || '') || '—'"
                 :class="!(detailUser?.telefono) && 'text-slate-300'"></p>
            </div>
            <div>
              <p class="label">País</p>
              <p class="text-sm" :class="detailUser?.pais ? 'text-slate-700' : 'text-slate-300'"
                 x-text="detailUser?.pais || '—'"></p>
            </div>
            <div>
              <p class="label">Ciudad</p>
              <p class="text-sm" :class="detailUser?.ciudad ? 'text-slate-700' : 'text-slate-300'"
                 x-text="detailUser?.ciudad || '—'"></p>
            </div>
            <div>
              <p class="label">Sitio Web</p>
              <template x-if="detailUser?.sitio_web">
                <a :href="detailUser.sitio_web" target="_blank" rel="noopener noreferrer"
                   class="text-sm text-[#8eb02f] hover:underline break-all" x-text="detailUser.sitio_web"></a>
              </template>
              <template x-if="!detailUser?.sitio_web">
                <p class="text-sm text-slate-300">—</p>
              </template>
            </div>
          </div>
        </div>

        <!-- Sección: Empresa / Legal -->
        <div class="pt-3 border-t border-slate-100">
          <p class="text-xs font-bold text-slate-400 uppercase tracking-widest mb-2">Empresa / Legal</p>
          <div class="grid grid-cols-2 gap-x-4 gap-y-3">
            <div>
              <p class="label">Empresa</p>
              <p class="text-sm" :class="detailUser?.empresa ? 'text-slate-700' : 'text-slate-300'"
                 x-text="detailUser?.empresa || '—'"></p>
            </div>
            <div>
              <p class="label">NIT / Documento</p>
              <p class="text-sm font-mono" :class="detailUser?.documento ? 'text-slate-700' : 'text-slate-300'"
                 x-text="detailUser?.documento || '—'"></p>
            </div>
            <div x-show="detailUser?.rol==='cliente'" class="col-span-2">
              <p class="label">Cliente asignado</p>
              <p class="text-sm" :class="detailUser?.cliente ? 'text-slate-700' : 'text-slate-300'"
                 x-text="detailUser?.cliente?.empresa || detailUser?.cliente?.nombre || '—'"></p>
            </div>
          </div>
        </div>

        <!-- Sección: Canales -->
        <div class="pt-3 border-t border-slate-100">
          <p class="text-xs font-bold text-slate-400 uppercase tracking-widest mb-2">Canales</p>
          <div class="grid grid-cols-2 gap-x-4 gap-y-3">
            <div class="col-span-2">
              <p class="label">Telegram Chat ID</p>
              <p class="text-sm font-mono" :class="detailUser?.telegram_chat_id ? 'text-slate-700' : 'text-slate-300'"
                 x-text="detailUser?.telegram_chat_id || '—'"></p>
            </div>
          </div>
        </div>

        <!-- Sección: Notas -->
        <div class="pt-3 border-t border-slate-100">
          <p class="text-xs font-bold text-slate-400 uppercase tracking-widest mb-2">Notas internas</p>
          <p class="text-sm whitespace-pre-wrap" :class="detailUser?.notas ? 'text-slate-600' : 'text-slate-300'"
             x-text="detailUser?.notas || 'Sin notas'"></p>
        </div>

        <!-- Sección: Documento RUT -->
        <div class="pt-3 border-t border-slate-100">
          <p class="text-xs font-bold text-slate-400 uppercase tracking-widest mb-2">Documento RUT / Cámara de comercio</p>
          <template x-if="detailUser?.documento_rut_file">
            <div class="flex items-center gap-2">
              <svg class="w-4 h-4 text-slate-400 flex-shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
              <span class="text-sm text-slate-600 truncate" x-text="detailUser?.documento_rut_nombre || 'Archivo RUT'"></span>
              <a :href="`/app/portal-usuarios/${detailUser?.ID}/rut-file`" target="_blank"
                 class="text-[#8eb02f] text-xs font-semibold hover:underline flex-shrink-0">Descargar</a>
            </div>
          </template>
          <template x-if="!detailUser?.documento_rut_file">
            <p class="text-sm text-slate-300">Sin archivo adjunto</p>
          </template>
        </div>

        <!-- Sección: Accesos partner -->
        <div x-show="detailUser?.rol==='partner'" class="pt-3 border-t border-slate-100">
          <p class="text-xs font-bold text-slate-400 uppercase tracking-widest mb-2">Accesos de cliente</p>
          <div class="flex flex-wrap gap-1">
            <template x-for="acc in (detailUser?.portal_accesos || [])" :key="acc.ID">
              <span class="bg-slate-100 text-slate-600 px-2 py-0.5 rounded text-xs"
                    x-text="acc.cliente?.empresa || acc.cliente?.nombre || acc.cliente_id"></span>
            </template>
            <span x-show="!(detailUser?.portal_accesos?.length)" class="text-slate-300 text-xs">Sin accesos asignados</span>
          </div>
        </div>

        <!-- Fecha de registro -->
        <div class="pt-3 border-t border-slate-100 text-xs text-slate-400">
          Registrado: <span x-text="detailUser?.CreatedAt ? new Date(detailUser.CreatedAt).toLocaleDateString('es-CO', {year:'numeric',month:'long',day:'numeric'}) : '—'"></span>
        </div>
      </div>

      <!-- Footer -->
      <div x-show="detailUser && !loadingDetail" class="flex-shrink-0 px-5 py-4 border-t border-slate-200 bg-slate-50 flex gap-2 flex-wrap">
        <button @click="openEdit(detailUser); showDetail=false;" class="btn-secondary flex-1">Editar</button>
        <button @click="openCredModal(detailUser)" class="flex-1 flex items-center justify-center gap-1.5 text-sm font-semibold px-3 py-2 rounded-lg border border-[#8eb02f] text-[#6d8c24] hover:bg-[#8eb02f]/10 transition-colors">
          <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="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
          Enviar accesos
        </button>
        <button @click="showDetail=false" class="btn-primary flex-1">Cerrar</button>
      </div>

    </div>
  </div>

</div>

<script>
function portalUsuariosApp() {
  return {
    items: [], clientes: [], loading: false, saving: false,
    showModal: false, showDelete: false, showAccesoModal: false,
    showDetail: false, detailUser: null, loadingDetail: false,
    editId: null, deleteId: null, error: '',
    accesoUserId: null, accesoClienteId: '',
    showCredModal: false, credUserId: null, credNombre: '', credEmail: '', credPassword: '', credSending: false, credMsg: '', credOk: false,
    form: { nombre:'', email:'', password:'', rol:'cliente', cliente_id:'', activo:true, notas:'', telegram_chat_id:'', sitio_web:'', telefono:'', indicativo:'', pais:'', ciudad:'' },

    async init() { await this.load(); },

    async load() {
      this.loading = true;
      try {
        const r = await axios.get('/app/loadportalusuarios');
        this.items = r.data.items || [];
        this.clientes = r.data.clientes || [];
      } finally { this.loading = false; }
    },

    async openDetail(u) {
      this.detailUser = null;
      this.loadingDetail = true;
      this.showDetail = true;
      try {
        const r = await axios.get(`/app/loadportalusuarios/${u.ID}`);
        this.detailUser = r.data;
      } catch(e) {
        this.showDetail = false;
      } finally {
        this.loadingDetail = false;
      }
    },

    openCreate() {
      this.editId=null; this.error='';
      this.form={nombre:'',email:'',password:'',rol:'cliente',cliente_id:'',activo:true,notas:'',telegram_chat_id:'',sitio_web:'',telefono:'',indicativo:'',pais:'',ciudad:''};
      this.showModal=true;
    },
    openEdit(u) {
      this.editId=u.ID; this.error='';
      this.form={nombre:u.nombre,email:u.email,password:'',rol:u.rol,cliente_id:u.cliente_id||'',activo:u.activo,notas:u.notas||'',telegram_chat_id:u.telegram_chat_id||'',sitio_web:u.sitio_web||'',telefono:u.telefono||'',indicativo:u.indicativo||'',pais:u.pais||'',ciudad:u.ciudad||''};
      this.showModal=true;
    },
    async save() {
      this.saving=true; this.error='';
      const payload={...this.form};
      const plainPassword = payload.password;
      if(payload.cliente_id==='') payload.cliente_id=null;
      try {
        if(this.editId) {
          await axios.put(`/app/portal-usuarios/${this.editId}`, payload);
          this.showModal=false;
        } else {
          const r = await axios.post('/app/portal-usuarios', payload);
          this.showModal=false;
          // Ofrecer envío de credenciales al crear
          this.credUserId = r.data.ID;
          this.credNombre = r.data.nombre;
          this.credEmail = r.data.email;
          this.credPassword = plainPassword;
          this.credMsg = ''; this.credOk = false;
          this.showCredModal = true;
        }
        await this.load();
      } catch(e) { this.error=e.response?.data?.error||'Error al guardar'; }
      finally { this.saving=false; }
    },
    openCredModal(u) {
      this.credUserId = u.ID;
      this.credNombre = u.nombre;
      this.credEmail = u.email;
      this.credPassword = '';
      this.credMsg = ''; this.credOk = false;
      this.showCredModal = true;
    },
    async enviarCredenciales() {
      this.credSending = true; this.credMsg = '';
      try {
        const r = await axios.post(`/app/portal-usuarios/${this.credUserId}/send-credentials`, { password: this.credPassword });
        this.credMsg = '✅ ' + (r.data.message || 'Correo enviado correctamente.');
        this.credOk = true;
      } catch(e) {
        this.credMsg = e.response?.data?.error || 'Error al enviar el correo.';
        this.credOk = false;
      } finally { this.credSending = false; }
    },
    confirmDelete(u) { this.deleteId=u.ID; this.showDelete=true; },
    async doDelete() {
      this.saving=true;
      try { await axios.delete(`/app/portal-usuarios/${this.deleteId}`); this.showDelete=false; await this.load(); }
      finally { this.saving=false; }
    },

    openAddAcceso(u) { this.accesoUserId=u.ID; this.accesoClienteId=''; this.showAccesoModal=true; },
    async addAcceso() {
      await axios.post(`/app/portal-usuarios/${this.accesoUserId}/acceso`, {cliente_id: this.accesoClienteId});
      this.showAccesoModal=false; await this.load();
    },
    async removeAcceso(u, clienteId) {
      if(!confirm('¿Quitar acceso a este cliente?')) return;
      await axios.delete(`/app/portal-usuarios/${u.ID}/acceso/${clienteId}`);
      await this.load();
    },
  }
}
</script>

<style>
.btn-primary{background:#8eb02f;color:#fff;padding:.5rem 1rem;border-radius:.5rem;font-weight:600;font-size:.875rem;}
.btn-primary:hover{background:#6d8c24;}
.btn-secondary{background:#f1f5f9;color:#475569;padding:.5rem 1rem;border-radius:.5rem;font-weight:500;font-size:.875rem;border:1px solid #e2e8f0;}
.btn-danger{background:#ef4444;color:#fff;padding:.5rem 1rem;border-radius:.5rem;font-weight:600;font-size:.875rem;}
.btn-icon{display:inline-flex;align-items:center;padding:.25rem;border-radius:.375rem;}
.btn-icon:hover{background:#f1f5f9;}
.input-field{border:1px solid #e2e8f0;border-radius:.5rem;padding:.5rem .75rem;font-size:.875rem;outline:none;}
.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-blue{background:#dbeafe;color:#1d4ed8;}
.badge-slate{background:#f1f5f9;color:#475569;}
.text-primary{color:#8eb02f;}
</style>
