<!-- Portal Proyecto Detalle -->
<div x-data="portalProyecto()" x-init="init()">

  <!-- Header -->
  <div class="flex items-center gap-3 mb-6">
    <a href="/portal/dashboard" class="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="M15 19l-7-7 7-7"/></svg>
    </a>
    <span class="w-4 h-4 rounded-full border" style="background:{{ .proyecto.Color }}"></span>
    <div>
      <h1 class="text-xl font-bold text-slate-800">{{ .proyecto.Nombre }}</h1>
      <p class="text-xs text-slate-400">{{ .proyecto.Descripcion }}</p>
    </div>
    <div class="ml-auto">
      <div class="flex items-center gap-2">
        <div class="w-32 bg-slate-200 rounded-full h-2">
          <div class="h-2 rounded-full" style="background:{{ .proyecto.Color }};width:{{ .proyecto.Progreso }}%"></div>
        </div>
        <span class="text-sm font-bold text-slate-700">{{ .proyecto.Progreso }}%</span>
      </div>
      <p class="text-xs text-slate-400 mt-1 text-right capitalize">{{ .proyecto.Estado }}</p>
    </div>
  </div>

  <!-- Tabs -->
  <div class="flex border-b border-slate-200 mb-6 gap-0 overflow-x-auto">
    <template x-for="tab in ['Roadmap','Avances','Entregables','Documentos','Tickets','Facturas']" :key="tab">
      <button @click="activeTab=tab; if(tab==='Tickets') marcarTicketsPendientesLeidos(); if(tab==='Facturas') marcarFacturasLeidas()" class="relative px-4 py-2 text-sm whitespace-nowrap border-b-2 -mb-px transition-colors"
        :class="activeTab===tab ? 'font-semibold border-[#8eb02f] text-[#8eb02f]' : 'border-transparent text-slate-500 hover:text-slate-700'">
        <span x-text="tab"></span>
        <template x-if="tab === 'Tickets' && ticketsNoLeidos > 0">
          <span class="absolute -top-1 -right-1 min-w-[18px] h-[18px] bg-red-500 text-white text-[10px] font-bold rounded-full flex items-center justify-center px-1" x-text="ticketsNoLeidos > 9 ? '9+' : ticketsNoLeidos"></span>
        </template>
        <template x-if="tab === 'Facturas' && facturasNoLeidas > 0">
          <span class="absolute -top-1 -right-1 min-w-[18px] h-[18px] bg-amber-500 text-white text-[10px] font-bold rounded-full flex items-center justify-center px-1" x-text="facturasNoLeidas > 9 ? '9+' : facturasNoLeidas"></span>
        </template>
      </button>
    </template>
  </div>

  <!-- ─── ROADMAP ────────────────────────────────────────────────────────────── -->
  <div x-show="activeTab==='Roadmap'" x-cloak>
    <div class="relative">
      <!-- Línea vertical -->
      <div class="absolute left-6 top-0 bottom-0 w-0.5 bg-slate-200"></div>

      <div class="space-y-0">
        {{ range $i, $f := .fases }}
        <div class="relative flex items-start gap-4 pb-6">
          <!-- Dot -->
          <div class="relative z-10 flex-shrink-0">
            {{ if eq $f.Estado "completado" }}
            <div class="w-12 h-12 rounded-full flex items-center justify-center text-white font-bold text-sm" style="background:#8eb02f">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"/></svg>
            </div>
            {{ else if eq $f.Estado "en_progreso" }}
            <div class="w-12 h-12 rounded-full flex items-center justify-center font-bold text-sm border-2 border-[#8eb02f] text-[#8eb02f] bg-white">
              {{ $f.Orden }}
            </div>
            {{ else }}
            <div class="w-12 h-12 rounded-full flex items-center justify-center font-bold text-sm border-2 border-slate-200 text-slate-400 bg-white">
              {{ $f.Orden }}
            </div>
            {{ end }}
          </div>
          <!-- Contenido -->
          <div class="flex-1 bg-white rounded-xl border border-slate-200 p-4 mt-1">
            <div class="flex items-start justify-between">
              <div>
                <div class="flex items-center gap-2 mb-1">
                  <h3 class="font-semibold text-slate-800 text-sm">{{ $f.Nombre }}</h3>
                  <span class="text-xs px-2 py-0.5 rounded-full capitalize font-medium
                    {{ if eq $f.Estado "completado" }}bg-green-100 text-green-700
                    {{ else if eq $f.Estado "en_progreso" }}bg-yellow-100 text-yellow-700
                    {{ else if eq $f.Estado "bloqueado" }}bg-red-100 text-red-700
                    {{ else }}bg-slate-100 text-slate-500{{ end }}">
                    {{ $f.Estado }}
                  </span>
                </div>
                <p class="text-xs text-slate-500">{{ $f.Descripcion }}</p>
              </div>
              {{ if $f.FechaEstimada }}
              <span class="text-xs text-slate-400 flex-shrink-0 ml-3">
                Est: {{ $f.FechaEstimada.Format "02 Jan 2006" }}
              </span>
              {{ end }}
            </div>
          </div>
        </div>
        {{ end }}
        {{ if not .fases }}
        <p class="text-slate-400 text-sm text-center py-10">El roadmap aún no está disponible.</p>
        {{ end }}
      </div>
    </div>
  </div>

  <!-- ─── AVANCES ───────────────────────────────────────────────────────────── -->
  <div x-show="activeTab==='Avances'" x-cloak>
    <div class="space-y-4">
      {{ range .avances }}
      <div class="bg-white rounded-xl border border-slate-200 p-5">
        <div class="flex items-start gap-3">
          <div class="w-8 h-8 rounded-full flex-shrink-0 flex items-center justify-center text-xs font-bold"
            style="background:#8eb02f;color:#fff">
            {{ if eq .Tipo "milestone" }}🎯{{ else if eq .Tipo "alerta" }}⚠️{{ else if eq .Tipo "nota" }}📝{{ else if eq .Tipo "update" }}✨{{ else }}✓{{ end }}
          </div>
          <div>
            <h3 class="font-semibold text-slate-800 text-sm">{{ .Titulo }}</h3>
            <p class="text-sm text-slate-600 mt-1">{{ .Contenido }}</p>
            <p class="text-xs text-slate-400 mt-2">{{ .CreatedAt.Format "02 Jan 2006" }}</p>
          </div>
        </div>
      </div>
      {{ end }}
      {{ if not .avances }}
      <p class="text-slate-400 text-sm text-center py-10">Sin avances publicados aún.</p>
      {{ end }}
    </div>
  </div>

  <!-- ─── ENTREGABLES ───────────────────────────────────────────────────────── -->
  <div x-show="activeTab==='Entregables'" x-cloak>
    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
      {{ range .entregables }}
      <div class="bg-white rounded-xl border border-slate-200 p-4 flex items-center gap-4">
        <div class="w-10 h-10 rounded-xl flex items-center justify-center bg-slate-100 flex-shrink-0">
          <svg class="w-5 h-5 text-slate-500" 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>
        </div>
        <div class="flex-1 min-w-0">
          <p class="font-semibold text-sm text-slate-800 truncate">{{ .Nombre }}</p>
          <p class="text-xs text-slate-500">v{{ .Version }} &middot; {{ .OriginalName }}</p>
        </div>
        <a href="/portal/entregables/{{ .ID }}/download" class="flex-shrink-0 text-[#8eb02f] hover:text-[#6d8c24]">
          <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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
        </a>
      </div>
      {{ end }}
      {{ if not .entregables }}
      <p class="col-span-2 text-slate-400 text-sm text-center py-10">Sin entregables disponibles.</p>
      {{ end }}
    </div>
  </div>

  <!-- ─── DOCUMENTOS ─────────────────────────────────────────────────────────── -->
  <div x-show="activeTab==='Documentos'" x-cloak>
    <div class="space-y-3">
      <template x-if="documentos.length === 0">
        <p class="text-slate-400 text-sm text-center py-10">Sin documentos disponibles.</p>
      </template>
      <template x-for="d in documentos" :key="d.ID">
        <div class="bg-white rounded-xl border border-slate-200 p-4 flex items-center gap-4">
          <!-- Icono por tipo -->
          <div class="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0"
               :class="d.tipo==='contrato' ? 'bg-blue-50 text-blue-500' : d.tipo==='orden_servicio' ? 'bg-amber-50 text-amber-500' : 'bg-slate-100 text-slate-400'">
            <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="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>
          </div>
          <!-- Info -->
          <div class="flex-1 min-w-0">
            <p class="font-semibold text-sm text-slate-800 truncate" x-text="d.nombre"></p>
            <div class="flex items-center gap-2 mt-0.5">
              <span class="text-xs px-2 py-0.5 rounded-full font-medium capitalize"
                :class="d.tipo==='contrato' ? 'bg-blue-100 text-blue-700' : d.tipo==='orden_servicio' ? 'bg-amber-100 text-amber-700' : 'bg-slate-100 text-slate-500'"
                x-text="(d.tipo||'').replace('_',' ')"></span>
              <span x-show="d.original_name" class="text-xs text-slate-400 truncate" x-text="d.original_name"></span>
            </div>
            <p x-show="d.descripcion" class="text-xs text-slate-500 mt-0.5 truncate" x-text="d.descripcion"></p>
          </div>
          <!-- Descarga -->
          <a :href="`/portal/documentos/${d.ID}/download`"
             class="flex-shrink-0 w-8 h-8 rounded-lg flex items-center justify-center text-[#8eb02f] hover:bg-[#8eb02f]/10 transition-colors" title="Descargar">
            <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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
          </a>
        </div>
      </template>
    </div>
  </div>

  <!-- ─── TICKETS ───────────────────────────────────────────────────────────── -->
  <div x-show="activeTab==='Tickets'" x-cloak>
    <!-- Crear ticket -->
    <div class="bg-white rounded-xl border border-slate-200 p-5 mb-6">
      <h3 class="font-semibold text-slate-700 mb-3 text-sm">Abrir nuevo ticket</h3>
      <form @submit.prevent="crearTicket()">
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mb-3">
          <div class="sm:col-span-2"><input x-model="ticketForm.titulo" type="text" placeholder="Título del ticket" class="input-field w-full" required></div>
          <div>
            <select x-model="ticketForm.prioridad" class="input-field w-full">
              <option value="baja">Prioridad baja</option>
              <option value="media" selected>Prioridad media</option>
              <option value="alta">Prioridad alta</option>
            </select>
          </div>
          <div class="sm:col-span-2"><textarea x-model="ticketForm.descripcion" placeholder="Describe el problema o consulta..." rows="3" class="input-field w-full"></textarea></div>
        </div>
        <button type="submit" :disabled="creandoTicket" class="btn-primary text-sm" x-text="creandoTicket ? 'Enviando...' : 'Enviar ticket'"></button>
      </form>
    </div>

    <!-- Lista de tickets -->
    <div class="space-y-3">
      <template x-for="t in tickets" :key="t.ID">
        <div :id="'portal-ticket-' + t.ID" class="bg-white rounded-xl border overflow-hidden" :class="t._noLeidos > 0 ? 'border-[#8eb02f]' : 'border-slate-200'">
          <div class="p-4 flex items-start justify-between cursor-pointer" @click="abrirTicket(t)">
            <div>
              <div class="flex items-center gap-2 mb-1">
                <span class="badge" :class="ticketBadge(t.estado)" x-text="t.estado"></span>
                <span class="badge" :class="prioBadge(t.prioridad)" x-text="t.prioridad"></span>
                <template x-if="t._noLeidos > 0">
                  <span class="inline-flex items-center gap-1 text-[10px] font-bold bg-red-500 text-white px-1.5 py-0.5 rounded-full">
                    <span x-text="t._noLeidos"></span> nuevo<span x-show="t._noLeidos > 1">s</span>
                  </span>
                </template>
              </div>
              <h4 class="font-semibold text-slate-800 text-sm" x-text="t.titulo"></h4>
              <p class="text-xs text-slate-400" x-text="formatDate(t.CreatedAt)"></p>
            </div>
            <svg class="w-4 h-4 text-slate-400 transition-transform" :class="t._open ? 'rotate-180' : ''" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7"/></svg>
          </div>
          <div x-show="t._open" class="border-t border-slate-100 px-4 pb-4">
            <p class="text-sm text-slate-600 py-3 border-b border-slate-100 leading-relaxed" x-text="t.descripcion"></p>
            <!-- Mensajes con scroll -->
            <div class="overflow-y-auto space-y-2 mt-3 pr-1" style="max-height:260px" x-ref="msgBox">
              <template x-for="m in (t.mensajes||[])" :key="m.ID">
                <div class="flex" :class="m.es_admin ? 'justify-start' : 'justify-end'">
                  <div class="rounded-xl px-3 py-2 text-sm max-w-[75%]"
                    :class="m.es_admin ? 'bg-slate-100 text-slate-700' : 'text-white'" :style="m.es_admin ? '' : 'background:#8eb02f'">
                    <div class="text-xs font-semibold mb-0.5" x-text="m.autor_nombre" :style="m.es_admin ? 'color:#64748b' : 'color:rgba(255,255,255,.8)'"></div>
                    <p class="leading-snug break-words" x-text="m.contenido"></p>
                    <p class="text-[10px] mt-0.5 opacity-60 text-right" x-text="formatDate(m.CreatedAt)"></p>
                  </div>
                </div>
              </template>
            </div>
            <template x-if="t.estado !== 'cerrado' && t.estado !== 'resuelto'">
              <div class="flex gap-2 mt-3 pt-3 border-t border-slate-100">
                <input x-model="t._reply" type="text" placeholder="Responder..." class="input-field flex-1 text-sm"
                  @keydown.enter.prevent="responderTicket(t)">
                <button @click="responderTicket(t)" class="btn-primary text-xs px-4">Enviar</button>
              </div>
            </template>
          </div>
        </div>
      </template>
      <p x-show="tickets.length===0 && !loadingTickets" class="text-slate-400 text-sm text-center py-6">No tienes tickets abiertos.</p>
    </div>
  </div>

  <!-- ─── FACTURAS ──────────────────────────────────────────────────────────── -->
  <div x-show="activeTab==='Facturas'" x-cloak>
    <div class="space-y-3">
      <template x-for="f in facturas" :key="f.ID">
        <div class="bg-white rounded-xl border border-slate-200 p-4 flex items-center gap-4">
          <div class="flex-1">
            <div class="flex items-center gap-2 mb-1">
              <span class="font-semibold text-sm text-slate-800" x-text="f.numero || ('Factura #' + f.ID)"></span>
              <span class="text-xs px-2 py-0.5 rounded-full font-semibold capitalize"
                :class="{
                  'bg-green-100 text-green-700': f.estado === 'pagada',
                  'bg-red-100 text-red-700': f.estado === 'vencida',
                  'bg-slate-100 text-slate-500': f.estado === 'cancelada',
                  'bg-yellow-100 text-yellow-700': !['pagada','vencida','cancelada'].includes(f.estado)
                }" x-text="f.estado"></span>
              <span x-show="f._nuevo" class="text-[10px] font-bold bg-amber-500 text-white px-1.5 py-0.5 rounded-full">Nuevo</span>
            </div>
            <p class="text-xs text-slate-500" x-text="f.descripcion"></p>
            <p class="text-sm font-bold text-slate-700 mt-1" x-text="(f.moneda || '') + ' ' + Number(f.monto || 0).toLocaleString('es-CO')"></p>
            <p x-show="f.fecha_vencimiento" class="text-xs text-slate-400" x-text="'Vence: ' + formatDate(f.fecha_vencimiento)"></p>
          </div>
          <template x-if="f.archivo">
            <a :href="`/portal/facturas/${f.ID}/download`" class="text-[#8eb02f] hover:text-[#6d8c24] flex-shrink-0" title="Descargar factura">
              <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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
            </a>
          </template>
        </div>
      </template>
      <p x-show="!facturas.length && !loadingTickets" class="text-slate-400 text-sm text-center py-10">Sin facturas disponibles.</p>
    </div>
  </div>

