{{-- resources/views/formularios/sections/_resumen.blade.php --}}
<section x-show="step === 5" x-transition x-ref="step5" x-data="{
    // ====== Locales (copiados desde $store.resumen) ======
    dTot:0, dObt:0, dPct:0,   // Disposiciones
    eTot:0, eObt:0, ePct:0,   // EjecuciÃ³n (checklist paso 3)
    rTot:0, rObt:0, rPct:0,   // Resultados en Salud (checklist paso 4)
    gTot:0, gObt:0, gPct:0,   // Global
    // Periodo actual (desde servidor para decidir ajuste)
    periodo: @js($ejecucion['periodo'] ?? ($seleccion['trimestre'] ?? '')),

    // ====== Helpers ======
    num(n){ n = Number(n||0); return Number.isInteger(n) ? n : Number(n).toFixed(1); },
    estado(p){
      p = Number(p||0);
      if (p > 90) return 'Ã“ptimo';
      if (p > 80) return 'Aceptable';
      if (p > 70) return 'Deficiente';
      return 'Inaceptable';
    },
    estadoCls(p){
      p = Number(p||0);
      if (p > 90) return 'bg-green-100 text-green-800 border-green-300';
      if (p > 80) return 'bg-yellow-100 text-yellow-800 border-yellow-300';
      if (p > 70) return 'bg-orange-100 text-orange-800 border-orange-300';
      return 'bg-red-100 text-red-800 border-red-300';
    },
    barCls(p){
      p = Number(p||0);
      if (p > 90) return 'bg-green-600';
      if (p > 80) return 'bg-yellow-500';
      if (p > 70) return 'bg-orange-500';
      return 'bg-red-600';
    },

     // ðŸ†• Campos locales para trimestres
  tI: {vc:0, ve:0, aj:0, pct:0}, 
  tII:{vc:0, ve:0, aj:0, pct:0},
  tIII:{vc:0, ve:0, aj:0, pct:0},
  tIV:{vc:0, ve:0, aj:0, pct:0},

  // ðŸ†• Construir arreglo de tarjetas (solo trimestres presentes)
  resumenTrimestres(){
    const cards = [];
    const add = (tri, o) => {
      const hasData = (o.vc||0) > 0 || (o.ve||0) > 0 || (o.aj||0) > 0 || (o.pct||0) > 0;
      if (hasData) cards.push({ tri, ...o });
    };
    add('I',   this.tI);
    add('II',  this.tII);
    add('III', this.tIII);
    add('IV',  this.tIV);
    return cards;
  },

  // ðŸ”„ Leer del store (amplÃ­a tu funciÃ³n existente)
  pullFromStore(){
    const S = (window.Alpine && Alpine.store('resumen')) || {};

    /* === LO TUYO (disposiciones/ejecuciÃ³n/salud/global) === */
    this.dTot = Number(S.disposicionesTotal    ?? 0);
    this.dObt = Number(S.disposicionesObtenido ?? 0);
    this.dPct = Number(S.disposiciones         ?? 0);
    this.eTot = Number(S.ejecucionTotal    ?? 0);
    this.eObt = Number(S.ejecucionObtenido ?? 0);
    this.ePct = Number(S.ejecucion         ?? 0);
    this.rTot = Number(S.resultadosTotal    ?? 0);
    this.rObt = Number(S.resultadosObtenido ?? 0);
    this.rPct = Number(S.resultados         ?? 0);
    this.gTot = this.dTot + this.eTot + this.rTot;
    this.gObt = this.dObt + this.eObt + this.rObt;
    this.gPct = this.gTot > 0 ? (this.gObt / this.gTot) * 100 : 0;

    /* === ðŸ†• Trimestres desde el store de la Matriz === */
    this.tI   = { 
      vc: Number(S.matrizVCI ?? 0),
      ve: Number(S.matrizVEI ?? 0),
      aj: Number(S.matrizAjustesI ?? 0),
      pct: Number(S.matrizPctI ?? 0)
    };
    this.tII  = { 
      vc: Number(S.matrizVCII ?? 0),
      ve: Number(S.matrizVEII ?? 0),
      aj: Number(S.matrizAjustesII ?? 0),
      pct: Number(S.matrizPctII ?? 0)
    };
    this.tIII = { 
      vc: Number(S.matrizVCIII ?? 0),
      ve: Number(S.matrizVEIII ?? 0),
      aj: Number(S.matrizAjustesIII ?? 0),
      pct: Number(S.matrizPctIII ?? 0)
    };
    this.tIV  = { 
      vc: Number(S.matrizVCIV ?? 0),
      ve: Number(S.matrizVEIV ?? 0),
      aj: Number(S.matrizAjustesIV ?? 0),
      pct: Number(S.matrizPctIV ?? 0)
    };
  },

  // Ajuste segn ltimo tramo del periodo seleccionado
  ajusteActual(){
    const p = (this.periodo||'').trim();
    if (p === 'I') return Number(this.tI.aj||0);
    if (p === 'I-II') return Number(this.tII.aj||0);
    if (p === 'I-II-III') return Number(this.tIII.aj||0);
    if (p === 'I-II-III-IV') return Number(this.tIV.aj||0);
    return 0;
  },
  }" x-init="pullFromStore()" @resumen-updated.window="pullFromStore()" @sync-resumen.window="pullFromStore()"
  class="sec sec-azul">

  <h2 class="sec-title">RESULTADOS DE SEGUIMIENTO A CONTRATO</h2>
  <p class="text-sm text-gray-600 mb-4">
    Estado por rangos: <span class="font-medium">>90</span> Ã“ptimo Â· <span class="font-medium">>80</span> Aceptable Â·
    <span class="font-medium">>70</span> Deficiente Â· <span class="font-medium">â‰¤70</span> Inaceptable
  </p>

  {{-- ====== Global ====== --}}
  <div class="rounded-lg border p-4 bg-white white:bg-zinc-900 mb-6">
    <div class="flex flex-wrap items-center justify-between gap-3">
      <div>
        <h3 class="font-semibold">RESULTADO PONDERADO</h3>
        <div class="text-sm text-gray-600">
          Obtenido: <span x-text="num(gObt)"></span> / <span x-text="num(gTot)"></span>
        </div>
      </div>
      <div class="flex items-center gap-2">
        <div class="text-xl font-bold" x-text="num(gPct) + '%'"></div>
        <span class="px-2 py-1 border rounded text-xs" :class="estadoCls(gPct)" x-text="estado(gPct)"></span>
      </div>
    </div>

    <div class="mt-3 h-2 w-full rounded bg-gray-200 overflow-hidden">
      <div class="h-2 rounded" :class="barCls(gPct)" :style="`width: ${Math.min(100, Math.max(0, gPct)).toFixed(1)}%`">
      </div>
    </div>

    {{-- Opcional: enviar el global al backend --}}
    <input type="hidden" name="resumen[global_porcentaje]" :value="Number(gPct).toFixed(1)">
    <input type="hidden" name="resumen[global_estado]" :value="estado(gPct)">
  </div>

  {{-- ====== Tarjetas por secciÃ³n ====== --}}
  <div class="grid md:grid-cols-3 gap-4">
    {{-- Disposiciones --}}
    <div class="rounded-lg border p-4 bg-white white:bg-zinc-900">
      <div class="flex items-center justify-between mb-1">
        <h3 class="font-semibold">GENERALIDADES</h3>
        <span class="px-2 py-1 border rounded text-xs" :class="estadoCls(dPct)" x-text="estado(dPct)"></span>
      </div>
      <div class="text-sm space-y-1">
        <div class="flex justify-between"><span>Totales</span><span x-text="num(dTot)"></span></div>
        <div class="flex justify-between"><span>Obtenido</span><span><span x-text="num(dObt)"></span> / <span
              x-text="num(dTot)"></span></span></div>
        <div class="mt-1 font-medium">Cumplimiento: <span x-text="num(dPct) + '%'"></span></div>
      </div>
    </div>

    {{-- EjecuciÃ³n --}}
    <div class="rounded-lg border p-4 bg-white white:bg-zinc-900">
      <div class="flex items-center justify-between mb-1">
        <h3 class="font-semibold">EJECUCION</h3>
        <span class="px-2 py-1 border rounded text-xs" :class="estadoCls(ePct)" x-text="estado(ePct)"></span>
      </div>
      <div class="text-sm space-y-1">
        <div class="flex justify-between"><span>Totales</span><span x-text="num(eTot)"></span></div>
        <div class="flex justify-between"><span>Obtenido</span><span><span x-text="num(eObt)"></span> / <span
              x-text="num(eTot)"></span></span></div>
        <div class="mt-1 font-medium">Cumplimiento: <span x-text="num(ePct) + '%'"></span></div>
      </div>
    </div>

    {{-- Resultados en Salud --}}
    <div class="rounded-lg border p-4 bg-white white:bg-zinc-900">
      <div class="flex items-center justify-between mb-1">
        <h3 class="font-semibold">SALUD</h3>
        <span class="px-2 py-1 border rounded text-xs" :class="estadoCls(rPct)" x-text="estado(rPct)"></span>
      </div>
      <div class="text-sm space-y-1">
        <div class="flex justify-between"><span>Totales</span><span x-text="num(rTot)"></span></div>
        <div class="flex justify-between"><span>Obtenido</span><span><span x-text="num(rObt)"></span> / <span
              x-text="num(rTot)"></span></span></div>
        <div class="mt-1 font-medium">Cumplimiento: <span x-text="num(rPct) + '%'"></span></div>
      </div>
    </div>
  </div>

  <!-- ===== Resumen por Trimestre (VC, VE, Ajuste y %) ===== -->
  <div class="mt-6 rounded-lg border p-4 bg-white white:bg-zinc-900">
    <h3 class="font-semibold mb-3">Resumen por trimestre</h3>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
      <template x-for="card in resumenTrimestres()" :key="card.tri">
        <div class="rounded-lg border p-3">
          <div class="font-semibold text-blue-900 mb-1">Trimestre <span x-text="card.tri"></span></div>
          <div class="flex justify-between text-sm"><span>VC</span><span>$ <span
                x-text="Number(card.vc).toFixed(2)"></span></span></div>
          <div class="flex justify-between text-sm"><span>VE</span><span>$ <span
                x-text="Number(card.ve).toFixed(2)"></span></span></div>
          <div class="flex justify-between text-sm"><span>Ajuste</span><span>$ <span
                x-text="Number(card.aj).toFixed(2)"></span></span></div>
          <div class="flex justify-between text-sm font-medium border-t pt-1 mt-1">
            <span>% EjecuciÃ³n</span><span><span x-text="Number(card.pct).toFixed(1)"></span>%</span>
          </div>

          <!-- (Opcional) si quieres enviar al backend -->
          <template x-if="false">
            <div style="display:none">
              <input type="hidden" :name="`resumen[tris][${card.tri}][vc]`" :value="Number(card.vc).toFixed(2)">
              <input type="hidden" :name="`resumen[tris][${card.tri}][ve]`" :value="Number(card.ve).toFixed(2)">
              <input type="hidden" :name="`resumen[tris][${card.tri}][aj]`" :value="Number(card.aj).toFixed(2)">
              <input type="hidden" :name="`resumen[tris][${card.tri}][pct]`" :value="Number(card.pct).toFixed(1)">
            </div>
          </template>
        </div>
      </template>
    </div>
  </div>


  {{-- Acciones --}}
  <div class="mt-6 flex flex-wrap gap-3" x-data>
    <div class="mt-6 flex flex-wrap justify-end gap-3">
      <button type="button" class="px-4 py-2 rounded-lg border" @click="window.descargarReporte && window.descargarReporte()">
        Ver reporte (sin guardar)
      </button>
      <button type="button" class="px-4 py-2 rounded-lg border" @click="step = 1">Revisar formulario</button>
      <button type="button" class="px-4 py-2 rounded border" @click="step--">Atras</button>
      <button type="submit" formnovalidate class="px-5 py-2 rounded bg-indigo-600 text-white">
        Guardar para revision
      </button>
    </div>
  </div></section>