@extends('layouts.ownerLayout')

@section('title', 'Paquetes')

@section('page-script')
@vite('resources/assets/js/owner-price-rules.js')
@endsection

@php
  $giftIncludedOptions = $giftOptions->where('type', 'included')->values();
  $giftAdditionalOptions = $giftOptions->where('type', 'additional')->values();
  $giftRuleCatalog = $giftOptions->map(function ($item) {
      return [
          'code' => $item->code,
          'name' => $item->name,
          'type' => $item->type,
          'internal_cost' => (float) $item->internal_cost,
          'base_price' => (float) $item->base_price,
      ];
  })->values()->all();
  $artistRuleCatalog = $artistOptions->map(function ($item) {
      return [
          'code' => $item->code,
          'name' => $item->name,
          'internal_cost' => (float) $item->internal_cost,
          'base_price' => (float) $item->base_price,
      ];
  })->values()->all();
  $otherCostRuleCatalog = $otherCostOptions->map(function ($item) {
      return [
          'code' => $item->code,
          'name' => $item->name,
          'internal_cost' => (float) $item->internal_cost,
          'base_price' => (float) $item->base_price,
      ];
  })->values()->all();
@endphp

@section('content')
@if($currentGroup)
<div class="card mb-4">
  <div class="card-body d-flex flex-column flex-lg-row align-items-lg-center justify-content-between gap-3">
    <div>
      <h5 class="mb-1">Paquetes de {{ $currentGroup->name }}</h5>
      <p class="mb-0 text-body-secondary">Los paquetes, obsequios, artistas y otros costos ya se administran por grupo mariachi.</p>
    </div>
    <div class="d-flex flex-column flex-sm-row gap-2">
      <form method="GET" action="{{ route('owner.settings.packages') }}">
        <select class="form-select" name="mariachi_group_id" onchange="this.form.submit()">
          @foreach($mariachiGroups as $group)
            <option value="{{ $group->id }}" @selected((int) $currentGroup->id === (int) $group->id)>{{ $group->name }}</option>
          @endforeach
        </select>
      </form>
      <a href="{{ route('owner.settings.mariachi-groups.show', $currentGroup) }}" class="btn btn-label-primary">Ver grupo</a>
    </div>
  </div>
</div>
@endif

<div class="d-flex align-items-center justify-content-between flex-wrap gap-3 mb-4">
  <div>
    <h4 class="mb-1">Paquetes de serenata</h4>
    <p class="mb-0 text-body-secondary">Administra paquetes por ciudad y define costo interno, comisión y precio final.</p>
  </div>
  <button type="button" class="btn btn-primary" id="btnOpenPackageCreate" @disabled(!$canManagePackages)>
    <i class="icon-base ti tabler-plus icon-xs me-1"></i>
    Agregar paquete
  </button>
</div>

@if(session('status'))
  <div class="alert alert-success mb-4">{{ session('status') }}</div>
@endif
@if($errors->any())
  <div class="alert alert-danger mb-4">
    <ul class="mb-0">
      @foreach($errors->all() as $error)
        <li>{{ $error }}</li>
      @endforeach
    </ul>
  </div>
@endif

