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

  <!-- Header -->
  <div class="flex items-center justify-between mb-6">
    <div>
      <h1 class="text-2xl font-bold text-slate-800">Proyectos</h1>
      <p class="text-sm text-slate-500 mt-1">Gestión de proyectos 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 proyecto
    </button>
  </div>

  <!-- Buscador -->
  <div class="mb-4 flex gap-3">
    <input x-model="search" @input.debounce.400ms="page=1;load()" type="text" placeholder="Buscar proyecto..." class="input-field w-full max-w-sm">
  </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">Color</th>
          <th class="px-4 py-3 text-left">Nombre</th>
          <th class="px-4 py-3 text-left">Cliente</th>
          <th class="px-4 py-3 text-left">Estado</th>
          <th class="px-4 py-3 text-left">Progreso</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-if="!loading && items.length === 0">
          <tr><td colspan="6" class="text-center py-10 text-slate-400">Sin proyectos</td></tr>
        </template>
        <template x-for="p in items" :key="p.ID">
          <tr class="hover:bg-slate-50">
            <td class="px-4 py-3">
              <span class="w-5 h-5 rounded-full inline-block border border-slate-200" :style="`background:${p.color}`"></span>
            </td>
            <td class="px-4 py-3 font-medium text-slate-800">
              <a :href="`/app/proyectos/${p.ID}/detalle`" class="hover:underline text-primary" x-text="p.nombre"></a>
            </td>
            <td class="px-4 py-3 text-slate-600" x-text="p.cliente?.empresa || p.cliente?.nombre || '-'"></td>
            <td class="px-4 py-3">
              <span class="badge" :class="{
                'badge-green': p.estado==='activo',
                'badge-yellow': p.estado==='pausado',
                'badge-slate': p.estado==='completado',
                'badge-red': p.estado==='cancelado'
              }" x-text="p.estado"></span>
            </td>
            <td class="px-4 py-3">
              <div class="flex items-center gap-2">
                <div class="w-24 bg-slate-200 rounded-full h-2">
                  <div class="h-2 rounded-full" style="background:#8eb02f" :style="`width:${p.progreso||0}%`"></div>
                </div>
                <span class="text-xs text-slate-500" x-text="`${p.progreso||0}%`"></span>
              </div>
            </td>
            <td class="px-4 py-3 flex items-center gap-2">
              <a :href="`/app/proyectos/${p.ID}/detalle`" class="btn-icon text-blue-500" title="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>
              </a>
              <button @click="openEdit(p)" 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(p)" 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>

  <!-- Paginación -->
  <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 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-lg mx-4 p-6">
      <h2 class="text-lg font-bold text-slate-800 mb-4" x-text="editId ? 'Editar proyecto' : 'Nuevo proyecto'"></h2>
      <form @submit.prevent="save()">
        <div class="grid grid-cols-2 gap-4">
          <div class="col-span-2">
            <label class="label">Cliente</label>
            <select x-model="form.cliente_id" class="input-field w-full" required>
              <option value="">Seleccionar cliente</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 class="col-span-2">
            <label class="label">Nombre</label>
            <input x-model="form.nombre" type="text" class="input-field w-full" required placeholder="Nombre del proyecto">
          </div>
          <div>
            <label class="label">Slug</label>
            <input x-model="form.slug" type="text" class="input-field w-full" placeholder="se genera automático">
          </div>
          <div>
            <label class="label">Color</label>
            <input x-model="form.color" type="color" class="h-10 w-full rounded border border-slate-200 cursor-pointer">
          </div>
          <div class="col-span-2">
            <label class="label">Descripción</label>
            <textarea x-model="form.descripcion" class="input-field w-full" rows="2"></textarea>
          </div>
          <div>
            <label class="label">Estado</label>
            <select x-model="form.estado" class="input-field w-full">
              <option value="activo">Activo</option>
              <option value="pausado">Pausado</option>
              <option value="completado">Completado</option>
              <option value="cancelado">Cancelado</option>
            </select>
          </div>
          <div>
            <label class="label">Progreso (%)</label>
            <input x-model.number="form.progreso" type="number" min="0" max="100" class="input-field w-full">
          </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 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 text-slate-800 mb-2">¿Eliminar proyecto?</h2>
      <p class="text-slate-600 text-sm mb-5">Esta acción no se puede deshacer. Se eliminarán todas las fases, avances, entregables y tickets asociados.</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>

</div>

<script>
function proyectosApp() {
  return {
    items: [], clientes: [], total: 0, totalPages: 1, page: 1, search: '',
    loading: false, saving: false, showModal: false, showDelete: false,
    editId: null, deleteId: null, error: '',
    form: { cliente_id: '', nombre: '', slug: '', descripcion: '', color: '#8eb02f', estado: 'activo', progreso: 0 },

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

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

    openCreate() {
      this.editId = null;
      this.error = '';
      this.form = { cliente_id: '', nombre: '', slug: '', descripcion: '', color: '#8eb02f', estado: 'activo', progreso: 0 };
      this.showModal = true;
    },

    openEdit(p) {
      this.editId = p.ID;
      this.error = '';
      this.form = { cliente_id: p.cliente_id, nombre: p.nombre, slug: p.slug, descripcion: p.descripcion||'', color: p.color||'#8eb02f', estado: p.estado, progreso: p.progreso||0 };
      this.showModal = true;
    },

    async save() {
      this.saving = true; this.error = '';
      try {
        if (this.editId) {
          await axios.put(`/app/proyectos/${this.editId}`, this.form);
        } else {
          await axios.post('/app/proyectos', this.form);
        }
        this.showModal = false;
        await this.load();
      } catch(e) {
        this.error = e.response?.data?.error || 'Error al guardar';
      } finally { this.saving = false; }
    },

    confirmDelete(p) { this.deleteId = p.ID; this.showDelete = true; },

    async doDelete() {
      this.saving = true;
      try {
        await axios.delete(`/app/proyectos/${this.deleteId}`);
        this.showDelete = false;
        await this.load();
      } catch(e) {
        alert(e.response?.data?.error || 'Error al eliminar');
      } 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-slate { background:#f1f5f9; color:#475569; }
.badge-red { background:#fee2e2; color:#991b1b; }
.text-primary { color:#8eb02f; }
</style>
