<div x-data="entidadesApp()" 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">Entidades</h1>
      <p class="text-sm text-slate-500 mt-1">Clientes, proveedores y empresas</p>
    </div>
    <button @click="openCreate()" class="btn-primary flex items-center gap-2">Nueva entidad</button>
  </div>

  <div class="mb-4">
    <input x-model="search" @input.debounce.400ms="page=1;load()" type="text" placeholder="Buscar por nombre, documento..." class="input-field w-full max-w-sm">
  </div>

  <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">Tipo</th>
          <th class="px-4 py-3 text-left">Documento</th>
          <th class="px-4 py-3 text-left">Email</th>
          <th class="px-4 py-3 text-left">Teléfono</th>
          <th class="px-4 py-3 text-left">Contacto</th>
          <th class="px-4 py-3 text-left">Activo</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="8" class="text-center py-10 text-slate-400">Cargando...</td></tr>
        </template>
        <template x-for="e in items" :key="e.ID">
          <tr class="hover:bg-slate-50">
            <td class="px-4 py-3 text-slate-700 font-medium" x-text="e.nombre"></td>
            <td class="px-4 py-3"><span class="badge" :class="{'badge-green':e.tipo==='cliente','badge-blue':e.tipo==='proveedor','badge-slate':e.tipo==='ambos'}" x-text="e.tipo||'-'"></span></td>
            <td class="px-4 py-3 text-slate-600 text-xs font-mono" x-text="e.documento||'-'"></td>
            <td class="px-4 py-3 text-slate-600" x-text="e.email||'-'"></td>
            <td class="px-4 py-3 text-slate-600" x-text="e.telefono||'-'"></td>
            <td class="px-4 py-3 text-slate-600" x-text="e.contacto||'-'"></td>
            <td class="px-4 py-3"><span x-show="e.activo" class="text-green-500">Activo</span><span x-show="!e.activo" class="text-red-400">Inactivo</span></td>
            <td class="px-4 py-3">
              <div class="flex items-center gap-2">
                <button @click="openEdit(e)" class="btn-icon text-yellow-500">✏️</button>
                <button @click="confirmDelete(e)" class="btn-icon text-red-500">🗑️</button>
              </div>
            </td>
          </tr>
        </template>
      </tbody>
    </table>
  </div>

  <div class="flex justify-between items-center mt-4 text-sm text-slate-500">
    <span>Total: <strong x-text="total"></strong></span>
    <div class="flex gap-1">
      <button @click="page--;load()" :disabled="page<=1" class="px-3 py-1 rounded border border-slate-200 disabled:opacity-40">Ant</button>
      <span class="px-3 py-1" x-text="`${page} / ${totalPages||1}`"></span>
      <button @click="page++;load()" :disabled="page>=totalPages" class="px-3 py-1 rounded border border-slate-200 disabled:opacity-40">Sig</button>
    </div>
  </div>

  <!-- Modal -->
  <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-lg mx-4 p-6">
      <h2 class="text-lg font-bold text-slate-800 mb-4" x-text="editId?'Editar entidad':'Nueva entidad'"></h2>
      <form @submit.prevent="save()">
        <div class="grid grid-cols-2 gap-3">
          <div class="col-span-2">
            <label class="label">Nombre</label>
            <input x-model="form.nombre" class="input-field w-full" required>
          </div>
          <div>
            <label class="label">Tipo</label>
            <select x-model="form.tipo" class="input-field w-full">
              <option value="">Seleccionar...</option>
              <option value="cliente">Cliente</option>
              <option value="proveedor">Proveedor</option>
              <option value="ambos">Ambos</option>
            </select>
          </div>
          <div>
            <label class="label">Documento/NIT</label>
            <input x-model="form.documento" class="input-field w-full">
          </div>
          <div>
            <label class="label">Email</label>
            <input x-model="form.email" type="email" class="input-field w-full">
          </div>
          <div>
            <label class="label">Teléfono</label>
            <input x-model="form.telefono" class="input-field w-full">
          </div>
          <div>
            <label class="label">Contacto persona</label>
            <input x-model="form.contacto" class="input-field w-full">
          </div>
          <div class="col-span-2">
            <label class="label">Notas</label>
            <textarea x-model="form.notas" class="input-field w-full" rows="2"></textarea>
          </div>
          <div class="col-span-2 flex items-center gap-2">
            <input type="checkbox" x-model="form.activo" id="ea" class="w-4 h-4">
            <label for="ea" class="text-sm text-slate-600">Activo</label>
          </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>

  <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 text-slate-800 mb-2">¿Eliminar entidad?</h2>
      <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>

</div>

<script>
function entidadesApp() {
  return {
    items:[], total:0, totalPages:1, page:1, search:'',
    loading:false, saving:false, showModal:false, showDelete:false,
    editId:null, deleteId:null, error:'',
    form:{ nombre:'', tipo:'', documento:'', email:'', telefono:'', contacto:'', notas:'', activo:true },

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

    async load(){
      this.loading=true;
      try {
        const r=await axios.get(`/app/contabilidad/entidades?page=${this.page}&search=${encodeURIComponent(this.search)}`);
        this.items=r.data.items; this.total=r.data.total; this.totalPages=r.data.totalPages;
      } finally{ this.loading=false; }
    },

    openCreate(){ this.editId=null; this.error=''; this.form={nombre:'',tipo:'',documento:'',email:'',telefono:'',contacto:'',notas:'',activo:true}; this.showModal=true; },
    openEdit(e){
      this.editId=e.ID; this.error='';
      this.form={nombre:e.nombre,tipo:e.tipo||'',documento:e.documento||'',email:e.email||'',telefono:e.telefono||'',contacto:e.contacto||'',notas:e.notas||'',activo:e.activo};
      this.showModal=true;
    },
    async save(){
      this.saving=true; this.error='';
      try {
        if(this.editId) await axios.put(`/app/contabilidad/entidades/${this.editId}`, this.form);
        else await axios.post('/app/contabilidad/entidades', this.form);
        this.showModal=false; await this.load();
      } catch(e){ this.error=e.response?.data?.error||'Error al guardar'; }
      finally{ this.saving=false; }
    },
    confirmDelete(e){ this.deleteId=e.ID; this.showDelete=true; },
    async doDelete(){
      this.saving=true;
      try{ await axios.delete(`/app/contabilidad/entidades/${this.deleteId}`); this.showDelete=false; await this.load(); }
      finally{ this.saving=false; }
    },
  }
}
</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-danger { background:#ef4444; color:#fff; padding:0.5rem 1rem; border-radius:0.5rem; font-weight:600; font-size:.875rem; }
.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-blue { background:#dbeafe; color:#1d4ed8; }
.badge-slate { background:#f1f5f9; color:#475569; }
.badge-red { background:#fee2e2; color:#991b1b; }
.text-primary { color:#8eb02f; }
</style>