<div class="card">
  <div class="card-header border-bottom">
    <h5 class="card-title mb-0">Lista de paquetes</h5>
  </div>
  <div class="table-responsive">
    <table class="table mb-0">
      <thead>
        <tr>
          <th>Nombre</th>
          <th>Ciudad</th>
          <th>Costo interno</th>
          <th>Comisión</th>
          <th>Precio paquete</th>
          <th>Incluye</th>
          <th>Estado</th>
          <th>Orden</th>
          <th>Acciones</th>
        </tr>
      </thead>
      <tbody>
      @forelse($items as $item)
        <tr>
          <td>
            <span class="fw-medium">{{ $item->name }}</span>
            @if($item->is_default)
              <span class="badge bg-label-success ms-1">Por defecto</span>
            @endif
          </td>
          <td>{{ $item->city }}</td>
          <td>${{ number_format((float) $item->internal_cost, 0, ',', '.') }}</td>
          <td>${{ number_format((float) $item->commission_amount, 0, ',', '.') }}</td>
          <td>${{ number_format((float) $item->base_price, 0, ',', '.') }}</td>
          <td class="small text-body-secondary">
            Obsequios: {{ count($item->gift_codes ?? []) }}<br>
            Artistas: {{ count($item->artist_codes ?? []) }}<br>
            Otros costos: {{ count($item->other_cost_codes ?? []) }}
          </td>
          <td>
            <span class="badge {{ $item->is_active ? 'bg-label-success' : 'bg-label-secondary' }}">
              {{ $item->is_active ? 'Activo' : 'Inactivo' }}
            </span>
          </td>
          <td>{{ $item->sort_order }}</td>
          <td>
            <div class="d-flex gap-2">
              @php
                $packagePayload = json_encode([
                  'id' => (int) $item->id,
                  'name' => (string) $item->name,
                  'city' => (string) $item->city,
                  'internal_cost' => (float) $item->internal_cost,
                  'commission_amount' => (float) $item->commission_amount,
                  'base_price' => (float) $item->base_price,
                  'sort_order' => (int) $item->sort_order,
                  'is_active' => (bool) $item->is_active,
                  'is_default' => (bool) $item->is_default,
                  'gift_codes' => array_values($item->gift_codes ?? []),
                  'artist_codes' => array_values($item->artist_codes ?? []),
                  'other_cost_codes' => array_values($item->other_cost_codes ?? []),
                ], JSON_UNESCAPED_UNICODE);
                $packagePayloadEncoded = base64_encode($packagePayload);
              @endphp
              <button
                type="button"
                class="btn btn-sm btn-label-secondary btn-view-package"
                data-package="{{ $packagePayloadEncoded }}">
                Ver
              </button>
              <button
                type="button"
                class="btn btn-sm btn-label-primary btn-edit-package"
                data-package="{{ $packagePayloadEncoded }}">
                Editar
              </button>
              <button
                type="button"
                class="btn btn-sm btn-label-info btn-manage-price-rules"
                data-target-type="package"
                data-target-id="{{ $item->id }}"
                data-target-name="{{ $item->name }}">
                Reglas
              </button>
              <button
                type="button"
                class="btn btn-sm btn-label-danger btn-delete-package"
                data-id="{{ $item->id }}"
                data-name="{{ $item->name }}">
                Eliminar
              </button>
            </div>
          </td>
        </tr>
      @empty
        <tr>
          <td colspan="9" class="text-center text-body-secondary py-5">No hay paquetes creados.</td>
        </tr>
      @endforelse
      </tbody>
    </table>
  </div>
</div>

