<div x-data="cuentasApp()" 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">Categorías contables</h1>
      <p class="text-sm text-slate-500 mt-1">Plan de cuentas para clasificar transacciones</p>
    </div>
    <button @click="openCreate()" class="btn-primary flex items-center gap-2">Nueva categoría</button>
  </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">Código</th>
          <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">Color</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="6" class="text-center py-10 text-slate-400">Cargando...</td></tr>
        </template>
        <template x-for="c in items" :key="c.ID">
          <tr class="hover:bg-slate-50">
            <td class="px-4 py-3 font-mono text-xs text-slate-500" x-text="c.codigo||'-'"></td>
            <td class="px-4 py-3 text-slate-700">
              <span class="inline-block w-3 h-3 rounded-full mr-2" :style="'background:'+(c.color||'#ccc')"></span>
              <span x-text="c.nombre"></span>
            </td>
            <td class="px-4 py-3">
              <span class="badge" :class="c.tipo==='ingreso'?'badge-green':'badge-red'" x-text="c.tipo"></span>
            </td>
            <td class="px-4 py-3 font-mono text-xs text-slate-500" x-text="c.color||'-'"></td>
            <td class="px-4 py-3">
              <span x-show="c.activo" class="text-green-500">Activo</span>
              <span x-show="!c.activo" class="text-red-400">Inactivo</span>
            </td>
            <td class="px-4 py-3">
              <div class="flex items-center gap-2">
                <button @click="openEdit(c)" class="btn-icon text-yellow-500">
                  <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(c)" class="btn-icon text-red-500">
                  <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>
              </div>
            </td>
          </tr>
        </template>
      </tbody>
    </table>
  </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-md mx-4 p-6">
      <h2 class="text-lg font-bold text-slate-800 mb-4" x-text="editId ? 'Editar categoría' : 'Nueva categoría'"></h2>
      <form @submit.prevent="save()">
        <div class="grid grid-cols-2 gap-3">
          <div>
            <label class="label">Código</label>
            <input x-model="form.codigo" class="input-field w-full" placeholder="ING-FAC">
          </div>
          <div>
            <label class="label">Tipo</label>
            <select x-model="form.tipo" class="input-field w-full" required>
              <option value="ingreso">Ingreso</option>
              <option value="egreso">Egreso</option>
            </select>
          </div>
          <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">Color</label>
            <input x-model="form.color" type="color" class="input-field w-full h-10">
          </div>
          <div class="flex items-center gap-2 pt-5">
            <input type="checkbox" x-model="form.activo" id="ca" class="w-4 h-4">
            <label for="ca" 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 categoría?</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 cuentasApp() {
  return {
    items:[], total:0, totalPages:1, page:1,
    loading:false, saving:false, showModal:false, showDelete:false,
    editId:null, deleteId:null, error:'',
    form:{ codigo:'', nombre:'', tipo:'egreso', color:'#3b82f6', activo:true },

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

    async load(){
      this.loading=true;
      try {
        const r=await axios.get(`/app/contabilidad/cuentas/list?page=${this.page}`);
        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={codigo:'',nombre:'',tipo:'egreso',color:'#3b82f6',activo:true}; this.showModal=true; },
    openEdit(c){
      this.editId=c.ID; this.error='';
      this.form={codigo:c.codigo||'',nombre:c.nombre,tipo:c.tipo,color:c.color||'#3b82f6',activo:c.activo};
      this.showModal=true;
    },
    async save(){
      this.saving=true; this.error='';
      try {
        if(this.editId) await axios.put(`/app/contabilidad/cuentas/${this.editId}`, this.form);
        else await axios.post('/app/contabilidad/cuentas', this.form);
        this.showModal=false; await this.load();
      } catch(e){ this.error=e.response?.data?.error||'Error al guardar'; }
      finally{ this.saving=false; }
    },
    confirmDelete(c){ this.deleteId=c.ID; this.showDelete=true; },
    async doDelete(){
      this.saving=true;
      try{ await axios.delete(`/app/contabilidad/cuentas/${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>