</div>

<script>
const PROYECTO_SLUG = '{{ .proyecto.Slug }}';

function portalProyecto() {
  return {
    activeTab: 'Roadmap',
    tickets: [],
    ticketsNoLeidos: 0,
    loadingTickets: false,
    creandoTicket: false,
    ticketForm: { titulo:'', descripcion:'', prioridad:'media' },
    facturas: [],
    facturasNoLeidas: 0,
    documentos: [],

    async init() {
      const params = new URLSearchParams(window.location.search);
      const tabParam = params.get('tab');
      if (tabParam) this.activeTab = tabParam;
      await this.loadTickets();
      const ticketId = params.get('ticket');
      if (ticketId) {
        this.activeTab = 'Tickets';
        const t = this.tickets.find(x => String(x.ID) === String(ticketId));
        if (t) {
          t._open = true;
          this.$nextTick(() => {
            const el = document.getElementById('portal-ticket-' + t.ID);
            if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
          });
        }
      }
      if (this.activeTab === 'Facturas') {
        this.marcarFacturasLeidas();
      }
    },

    async loadTickets() {
      this.loadingTickets = true;
      try {
        const r = await axios.get(`/portal/api/proyecto/${PROYECTO_SLUG}`);
        this.tickets = (r.data.tickets||[]).map(t => ({
          ...t,
          _open: false,
          _reply: '',
          _noLeidos: (t.mensajes||[]).filter(m => m.es_admin && !m.leido_portal).length,
        }));
        this.recalcNoLeidos();
        // Cargar facturas y conteo de no leídas
        this.facturasNoLeidas = r.data.facturasNoLeidas || 0;
        this.facturas = (r.data.facturas||[]).map(f => ({
          ...f,
          _nuevo: this.facturasNoLeidas > 0,
        }));
        this.documentos = r.data.documentos || [];
      } catch(e){} finally { this.loadingTickets=false; }
    },

    recalcNoLeidos() {
      this.ticketsNoLeidos = this.tickets.reduce((sum, t) => sum + (t._noLeidos||0), 0);
    },

    async abrirTicket(t) {
      t._open = !t._open;
      if (t._open) {
        if (t._noLeidos > 0) {
          t._noLeidos = 0;
          this.recalcNoLeidos();
          axios.post(`/portal/tickets/${t.ID}/leido`).catch(()=>{});
        }
        // scroll al final de mensajes al abrir
        await this.$nextTick();
        const boxes = document.querySelectorAll('[x-ref="msgBox"]');
        boxes.forEach(b => { b.scrollTop = b.scrollHeight; });
      }
    },

    async marcarTicketsPendientesLeidos() {
      // Al abrir el tab Tickets, si alguno está abierto y tiene no leídos, marcarlos
      this.tickets.forEach(t => {
        if (t._open && t._noLeidos > 0) {
          t._noLeidos = 0;
          axios.post(`/portal/tickets/${t.ID}/leido`).catch(()=>{});
        }
      });
      this.recalcNoLeidos();
    },

    async marcarFacturasLeidas() {
      if (this.facturasNoLeidas > 0) {
        this.facturasNoLeidas = 0;
        this.facturas.forEach(f => { f._nuevo = false; });
        axios.post('/portal/mis-notifs/marcar-facturas').catch(()=>{});
      }
    },

    async crearTicket() {
      this.creandoTicket=true;
      try {
        const r = await axios.post('/portal/tickets', { ...this.ticketForm, proyecto_slug: PROYECTO_SLUG });
        this.tickets.unshift({...r.data, _open:false, _reply:'', _noLeidos:0});
        this.ticketForm={titulo:'',descripcion:'',prioridad:'media'};
      } catch(e) {
        alert(e.response?.data?.error || 'Error al crear ticket');
      } finally { this.creandoTicket=false; }
    },

    async responderTicket(t) {
      if(!t._reply?.trim()) return;
      try {
        const r = await axios.post(`/portal/tickets/${t.ID}/mensaje`, {contenido: t._reply});
        if(!t.mensajes) t.mensajes=[];
        t.mensajes.push(r.data);
        t._reply='';
        // scroll al último mensaje
        await this.$nextTick();
        const boxes = document.querySelectorAll('[x-ref="msgBox"]');
        boxes.forEach(b => { b.scrollTop = b.scrollHeight; });
      } catch(e) { alert(e.response?.data?.error||'Error'); }
    },

    ticketBadge(e){ return {abierto:'badge-red',en_progreso:'badge-yellow',resuelto:'badge-green',cerrado:'badge-slate'}[e]||'badge-slate'; },
    prioBadge(p){ return {alta:'badge-red',media:'badge-yellow',baja:'badge-green'}[p]||'badge-slate'; },
    formatDate(d){ if(!d) return ''; return new Date(d).toLocaleDateString('es-CO',{day:'2-digit',month:'short',year:'numeric'}); },
  }
}
</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;}
.input-field{border:1px solid #e2e8f0;border-radius:.5rem;padding:.5rem .75rem;font-size:.875rem;outline:none;}
.input-field:focus{border-color:#8eb02f;}
.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;}
</style>