<div class="modal fade" id="packageEditorModal" tabindex="-1" aria-labelledby="packageEditorModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-fullscreen">
    <div class="modal-content">
      <div class="modal-header border-bottom">
        <h5 id="packageEditorModalLabel" class="modal-title">Agregar paquete</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="packageEditorForm" method="POST" action="{{ route('owner.settings.packages.store') }}">
        @csrf
        <input type="hidden" name="mariachi_group_id" value="{{ $currentGroup?->id }}">
        <input type="hidden" name="_method" id="packageMethod" value="POST">

        <div class="modal-body">
          <div class="row g-4">
            <div class="col-12 col-xl-4">
              <div class="card border shadow-none h-100">
                <div class="card-body">
                  <h6 class="mb-3">Datos del paquete</h6>

                  <div class="mb-3">
                    <label class="form-label" for="packageName">Nombre</label>
                    <input type="text" name="name" id="packageName" class="form-control" required>
                  </div>

                  <div class="mb-3">
                    <label class="form-label" for="packageCity">Ciudad</label>
                    <input type="text" name="city" id="packageCity" class="form-control" placeholder="Bogotá o *" required>
                  </div>

                  <div class="mb-3">
                    <label class="form-label" for="packageCommissionAmount">Comisión ganada (COP)</label>
                    <input type="number" min="0" step="1000" name="commission_amount" id="packageCommissionAmount" class="form-control" value="0" required>
                  </div>

                  <div class="mb-3">
                    <label class="form-label" for="packageInternalCostDisplay">Costo interno calculado (COP)</label>
                    <input type="text" id="packageInternalCostDisplay" class="form-control" value="$0" readonly>
                    <small class="text-body-secondary">Se calcula con obsequios, artistas y otros costos seleccionados.</small>
                  </div>

                  <div class="mb-3">
                    <label class="form-label" for="packageBasePriceDisplay">Precio del paquete (COP)</label>
                    <input type="text" id="packageBasePriceDisplay" class="form-control" value="$0" readonly>
                    <small class="text-body-secondary">Precio = Costo interno + Comisión.</small>
                  </div>

                  <div class="row g-3">
                    <div class="col-6">
                      <label class="form-label" for="packageIsActive">Estado</label>
                      <select name="is_active" id="packageIsActive" class="form-select">
                        <option value="1">Activo</option>
                        <option value="0">Inactivo</option>
                      </select>
                    </div>

                    <div class="col-6">
                      <label class="form-label" for="packageIsDefault">Por defecto</label>
                      <select name="is_default" id="packageIsDefault" class="form-select">
                        <option value="0">No</option>
                        <option value="1">Sí</option>
                      </select>
                    </div>

                    <div class="col-12">
                      <label class="form-label" for="packageSortOrder">Orden</label>
                      <input type="number" min="0" name="sort_order" id="packageSortOrder" class="form-control" value="100">
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="col-12 col-xl-8">
              <div class="card border shadow-none h-100">
                <div class="card-body">
                  <h6 class="mb-3">Incluye en este paquete</h6>

                  <div class="row g-0 border rounded overflow-hidden">
                    <div class="col-md-4 border-end">
                      <div class="nav flex-column nav-pills p-3 gap-2" id="package-catalog-tabs" role="tablist">
                        <button class="btn btn-label-primary text-start active" data-bs-toggle="pill" data-bs-target="#pkg-tab-gifts-included" type="button">Obsequios incluidos</button>
                        <button class="btn btn-label-primary text-start" data-bs-toggle="pill" data-bs-target="#pkg-tab-gifts-additional" type="button">Obsequios adicionales</button>
                        <button class="btn btn-label-primary text-start" data-bs-toggle="pill" data-bs-target="#pkg-tab-artists" type="button">Artistas</button>
                        <button class="btn btn-label-primary text-start" data-bs-toggle="pill" data-bs-target="#pkg-tab-other-costs" type="button">Otros costos</button>
                      </div>
                    </div>

                    <div class="col-md-8">
                      <div class="tab-content p-3">
                        <div class="tab-pane fade show active" id="pkg-tab-gifts-included">
                          <div class="small text-body-secondary mb-2">Selecciona obsequios incluidos.</div>
                          <div class="row g-2">
                            @forelse($giftIncludedOptions as $item)
                              <div class="col-md-6">
                                <label class="border rounded p-2 d-flex align-items-start gap-2 w-100">
                                  <input
                                    type="checkbox"
                                    class="form-check-input mt-1 pkg-item-checkbox"
                                    name="gift_codes[]"
                                    value="{{ $item->code }}"
                                    data-internal-cost="{{ (float) $item->internal_cost }}">
                                  <span>
                                    <strong>{{ $item->name }}</strong><br>
                                    <small class="text-body-secondary">Interno: ${{ number_format((float) $item->internal_cost, 0, ',', '.') }} | Cliente: ${{ number_format((float) $item->base_price, 0, ',', '.') }}</small>
                                  </span>
                                </label>
                              </div>
                            @empty
                              <div class="col-12 text-body-secondary small">No hay obsequios incluidos activos.</div>
                            @endforelse
                          </div>
                        </div>

                        <div class="tab-pane fade" id="pkg-tab-gifts-additional">
                          <div class="small text-body-secondary mb-2">Selecciona obsequios adicionales.</div>
                          <div class="row g-2">
                            @forelse($giftAdditionalOptions as $item)
                              <div class="col-md-6">
                                <label class="border rounded p-2 d-flex align-items-start gap-2 w-100">
                                  <input
                                    type="checkbox"
                                    class="form-check-input mt-1 pkg-item-checkbox"
                                    name="gift_codes[]"
                                    value="{{ $item->code }}"
                                    data-internal-cost="{{ (float) $item->internal_cost }}">
                                  <span>
                                    <strong>{{ $item->name }}</strong><br>
                                    <small class="text-body-secondary">Interno: ${{ number_format((float) $item->internal_cost, 0, ',', '.') }} | Cliente: ${{ number_format((float) $item->base_price, 0, ',', '.') }}</small>
                                  </span>
                                </label>
                              </div>
                            @empty
                              <div class="col-12 text-body-secondary small">No hay obsequios adicionales activos.</div>
                            @endforelse
                          </div>
                        </div>

                        <div class="tab-pane fade" id="pkg-tab-artists">
                          <div class="small text-body-secondary mb-2">Selecciona artistas base del paquete.</div>
                          <div class="row g-2">
                            @forelse($artistOptions as $item)
                              <div class="col-md-6">
                                <label class="border rounded p-2 d-flex align-items-start gap-2 w-100">
                                  <input
                                    type="checkbox"
                                    class="form-check-input mt-1 pkg-item-checkbox"
                                    name="artist_codes[]"
                                    value="{{ $item->code }}"
                                    data-internal-cost="{{ (float) $item->internal_cost }}">
                                  <span>
                                    <strong>{{ $item->name }}</strong><br>
                                    <small class="text-body-secondary">{{ $item->type === 'included' ? 'Incluido' : 'Adicional' }} | Interno: ${{ number_format((float) $item->internal_cost, 0, ',', '.') }} | Cliente: ${{ number_format((float) $item->base_price, 0, ',', '.') }}</small>
                                  </span>
                                </label>
                              </div>
                            @empty
                              <div class="col-12 text-body-secondary small">No hay artistas activos.</div>
                            @endforelse
                          </div>
                        </div>

                        <div class="tab-pane fade" id="pkg-tab-other-costs">
                          <div class="small text-body-secondary mb-2">Selecciona otros costos incluidos.</div>
                          <div class="row g-2">
                            @forelse($otherCostOptions as $item)
                              <div class="col-md-6">
                                <label class="border rounded p-2 d-flex align-items-start gap-2 w-100">
                                  <input
                                    type="checkbox"
                                    class="form-check-input mt-1 pkg-item-checkbox"
                                    name="other_cost_codes[]"
                                    value="{{ $item->code }}"
                                    data-internal-cost="{{ (float) $item->internal_cost }}">
                                  <span>
                                    <strong>{{ $item->name }}</strong><br>
                                    <small class="text-body-secondary">Interno: ${{ number_format((float) $item->internal_cost, 0, ',', '.') }} | Cliente: ${{ number_format((float) $item->base_price, 0, ',', '.') }}</small>
                                  </span>
                                </label>
                              </div>
                            @empty
                              <div class="col-12 text-body-secondary small">No hay otros costos activos.</div>
                            @endforelse
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="modal-footer border-top">
          <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" class="btn btn-primary" id="packageSubmitBtn">Guardar paquete</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="packageViewModal" tabindex="-1" aria-labelledby="packageViewModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-fullscreen">
    <div class="modal-content">
      <div class="modal-header border-bottom">
        <h5 id="packageViewModalLabel" class="modal-title">Detalle del paquete</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="row g-4">
          <div class="col-12 col-xl-4">
            <div class="card border shadow-none h-100">
              <div class="card-body">
                <h6 class="mb-3">Resumen</h6>
                <div class="d-flex flex-column gap-3">
                  <div>
                    <small class="text-body-secondary d-block">Nombre</small>
                    <span class="fw-semibold" id="viewPackageName">-</span>
                  </div>
                  <div>
                    <small class="text-body-secondary d-block">Ciudad</small>
                    <span class="fw-semibold" id="viewPackageCity">-</span>
                  </div>
                  <div>
                    <small class="text-body-secondary d-block">Costo interno</small>
                    <span class="fw-semibold" id="viewPackageInternalCost">$0</span>
                  </div>
                  <div>
                    <small class="text-body-secondary d-block">Comisión</small>
                    <span class="fw-semibold" id="viewPackageCommission">$0</span>
                  </div>
                  <div>
                    <small class="text-body-secondary d-block">Precio paquete</small>
                    <span class="fw-semibold" id="viewPackageBasePrice">$0</span>
                  </div>
                  <div>
                    <small class="text-body-secondary d-block">Estado</small>
                    <span class="fw-semibold" id="viewPackageStatus">-</span>
                  </div>
                  <div>
                    <small class="text-body-secondary d-block">Orden</small>
                    <span class="fw-semibold" id="viewPackageOrder">-</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="col-12 col-xl-8">
            <div class="card border shadow-none mb-4">
              <div class="card-body">
                <h6 class="mb-3">Obsequios incluidos</h6>
                <div id="viewPackageGifts" class="d-flex flex-wrap gap-2"></div>
              </div>
            </div>
            <div class="card border shadow-none mb-4">
              <div class="card-body">
                <h6 class="mb-3">Artistas</h6>
                <div id="viewPackageArtists" class="d-flex flex-wrap gap-2"></div>
              </div>
            </div>
            <div class="card border shadow-none">
              <div class="card-body">
                <h6 class="mb-3">Otros costos</h6>
                <div id="viewPackageOtherCosts" class="d-flex flex-wrap gap-2"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
  window.packageRuleCatalogOptions = {
    gifts: @json($giftRuleCatalog),
    artists: @json($artistRuleCatalog),
    otherCosts: @json($otherCostRuleCatalog),
  };
