<template>
  <div class="layout-px-spacing" v-if="lot">
    <div class="row layout-top-spacing">
      <div class="col-12 layout-spacing">
        <div class="panel p-4">
          <router-link to="/ganaderia/engorda" class="btn btn-link px-0">← Lotes</router-link>
          <div class="d-flex justify-content-between align-items-start flex-wrap gap-2 mb-2">
            <div>
              <h3 class="mb-1">{{ lot.name }}</h3>
              <p class="text-muted mb-0">{{ lot.description }}</p>
            </div>
            <div class="d-flex gap-2 flex-wrap">
              <button type="button" class="btn btn-sm btn-outline-secondary" :disabled="exportingPdf" @click="exportPdf">
                {{ exportingPdf ? 'Generando…' : 'Exportar PDF' }}
              </button>
              <button
                v-if="canWeigh && lot.status === 'open'"
                type="button"
                class="btn btn-sm btn-primary btn-weigh-cta"
                @click="goToWeighTab()"
              >
                Registrar pesaje
              </button>
              <button v-if="lot.status === 'open'" type="button" class="btn btn-sm btn-outline-primary" @click="showPurchase = true">
                Registrar compra
              </button>
            </div>
          </div>
          <p v-if="evaluation?.planned_exit_date" class="small text-muted mb-3">
            Periodo: {{ lot.planned_duration_days ?? defaultDuration }} días ·
            Fin planificado: {{ evaluation.planned_exit_date }} ·
            Restan {{ evaluation.days_remaining }} días
            <span v-if="evaluation.pasture_accrual_start_date">
              · Pastura desde {{ evaluation.pasture_accrual_start_date }}
            </span>
          </p>

          <div class="row mb-3 ranch-kpi-grid" v-if="evaluation">
            <div class="col-6 col-md-4 col-lg-3 mb-2">
              <div class="card p-3 h-100"><small>Días confinamiento</small><h5>{{ evaluation.days_in_confinement }}</h5></div>
            </div>
            <div class="col-6 col-md-4 col-lg-3 mb-2">
              <div class="card p-3 h-100"><small>Alimento</small><h5>{{ money(feedInvestment?.total_cost ?? evaluation.total_feed_cost) }}</h5></div>
            </div>
            <div class="col-6 col-md-4 col-lg-3 mb-2">
              <div class="card p-3 h-100"><small>Pastura</small><h5>{{ money(evaluation.pasture_cost) }}</h5></div>
            </div>
            <div class="col-6 col-md-4 col-lg-3 mb-2">
              <div class="card p-3 h-100">
                <small>Vacunación / salud</small>
                <h5>{{ money(evaluation.health_cost) }}</h5>
                <p
                  v-if="evaluation.projected_health_cost > evaluation.health_cost"
                  class="small text-muted mb-0"
                >
                  est. {{ money(evaluation.projected_health_cost) }} al cierre
                </p>
              </div>
            </div>
            <div class="col-6 col-md-4 col-lg-3 mb-2">
              <div class="card p-3 h-100"><small>Inversión total</small><h5>{{ money(evaluation.total_investment) }}</h5></div>
            </div>
            <div class="col-6 col-md-4 col-lg-3 mb-2">
              <div class="card p-3 h-100"><small>Ganancia kg</small><h5>{{ currentTotalGain }} kg</h5></div>
            </div>
            <div class="col-6 col-md-6 col-lg-4 mb-2">
              <div class="card p-3 h-100"><small>Venta est. total</small><h5 class="text-success">{{ money(projection?.projected_income) }}</h5></div>
            </div>
            <div class="col-6 col-md-6 col-lg-4 mb-2">
              <div class="card p-3 h-100"><small>Ganancia est. total</small><h5 :class="profitClass(projection?.projected_net_profit)">{{ money(projection?.projected_net_profit) }}</h5></div>
            </div>
            <div class="col-6 col-md-4 col-lg-3 mb-2">
              <div class="card p-3 h-100"><small>Inversión / cabeza</small><h5>{{ money(animalRows[0]?.estimated_total_investment) }}</h5></div>
            </div>
          </div>

          <div v-if="groupGainSummary" class="group-gain-panel mb-3">
            <h6 class="group-gain-title">Resultado grupal por ganancia de peso</h6>
            <p class="small text-muted mb-3">
              Suma de kg ganados del grupo × precio objetivo, menos inversión acumulada (al día de hoy).
            </p>
            <div class="group-gain-flow">
              <div class="group-gain-step">
                <span class="group-gain-label">Ganancia kg (grupo)</span>
                <strong>{{ groupGainSummary.total_kg }} kg</strong>
              </div>
              <span class="group-gain-op">×</span>
              <div class="group-gain-step">
                <span class="group-gain-label">Precio</span>
                <strong>{{ money(groupGainSummary.price_per_kg) }}/kg</strong>
              </div>
              <span class="group-gain-op">=</span>
              <div class="group-gain-step highlight">
                <span class="group-gain-label">Valor ganancia</span>
                <strong>{{ money(groupGainSummary.value_at_price) }}</strong>
              </div>
              <span class="group-gain-op">−</span>
              <div class="group-gain-step">
                <span class="group-gain-label">Inversión</span>
                <strong>{{ money(groupGainSummary.investment) }}</strong>
              </div>
              <span class="group-gain-op">=</span>
              <div class="group-gain-step result">
                <span class="group-gain-label">Utilidad neta</span>
                <strong :class="profitClass(groupGainSummary.net_profit)">{{ money(groupGainSummary.net_profit) }}</strong>
              </div>
            </div>
          </div>

          <nav class="ranch-tabs" aria-label="Secciones del lote">
            <button
              v-for="tab in tabs"
              :key="tab.id"
              type="button"
              class="ranch-tab"
              :class="{ 'is-active': activeTab === tab.id }"
              @click="activeTab = tab.id"
            >
              {{ tab.label }}
            </button>
          </nav>

          <!-- Resumen -->
          <div v-show="activeTab === 'resumen'">
            <div class="row mb-3" v-if="analytics?.weight_series?.length">
              <div class="col-lg-7 mb-3">
                <div class="card p-3 h-100">
                  <h6 class="mb-2">Progreso de peso (kg)</h6>
                  <apexchart type="line" height="300" :options="weightChartOptions" :series="weightChartSeries" />
                </div>
              </div>
              <div class="col-lg-5 mb-3">
                <div class="card p-3 h-100">
                  <h6 class="mb-2">Inversión acumulada en alimento</h6>
                  <apexchart type="area" height="300" :options="feedChartOptions" :series="feedChartSeries" />
                </div>
              </div>
            </div>

            <div class="row" v-if="analytics?.investment_breakdown">
              <div class="col-md-4 mb-3">
                <div class="card p-3 h-100">
                  <h6>Inversión del grupo</h6>
                  <div class="investment-bars mt-3">
                    <div v-for="item in investmentBarItems" :key="item.label" class="investment-bar-row">
                      <span class="investment-bar-label">{{ item.label }}</span>
                      <div class="investment-bar-track">
                        <div
                          class="investment-bar-fill"
                          :style="{ width: item.pct + '%', background: item.color }"
                        />
                      </div>
                      <span class="investment-bar-value">{{ money(item.value) }}</span>
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-md-8 mb-3" v-if="projection">
                <div class="card p-3 h-100">
                  <h6>Proyección al fin del periodo ({{ projection.planned_exit_date }})</h6>
                  <div class="row g-2 small">
                    <div class="col-md-3"><strong>Peso proyectado total</strong><br />{{ projectedTotalWeight }} kg</div>
                    <div class="col-md-3"><strong>Ingreso estimado</strong><br />{{ money(projection.projected_income) }}</div>
                    <div class="col-md-3"><strong>Costos totales</strong><br />{{ money(projection.projected_total_cost) }}</div>
                    <div class="col-md-3"><strong>Utilidad neta</strong><br />{{ money(projection.projected_net_profit) }}</div>
                  </div>
                  <p class="small text-muted mb-2">
                    Desglose costos: alimento {{ money(projection.projected_feed_cost) }} ·
                    vacunación/salud {{ money(projection.projected_health_cost) }}
                    <span v-if="projection.current_health_cost != null && projection.current_health_cost !== projection.projected_health_cost">
                      (hoy {{ money(projection.current_health_cost) }})
                    </span>
                    · pastura {{ money(projection.projected_pasture_cost) }}
                  </p>
                  <table class="table table-sm mt-2 mb-0">
                    <thead><tr><th>Arete</th><th>Actual</th><th>Proyectado</th><th>Salud est.</th><th>Ganancia est.</th></tr></thead>
                    <tbody>
                      <tr v-for="a in projection.animals || []" :key="a.cattle_id">
                        <td>{{ a.ear_tag }}</td>
                        <td>{{ currentWeight(a.cattle_id) }} kg</td>
                        <td>{{ a.exit_weight_kg }} kg</td>
                        <td>{{ healthCostLabel(a.cattle_id) }}</td>
                        <td>{{ (a.exit_weight_kg - a.entry_weight_kg).toFixed(1) }} kg</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>

          <!-- Animales -->
          <div v-show="activeTab === 'animales'">
            <div v-if="canWeigh && lot.status === 'open'" class="weigh-callout mb-3">
              <div class="weigh-callout-icon" aria-hidden="true">⚖</div>
              <div>
                <strong>Actualiza la proyección con pesajes periódicos</strong>
                <p class="mb-0 small text-muted">
                  Cada pesaje recalcula GDP, venta estimada y utilidad al cierre del periodo.
                </p>
              </div>
              <button type="button" class="btn btn-sm btn-primary ms-auto" @click="goToWeighTab()">
                Ir a pesajes
              </button>
            </div>
            <p v-if="animalRows[0]?.price_per_kg_used" class="small text-muted">
              Venta estimada a ${{ animalRows[0].price_per_kg_used }}/kg (peso actual × precio objetivo).
              Utilidad por ganancia = kg ganados × precio − inversión.
            </p>
            <div class="table-responsive">
              <table class="table table-hover align-middle">
                <thead>
                  <tr>
                    <th>Arete</th>
                    <th>Entrada</th>
                    <th>Actual</th>
                    <th>Ganancia kg</th>
                    <th>Valor ganancia</th>
                    <th v-if="canWeigh">GDP</th>
                    <th>Salud / vet</th>
                    <th>Inversión</th>
                    <th>Util. ganancia</th>
                    <th>Venta total</th>
                    <th>Util. venta total</th>
                    <th v-if="lot.status === 'open'">Util. al cierre</th>
                    <th v-if="lot.status === 'open'">Peso venta</th>
                    <th v-if="canWeigh && lot.status === 'open'" class="text-end">Pesaje</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="a in animalRows" :key="a.id">
                    <td><router-link :to="`/ganaderia/animales/${a.cattle_id}`">{{ a.cattle?.ear_tag }}</router-link></td>
                    <td>{{ a.entry_weight_kg }} kg</td>
                    <td>{{ a.current_weight_kg ?? '—' }} kg</td>
                    <td>{{ a.weight_gain_kg ?? '—' }} kg</td>
                    <td>
                      <template v-if="animalGainSummary(a)">
                        {{ money(animalGainSummary(a).value_at_price) }}
                        <span class="gain-formula-hint d-block text-muted small">
                          {{ animalGainSummary(a).total_kg }} kg × {{ money(animalGainSummary(a).price_per_kg) }}
                        </span>
                      </template>
                      <span v-else class="text-muted">—</span>
                    </td>
                    <td v-if="canWeigh">
                      <span v-if="weighRowFor(a.cattle_id)?.last_weigh?.daily_weight_gain != null" class="gdp-badge">
                        {{ Number(weighRowFor(a.cattle_id).last_weigh.daily_weight_gain).toFixed(2) }}
                      </span>
                      <span v-else class="text-muted">—</span>
                    </td>
                    <td>
                      <span>{{ money(a.estimated_health_cost) }}</span>
                      <span
                        v-if="a.projected_health_cost > a.estimated_health_cost"
                        class="health-proj-hint d-block"
                      >
                        est. {{ money(a.projected_health_cost) }} al cierre
                      </span>
                    </td>
                    <td>{{ money(a.estimated_total_investment) }}</td>
                    <td :class="profitClass(animalGainSummary(a)?.net_profit)">
                      {{ animalGainSummary(a) ? money(animalGainSummary(a).net_profit) : '—' }}
                    </td>
                    <td>{{ money(a.estimated_sale_total) }}</td>
                    <td :class="profitClass(a.estimated_net_profit)">{{ money(a.estimated_net_profit) }}</td>
                    <td v-if="lot.status === 'open'" :class="profitClass(a.projected_net_profit)">
                      {{ a.projected_net_profit != null ? money(a.projected_net_profit) : '—' }}
                    </td>
                    <td v-if="lot.status === 'open'">
                      <input v-model.number="exitWeights[a.cattle_id]" type="number" step="0.01" class="form-control form-control-sm" style="max-width:110px" @change="refreshPreview" />
                    </td>
                    <td v-if="canWeigh && lot.status === 'open'" class="text-end">
                      <button
                        type="button"
                        class="btn btn-sm btn-outline-primary btn-weigh-row"
                        @click="openWeighForAnimal(a.cattle_id)"
                      >
                        Pesar
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <div v-if="closePreview && lot.status === 'open'" class="alert mb-3" :class="closePreview.meets_target === false ? 'alert-danger' : 'alert-info'">
              <strong>Cierre a ${{ salePrice }}/kg:</strong>
              Venta {{ money(closePreview.projected_income) }} −
              costos {{ money(closePreview.projected_total_cost) }}
              (alimento {{ money(closePreview.projected_feed_cost) }}, vacunación/salud {{ money(closePreview.projected_health_cost) }}, pastura {{ money(closePreview.projected_pasture_cost) }}) =
              utilidad {{ money(closePreview.projected_net_profit) }}
            </div>

            <div v-if="lot.status === 'open'" class="d-flex flex-wrap gap-2 mt-2">
              <button class="btn btn-outline-secondary" @click="fillProjectedWeights">Usar pesos proyectados</button>
              <button class="btn btn-outline-secondary" @click="fillCurrentWeights">Usar peso actual</button>
              <button class="btn btn-warning" @click="closeLot">Cerrar sin vender</button>
              <button class="btn btn-success" @click="closeAndSell">Cerrar y vender grupo</button>
            </div>
          </div>

          <!-- Pesajes -->
          <div v-show="activeTab === 'pesajes'">
            <div class="weigh-panel-intro mb-4">
              <div>
                <h5 class="mb-1">Control de peso del lote</h5>
                <p class="text-muted small mb-0">
                  Registra pesajes periódicos para mantener GDP y proyección de cierre al día.
                </p>
              </div>
              <div v-if="projection?.planned_exit_date" class="weigh-panel-meta">
                <span class="text-muted small">Proyección al</span>
                <strong>{{ projection.planned_exit_date }}</strong>
              </div>
            </div>

            <div class="weigh-card-grid">
              <article
                v-for="row in weighRows"
                :key="row.cattle_id"
                class="weigh-card"
                :class="{ 'has-alert': !row.last_weigh && lot.status === 'open' }"
              >
                <header class="weigh-card-head">
                  <div>
                    <router-link :to="`/ganaderia/animales/${row.cattle_id}`" class="weigh-card-tag">
                      {{ row.ear_tag || '—' }}
                    </router-link>
                    <span v-if="row.last_weigh?.daily_weight_gain != null" class="gdp-badge ms-2">
                      GDP {{ Number(row.last_weigh.daily_weight_gain).toFixed(2) }}
                    </span>
                  </div>
                  <span class="weigh-card-gain">+{{ row.weight_gain_kg ?? 0 }} kg</span>
                </header>

                <div class="weigh-card-track">
                  <span class="weigh-card-weight">{{ row.entry_weight_kg }} kg</span>
                  <span class="weigh-card-arrow">→</span>
                  <span class="weigh-card-weight current">{{ row.current_weight_kg ?? '—' }} kg</span>
                </div>

                <p class="weigh-card-last small text-muted mb-0">
                  <template v-if="row.last_weigh">
                    Último pesaje: {{ row.last_weigh.weight_kg }} kg · {{ row.last_weigh.weighed_at }}
                  </template>
                  <template v-else>Solo peso de entrada registrado</template>
                </p>
                <p v-if="healthCostFor(row.cattle_id)" class="weigh-card-health small mb-0">
                  Salud / vet: {{ money(healthCostFor(row.cattle_id).actual) }}
                  <span v-if="healthCostFor(row.cattle_id).projected > healthCostFor(row.cattle_id).actual">
                    · est. {{ money(healthCostFor(row.cattle_id).projected) }}
                  </span>
                </p>

                <button
                  v-if="canWeigh && lot.status === 'open'"
                  type="button"
                  class="btn btn-primary btn-sm w-100 mt-3"
                  @click="openWeighForm(row)"
                >
                  Registrar peso
                </button>
              </article>

              <p v-if="!weighRows.length" class="text-muted mb-0">Sin animales en el lote.</p>
            </div>
          </div>

          <!-- Alimentación -->
          <div v-show="activeTab === 'alimentacion'">
            <div v-if="feedInventory.length" class="card mb-4 p-3">
              <h5 class="mb-3">Inventario de alimento</h5>
              <table class="table table-sm mb-0">
                <thead><tr><th>Producto</th><th>Disponible</th></tr></thead>
                <tbody>
                  <tr v-for="row in feedInventory" :key="row.id">
                    <td>{{ row.name }}</td>
                    <td>{{ row.stock_quantity }} {{ row.unit }}</td>
                  </tr>
                </tbody>
              </table>
            </div>

            <div v-if="lot.status === 'open'" class="card mb-4 p-3">
              <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
                <div>
                  <h5 class="mb-0">Consumo del día (grupo)</h5>
                  <small class="text-muted">Descuenta del inventario al guardar. </small>
                  <button v-if="lastIntakeItems.length" type="button" class="btn btn-link btn-sm p-0 align-baseline" @click="applyLastIntake">
                    Usar última ración
                  </button>
                </div>
                <router-link to="/ganaderia/alimentos" class="btn btn-sm btn-outline-secondary">Catálogo</router-link>
              </div>

              <form class="row g-2 mb-3" @submit.prevent="saveIntake">
                <div class="col-md-3">
                  <label class="form-label small">Fecha</label>
                  <input v-model="intakeForm.intake_date" type="date" class="form-control" required />
                </div>
                <div class="col-md-3">
                  <label class="form-label small">Animales</label>
                  <input class="form-control" :value="animalCount" readonly />
                </div>
                <div class="col-md-6">
                  <label class="form-label small">Notas</label>
                  <input v-model="intakeForm.notes" class="form-control" placeholder="Opcional" />
                </div>
                <div class="col-12">
                  <div class="table-responsive">
                    <table class="table table-sm align-middle mb-2">
                      <thead>
                        <tr>
                          <th>Alimento</th>
                          <th>Cantidad</th>
                          <th>Precio / u</th>
                          <th>Stock</th>
                          <th>Costo</th>
                          <th></th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr v-for="(line, idx) in intakeForm.items" :key="idx">
                          <td>
                            <select v-model.number="line.material_type_id" class="form-select form-select-sm" required @change="onFeedSelected(line)">
                              <option :value="null" disabled>Seleccionar…</option>
                              <option v-for="f in feedTypes" :key="f.id" :value="f.id">{{ f.name }}</option>
                            </select>
                          </td>
                          <td><input v-model.number="line.quantity" type="number" step="0.001" min="0.001" class="form-control form-control-sm" required /></td>
                          <td><input v-model.number="line.unit_price" type="number" step="0.0001" min="0" class="form-control form-control-sm" /></td>
                          <td><small>{{ stockFor(line.material_type_id) }}</small></td>
                          <td>{{ money(lineCost(line)) }}</td>
                          <td><button type="button" class="btn btn-sm btn-outline-danger" @click="removeLine(idx)" :disabled="intakeForm.items.length === 1">×</button></td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                  <button type="button" class="btn btn-sm btn-outline-primary me-2" @click="addLine">+ Línea</button>
                  <strong>Total: {{ money(intakeTotal) }}</strong>
                </div>
                <div class="col-12"><button class="btn btn-primary" type="submit">Guardar ración</button></div>
              </form>
            </div>

            <h6 class="mt-2">Historial de raciones</h6>
            <div class="table-responsive" style="max-height: 320px; overflow-y: auto">
              <table class="table table-sm">
                <thead><tr><th>Fecha</th><th>Detalle</th><th>Total</th><th>/ cabeza</th><th></th></tr></thead>
                <tbody>
                  <tr v-for="row in intakes" :key="row.id">
                    <td>{{ row.intake_date?.slice?.(0, 10) || row.intake_date }}</td>
                    <td>
                      <small v-for="it in row.items || []" :key="it.id" class="d-block">{{ it.material_type?.name }}: {{ it.quantity }}</small>
                    </td>
                    <td>{{ money(row.total_cost) }}</td>
                    <td>{{ money(row.cost_per_head) }}</td>
                    <td><button v-if="lot.status === 'open'" class="btn btn-sm btn-outline-danger" type="button" @click="removeIntake(row)">×</button></td>
                  </tr>
                  <tr v-if="!intakes.length"><td colspan="5" class="text-muted text-center">Sin raciones.</td></tr>
                </tbody>
              </table>
            </div>
          </div>

          <!-- Salud / vacunación -->
          <div v-show="activeTab === 'salud'">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
              <div>
                <h5 class="mb-1">Gasto en vacunación y salud</h5>
                <p class="text-muted small mb-0">
                  Total del lote: <strong>{{ money(evaluation?.health_cost) }}</strong>
                  <span v-if="evaluation?.estimated_health_cost_per_head">
                    · {{ money(evaluation.estimated_health_cost_per_head) }} / cabeza
                  </span>
                  <span v-if="evaluation?.projected_health_cost > evaluation?.health_cost">
                    · est. {{ money(evaluation.projected_health_cost) }} al cierre
                  </span>
                </p>
              </div>
              <div class="d-flex gap-2 flex-wrap">
                <button
                  v-if="canManageHealth && lot.status === 'open'"
                  type="button"
                  class="btn btn-sm btn-primary"
                  @click="openHealthForm()"
                >
                  Registrar aplicación
                </button>
                <router-link to="/ganaderia/salud" class="btn btn-sm btn-outline-secondary">Historial general</router-link>
              </div>
            </div>

            <ul class="nav nav-pills mb-3 gap-1">
              <li class="nav-item">
                <button type="button" class="nav-link py-1 px-3" :class="{ active: healthViewMode === 'animal' }" @click="healthViewMode = 'animal'">
                  Por animal (dosis)
                </button>
              </li>
              <li class="nav-item">
                <button type="button" class="nav-link py-1 px-3" :class="{ active: healthViewMode === 'date' }" @click="healthViewMode = 'date'">
                  Por fecha
                </button>
              </li>
            </ul>

            <!-- Por animal -->
            <template v-if="healthViewMode === 'animal'">
              <div v-if="!lotHealthRows.length" class="text-muted text-center py-4">
                Sin animales en el lote.
              </div>
              <div v-for="animal in lotHealthRows" :key="animal.cattle_id" class="animal-health-group mb-3">
                <div class="animal-health-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                  <h6 class="mb-0">
                    Arete {{ animal.ear_tag }}
                    <router-link :to="`/ganaderia/animales/${animal.cattle_id}`" class="small ms-2">Ver animal</router-link>
                  </h6>
                  <div class="d-flex align-items-center gap-2">
                    <span class="small text-muted">
                      {{ animal.applications.length }} {{ animal.applications.length === 1 ? 'aplicación' : 'aplicaciones' }} ·
                      Total: <strong class="text-body">{{ money(animal.total_cost) }}</strong>
                    </span>
                    <button
                      v-if="canManageHealth && lot.status === 'open'"
                      type="button"
                      class="btn btn-sm btn-outline-primary"
                      @click="openHealthForm(animal)"
                    >
                      Aplicar
                    </button>
                  </div>
                </div>
                <div v-if="animal.applications.length" class="table-responsive">
                  <table class="table table-sm table-hover mb-0">
                    <thead>
                      <tr>
                        <th>Fecha</th>
                        <th>Tipo</th>
                        <th>Producto</th>
                        <th class="text-end">Dosis</th>
                        <th class="text-end">Costo</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="app in animal.applications" :key="app.id">
                        <td>{{ formatRanchDate(app.event_date) }}</td>
                        <td>{{ healthTypeLabel(app.event_type) }}</td>
                        <td>{{ app.product_name || app.material_type?.name || '—' }}</td>
                        <td class="text-end">{{ healthEventDose(app) }}</td>
                        <td class="text-end">{{ money(app.material_expense?.total_cost ?? app.cost) }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
                <p v-else class="small text-muted mb-0 px-3 py-2">Sin aplicaciones registradas en este lote.</p>
              </div>
            </template>

            <!-- Por fecha -->
            <div v-else class="table-responsive">
              <table class="table table-sm table-hover">
                <thead>
                  <tr>
                    <th>Fecha</th>
                    <th>Arete</th>
                    <th>Tipo</th>
                    <th>Producto</th>
                    <th class="text-end">Dosis</th>
                    <th class="text-end">Gasto</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="event in healthEvents" :key="event.id">
                    <td>{{ formatRanchDate(event.event_date) }}</td>
                    <td>{{ event.cattle?.ear_tag || '—' }}</td>
                    <td>{{ healthTypeLabel(event.event_type) }}</td>
                    <td>{{ event.product_name || event.material_type?.name || '—' }}</td>
                    <td class="text-end">{{ healthEventDose(event) }}</td>
                    <td class="text-end">{{ money(event.material_expense?.total_cost ?? event.cost) }}</td>
                  </tr>
                  <tr v-if="!healthEvents.length">
                    <td colspan="6" class="text-muted text-center py-4">Sin aplicaciones de salud registradas en este lote.</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          <!-- Metas -->
          <div v-show="activeTab === 'metas'">
            <div v-if="lot.status === 'open'" class="card p-3">
              <h5 class="mb-3">Metas y periodo</h5>
              <form class="row g-2" @submit.prevent="saveTargets">
                <div class="col-md-4 col-lg-2">
                  <label class="form-label small">Duración (días)</label>
                  <input v-model.number="targets.planned_duration_days" type="number" min="1" class="form-control" :placeholder="String(defaultDuration)" />
                </div>
                <div class="col-md-4 col-lg-2">
                  <label class="form-label small">Pastura $/cab/mes</label>
                  <input v-model.number="targets.pasture_cost_per_animal_month" type="number" step="0.01" class="form-control" />
                </div>
                <div class="col-md-4 col-lg-2">
                  <label class="form-label small">Utilidad mínima ($)</label>
                  <input v-model.number="targets.target_net_profit" type="number" step="0.01" class="form-control" />
                </div>
                <div class="col-md-4 col-lg-2">
                  <label class="form-label small">Precio venta ($/kg)</label>
                  <input v-model.number="targets.target_price_per_kg" type="number" step="0.01" class="form-control" :placeholder="String(defaultPrice)" @change="refreshPreview" />
                </div>
                <div class="col-md-4 col-lg-2">
                  <label class="form-label small">GDP mínimo</label>
                  <input v-model.number="targets.target_min_gdp_kg_per_day" type="number" step="0.01" class="form-control" :placeholder="String(defaultMinGdp)" />
                </div>
                <div class="col-md-4 col-lg-2 d-flex align-items-end">
                  <button type="submit" class="btn btn-outline-primary w-100">Guardar</button>
                </div>
              </form>
            </div>
            <div v-else class="alert alert-secondary mb-0">
              Este lote está cerrado. Las metas ya no se pueden editar.
            </div>
          </div>

          <AppModal v-model="showPurchase" title="Registrar compra de alimento" size="md" :busy="savingPurchase">
            <form id="purchase-form" class="row g-2" @submit.prevent="savePurchase">
              <div class="col-12">
                <label class="form-label small">Producto</label>
                <select v-model.number="purchaseForm.material_type_id" class="form-select" required @change="onPurchaseMaterialSelected">
                  <option :value="null" disabled>Seleccionar…</option>
                  <option v-for="f in feedTypes" :key="f.id" :value="f.id">{{ f.name }} (stock: {{ f.stock_quantity ?? 0 }} {{ f.unit }})</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label small">Fecha</label>
                <input v-model="purchaseForm.expense_date" type="date" class="form-control" required />
              </div>
              <div class="col-md-6">
                <label class="form-label small">Cantidad</label>
                <input v-model.number="purchaseForm.quantity" type="number" step="0.001" min="0.001" class="form-control" required />
              </div>
              <div class="col-md-6">
                <label class="form-label small">Precio unitario</label>
                <input v-model.number="purchaseForm.unit_cost" type="number" step="0.01" min="0" class="form-control" required />
              </div>
              <div class="col-md-6 d-flex align-items-end">
                <p class="mb-2">Total: {{ money(purchaseTotal) }}</p>
              </div>
              <div class="col-12">
                <label class="form-label small">Notas</label>
                <input v-model="purchaseForm.notes" class="form-control" placeholder="Compra alimento" />
              </div>
              <p class="col-12 small text-muted mb-0">La compra incrementa el inventario global. Las raciones lo descuentan al registrarlas.</p>
            </form>
            <template #footer="{ close }">
              <button type="button" class="btn btn-outline-secondary" :disabled="savingPurchase" @click="close">Cancelar</button>
              <button type="submit" form="purchase-form" class="btn btn-primary" :disabled="savingPurchase">
                {{ savingPurchase ? 'Guardando…' : 'Registrar compra' }}
              </button>
            </template>
          </AppModal>

          <AppModal v-model="showWeighForm" :title="weighFormTitle" size="md" :busy="savingWeigh">
            <form id="lot-weigh-form" class="row g-2" @submit.prevent="submitWeigh">
              <div class="col-12">
                <div class="alert alert-light border mb-0 py-2">
                  <strong>Arete:</strong> {{ weighTarget?.ear_tag || '—' }}<br />
                  <span class="text-muted small">
                    Entrada {{ weighTarget?.entry_weight_kg }} kg ·
                    Actual {{ weighTarget?.current_weight_kg ?? '—' }} kg
                  </span>
                </div>
              </div>
              <div class="col-md-6">
                <label class="form-label">Peso (kg)</label>
                <input v-model.number="weighForm.weight_kg" type="number" step="0.01" min="0.01" class="form-control" required />
              </div>
              <div class="col-md-6">
                <label class="form-label">Fecha</label>
                <input v-model="weighForm.weighed_at" type="date" class="form-control" required />
              </div>
              <div class="col-12">
                <label class="form-label">Notas (opcional)</label>
                <input v-model="weighForm.notes" class="form-control" maxlength="500" placeholder="Ej. pesaje quincenal engorda" />
              </div>
              <div v-if="lastWeighResult" class="col-12">
                <div class="alert alert-info mb-0">
                  <strong>Ganancia:</strong> {{ lastWeighResult.weight_gain_kg ?? 'Primer pesaje' }} kg<br />
                  <strong>GDP:</strong> {{ lastWeighResult.daily_weight_gain ?? '—' }} kg/día
                </div>
              </div>
            </form>
            <template #footer="{ close }">
              <button type="button" class="btn btn-outline-secondary" :disabled="savingWeigh" @click="close">Cancelar</button>
              <button type="submit" form="lot-weigh-form" class="btn btn-primary" :disabled="savingWeigh">
                {{ savingWeigh ? 'Guardando…' : 'Guardar pesaje' }}
              </button>
            </template>
          </AppModal>

          <AppModal v-model="showHealthForm" :title="healthFormTitle" size="lg" :busy="savingHealth">
            <form id="lot-health-form" class="row g-2" @submit.prevent="submitHealth">
              <div class="col-12">
                <label class="form-label">Animal *</label>
                <select
                  v-model.number="healthForm.cattle_id"
                  class="form-select"
                  required
                  :disabled="!!healthTarget?.cattle_id"
                >
                  <option :value="null" disabled>Seleccionar arete…</option>
                  <option v-for="a in lotHealthRows" :key="a.cattle_id" :value="a.cattle_id">
                    {{ a.ear_tag }}
                  </option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">Tipo *</label>
                <select v-model="healthForm.event_type" class="form-select" required>
                  <option v-for="(label, key) in healthCatalog.event_types || {}" :key="key" :value="key">{{ label }}</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">Fecha *</label>
                <input v-model="healthForm.event_date" type="date" class="form-control" required />
              </div>
              <div class="col-12">
                <label class="form-label">Concepto *</label>
                <input v-model="healthForm.title" class="form-control" placeholder="Ej. Vacuna clostridial" required />
              </div>
              <div class="col-md-6">
                <label class="form-label">Medicamento</label>
                <select v-model.number="healthForm.material_type_id" class="form-select" @change="onHealthMaterialSelected">
                  <option :value="null">Seleccionar…</option>
                  <option v-for="m in healthCatalog.material_types || []" :key="m.id" :value="m.id">{{ m.name }}</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">Producto (texto)</label>
                <input v-model="healthForm.product_name" class="form-control" />
              </div>
              <div class="col-md-4">
                <label class="form-label">Dosis</label>
                <input v-model.number="healthForm.quantity" type="number" step="0.1" min="0.001" class="form-control" @input="syncHealthCost" />
              </div>
              <div class="col-md-4">
                <label class="form-label">Costo ($)</label>
                <input v-model.number="healthForm.cost" type="number" step="0.01" min="0" class="form-control" />
              </div>
              <div class="col-md-4" v-if="healthForm.event_type === 'illness'">
                <label class="form-label">Resultado *</label>
                <select v-model="healthForm.outcome" class="form-select" required>
                  <option value="">Seleccione…</option>
                  <option v-for="(label, key) in healthCatalog.outcomes || {}" :key="key" :value="key">{{ label }}</option>
                </select>
              </div>
              <div class="col-12">
                <label class="form-label">Notas</label>
                <textarea v-model="healthForm.notes" class="form-control" rows="2" />
              </div>
              <p v-if="healthCatalog.auto_material_expense" class="col-12 small text-muted mb-0">
                El costo se asocia automáticamente a este lote de engorda y actualiza la proyección.
              </p>
            </form>
            <template #footer="{ close }">
              <button type="button" class="btn btn-outline-secondary" :disabled="savingHealth" @click="close">Cancelar</button>
              <button type="submit" form="lot-health-form" class="btn btn-primary" :disabled="savingHealth">
                {{ savingHealth ? 'Guardando…' : 'Guardar aplicación' }}
              </button>
            </template>
          </AppModal>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import RanchRepository from '@/repositories/RanchRepository';
import apexchart from 'vue3-apexcharts';
import AppModal from '@/components/ui/AppModal.vue';
import Swal from 'sweetalert2';
import { formatRanchDate, healthEventDose } from '@/utils/ranchFormat';
import { usePermissions } from '@/composables/use-permissions';

const route = useRoute();
const router = useRouter();
const { hasPermission } = usePermissions();
const canWeigh = computed(() => hasPermission('ranch.weight.record'));
const canManageHealth = computed(() => hasPermission('ranch.health.manage'));
const lot = ref(null);
const evaluation = ref(null);
const feedInvestment = ref(null);
const animalMeta = ref([]);
const analytics = ref(null);
const projection = ref(null);
const feedInventory = ref([]);
const intakes = ref([]);
const feedTypes = ref([]);
const healthEvents = ref([]);
const healthViewMode = ref('animal');
const healthCatalog = ref({});
const showHealthForm = ref(false);
const savingHealth = ref(false);
const healthTarget = ref(null);
const healthForm = ref({
  cattle_id: null,
  event_type: 'vaccination',
  event_date: new Date().toISOString().slice(0, 10),
  title: '',
  product_name: '',
  material_type_id: null,
  quantity: null,
  cost: null,
  outcome: '',
  notes: '',
});
const closePreview = ref(null);
const exportingPdf = ref(false);
const showPurchase = ref(false);
const savingPurchase = ref(false);
const lastIntakeItems = ref([]);
const defaultPrice = ref(45);
const defaultMinGdp = ref(0.5);
const defaultDuration = ref(90);
const activeTab = ref('resumen');
const tabs = computed(() => {
  const items = [
    { id: 'resumen', label: 'Resumen' },
    { id: 'animales', label: 'Animales' },
  ];
  if (canWeigh.value || (analytics.value?.weight_series || []).length) {
    items.push({ id: 'pesajes', label: 'Pesajes' });
  }
  items.push(
    { id: 'alimentacion', label: 'Alimentación' },
    { id: 'salud', label: 'Vacunación' },
    { id: 'metas', label: 'Metas' },
  );
  return items;
});
const showWeighForm = ref(false);
const savingWeigh = ref(false);
const weighTarget = ref(null);
const lastWeighResult = ref(null);
const weighForm = ref({
  weight_kg: null,
  weighed_at: new Date().toISOString().slice(0, 10),
  notes: '',
});
const targets = ref({
  planned_duration_days: 90,
  pasture_cost_per_animal_month: 100,
  target_net_profit: null,
  target_price_per_kg: null,
  target_min_gdp_kg_per_day: null,
});
const exitWeights = reactive({});

const intakeForm = ref({
  intake_date: new Date().toISOString().slice(0, 10),
  notes: '',
  items: [emptyLine()],
});

const purchaseForm = ref({
  material_type_id: null,
  expense_date: new Date().toISOString().slice(0, 10),
  quantity: null,
  unit_cost: null,
  notes: 'Compra alimento',
  adds_to_inventory: true,
});

const purchaseTotal = computed(() => {
  const q = Number(purchaseForm.value.quantity) || 0;
  const u = Number(purchaseForm.value.unit_cost) || 0;
  return Math.round(q * u * 100) / 100;
});

function emptyLine() {
  return { material_type_id: null, quantity: null, unit_price: null };
}

function money(n) {
  return new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN' }).format(n || 0);
}

const healthTypeLabels = {
  vaccination: 'Vacunación',
  deworming: 'Desparasitación',
  illness: 'Enfermedad',
  treatment: 'Tratamiento',
  checkup: 'Revisión',
};

function healthTypeLabel(type) {
  return healthTypeLabels[type] || type;
}

const healthByAnimal = computed(() => {
  const byCattle = new Map();

  for (const event of healthEvents.value) {
    const cattleId = event.cattle_id ?? event.cattle?.id;
    if (!cattleId) continue;

    if (!byCattle.has(cattleId)) {
      byCattle.set(cattleId, {
        cattle_id: cattleId,
        ear_tag: event.cattle?.ear_tag || '—',
        applications: [],
        total_cost: 0,
      });
    }

    const row = byCattle.get(cattleId);
    row.applications.push(event);
    row.total_cost += Number(event.material_expense?.total_cost ?? event.cost ?? 0);
  }

  return [...byCattle.values()]
    .map((row) => ({
      ...row,
      applications: [...row.applications].sort((a, b) => String(b.event_date).localeCompare(String(a.event_date))),
      total_cost: Math.round(row.total_cost * 100) / 100,
    }))
    .sort((a, b) => String(a.ear_tag).localeCompare(String(b.ear_tag)));
});

const lotHealthRows = computed(() => {
  const byId = new Map(healthByAnimal.value.map((row) => [row.cattle_id, row]));

  return animalRows.value
    .map((a) => {
      const existing = byId.get(a.cattle_id);
      if (existing) return existing;

      return {
        cattle_id: a.cattle_id,
        ear_tag: a.cattle?.ear_tag || weighRowFor(a.cattle_id)?.ear_tag || '—',
        applications: [],
        total_cost: 0,
      };
    })
    .sort((a, b) => String(a.ear_tag).localeCompare(String(b.ear_tag)));
});

const healthFormTitle = computed(() => {
  if (healthTarget.value?.ear_tag) return `Salud · ${healthTarget.value.ear_tag}`;
  return 'Registrar aplicación de salud';
});

function profitClass(value) {
  const n = Number(value);
  if (Number.isNaN(n)) return '';
  return n >= 0 ? 'text-success fw-semibold' : 'text-danger fw-semibold';
}

function lineCost(line) {
  return Math.round((Number(line.quantity) || 0) * (Number(line.unit_price) || 0) * 100) / 100;
}

const salePrice = computed(() => targets.value.target_price_per_kg ?? lot.value?.target_price_per_kg ?? defaultPrice.value);
const intakeTotal = computed(() => intakeForm.value.items.reduce((s, l) => s + lineCost(l), 0));
const animalCount = computed(() => (lot.value?.active_animals || []).length);
const animalRows = computed(() => animalMeta.value?.length ? animalMeta.value : lot.value?.active_animals || []);
const weighRows = computed(() => analytics.value?.weight_series || []);
const weighFormTitle = computed(() =>
  weighTarget.value?.ear_tag ? `Pesaje · ${weighTarget.value.ear_tag}` : 'Registrar peso',
);
const currentTotalGain = computed(() =>
  animalRows.value.reduce((s, a) => s + (Number(a.weight_gain_kg) || 0), 0).toFixed(1)
);

const groupGainSummary = computed(() => {
  const fromApi = evaluation.value?.weight_gain_summary;
  if (fromApi) return fromApi;

  const kg = Number(currentTotalGain.value) || 0;
  const price = Number(
    lot.value?.target_price_per_kg
    ?? animalRows.value[0]?.price_per_kg_used
    ?? defaultPrice.value,
  );
  const investment = Number(evaluation.value?.total_investment || 0);
  if (!price) return null;

  const value = Math.round(kg * price * 100) / 100;

  return {
    total_kg: kg,
    price_per_kg: price,
    value_at_price: value,
    investment,
    net_profit: Math.round((value - investment) * 100) / 100,
  };
});

function animalGainSummary(animal) {
  const fromApi = animal?.weight_gain_summary;
  if (fromApi?.value_at_price != null) return fromApi;

  const kg = animal?.weight_gain_kg;
  const price = Number(animal?.price_per_kg_used ?? salePrice.value);
  const investment = Number(animal?.estimated_total_investment || 0);
  if (kg == null || !price) return null;

  const gainKg = Number(kg);
  const value = Math.round(gainKg * price * 100) / 100;

  return {
    total_kg: gainKg,
    price_per_kg: price,
    value_at_price: value,
    investment,
    net_profit: Math.round((value - investment) * 100) / 100,
  };
}

const projectedTotalWeight = computed(() =>
  (projection.value?.animals || []).reduce((s, a) => s + Number(a.exit_weight_kg || 0), 0).toFixed(0)
);

const weightChartSeries = computed(() =>
  (analytics.value?.weight_series || []).map((s) => ({
    name: s.ear_tag,
    data: s.points.map((p) => ({ x: p.date, y: p.weight_kg })),
  }))
);

const weightChartOptions = computed(() => ({
  chart: { toolbar: { show: false }, zoom: { enabled: false } },
  xaxis: { type: 'datetime' },
  yaxis: { title: { text: 'kg' }, min: 0 },
  stroke: { width: 2, curve: 'smooth' },
  legend: { position: 'top' },
}));

const feedChartSeries = computed(() => [{
  name: 'Acumulado',
  data: (analytics.value?.feed_timeline || []).map((p) => ({ x: p.date, y: p.cumulative_cost })),
}]);

const feedChartOptions = computed(() => ({
  chart: { toolbar: { show: false } },
  xaxis: { type: 'datetime' },
  yaxis: { labels: { formatter: (v) => `$${Math.round(v)}` } },
  dataLabels: { enabled: false },
  stroke: { curve: 'smooth' },
}));

const investmentBarItems = computed(() => {
  const b = analytics.value?.investment_breakdown || {};
  const items = [
    { label: 'Alimento', value: Number(b.feed_cost || 0), color: '#4361ee' },
    { label: 'Vacunación / salud', value: Number(b.health_cost || 0), color: '#2d6a4f' },
    { label: 'Pastura', value: Number(b.pasture_cost || 0), color: '#bc6c25' },
  ].filter((i) => i.value > 0);
  const max = Math.max(...items.map((i) => i.value), 1);
  return items.map((i) => ({ ...i, pct: Math.round((i.value / max) * 100) }));
});

function stockFor(materialTypeId) {
  const row = feedInventory.value.find((f) => f.id === materialTypeId);
  return row ? `${row.stock_quantity} ${row.unit}` : '—';
}

function currentWeight(cattleId) {
  const row = animalRows.value.find((a) => a.cattle_id === cattleId);
  return row?.current_weight_kg ?? '—';
}

function onFeedSelected(line) {
  const feed = feedTypes.value.find((f) => f.id === line.material_type_id);
  if (feed && (line.unit_price == null || line.unit_price === '')) {
    line.unit_price = feed.default_unit_price != null ? Number(feed.default_unit_price) : null;
  }
}

function onPurchaseMaterialSelected() {
  const feed = feedTypes.value.find((f) => f.id === purchaseForm.value.material_type_id);
  if (feed && (purchaseForm.value.unit_cost == null || purchaseForm.value.unit_cost === '')) {
    purchaseForm.value.unit_cost = feed.default_unit_price != null ? Number(feed.default_unit_price) : null;
  }
}

function applyLastIntake() {
  if (!lastIntakeItems.value.length) return;
  intakeForm.value.items = lastIntakeItems.value.map((i) => ({
    material_type_id: i.material_type_id,
    quantity: Number(i.quantity),
    unit_price: i.unit_price != null ? Number(i.unit_price) : null,
  }));
}

function addLine() { intakeForm.value.items.push(emptyLine()); }
function removeLine(idx) { intakeForm.value.items.splice(idx, 1); }

function buildExitPayload() {
  return (lot.value.active_animals || []).map((a) => ({
    cattle_id: a.cattle_id,
    exit_weight_kg: exitWeights[a.cattle_id],
  }));
}

function fillProjectedWeights() {
  (projection.value?.animals || []).forEach((a) => {
    exitWeights[a.cattle_id] = a.exit_weight_kg;
  });
  refreshPreview();
}

function fillCurrentWeights() {
  animalRows.value.forEach((a) => {
    if (a.current_weight_kg) exitWeights[a.cattle_id] = a.current_weight_kg;
  });
  refreshPreview();
}

async function loadFeeds() {
  const all = await RanchRepository.listFeedCatalog() || [];
  feedTypes.value = all.filter((f) => f.active);
  const inv = await RanchRepository.getFeedInventory().catch(() => []);
  const stockMap = Object.fromEntries((inv || []).map((r) => [r.id, r.stock_quantity]));
  feedTypes.value = feedTypes.value.map((f) => ({ ...f, stock_quantity: stockMap[f.id] ?? f.stock_quantity ?? 0 }));
}

async function loadIntakes() {
  const res = await RanchRepository.listFeedIntakes(route.params.id);
  intakes.value = res.data || [];
  lastIntakeItems.value = res.meta?.last_intake?.items || intakes.value[0]?.items || [];
  if (res.meta?.feed_investment) feedInvestment.value = res.meta.feed_investment;
  if (lastIntakeItems.value.length && intakeForm.value.items.length === 1 && !intakeForm.value.items[0].material_type_id) {
    applyLastIntake();
  }
}

function weighRowFor(cattleId) {
  return weighRows.value.find((row) => row.cattle_id === cattleId) || null;
}

function animalFinancial(cattleId) {
  return animalRows.value.find((row) => row.cattle_id === cattleId) || null;
}

function healthCostFor(cattleId) {
  const row = animalFinancial(cattleId);
  if (!row) return null;
  return {
    actual: Number(row.estimated_health_cost || 0),
    projected: Number(row.projected_health_cost || row.estimated_health_cost || 0),
  };
}

function healthCostLabel(cattleId) {
  const health = healthCostFor(cattleId);
  if (!health) return '—';
  if (health.projected > health.actual) {
    return `${money(health.actual)} → est. ${money(health.projected)}`;
  }
  return money(health.actual);
}

watch(
  () => healthForm.value.event_type,
  (t) => {
    if (t !== 'illness') healthForm.value.outcome = '';
  },
);

function goToWeighTab(cattleId = null) {
  activeTab.value = 'pesajes';
  const query = { tab: 'pesajes' };
  if (cattleId) query.cattle_id = cattleId;
  router.replace({ query });
  if (cattleId) {
    const row = weighRowFor(cattleId);
    if (row) openWeighForm(row);
  }
}

function goToHealthTab(cattleId = null) {
  activeTab.value = 'salud';
  const query = { tab: 'salud' };
  if (cattleId) query.cattle_id = cattleId;
  router.replace({ query });
  if (cattleId) {
    const row = lotHealthRows.value.find((r) => r.cattle_id === Number(cattleId));
    if (row) openHealthForm(row);
  } else {
    openHealthForm();
  }
}

function openWeighForAnimal(cattleId) {
  goToWeighTab(cattleId);
}

function applyRouteTab() {
  const tab = route.query.tab;
  if (tab && tabs.value.some((item) => item.id === tab)) {
    activeTab.value = tab;
  }
  const cattleId = route.query.cattle_id;
  if (cattleId && activeTab.value === 'pesajes') {
    const row = weighRowFor(Number(cattleId));
    if (row) openWeighForm(row);
  }
  if (cattleId && activeTab.value === 'salud') {
    const row = lotHealthRows.value.find((r) => r.cattle_id === Number(cattleId));
    if (row) openHealthForm(row);
  }
}

async function ensureHealthCatalog() {
  if (healthCatalog.value.event_types) return;
  healthCatalog.value = await RanchRepository.healthCatalog();
}

function resetHealthForm() {
  healthForm.value = {
    cattle_id: null,
    event_type: 'vaccination',
    event_date: new Date().toISOString().slice(0, 10),
    title: '',
    product_name: '',
    material_type_id: null,
    quantity: null,
    cost: null,
    outcome: '',
    notes: '',
  };
}

async function openHealthForm(animal = null) {
  if (!canManageHealth.value || lot.value?.status !== 'open') return;
  await ensureHealthCatalog();
  healthTarget.value = animal;
  resetHealthForm();
  if (animal) healthForm.value.cattle_id = animal.cattle_id;
  else if (lotHealthRows.value.length === 1) healthForm.value.cattle_id = lotHealthRows.value[0].cattle_id;
  showHealthForm.value = true;
  activeTab.value = 'salud';
}

function onHealthMaterialSelected() {
  const material = (healthCatalog.value.material_types || []).find(
    (m) => m.id === healthForm.value.material_type_id,
  );
  if (material && !healthForm.value.product_name) {
    healthForm.value.product_name = material.name;
  }
  syncHealthCost();
}

function syncHealthCost() {
  const material = (healthCatalog.value.material_types || []).find(
    (m) => m.id === healthForm.value.material_type_id,
  );
  const qty = Number(healthForm.value.quantity);
  const unit = Number(material?.default_unit_price);
  if (qty > 0 && unit >= 0) {
    healthForm.value.cost = Math.round(qty * unit * 100) / 100;
  }
}

async function submitHealth() {
  if (!healthForm.value.cattle_id) {
    Swal.fire({ icon: 'warning', title: 'Seleccione un animal' });
    return;
  }
  if (healthForm.value.event_type === 'illness' && !healthForm.value.outcome) {
    Swal.fire({ icon: 'warning', title: 'Indique el resultado de la enfermedad' });
    return;
  }
  savingHealth.value = true;
  try {
    await RanchRepository.createHealthEvent({
      cattle_id: healthForm.value.cattle_id,
      event_type: healthForm.value.event_type,
      event_date: healthForm.value.event_date,
      title: healthForm.value.title,
      product_name: healthForm.value.product_name || null,
      material_type_id: healthForm.value.material_type_id,
      quantity: healthForm.value.quantity || null,
      cost: healthForm.value.cost || null,
      outcome: healthForm.value.outcome || null,
      notes: healthForm.value.notes || null,
    });
    showHealthForm.value = false;
    healthTarget.value = null;
    Swal.fire({ icon: 'success', title: 'Aplicación registrada', timer: 1200, showConfirmButton: false });
    await load();
  } catch (e) {
    Swal.fire('Error', e?.response?.data?.message || 'No se pudo registrar la aplicación.', 'error');
  } finally {
    savingHealth.value = false;
  }
}

function openWeighForm(row) {
  weighTarget.value = row;
  lastWeighResult.value = null;
  weighForm.value = {
    weight_kg: row.current_weight_kg ?? null,
    weighed_at: new Date().toISOString().slice(0, 10),
    notes: '',
  };
  showWeighForm.value = true;
}

async function submitWeigh() {
  if (!weighTarget.value) return;
  savingWeigh.value = true;
  try {
    const record = await RanchRepository.createWeightRecord({
      cattle_id: weighTarget.value.cattle_id,
      weight_kg: weighForm.value.weight_kg,
      weighed_at: weighForm.value.weighed_at,
      notes: weighForm.value.notes || null,
    });
    lastWeighResult.value = record;
    Swal.fire({ icon: 'success', title: 'Pesaje registrado', timer: 1200, showConfirmButton: false });
    showWeighForm.value = false;
    await load();
  } catch (e) {
    Swal.fire('Error', e?.response?.data?.message || 'No se pudo registrar el pesaje.', 'error');
  } finally {
    savingWeigh.value = false;
  }
}

async function load() {
  const res = await RanchRepository.getFatteningLot(route.params.id);
  lot.value = res.data;
  evaluation.value = res.meta?.evaluation;
  feedInvestment.value = res.meta?.feed_investment || null;
  animalMeta.value = res.meta?.animals || [];
  analytics.value = res.meta?.analytics || null;
  projection.value = analytics.value?.projection || null;
  feedInventory.value = res.meta?.feed_inventory || [];
  healthEvents.value = res.meta?.health_events || [];

  if (!healthEvents.value.length) {
    const page = await RanchRepository.listHealthEvents({
      fattening_lot_id: route.params.id,
      per_page: 100,
    });
    healthEvents.value = page.data || [];
  }

  defaultPrice.value = res.meta?.default_price_per_kg ?? 45;
  defaultMinGdp.value = res.meta?.default_min_gdp_kg_per_day ?? 0.5;
  defaultDuration.value = res.meta?.default_duration_days ?? 90;
  targets.value = {
    planned_duration_days: lot.value.planned_duration_days ?? defaultDuration.value,
    pasture_cost_per_animal_month: lot.value.pasture_cost_per_animal_month ?? 100,
    target_net_profit: lot.value.target_net_profit,
    target_price_per_kg: lot.value.target_price_per_kg,
    target_min_gdp_kg_per_day: lot.value.target_min_gdp_kg_per_day,
  };
  (lot.value.active_animals || []).forEach((a) => {
    if (exitWeights[a.cattle_id] == null && a.current_weight_kg) {
      exitWeights[a.cattle_id] = a.current_weight_kg;
    }
  });
  await Promise.all([loadIntakes(), refreshPreview()]);
}

async function refreshPreview() {
  if (lot.value?.status !== 'open') return;
  const payload = buildExitPayload();
  if (payload.some((p) => !p.exit_weight_kg)) { closePreview.value = null; return; }
  try {
    closePreview.value = await RanchRepository.previewCloseFatteningLot(route.params.id, payload, salePrice.value);
  } catch { closePreview.value = null; }
}

async function saveTargets() {
  await RanchRepository.updateFatteningLot(route.params.id, targets.value);
  Swal.fire({ icon: 'success', title: 'Guardado', timer: 1200, showConfirmButton: false });
  await load();
}

async function saveIntake() {
  try {
    await RanchRepository.createFeedIntake(route.params.id, {
      intake_date: intakeForm.value.intake_date,
      notes: intakeForm.value.notes || null,
      items: intakeForm.value.items.map((l) => ({
        material_type_id: l.material_type_id,
        quantity: l.quantity,
        unit_price: l.unit_price,
      })),
    });
    intakeForm.value.intake_date = new Date().toISOString().slice(0, 10);
    intakeForm.value.notes = '';
    Swal.fire({ icon: 'success', title: 'Ración guardada', timer: 1200, showConfirmButton: false });
    await load();
  } catch (e) {
    Swal.fire('Error', e?.response?.data?.message || 'No se pudo guardar.', 'error');
  }
}

async function savePurchase() {
  savingPurchase.value = true;
  try {
    await RanchRepository.createExpense({
      ...purchaseForm.value,
      fattening_lot_id: null,
      adds_to_inventory: true,
    });
    showPurchase.value = false;
    purchaseForm.value = {
      material_type_id: null,
      expense_date: new Date().toISOString().slice(0, 10),
      quantity: null,
      unit_cost: null,
      notes: 'Compra alimento',
      adds_to_inventory: true,
    };
    Swal.fire({ icon: 'success', title: 'Compra registrada', timer: 1200, showConfirmButton: false });
    await loadFeeds();
    await load();
  } catch (e) {
    Swal.fire('Error', e?.response?.data?.message || 'No se pudo registrar la compra.', 'error');
  } finally {
    savingPurchase.value = false;
  }
}

async function exportPdf() {
  exportingPdf.value = true;
  try {
    const blob = await RanchRepository.downloadFatteningLotPdf(route.params.id);
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `lote-engorda-${lot.value?.name || route.params.id}.pdf`.replace(/[^a-z0-9._-]+/gi, '-');
    a.click();
    URL.revokeObjectURL(url);
  } catch {
    Swal.fire({ icon: 'error', title: 'No se pudo generar el PDF' });
  } finally {
    exportingPdf.value = false;
  }
}

async function removeIntake(row) {
  const ok = await Swal.fire({ icon: 'warning', title: '¿Eliminar ración?', showCancelButton: true });
  if (!ok.isConfirmed) return;
  await RanchRepository.deleteFeedIntake(route.params.id, row.id);
  await load();
}

async function closeLot() {
  const payload = buildExitPayload();
  if (payload.some((p) => !p.exit_weight_kg)) {
    Swal.fire({ icon: 'warning', title: 'Indique peso de cierre para todos' });
    return;
  }
  const res = await RanchRepository.closeFatteningLot(route.params.id, payload);
  Swal.fire({ icon: 'success', title: 'Lote cerrado' });
  lot.value = res.data;
  evaluation.value = res.meta?.evaluation;
}

async function closeAndSell() {
  const payload = buildExitPayload();
  if (payload.some((p) => !p.exit_weight_kg)) {
    Swal.fire({ icon: 'warning', title: 'Indique peso de venta para todos' });
    return;
  }
  const confirm = await Swal.fire({
    icon: 'question',
    title: '¿Vender todo el grupo?',
    html: `Precio: <strong>${money(salePrice.value)}/kg</strong><br>Utilidad estimada: ${money(closePreview.value?.projected_net_profit)}`,
    showCancelButton: true,
    confirmButtonText: 'Vender',
  });
  if (!confirm.isConfirmed) return;
  try {
    const res = await RanchRepository.closeAndSellFatteningLot(route.params.id, payload, salePrice.value);
    Swal.fire({ icon: 'success', title: 'Grupo vendido y lote cerrado' });
    lot.value = res.data;
    evaluation.value = res.meta?.evaluation;
    closePreview.value = res.meta?.close_preview;
  } catch (e) {
    Swal.fire('Error', e?.response?.data?.message || 'Error al vender', 'error');
  }
}

onMounted(async () => {
  await loadFeeds();
  await load();
  applyRouteTab();
});

watch(() => route.query.tab, applyRouteTab);
</script>

<style scoped>
.animal-health-group {
  border: 1px solid var(--bs-border-color, #dee2e6);
  border-radius: 0.5rem;
  overflow: hidden;
}

.animal-health-header {
  padding: 0.75rem 1rem;
  background: var(--bs-light, #f8f9fa);
  border-bottom: 1px solid var(--bs-border-color, #dee2e6);
}

.animal-health-group .table {
  margin-bottom: 0;
}

.animal-health-group .table thead th {
  background: #fff;
  border-top: none;
}

.investment-bars {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.investment-bar-row {
  display: grid;
  grid-template-columns: minmax(88px, 1fr) minmax(60px, 2fr) auto;
  gap: 10px;
  align-items: center;
  font-size: 0.88rem;
}

.investment-bar-label {
  color: #888ea8;
  line-height: 1.3;
}

.investment-bar-track {
  height: 12px;
  border-radius: 999px;
  background: #eef2f7;
  overflow: hidden;
}

.investment-bar-fill {
  height: 100%;
  border-radius: 999px;
  min-width: 2px;
}

.investment-bar-value {
  font-weight: 700;
  white-space: nowrap;
  color: var(--ranch-accent-dark, #1b4332);
}

.weigh-callout {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 14px 16px;
  border-radius: 12px;
  border: 1px solid #dbeafe;
  background: linear-gradient(135deg, #f8fbff 0%, #f0f7ff 100%);
}

.weigh-callout-icon {
  width: 42px;
  height: 42px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #4361ee;
  color: #fff;
  font-size: 1.15rem;
  flex-shrink: 0;
}

.btn-weigh-cta {
  box-shadow: 0 2px 8px rgba(67, 97, 238, 0.25);
}

.btn-weigh-row {
  min-width: 72px;
  font-weight: 600;
}

.gdp-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 999px;
  background: #ecfdf5;
  color: #047857;
  font-size: 0.78rem;
  font-weight: 700;
}

.weigh-panel-intro {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 16px;
  flex-wrap: wrap;
}

.weigh-panel-meta {
  text-align: right;
  padding: 8px 14px;
  border-radius: 10px;
  background: #f8f9fc;
  border: 1px solid #e9ecef;
}

.weigh-card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 16px;
}

.weigh-card {
  border: 1px solid #e9ecef;
  border-radius: 14px;
  padding: 16px;
  background: #fff;
  box-shadow: 0 2px 10px rgba(15, 23, 42, 0.04);
  transition: box-shadow 0.15s ease, border-color 0.15s ease;
}

.weigh-card:hover {
  border-color: #c7d2fe;
  box-shadow: 0 4px 16px rgba(67, 97, 238, 0.08);
}

.weigh-card.has-alert {
  border-color: #fde68a;
  background: linear-gradient(180deg, #fffef8 0%, #fff 100%);
}

.weigh-card-head {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 12px;
}

.weigh-card-tag {
  font-weight: 700;
  color: #1e293b;
  text-decoration: none;
}

.weigh-card-tag:hover {
  color: #4361ee;
}

.weigh-card-gain {
  font-size: 0.82rem;
  font-weight: 700;
  color: #059669;
  white-space: nowrap;
}

.weigh-card-track {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 0.95rem;
}

.weigh-card-weight.current {
  font-weight: 700;
  color: #1e293b;
}

.weigh-card-arrow {
  color: #94a3b8;
}

.weigh-card-last {
  min-height: 2.4em;
}

.weigh-card-health {
  margin-top: 6px;
  color: #64748b;
}

.health-proj-hint {
  font-size: 0.75rem;
  color: #64748b;
}

.group-gain-panel {
  padding: 16px 18px;
  border-radius: 14px;
  border: 1px solid #c7d2fe;
  background: linear-gradient(135deg, #fafbff 0%, #f0f4ff 100%);
}

.group-gain-title {
  margin: 0 0 4px;
  font-weight: 700;
  color: #1e293b;
}

.group-gain-flow {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;
  gap: 10px 14px;
}

.group-gain-step {
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 88px;
}

.group-gain-step.highlight strong {
  color: #059669;
}

.group-gain-step.result strong {
  font-size: 1.15rem;
}

.group-gain-label {
  font-size: 0.72rem;
  text-transform: uppercase;
  letter-spacing: 0.03em;
  color: #64748b;
}

.group-gain-op {
  font-size: 1.1rem;
  font-weight: 700;
  color: #94a3b8;
  padding-bottom: 4px;
}

@media (max-width: 767px) {
  .group-gain-flow {
    display: grid;
    grid-template-columns: 1fr auto 1fr;
    gap: 8px;
  }

  .group-gain-op {
    display: none;
  }

  .group-gain-step.result {
    grid-column: 1 / -1;
    padding-top: 8px;
    border-top: 1px dashed #cbd5e1;
  }
}
</style>