</script>

@include('content.owner.settings.partials.price-rules-modal')

<div class="modal fade" id="deletePackageModal" tabindex="-1" aria-labelledby="deletePackageModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="deletePackageModalLabel">Eliminar paquete</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        Vas a eliminar <strong id="deletePackageName">este paquete</strong>. Esta acción no afecta serenatas ya registradas.
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cancelar</button>
        <form id="deletePackageForm" method="POST" action="#">
          @csrf
          @method('DELETE')
          <button type="submit" class="btn btn-danger">Eliminar</button>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const createBtn = document.getElementById('btnOpenPackageCreate');
  const editorEl = document.getElementById('packageEditorModal');
  const editor = editorEl ? bootstrap.Modal.getOrCreateInstance(editorEl) : null;
  const viewEl = document.getElementById('packageViewModal');
  const viewModal = viewEl ? bootstrap.Modal.getOrCreateInstance(viewEl) : null;
  const form = document.getElementById('packageEditorForm');
  const methodInput = document.getElementById('packageMethod');
  const title = document.getElementById('packageEditorModalLabel');
  const submitBtn = document.getElementById('packageSubmitBtn');

  const fields = {
    name: document.getElementById('packageName'),
    city: document.getElementById('packageCity'),
    commissionAmount: document.getElementById('packageCommissionAmount'),
    internalCostDisplay: document.getElementById('packageInternalCostDisplay'),
    basePriceDisplay: document.getElementById('packageBasePriceDisplay'),
    isActive: document.getElementById('packageIsActive'),
    isDefault: document.getElementById('packageIsDefault'),
    sortOrder: document.getElementById('packageSortOrder'),
  };

  const itemCheckboxes = Array.from(document.querySelectorAll('.pkg-item-checkbox'));

  const baseStoreUrl = @json(route('owner.settings.packages.store'));
  const baseUpdateUrl = @json(url('/owner/configuracion/paquetes'));
  const giftsByCode = @json($giftOptions->mapWithKeys(fn($i) => [$i->code => $i->name])->all());
  const artistsByCode = @json($artistOptions->mapWithKeys(fn($i) => [$i->code => $i->name])->all());
  const otherCostsByCode = @json($otherCostOptions->mapWithKeys(fn($i) => [$i->code => $i->name])->all());

  const formatCOP = (value) => {
    const amount = Number.isFinite(value) ? value : 0;
    return `$${new Intl.NumberFormat('es-CO', { maximumFractionDigits: 0 }).format(Math.round(amount))}`;
  };

  const parseNumber = (value) => {
    const parsed = Number(value);
    if (!Number.isFinite(parsed) || parsed < 0) {
      return 0;
    }

    return parsed;
  };

  const resetChecks = () => {
    itemCheckboxes.forEach((cb) => {
      cb.checked = false;
    });
  };

  const parsePayload = (encodedPayload) => {
    if (!encodedPayload) {
      return null;
    }
    try {
      return JSON.parse(atob(encodedPayload));
    } catch (error) {
      console.error('No se pudo leer paquete', error);
      return null;
    }
  };

  const renderBadges = (container, codes, sourceMap) => {
    if (!container) return;
    const list = Array.isArray(codes) ? codes : [];
    if (list.length === 0) {
      container.innerHTML = '<span class="text-body-secondary">Sin elementos</span>';
      return;
    }
    container.innerHTML = list
      .map((code) => `<span class="badge bg-label-primary">${sourceMap[code] || code}</span>`)
      .join('');
  };

  const fillChecks = (codes = []) => {
    const codeSet = new Set(Array.isArray(codes) ? codes : []);
    itemCheckboxes.forEach((cb) => {
      cb.checked = codeSet.has(cb.value);
    });
  };

  const calculateInternalCost = () => {
    return itemCheckboxes.reduce((sum, cb) => {
      if (!cb.checked) {
        return sum;
      }

      return sum + parseNumber(cb.dataset.internalCost);
    }, 0);
  };

  const refreshTotals = () => {
    const internalCost = calculateInternalCost();
    const commissionAmount = parseNumber(fields.commissionAmount?.value || 0);
    const basePrice = internalCost + commissionAmount;

    fields.internalCostDisplay.value = formatCOP(internalCost);
    fields.basePriceDisplay.value = formatCOP(basePrice);
  };

  const setCreateMode = () => {
    form.action = baseStoreUrl;
    methodInput.value = 'POST';
    title.textContent = 'Agregar paquete';
    submitBtn.textContent = 'Guardar paquete';

    form.reset();
    fields.sortOrder.value = '100';
    fields.isActive.value = '1';
    fields.isDefault.value = '0';
    fields.commissionAmount.value = '0';
    resetChecks();
    refreshTotals();
  };

  createBtn?.addEventListener('click', () => {
    setCreateMode();
    editor?.show();
  });

  document.querySelectorAll('.btn-edit-package').forEach((btn) => {
    btn.addEventListener('click', () => {
      const pkg = parsePayload(btn.dataset.package || '');
      if (!pkg) return;

      form.action = `${baseUpdateUrl}/${pkg.id}`;
      methodInput.value = 'PUT';
      title.textContent = 'Editar paquete';
      submitBtn.textContent = 'Guardar cambios';

      fields.name.value = pkg.name || '';
      fields.city.value = pkg.city || '';
      fields.commissionAmount.value = String(parseNumber(pkg.commission_amount));
      fields.sortOrder.value = String(parseNumber(pkg.sort_order || 100));
      fields.isActive.value = pkg.is_active ? '1' : '0';
      fields.isDefault.value = pkg.is_default ? '1' : '0';

      const selectedCodes = [
        ...(Array.isArray(pkg.gift_codes) ? pkg.gift_codes : []),
        ...(Array.isArray(pkg.artist_codes) ? pkg.artist_codes : []),
        ...(Array.isArray(pkg.other_cost_codes) ? pkg.other_cost_codes : []),
      ];

      fillChecks(selectedCodes);
      refreshTotals();
      editor?.show();
    });
  });

  document.querySelectorAll('.btn-view-package').forEach((btn) => {
    btn.addEventListener('click', () => {
      const pkg = parsePayload(btn.dataset.package || '');
      if (!pkg) return;

      document.getElementById('viewPackageName').textContent = pkg.name || '-';
      document.getElementById('viewPackageCity').textContent = pkg.city || '-';
      document.getElementById('viewPackageInternalCost').textContent = formatCOP(parseNumber(pkg.internal_cost));
      document.getElementById('viewPackageCommission').textContent = formatCOP(parseNumber(pkg.commission_amount));
      document.getElementById('viewPackageBasePrice').textContent = formatCOP(parseNumber(pkg.base_price));
      document.getElementById('viewPackageStatus').textContent = pkg.is_active ? 'Activo' : 'Inactivo';
      document.getElementById('viewPackageOrder').textContent = String(parseNumber(pkg.sort_order || 0));

      renderBadges(document.getElementById('viewPackageGifts'), pkg.gift_codes, giftsByCode);
      renderBadges(document.getElementById('viewPackageArtists'), pkg.artist_codes, artistsByCode);
      renderBadges(document.getElementById('viewPackageOtherCosts'), pkg.other_cost_codes, otherCostsByCode);

      viewModal?.show();
    });
  });

  itemCheckboxes.forEach((checkbox) => {
    checkbox.addEventListener('change', refreshTotals);
  });

  fields.commissionAmount?.addEventListener('input', refreshTotals);

  const deleteModalEl = document.getElementById('deletePackageModal');
  const deleteModal = deleteModalEl ? bootstrap.Modal.getOrCreateInstance(deleteModalEl) : null;
  const deleteForm = document.getElementById('deletePackageForm');
  const deleteName = document.getElementById('deletePackageName');

  document.querySelectorAll('.btn-delete-package').forEach((btn) => {
    btn.addEventListener('click', () => {
      const id = btn.dataset.id;
      const name = btn.dataset.name || 'este paquete';
      deleteForm.action = `${baseUpdateUrl}/${id}`;
      deleteName.textContent = name;
      deleteModal?.show();
    });
  });

  refreshTotals();
});
</script>
@endsection
