@extends('layouts.ownerLayout')

@section('title', 'Detalle de Grupo Mariachi')

@section('vendor-style')
@vite([
  'resources/assets/vendor/libs/datatables-bs5/datatables.bootstrap5.scss',
  'resources/assets/vendor/libs/datatables-responsive-bs5/responsive.bootstrap5.scss',
  'resources/assets/vendor/libs/datatables-buttons-bs5/buttons.bootstrap5.scss'
])
@endsection

@section('vendor-script')
@vite([
  'resources/assets/vendor/libs/datatables-bs5/datatables-bootstrap5.js'
])
@endsection

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

@section('content')
<style>
  .group-sidebar-toggle {
    width: 38px;
    height: 38px;
    padding: 0;
    display: inline-flex;
    align-items: center;
    justify-content: center;
  }
</style>
<div class="d-flex flex-column align-items-start mb-6 text-start gap-2">
  <a href="{{ route('owner.settings.mariachi-groups') }}" class="btn btn-label-secondary d-inline-flex align-items-center gap-2">
    <i class="icon-base ti tabler-arrow-left icon-sm"></i>
    <span>Volver a grupos</span>
  </a>
  <div>
    <h4 class="mb-1">{{ $group->name }}</h4>
    <p class="mb-0 text-body-secondary">Código interno: {{ $group->code }} · Creado {{ $group->created_at?->format('d/m/Y H:i') }}</p>
  </div>
</div>

<div class="row">
  <div id="groupSidebarColumn" class="col-xl-4 col-lg-5 col-md-5 order-1 order-md-0">
    <div class="card mb-6">
      <div class="card-body pt-12">
        <div class="d-flex align-items-center flex-column">
          <span class="avatar avatar-xl mb-4">
            <span class="avatar-initial rounded bg-label-primary text-uppercase">{{ strtoupper(mb_substr($group->name, 0, 1)) }}</span>
          </span>
          <div class="text-center mb-6">
            <h5 class="mb-0">{{ $group->name }}</h5>
            <span>{{ $group->description ?: 'Grupo mariachi' }}</span>
          </div>
        </div>

        <div class="d-flex justify-content-around flex-wrap mb-6 gap-0 gap-md-3 gap-lg-4">
          <div class="d-flex align-items-center gap-4 me-5">
            <div class="avatar">
              <div class="avatar-initial rounded bg-label-primary">
                <i class="icon-base ti tabler-music icon-lg"></i>
              </div>
            </div>
            <div>
              <h5 class="mb-0">{{ number_format($stats['serenatas']) }}</h5>
              <span>Serenatas</span>
            </div>
          </div>
          <div class="d-flex align-items-center gap-4">
            <div class="avatar">
              <div class="avatar-initial rounded bg-label-success">
                <i class="icon-base ti tabler-package icon-lg"></i>
              </div>
            </div>
            <div>
              <h5 class="mb-0">{{ number_format($stats['paquetes']) }}</h5>
              <span>Paquetes</span>
            </div>
          </div>
        </div>

        <div class="info-container">
          <h5 class="pb-4 border-bottom text-capitalize mt-6 mb-4">Datos</h5>
          <ul class="list-unstyled mb-6">
            <li class="mb-2"><span class="h6 me-1">Nombre:</span><span>{{ $group->name }}</span></li>
            <li class="mb-2"><span class="h6 me-1">Descripción:</span><span>{{ $group->description ?: 'Sin descripción' }}</span></li>
            <li class="mb-2">
              <span class="h6 me-1">Estado:</span>
              <span class="badge {{ $group->is_active ? 'bg-label-success' : 'bg-label-secondary' }}">{{ $group->is_active ? 'Activo' : 'Inactivo' }}</span>
            </li>
            <li class="mb-2">
              <span class="h6 me-1">Grupo principal:</span>
              <span class="badge {{ $group->is_default ? 'bg-label-primary' : 'bg-label-secondary' }}">{{ $group->is_default ? 'Sí' : 'No' }}</span>
            </li>
            <li class="mb-2"><span class="h6 me-1">Clientes vinculados:</span><span>{{ number_format($stats['clientes']) }}</span></li>
            <li class="mb-2"><span class="h6 me-1">Última serenata:</span><span>{{ $stats['ultima_serenata'] ? \Illuminate\Support\Carbon::parse($stats['ultima_serenata'])->format('d/m/Y') : 'Sin serenatas' }}</span></li>
            <li class="mb-2"><span class="h6 me-1">Total cobrado:</span><span>${{ number_format((float) $stats['total_cobrado'], 0, ',', '.') }}</span></li>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <div id="groupContentColumn" class="col-xl-8 col-lg-7 col-md-7 order-0 order-md-1">
    <div class="nav-align-top">
      <ul class="nav nav-pills flex-column flex-md-row mb-6 row-gap-2 flex-wrap" role="tablist">
        <li class="nav-item">
          <button type="button" class="btn btn-label-secondary group-sidebar-toggle" id="groupSidebarToggle" title="Ocultar panel" aria-label="Ocultar panel">
            <span id="groupSidebarToggleIcon" class="d-inline-flex align-items-center justify-content-center text-heading">
              <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                <path d="m15 18l-6-6l6-6" />
              </svg>
            </span>
          </button>
        </li>
        <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#group-overview" type="button"><i class="icon-base ti tabler-user icon-sm me-1_5"></i>Resumen</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#group-packages" type="button"><i class="icon-base ti tabler-package icon-sm me-1_5"></i>Paquetes</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#group-gifts" type="button"><i class="icon-base ti tabler-gift icon-sm me-1_5"></i>Obsequios</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#group-artists" type="button"><i class="icon-base ti tabler-music icon-sm me-1_5"></i>Artistas</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#group-other-costs" type="button"><i class="icon-base ti tabler-tool icon-sm me-1_5"></i>Otros costos</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#group-serenatas" type="button"><i class="icon-base ti tabler-music-heart icon-sm me-1_5"></i>Serenatas</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#group-customers" type="button"><i class="icon-base ti tabler-users icon-sm me-1_5"></i>Clientes</button></li>
      </ul>
    </div>

    <div class="tab-content p-0">
      <div class="tab-pane fade show active" id="group-overview" role="tabpanel">
        <div class="card mb-6">
          <div class="card-header"><h5 class="card-title mb-0">Resumen del grupo</h5></div>
          <div class="card-body">
            <div class="row g-4">
              <div class="col-md-6">
                <div class="border rounded p-4 h-100">
                  <h6 class="mb-3">Catálogo propio</h6>
                  <p class="mb-1">Paquetes: <strong>{{ $stats['paquetes'] }}</strong></p>
                  <p class="mb-1">Obsequios: <strong>{{ $stats['obsequios'] }}</strong></p>
                  <p class="mb-1">Artistas: <strong>{{ $stats['artistas'] }}</strong></p>
                  <p class="mb-0">Otros costos: <strong>{{ $stats['otros_costos'] }}</strong></p>
                </div>
              </div>
              <div class="col-md-6">
                <div class="border rounded p-4 h-100">
                  <h6 class="mb-3">Operación</h6>
                  <p class="mb-1">Serenatas registradas: <strong>{{ $stats['serenatas'] }}</strong></p>
                  <p class="mb-1">Clientes vinculados: <strong>{{ $stats['clientes'] }}</strong></p>
                  <p class="mb-0">Total facturado: <strong>${{ number_format((float) $stats['total_cobrado'], 0, ',', '.') }}</strong></p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="tab-pane fade" id="group-packages" role="tabpanel">
        <div class="card mb-6">
          <div class="card-header">
            <div class="d-flex flex-column gap-4">
              <div class="d-flex justify-content-between align-items-center gap-3 flex-wrap">
                <h5 class="card-title mb-0">Paquetes del grupo</h5>
                <div class="d-flex align-items-center gap-2">
                  <span class="text-body-secondary small">{{ number_format($packages->total()) }} resultados</span>
                  <button type="button" class="btn btn-primary btn-sm" id="btnOpenGroupPackageCreate">Agregar paquete</button>
                </div>
              </div>
              <form method="GET" action="{{ route('owner.settings.mariachi-groups.show', $group) }}#group-packages" class="row g-3">
                <div class="col-md-7">
                  <label class="form-label">Buscar</label>
                  <input type="text" class="form-control" name="packages_q" value="{{ request('packages_q') }}" placeholder="Nombre o ciudad">
                </div>
                <div class="col-md-3">
                  <label class="form-label">Estado</label>
                  <select class="form-select" name="packages_status">
                    <option value="">Todos</option>
                    <option value="1" @selected(request('packages_status') === '1')>Activos</option>
                    <option value="0" @selected(request('packages_status') === '0')>Inactivos</option>
                  </select>
                </div>
                <div class="col-md-2 d-flex align-items-end gap-2">
                  <button type="submit" class="btn btn-primary w-100">Filtrar</button>
                  <a href="{{ route('owner.settings.mariachi-groups.show', $group) }}#group-packages" class="btn btn-label-secondary">Limpiar</a>
                </div>
              </form>
            </div>
          </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</th><th>Incluye</th><th>Estado</th><th>Orden</th><th>Acciones</th></tr></thead>
              <tbody>
                @forelse($packages as $item)
                  @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);
                  @endphp
                  <tr>
                    <td>{{ $item->name }} @if($item->is_default)<span class="badge bg-label-primary 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 flex-wrap">
                        <button type="button" class="btn btn-sm btn-label-secondary btn-view-group-package" data-package="{{ base64_encode($packagePayload) }}">Ver</button>
                        <button type="button" class="btn btn-sm btn-label-primary btn-edit-group-package" data-package="{{ base64_encode($packagePayload) }}">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-group-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-4">Este grupo aún no tiene paquetes.</td></tr>
                @endforelse
              </tbody>
            </table>
          </div>
          @if($packages->hasPages())
            <div class="card-body border-top">{{ $packages->onEachSide(1)->links() }}</div>
          @endif
        </div>
      </div>

      <div class="tab-pane fade" id="group-gifts" role="tabpanel">
        <div class="card mb-6">
          <div class="card-header">
            <div class="d-flex flex-column gap-4">
              <div class="d-flex justify-content-between align-items-center gap-3 flex-wrap">
                <h5 class="card-title mb-0">Obsequios del grupo</h5>
                <div class="d-flex align-items-center gap-2">
                  <span class="text-body-secondary small">{{ number_format($giftItems->total()) }} resultados</span>
                  <button type="button" class="btn btn-primary btn-sm" id="btnOpenGroupGiftCreate">Agregar obsequio</button>
                </div>
              </div>
              <form method="GET" action="{{ route('owner.settings.mariachi-groups.show', $group) }}#group-gifts" class="row g-3">
                <div class="col-md-5">
                  <label class="form-label">Buscar</label>
                  <input type="text" class="form-control" name="gifts_q" value="{{ request('gifts_q') }}" placeholder="Nombre del obsequio">
                </div>
                <div class="col-md-3">
                  <label class="form-label">Tipo</label>
                  <select class="form-select" name="gifts_type">
                    <option value="">Todos</option>
                    <option value="included" @selected(request('gifts_type') === 'included')>Incluidos</option>
                    <option value="additional" @selected(request('gifts_type') === 'additional')>Adicionales</option>
                  </select>
                </div>
                <div class="col-md-2">
                  <label class="form-label">Estado</label>
                  <select class="form-select" name="gifts_status">
                    <option value="">Todos</option>
                    <option value="1" @selected(request('gifts_status') === '1')>Activos</option>
                    <option value="0" @selected(request('gifts_status') === '0')>Inactivos</option>
                  </select>
                </div>
                <div class="col-md-2 d-flex align-items-end gap-2">
                  <button type="submit" class="btn btn-primary w-100">Filtrar</button>
                  <a href="{{ route('owner.settings.mariachi-groups.show', $group) }}#group-gifts" class="btn btn-label-secondary">Limpiar</a>
                </div>
              </form>
            </div>
          </div>
          <div class="table-responsive">
            <table class="table mb-0">
              <thead><tr><th>Nombre</th><th>Tipo</th><th>Costo interno</th><th>Precio</th><th>Estado</th><th>Por defecto</th><th>Orden</th><th>Acciones</th></tr></thead>
              <tbody>
                @forelse($giftItems as $item)
                  @php
                    $giftPayload = json_encode([
                      'id' => (int) $item->id,
                      'name' => (string) $item->name,
                      'type' => (string) $item->type,
                      'internal_cost' => (float) $item->internal_cost,
                      'base_price' => (float) $item->base_price,
                      'is_active' => (bool) $item->is_active,
                      'is_default' => (bool) $item->is_default,
                      'sort_order' => (int) $item->sort_order,
                    ], JSON_UNESCAPED_UNICODE);
                  @endphp
                  <tr>
                    <td>{{ $item->name }}</td>
                    <td>{{ $item->type === 'additional' ? 'Adicional' : 'Incluido' }}</td>
                    <td>${{ number_format((float) $item->internal_cost, 0, ',', '.') }}</td>
                    <td>${{ number_format((float) $item->base_price, 0, ',', '.') }}</td>
                    <td><span class="badge {{ $item->is_active ? 'bg-label-success' : 'bg-label-secondary' }}">{{ $item->is_active ? 'Activo' : 'Inactivo' }}</span></td>
                    <td><span class="badge {{ $item->is_default ? 'bg-label-primary' : 'bg-label-secondary' }}">{{ $item->is_default ? 'Sí' : 'No' }}</span></td>
                    <td>{{ $item->sort_order }}</td>
                    <td>
                      <div class="d-flex gap-2 flex-wrap">
                        <button type="button" class="btn btn-sm btn-label-secondary btn-view-group-gift" data-item="{{ base64_encode($giftPayload) }}">Ver</button>
                        <button type="button" class="btn btn-sm btn-label-primary btn-edit-group-gift" data-item="{{ base64_encode($giftPayload) }}">Editar</button>
                        <button type="button" class="btn btn-sm btn-label-info btn-manage-price-rules" data-target-type="gift" data-target-id="{{ $item->id }}" data-target-name="{{ $item->name }}">Reglas</button>
                        <button type="button" class="btn btn-sm btn-label-danger btn-delete-group-gift" data-id="{{ $item->id }}" data-name="{{ $item->name }}">Eliminar</button>
                      </div>
                    </td>
                  </tr>
                @empty
                  <tr><td colspan="8" class="text-center text-body-secondary py-4">Este grupo aún no tiene obsequios.</td></tr>
                @endforelse
              </tbody>
            </table>
          </div>
          @if($giftItems->hasPages())
            <div class="card-body border-top">{{ $giftItems->onEachSide(1)->links() }}</div>
          @endif
        </div>
      </div>

      <div class="tab-pane fade" id="group-artists" role="tabpanel">
        <div class="card mb-6">
          <div class="card-header">
            <div class="d-flex flex-column gap-4">
              <div class="d-flex justify-content-between align-items-center gap-3 flex-wrap">
                <h5 class="card-title mb-0">Artistas del grupo</h5>
                <div class="d-flex align-items-center gap-2">
                  <span class="text-body-secondary small">{{ number_format($artistItems->total()) }} resultados</span>
                  <button type="button" class="btn btn-primary btn-sm" id="btnOpenGroupArtistCreate">Agregar artista</button>
                </div>
              </div>
              <form method="GET" action="{{ route('owner.settings.mariachi-groups.show', $group) }}#group-artists" class="row g-3">
                <div class="col-md-5">
                  <label class="form-label">Buscar</label>
                  <input type="text" class="form-control" name="artists_q" value="{{ request('artists_q') }}" placeholder="Nombre del artista">
                </div>
                <div class="col-md-3">
                  <label class="form-label">Tipo</label>
                  <select class="form-select" name="artists_type">
                    <option value="">Todos</option>
                    <option value="included" @selected(request('artists_type') === 'included')>Incluidos</option>
                    <option value="additional" @selected(request('artists_type') === 'additional')>Adicionales</option>
                  </select>
                </div>
                <div class="col-md-2">
                  <label class="form-label">Estado</label>
                  <select class="form-select" name="artists_status">
                    <option value="">Todos</option>
                    <option value="1" @selected(request('artists_status') === '1')>Activos</option>
                    <option value="0" @selected(request('artists_status') === '0')>Inactivos</option>
                  </select>
                </div>
                <div class="col-md-2 d-flex align-items-end gap-2">
                  <button type="submit" class="btn btn-primary w-100">Filtrar</button>
                  <a href="{{ route('owner.settings.mariachi-groups.show', $group) }}#group-artists" class="btn btn-label-secondary">Limpiar</a>
                </div>
              </form>
            </div>
          </div>
          <div class="table-responsive">
            <table class="table mb-0">
              <thead><tr><th>Nombre</th><th>Tipo</th><th>Costo interno</th><th>Precio</th><th>Estado</th><th>Orden</th><th>Acciones</th></tr></thead>
              <tbody>
                @forelse($artistItems as $item)
                  @php
                    $artistPayload = json_encode([
                      'id' => (int) $item->id,
                      'name' => (string) $item->name,
                      'type' => (string) $item->type,
                      'internal_cost' => (float) $item->internal_cost,
                      'base_price' => (float) $item->base_price,
                      'is_active' => (bool) $item->is_active,
                      'sort_order' => (int) $item->sort_order,
                    ], JSON_UNESCAPED_UNICODE);
                  @endphp
                  <tr>
                    <td>{{ $item->name }}</td>
                    <td>{{ $item->type === 'additional' ? 'Adicional' : 'Incluido' }}</td>
                    <td>${{ number_format((float) $item->internal_cost, 0, ',', '.') }}</td>
                    <td>${{ number_format((float) $item->base_price, 0, ',', '.') }}</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 flex-wrap">
                        <button type="button" class="btn btn-sm btn-label-secondary btn-view-group-artist" data-item="{{ base64_encode($artistPayload) }}">Ver</button>
                        <button type="button" class="btn btn-sm btn-label-primary btn-edit-group-artist" data-item="{{ base64_encode($artistPayload) }}">Editar</button>
                        <button type="button" class="btn btn-sm btn-label-info btn-manage-price-rules" data-target-type="artist" data-target-id="{{ $item->id }}" data-target-name="{{ $item->name }}">Reglas</button>
                        <button type="button" class="btn btn-sm btn-label-danger btn-delete-group-artist" data-id="{{ $item->id }}" data-name="{{ $item->name }}">Eliminar</button>
                      </div>
                    </td>
                  </tr>
                @empty
                  <tr><td colspan="7" class="text-center text-body-secondary py-4">Este grupo aún no tiene artistas.</td></tr>
                @endforelse
              </tbody>
            </table>
          </div>
          @if($artistItems->hasPages())
            <div class="card-body border-top">{{ $artistItems->onEachSide(1)->links() }}</div>
          @endif
        </div>
      </div>

      <div class="tab-pane fade" id="group-other-costs" role="tabpanel">
        <div class="card mb-6">
          <div class="card-header">
            <div class="d-flex flex-column gap-4">
              <div class="d-flex justify-content-between align-items-center gap-3 flex-wrap">
                <h5 class="card-title mb-0">Otros costos del grupo</h5>
                <div class="d-flex align-items-center gap-2">
                  <span class="text-body-secondary small">{{ number_format($otherCostItems->total()) }} resultados</span>
                  <button type="button" class="btn btn-primary btn-sm" id="btnOpenGroupOtherCostCreate">Agregar costo</button>
                </div>
              </div>
              <form method="GET" action="{{ route('owner.settings.mariachi-groups.show', $group) }}#group-other-costs" class="row g-3">
                <div class="col-md-8">
                  <label class="form-label">Buscar</label>
                  <input type="text" class="form-control" name="other_costs_q" value="{{ request('other_costs_q') }}" placeholder="Nombre del costo">
                </div>
                <div class="col-md-2">
                  <label class="form-label">Estado</label>
                  <select class="form-select" name="other_costs_status">
                    <option value="">Todos</option>
                    <option value="1" @selected(request('other_costs_status') === '1')>Activos</option>
                    <option value="0" @selected(request('other_costs_status') === '0')>Inactivos</option>
                  </select>
                </div>
                <div class="col-md-2 d-flex align-items-end gap-2">
                  <button type="submit" class="btn btn-primary w-100">Filtrar</button>
                  <a href="{{ route('owner.settings.mariachi-groups.show', $group) }}#group-other-costs" class="btn btn-label-secondary">Limpiar</a>
                </div>
              </form>
            </div>
          </div>
          <div class="table-responsive">
            <table class="table mb-0">
              <thead><tr><th>Nombre</th><th>Costo interno</th><th>Precio</th><th>Estado</th><th>Orden</th><th>Acciones</th></tr></thead>
              <tbody>
                @forelse($otherCostItems as $item)
                  @php
                    $otherCostPayload = json_encode([
                      'id' => (int) $item->id,
                      'name' => (string) $item->name,
                      'internal_cost' => (float) $item->internal_cost,
                      'base_price' => (float) $item->base_price,
                      'is_active' => (bool) $item->is_active,
                      'sort_order' => (int) $item->sort_order,
                    ], JSON_UNESCAPED_UNICODE);
                  @endphp
                  <tr>
                    <td>{{ $item->name }}</td>
                    <td>${{ number_format((float) $item->internal_cost, 0, ',', '.') }}</td>
                    <td>${{ number_format((float) $item->base_price, 0, ',', '.') }}</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 flex-wrap">
                        <button type="button" class="btn btn-sm btn-label-secondary btn-view-group-other-cost" data-item="{{ base64_encode($otherCostPayload) }}">Ver</button>
                        <button type="button" class="btn btn-sm btn-label-primary btn-edit-group-other-cost" data-item="{{ base64_encode($otherCostPayload) }}">Editar</button>
                        <button type="button" class="btn btn-sm btn-label-info btn-manage-price-rules" data-target-type="other_cost" data-target-id="{{ $item->id }}" data-target-name="{{ $item->name }}">Reglas</button>
                        <button type="button" class="btn btn-sm btn-label-danger btn-delete-group-other-cost" data-id="{{ $item->id }}" data-name="{{ $item->name }}">Eliminar</button>
                      </div>
                    </td>
                  </tr>
                @empty
                  <tr><td colspan="6" class="text-center text-body-secondary py-4">Este grupo aún no tiene otros costos.</td></tr>
                @endforelse
              </tbody>
            </table>
          </div>
          @if($otherCostItems->hasPages())
            <div class="card-body border-top">{{ $otherCostItems->onEachSide(1)->links() }}</div>
          @endif
        </div>
      </div>

      <div class="tab-pane fade" id="group-serenatas" role="tabpanel">
        <div class="card mb-6">
          <div class="card-header">
            <div class="d-flex flex-column gap-4">
              <div class="d-flex justify-content-between align-items-center gap-3 flex-wrap">
                <h5 class="card-title mb-0">Serenatas del grupo</h5>
                <span class="text-body-secondary small">{{ number_format($serenatas->total()) }} resultados</span>
              </div>
              <form method="GET" action="{{ route('owner.settings.mariachi-groups.show', $group) }}#group-serenatas" class="row g-3">
                <div class="col-md-5">
                  <label class="form-label">Buscar</label>
                  <input type="text" class="form-control" name="serenatas_q" value="{{ request('serenatas_q') }}" placeholder="Código, cliente, motivo o dirección">
                </div>
                <div class="col-md-3">
                  <label class="form-label">Estado</label>
                  <select class="form-select" name="serenatas_status">
                    <option value="">Todos</option>
                    @foreach($serenataStatusOptions as $status)
                      <option value="{{ $status }}" @selected(request('serenatas_status') === $status)>{{ $status }}</option>
                    @endforeach
                  </select>
                </div>
                <div class="col-md-2">
                  <label class="form-label">Pago</label>
                  <select class="form-select" name="serenatas_payment">
                    <option value="">Todos</option>
                    @foreach($serenataPaymentOptions as $status)
                      <option value="{{ $status }}" @selected(request('serenatas_payment') === $status)>{{ $status }}</option>
                    @endforeach
                  </select>
                </div>
                <div class="col-md-2 d-flex align-items-end gap-2">
                  <button type="submit" class="btn btn-primary w-100">Filtrar</button>
                  <a href="{{ route('owner.settings.mariachi-groups.show', $group) }}#group-serenatas" class="btn btn-label-secondary">Limpiar</a>
                </div>
              </form>
            </div>
          </div>
          <div class="table-responsive">
            <table class="table mb-0">
              <thead><tr><th>Código</th><th>Fecha</th><th>Estado</th><th>Pago</th><th>Total</th><th>Acciones</th></tr></thead>
              <tbody>
                @forelse($serenatas as $serenata)
                  <tr>
                    <td>{{ $serenata->code }}</td>
                    <td>{{ optional($serenata->event_date)->format('d/m/Y') }} {{ $serenata->eventWindowLabel() }}</td>
                    <td>{{ $serenata->service_status }}</td>
                    <td>{{ $serenata->payment_status }}</td>
                    <td>${{ number_format((float) $serenata->total_charged, 0, ',', '.') }}</td>
                    <td><a href="{{ route('owner.serenatas.show', $serenata) }}" class="btn btn-sm btn-label-secondary">Ver</a></td>
                  </tr>
                @empty
                  <tr><td colspan="6" class="text-center text-body-secondary py-4">Este grupo aún no tiene serenatas.</td></tr>
                @endforelse
              </tbody>
            </table>
          </div>
          @if($serenatas->hasPages())
            <div class="card-body border-top">{{ $serenatas->onEachSide(1)->links() }}</div>
          @endif
        </div>
      </div>

      <div class="tab-pane fade" id="group-customers" role="tabpanel">
        <div class="card mb-6">
          <div class="card-header">
            <div class="d-flex flex-column gap-4">
              <div class="d-flex justify-content-between align-items-center gap-3 flex-wrap">
                <h5 class="card-title mb-0">Clientes del grupo</h5>
                <span class="text-body-secondary small">{{ number_format($customers->total()) }} resultados</span>
              </div>
              <form method="GET" action="{{ route('owner.settings.mariachi-groups.show', $group) }}#group-customers" class="row g-3">
                <div class="col-md-7">
                  <label class="form-label">Buscar</label>
                  <input type="text" class="form-control" name="customers_q" value="{{ request('customers_q') }}" placeholder="Nombre, correo, teléfono o dirección">
                </div>
                <div class="col-md-3">
                  <label class="form-label">Estado</label>
                  <select class="form-select" name="customers_status">
                    <option value="">Todos</option>
                    <option value="1" @selected(request('customers_status') === '1')>Activos</option>
                    <option value="0" @selected(request('customers_status') === '0')>Inactivos</option>
                  </select>
                </div>
                <div class="col-md-2 d-flex align-items-end gap-2">
                  <button type="submit" class="btn btn-primary w-100">Filtrar</button>
                  <a href="{{ route('owner.settings.mariachi-groups.show', $group) }}#group-customers" class="btn btn-label-secondary">Limpiar</a>
                </div>
              </form>
            </div>
          </div>
          <div class="table-responsive">
            <table class="table mb-0">
              <thead><tr><th>Nombre</th><th>Correo</th><th>Contacto</th><th>Estado</th><th>Acciones</th></tr></thead>
              <tbody>
                @forelse($customers as $customer)
                  <tr>
                    <td>{{ $customer->name }}</td>
                    <td>{{ $customer->email ?: '-' }}</td>
                    <td>{{ $customer->formatted_mobile ?: '-' }}</td>
                    <td><span class="badge {{ $customer->is_active ? 'bg-label-success' : 'bg-label-secondary' }}">{{ $customer->is_active ? 'Activo' : 'Inactivo' }}</span></td>
                    <td><a href="{{ route('owner.clients.show', $customer) }}" class="btn btn-sm btn-label-secondary">Ver</a></td>
                  </tr>
                @empty
                  <tr><td colspan="5" class="text-center text-body-secondary py-4">Este grupo aún no tiene clientes.</td></tr>
                @endforelse
              </tbody>
            </table>
          </div>
          @if($customers->hasPages())
            <div class="card-body border-top">{{ $customers->onEachSide(1)->links() }}</div>
          @endif
        </div>
      </div>
    </div>
  </div>
</div>
@php
  $giftIncludedOptions = $packageCatalogGifts->where('type', 'included')->values();
  $giftAdditionalOptions = $packageCatalogGifts->where('type', 'additional')->values();
  $giftRuleCatalog = $packageCatalogGifts->map(fn ($item) => [
    'code' => $item->code,
    'name' => $item->name,
    'type' => $item->type,
    'internal_cost' => (float) $item->internal_cost,
    'base_price' => (float) $item->base_price,
  ])->values()->all();
  $artistRuleCatalog = $packageCatalogArtists->map(fn ($item) => [
    'code' => $item->code,
    'name' => $item->name,
    'internal_cost' => (float) $item->internal_cost,
    'base_price' => (float) $item->base_price,
  ])->values()->all();
  $otherCostRuleCatalog = $packageCatalogOtherCosts->map(fn ($item) => [
    'code' => $item->code,
    'name' => $item->name,
    'internal_cost' => (float) $item->internal_cost,
    'base_price' => (float) $item->base_price,
  ])->values()->all();
@endphp

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

        <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="groupPackageName">Nombre</label>
                    <input type="text" name="name" id="groupPackageName" class="form-control" required>
                  </div>
                  <div class="mb-3">
                    <label class="form-label" for="groupPackageCity">Ciudad</label>
                    <input type="text" name="city" id="groupPackageCity" class="form-control" placeholder="Bogotá o *" required>
                  </div>
                  <div class="mb-3">
                    <label class="form-label" for="groupPackageCommissionAmount">Comisión ganada (COP)</label>
                    <input type="number" min="0" step="1000" name="commission_amount" id="groupPackageCommissionAmount" class="form-control" value="0" required>
                  </div>
                  <div class="mb-3">
                    <label class="form-label" for="groupPackageInternalCostDisplay">Costo interno calculado (COP)</label>
                    <input type="text" id="groupPackageInternalCostDisplay" class="form-control" value="$0" readonly>
                  </div>
                  <div class="mb-3">
                    <label class="form-label" for="groupPackageBasePriceDisplay">Precio del paquete (COP)</label>
                    <input type="text" id="groupPackageBasePriceDisplay" class="form-control" value="$0" readonly>
                  </div>
                  <div class="row g-3">
                    <div class="col-6">
                      <label class="form-label" for="groupPackageIsActive">Estado</label>
                      <select name="is_active" id="groupPackageIsActive" class="form-select">
                        <option value="1">Activo</option>
                        <option value="0">Inactivo</option>
                      </select>
                    </div>
                    <div class="col-6">
                      <label class="form-label" for="groupPackageIsDefault">Por defecto</label>
                      <select name="is_default" id="groupPackageIsDefault" class="form-select">
                        <option value="0">No</option>
                        <option value="1">Sí</option>
                      </select>
                    </div>
                    <div class="col-12">
                      <label class="form-label" for="groupPackageSortOrder">Orden</label>
                      <input type="number" min="0" name="sort_order" id="groupPackageSortOrder" 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" role="tablist">
                        <button class="btn btn-label-primary text-start active" data-bs-toggle="pill" data-bs-target="#group-pkg-tab-gifts-included" type="button">Obsequios incluidos</button>
                        <button class="btn btn-label-primary text-start" data-bs-toggle="pill" data-bs-target="#group-pkg-tab-gifts-additional" type="button">Obsequios adicionales</button>
                        <button class="btn btn-label-primary text-start" data-bs-toggle="pill" data-bs-target="#group-pkg-tab-artists" type="button">Artistas</button>
                        <button class="btn btn-label-primary text-start" data-bs-toggle="pill" data-bs-target="#group-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="group-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 group-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 activos.</div>
                            @endforelse
                          </div>
                        </div>
                        <div class="tab-pane fade" id="group-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 group-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="group-pkg-tab-artists">
                          <div class="small text-body-secondary mb-2">Selecciona artistas base del paquete.</div>
                          <div class="row g-2">
                            @forelse($packageCatalogArtists 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 group-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="group-pkg-tab-other-costs">
                          <div class="small text-body-secondary mb-2">Selecciona otros costos incluidos.</div>
                          <div class="row g-2">
                            @forelse($packageCatalogOtherCosts 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 group-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="groupPackageSubmitBtn">Guardar paquete</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="groupPackageViewModal" tabindex="-1" aria-labelledby="groupPackageViewModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-fullscreen">
    <div class="modal-content">
      <div class="modal-header border-bottom">
        <h5 id="groupPackageViewModalLabel" 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="groupViewPackageName">-</span></div>
                  <div><small class="text-body-secondary d-block">Ciudad</small><span class="fw-semibold" id="groupViewPackageCity">-</span></div>
                  <div><small class="text-body-secondary d-block">Costo interno</small><span class="fw-semibold" id="groupViewPackageInternalCost">$0</span></div>
                  <div><small class="text-body-secondary d-block">Comisión</small><span class="fw-semibold" id="groupViewPackageCommission">$0</span></div>
                  <div><small class="text-body-secondary d-block">Precio paquete</small><span class="fw-semibold" id="groupViewPackageBasePrice">$0</span></div>
                  <div><small class="text-body-secondary d-block">Estado</small><span class="fw-semibold" id="groupViewPackageStatus">-</span></div>
                  <div><small class="text-body-secondary d-block">Orden</small><span class="fw-semibold" id="groupViewPackageOrder">-</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</h6><div id="groupViewPackageGifts" 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="groupViewPackageArtists" 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="groupViewPackageOtherCosts" class="d-flex flex-wrap gap-2"></div></div></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

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

<div class="modal fade" id="deleteGroupPackageModal" tabindex="-1" aria-labelledby="deleteGroupPackageModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="deleteGroupPackageModalLabel">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="deleteGroupPackageName">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="deleteGroupPackageForm" method="POST" action="#">
          @csrf
          @method('DELETE')
          <input type="hidden" name="return_to_group_id" value="{{ $group->id }}">
          <button type="submit" class="btn btn-danger">Eliminar</button>
        </form>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="groupGiftEditorModal" tabindex="-1" aria-labelledby="groupGiftEditorModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header border-bottom">
        <h5 id="groupGiftEditorModalLabel" class="modal-title">Agregar obsequio</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="groupGiftEditorForm" method="POST" action="{{ route('owner.settings.gifts.store') }}">
        @csrf
        <input type="hidden" name="_method" id="groupGiftMethod" value="POST">
        <input type="hidden" name="mariachi_group_id" value="{{ $group->id }}">
        <input type="hidden" name="return_to_group_id" value="{{ $group->id }}">
        <div class="modal-body">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label" for="groupGiftName">Nombre</label>
              <input type="text" class="form-control" id="groupGiftName" name="name" required>
            </div>
            <div class="col-md-6">
              <label class="form-label" for="groupGiftType">Tipo</label>
              <select class="form-select" id="groupGiftType" name="type">
                <option value="included">Incluido</option>
                <option value="additional">Adicional</option>
              </select>
            </div>
            <div class="col-md-4">
              <label class="form-label" for="groupGiftInternalCost">Costo interno (COP)</label>
              <input type="number" min="0" step="1000" class="form-control" id="groupGiftInternalCost" name="internal_cost" value="0" required>
            </div>
            <div class="col-md-4">
              <label class="form-label" for="groupGiftBasePrice">Precio cliente (COP)</label>
              <input type="number" min="0" step="1000" class="form-control" id="groupGiftBasePrice" name="base_price" value="0" required>
            </div>
            <div class="col-md-4">
              <label class="form-label" for="groupGiftSortOrder">Orden</label>
              <input type="number" min="0" class="form-control" id="groupGiftSortOrder" name="sort_order" value="100">
            </div>
            <div class="col-md-6">
              <label class="form-label" for="groupGiftIsActive">Estado</label>
              <select class="form-select" id="groupGiftIsActive" name="is_active">
                <option value="1">Activo</option>
                <option value="0">Inactivo</option>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label" for="groupGiftIsDefault">Por defecto</label>
              <select class="form-select" id="groupGiftIsDefault" name="is_default">
                <option value="0">No</option>
                <option value="1">Sí</option>
              </select>
            </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="groupGiftSubmitBtn">Guardar obsequio</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="groupGiftViewModal" tabindex="-1" aria-labelledby="groupGiftViewModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header border-bottom">
        <h5 id="groupGiftViewModalLabel" class="modal-title">Detalle del obsequio</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="row g-3">
          <div class="col-md-6"><small class="text-body-secondary d-block">Nombre</small><span class="fw-semibold" id="groupGiftViewName">-</span></div>
          <div class="col-md-6"><small class="text-body-secondary d-block">Tipo</small><span class="fw-semibold" id="groupGiftViewType">-</span></div>
          <div class="col-md-6"><small class="text-body-secondary d-block">Costo interno</small><span class="fw-semibold" id="groupGiftViewInternalCost">$0</span></div>
          <div class="col-md-6"><small class="text-body-secondary d-block">Precio cliente</small><span class="fw-semibold" id="groupGiftViewBasePrice">$0</span></div>
          <div class="col-md-4"><small class="text-body-secondary d-block">Estado</small><span class="fw-semibold" id="groupGiftViewStatus">-</span></div>
          <div class="col-md-4"><small class="text-body-secondary d-block">Por defecto</small><span class="fw-semibold" id="groupGiftViewDefault">-</span></div>
          <div class="col-md-4"><small class="text-body-secondary d-block">Orden</small><span class="fw-semibold" id="groupGiftViewOrder">-</span></div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="deleteGroupGiftModal" tabindex="-1" aria-labelledby="deleteGroupGiftModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="deleteGroupGiftModalLabel">Eliminar obsequio</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="deleteGroupGiftName">este obsequio</strong>.</div>
      <div class="modal-footer">
        <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cancelar</button>
        <form id="deleteGroupGiftForm" method="POST" action="#">
          @csrf
          @method('DELETE')
          <input type="hidden" name="return_to_group_id" value="{{ $group->id }}">
          <button type="submit" class="btn btn-danger">Eliminar</button>
        </form>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="groupArtistEditorModal" tabindex="-1" aria-labelledby="groupArtistEditorModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header border-bottom">
        <h5 id="groupArtistEditorModalLabel" class="modal-title">Agregar artista</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="groupArtistEditorForm" method="POST" action="{{ route('owner.settings.artists.store') }}">
        @csrf
        <input type="hidden" name="_method" id="groupArtistMethod" value="POST">
        <input type="hidden" name="mariachi_group_id" value="{{ $group->id }}">
        <input type="hidden" name="return_to_group_id" value="{{ $group->id }}">
        <div class="modal-body">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label" for="groupArtistName">Nombre</label>
              <input type="text" class="form-control" id="groupArtistName" name="name" required>
            </div>
            <div class="col-md-6">
              <label class="form-label" for="groupArtistType">Tipo</label>
              <select class="form-select" id="groupArtistType" name="type">
                <option value="included">Incluido</option>
                <option value="additional">Adicional</option>
              </select>
            </div>
            <div class="col-md-4">
              <label class="form-label" for="groupArtistInternalCost">Costo interno (COP)</label>
              <input type="number" min="0" step="1000" class="form-control" id="groupArtistInternalCost" name="internal_cost" value="0" required>
            </div>
            <div class="col-md-4">
              <label class="form-label" for="groupArtistBasePrice">Precio cliente (COP)</label>
              <input type="number" min="0" step="1000" class="form-control" id="groupArtistBasePrice" name="base_price" value="0" required>
            </div>
            <div class="col-md-4">
              <label class="form-label" for="groupArtistSortOrder">Orden</label>
              <input type="number" min="0" class="form-control" id="groupArtistSortOrder" name="sort_order" value="100">
            </div>
            <div class="col-md-12">
              <label class="form-label" for="groupArtistIsActive">Estado</label>
              <select class="form-select" id="groupArtistIsActive" name="is_active">
                <option value="1">Activo</option>
                <option value="0">Inactivo</option>
              </select>
            </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="groupArtistSubmitBtn">Guardar artista</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="groupArtistViewModal" tabindex="-1" aria-labelledby="groupArtistViewModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header border-bottom">
        <h5 id="groupArtistViewModalLabel" class="modal-title">Detalle del artista</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="row g-3">
          <div class="col-md-6"><small class="text-body-secondary d-block">Nombre</small><span class="fw-semibold" id="groupArtistViewName">-</span></div>
          <div class="col-md-6"><small class="text-body-secondary d-block">Tipo</small><span class="fw-semibold" id="groupArtistViewType">-</span></div>
          <div class="col-md-4"><small class="text-body-secondary d-block">Costo interno</small><span class="fw-semibold" id="groupArtistViewInternalCost">$0</span></div>
          <div class="col-md-4"><small class="text-body-secondary d-block">Precio cliente</small><span class="fw-semibold" id="groupArtistViewBasePrice">$0</span></div>
          <div class="col-md-4"><small class="text-body-secondary d-block">Orden</small><span class="fw-semibold" id="groupArtistViewOrder">-</span></div>
          <div class="col-md-12"><small class="text-body-secondary d-block">Estado</small><span class="fw-semibold" id="groupArtistViewStatus">-</span></div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="deleteGroupArtistModal" tabindex="-1" aria-labelledby="deleteGroupArtistModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="deleteGroupArtistModalLabel">Eliminar artista</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="deleteGroupArtistName">este artista</strong>.</div>
      <div class="modal-footer">
        <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cancelar</button>
        <form id="deleteGroupArtistForm" method="POST" action="#">
          @csrf
          @method('DELETE')
          <input type="hidden" name="return_to_group_id" value="{{ $group->id }}">
          <button type="submit" class="btn btn-danger">Eliminar</button>
        </form>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="groupOtherCostEditorModal" tabindex="-1" aria-labelledby="groupOtherCostEditorModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header border-bottom">
        <h5 id="groupOtherCostEditorModalLabel" class="modal-title">Agregar costo</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="groupOtherCostEditorForm" method="POST" action="{{ route('owner.settings.other-costs.store') }}">
        @csrf
        <input type="hidden" name="_method" id="groupOtherCostMethod" value="POST">
        <input type="hidden" name="mariachi_group_id" value="{{ $group->id }}">
        <input type="hidden" name="return_to_group_id" value="{{ $group->id }}">
        <div class="modal-body">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label" for="groupOtherCostName">Nombre</label>
              <input type="text" class="form-control" id="groupOtherCostName" name="name" required>
            </div>
            <div class="col-md-3">
              <label class="form-label" for="groupOtherCostInternalCost">Costo interno (COP)</label>
              <input type="number" min="0" step="1000" class="form-control" id="groupOtherCostInternalCost" name="internal_cost" value="0" required>
            </div>
            <div class="col-md-3">
              <label class="form-label" for="groupOtherCostBasePrice">Precio cliente (COP)</label>
              <input type="number" min="0" step="1000" class="form-control" id="groupOtherCostBasePrice" name="base_price" value="0" required>
            </div>
            <div class="col-md-6">
              <label class="form-label" for="groupOtherCostSortOrder">Orden</label>
              <input type="number" min="0" class="form-control" id="groupOtherCostSortOrder" name="sort_order" value="100">
            </div>
            <div class="col-md-6">
              <label class="form-label" for="groupOtherCostIsActive">Estado</label>
              <select class="form-select" id="groupOtherCostIsActive" name="is_active">
                <option value="1">Activo</option>
                <option value="0">Inactivo</option>
              </select>
            </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="groupOtherCostSubmitBtn">Guardar costo</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="groupOtherCostViewModal" tabindex="-1" aria-labelledby="groupOtherCostViewModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header border-bottom">
        <h5 id="groupOtherCostViewModalLabel" class="modal-title">Detalle del costo</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="row g-3">
          <div class="col-md-6"><small class="text-body-secondary d-block">Nombre</small><span class="fw-semibold" id="groupOtherCostViewName">-</span></div>
          <div class="col-md-3"><small class="text-body-secondary d-block">Costo interno</small><span class="fw-semibold" id="groupOtherCostViewInternalCost">$0</span></div>
          <div class="col-md-3"><small class="text-body-secondary d-block">Precio cliente</small><span class="fw-semibold" id="groupOtherCostViewBasePrice">$0</span></div>
          <div class="col-md-6"><small class="text-body-secondary d-block">Estado</small><span class="fw-semibold" id="groupOtherCostViewStatus">-</span></div>
          <div class="col-md-6"><small class="text-body-secondary d-block">Orden</small><span class="fw-semibold" id="groupOtherCostViewOrder">-</span></div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="deleteGroupOtherCostModal" tabindex="-1" aria-labelledby="deleteGroupOtherCostModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="deleteGroupOtherCostModalLabel">Eliminar costo</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="deleteGroupOtherCostName">este costo</strong>.</div>
      <div class="modal-footer">
        <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cancelar</button>
        <form id="deleteGroupOtherCostForm" method="POST" action="#">
          @csrf
          @method('DELETE')
          <input type="hidden" name="return_to_group_id" value="{{ $group->id }}">
          <button type="submit" class="btn btn-danger">Eliminar</button>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
  window.packageRuleCatalogOptions = {
    gifts: @json($giftRuleCatalog),
    artists: @json($artistRuleCatalog),
    otherCosts: @json($otherCostRuleCatalog),
  };
</script>
<script>
document.addEventListener('DOMContentLoaded', () => {
  const sidebarStorageKey = 'owner.mariachi-group.sidebar.' + @json((int) $group->id);
  const sidebarColumn = document.getElementById('groupSidebarColumn');
  const contentColumn = document.getElementById('groupContentColumn');
  const sidebarToggle = document.getElementById('groupSidebarToggle');
  const sidebarToggleIcon = document.getElementById('groupSidebarToggleIcon');
  const groupPackageEditorEl = document.getElementById('groupPackageEditorModal');
  const groupPackageViewEl = document.getElementById('groupPackageViewModal');
  const deleteGroupPackageModalEl = document.getElementById('deleteGroupPackageModal');
  const groupPackageEditor = groupPackageEditorEl ? bootstrap.Modal.getOrCreateInstance(groupPackageEditorEl) : null;
  const groupPackageViewModal = groupPackageViewEl ? bootstrap.Modal.getOrCreateInstance(groupPackageViewEl) : null;
  const deleteGroupPackageModal = deleteGroupPackageModalEl ? bootstrap.Modal.getOrCreateInstance(deleteGroupPackageModalEl) : null;
  const openCreateBtn = document.getElementById('btnOpenGroupPackageCreate');
  const groupPackageForm = document.getElementById('groupPackageEditorForm');
  const groupPackageMethod = document.getElementById('groupPackageMethod');
  const groupPackageTitle = document.getElementById('groupPackageEditorModalLabel');
  const groupPackageSubmitBtn = document.getElementById('groupPackageSubmitBtn');
  const groupPackageDeleteForm = document.getElementById('deleteGroupPackageForm');
  const groupPackageDeleteName = document.getElementById('deleteGroupPackageName');
  const groupPackageFields = {
    name: document.getElementById('groupPackageName'),
    city: document.getElementById('groupPackageCity'),
    commissionAmount: document.getElementById('groupPackageCommissionAmount'),
    internalCostDisplay: document.getElementById('groupPackageInternalCostDisplay'),
    basePriceDisplay: document.getElementById('groupPackageBasePriceDisplay'),
    isActive: document.getElementById('groupPackageIsActive'),
    isDefault: document.getElementById('groupPackageIsDefault'),
    sortOrder: document.getElementById('groupPackageSortOrder'),
  };
  const groupPackageCheckboxes = Array.from(document.querySelectorAll('.group-pkg-item-checkbox'));
  const groupPackageStoreUrl = @json(route('owner.settings.packages.store'));
  const groupPackageUpdateBaseUrl = @json(url('/owner/configuracion/paquetes'));
  const groupPackageGiftsByCode = @json($packageCatalogGifts->mapWithKeys(fn($i) => [$i->code => $i->name])->all());
  const groupPackageArtistsByCode = @json($packageCatalogArtists->mapWithKeys(fn($i) => [$i->code => $i->name])->all());
  const groupPackageOtherCostsByCode = @json($packageCatalogOtherCosts->mapWithKeys(fn($i) => [$i->code => $i->name])->all());
  const setSidebarState = collapsed => {
    if (!sidebarColumn || !contentColumn || !sidebarToggle) {
      return;
    }

    sidebarColumn.classList.toggle('d-none', collapsed);
    contentColumn.classList.toggle('col-xl-8', !collapsed);
    contentColumn.classList.toggle('col-lg-7', !collapsed);
    contentColumn.classList.toggle('col-md-7', !collapsed);
    contentColumn.classList.toggle('col-12', collapsed);
    sidebarToggle.setAttribute('title', collapsed ? 'Mostrar panel' : 'Ocultar panel');
    sidebarToggle.setAttribute('aria-label', collapsed ? 'Mostrar panel' : 'Ocultar panel');

    if (sidebarToggleIcon) {
      sidebarToggleIcon.innerHTML = collapsed
        ? '<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 18l6-6l-6-6" /></svg>'
        : '<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 18l-6-6l6-6" /></svg>';
    }

    try {
      window.localStorage.setItem(sidebarStorageKey, collapsed ? '1' : '0');
    } catch (error) {
      // Ignore storage errors and keep current UI state.
    }
  };

  const loadSidebarState = () => {
    let collapsed = false;
    try {
      collapsed = window.localStorage.getItem(sidebarStorageKey) === '1';
    } catch (error) {
      collapsed = false;
    }
    setSidebarState(collapsed);
  };

  const formatCOP = value => `$${new Intl.NumberFormat('es-CO', { maximumFractionDigits: 0 }).format(Math.round(Number(value || 0) || 0))}`;
  const parseNumber = value => {
    const parsed = Number(value);
    return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;
  };
  const parsePayload = encoded => {
    if (!encoded) return null;
    try { return JSON.parse(atob(encoded)); } catch (error) { return null; }
  };
  const renderBadges = (container, codes, sourceMap) => {
    if (!container) return;
    const list = Array.isArray(codes) ? codes : [];
    container.innerHTML = list.length
      ? list.map(code => `<span class="badge bg-label-primary">${sourceMap[code] || code}</span>`).join('')
      : '<span class="text-body-secondary">Sin elementos</span>';
  };
  const resetChecks = () => {
    groupPackageCheckboxes.forEach(cb => { cb.checked = false; });
  };
  const fillChecks = codes => {
    const set = new Set(Array.isArray(codes) ? codes : []);
    groupPackageCheckboxes.forEach(cb => { cb.checked = set.has(cb.value); });
  };
  const calculateInternalCost = () => groupPackageCheckboxes.reduce((sum, cb) => cb.checked ? sum + parseNumber(cb.dataset.internalCost) : sum, 0);
  const refreshTotals = () => {
    const internalCost = calculateInternalCost();
    const commissionAmount = parseNumber(groupPackageFields.commissionAmount?.value || 0);
    groupPackageFields.internalCostDisplay.value = formatCOP(internalCost);
    groupPackageFields.basePriceDisplay.value = formatCOP(internalCost + commissionAmount);
  };
  const setCreateMode = () => {
    groupPackageForm.action = groupPackageStoreUrl;
    groupPackageMethod.value = 'POST';
    groupPackageTitle.textContent = 'Agregar paquete';
    groupPackageSubmitBtn.textContent = 'Guardar paquete';
    groupPackageForm.reset();
    groupPackageFields.sortOrder.value = '100';
    groupPackageFields.isActive.value = '1';
    groupPackageFields.isDefault.value = '0';
    groupPackageFields.commissionAmount.value = '0';
    resetChecks();
    refreshTotals();
  };

  openCreateBtn?.addEventListener('click', () => {
    setCreateMode();
    groupPackageEditor?.show();
  });

  document.querySelectorAll('.btn-edit-group-package').forEach(btn => {
    btn.addEventListener('click', () => {
      const pkg = parsePayload(btn.dataset.package || '');
      if (!pkg) return;
      groupPackageForm.action = `${groupPackageUpdateBaseUrl}/${pkg.id}`;
      groupPackageMethod.value = 'PUT';
      groupPackageTitle.textContent = 'Editar paquete';
      groupPackageSubmitBtn.textContent = 'Guardar cambios';
      groupPackageFields.name.value = pkg.name || '';
      groupPackageFields.city.value = pkg.city || '';
      groupPackageFields.commissionAmount.value = String(parseNumber(pkg.commission_amount));
      groupPackageFields.sortOrder.value = String(parseNumber(pkg.sort_order || 100));
      groupPackageFields.isActive.value = pkg.is_active ? '1' : '0';
      groupPackageFields.isDefault.value = pkg.is_default ? '1' : '0';
      fillChecks([...(pkg.gift_codes || []), ...(pkg.artist_codes || []), ...(pkg.other_cost_codes || [])]);
      refreshTotals();
      groupPackageEditor?.show();
    });
  });

  document.querySelectorAll('.btn-view-group-package').forEach(btn => {
    btn.addEventListener('click', () => {
      const pkg = parsePayload(btn.dataset.package || '');
      if (!pkg) return;
      document.getElementById('groupViewPackageName').textContent = pkg.name || '-';
      document.getElementById('groupViewPackageCity').textContent = pkg.city || '-';
      document.getElementById('groupViewPackageInternalCost').textContent = formatCOP(pkg.internal_cost);
      document.getElementById('groupViewPackageCommission').textContent = formatCOP(pkg.commission_amount);
      document.getElementById('groupViewPackageBasePrice').textContent = formatCOP(pkg.base_price);
      document.getElementById('groupViewPackageStatus').textContent = pkg.is_active ? 'Activo' : 'Inactivo';
      document.getElementById('groupViewPackageOrder').textContent = String(pkg.sort_order || '-');
      renderBadges(document.getElementById('groupViewPackageGifts'), pkg.gift_codes || [], groupPackageGiftsByCode);
      renderBadges(document.getElementById('groupViewPackageArtists'), pkg.artist_codes || [], groupPackageArtistsByCode);
      renderBadges(document.getElementById('groupViewPackageOtherCosts'), pkg.other_cost_codes || [], groupPackageOtherCostsByCode);
      groupPackageViewModal?.show();
    });
  });

  document.querySelectorAll('.btn-delete-group-package').forEach(btn => {
    btn.addEventListener('click', () => {
      groupPackageDeleteForm.action = `${groupPackageUpdateBaseUrl}/${btn.dataset.id}`;
      groupPackageDeleteName.textContent = btn.dataset.name || 'este paquete';
      deleteGroupPackageModal?.show();
    });
  });

  groupPackageCheckboxes.forEach(checkbox => checkbox.addEventListener('change', refreshTotals));
  groupPackageFields.commissionAmount?.addEventListener('input', refreshTotals);
  refreshTotals();
  loadSidebarState();

  sidebarToggle?.addEventListener('click', () => {
    const isCollapsed = sidebarColumn?.classList.contains('d-none');
    setSidebarState(!isCollapsed);
  });

  const activateTabFromHash = () => {
    const hash = window.location.hash;
    if (!hash) return;
    const trigger = document.querySelector(`[data-bs-target="${hash}"]`);
    if (trigger && window.bootstrap?.Tab) {
      window.bootstrap.Tab.getOrCreateInstance(trigger).show();
    }
  };

  activateTabFromHash();

  document.querySelectorAll('[data-bs-toggle="tab"]').forEach(trigger => {
    trigger.addEventListener('shown.bs.tab', event => {
      const target = event.target.getAttribute('data-bs-target');
      if (target) {
        window.history.replaceState(null, '', target);
      }
    });
  });

  window.addEventListener('hashchange', activateTabFromHash);
});
</script>
<script>
document.addEventListener('DOMContentLoaded', () => {
  const formatCOP = value => `$${new Intl.NumberFormat('es-CO', { maximumFractionDigits: 0 }).format(Math.round(Number(value || 0) || 0))}`;
  const parsePayload = encoded => {
    if (!encoded) return null;
    try { return JSON.parse(atob(encoded)); } catch (error) { return null; }
  };

  const setupCatalogCrud = config => {
    const editorEl = document.getElementById(config.editorModalId);
    const viewEl = document.getElementById(config.viewModalId);
    const deleteEl = document.getElementById(config.deleteModalId);
    const form = document.getElementById(config.formId);
    const methodInput = document.getElementById(config.methodInputId);
    const titleEl = document.getElementById(config.editorTitleId);
    const submitBtn = document.getElementById(config.submitButtonId);
    const deleteForm = document.getElementById(config.deleteFormId);
    const deleteName = document.getElementById(config.deleteNameId);
    const editorModal = editorEl ? bootstrap.Modal.getOrCreateInstance(editorEl) : null;
    const viewModal = viewEl ? bootstrap.Modal.getOrCreateInstance(viewEl) : null;
    const deleteModal = deleteEl ? bootstrap.Modal.getOrCreateInstance(deleteEl) : null;
    const createBtn = document.getElementById(config.openCreateButtonId);
    const fieldEls = Object.fromEntries(Object.entries(config.formFields).map(([key, id]) => [key, document.getElementById(id)]));
    const viewEls = Object.fromEntries(Object.entries(config.viewFields).map(([key, id]) => [key, document.getElementById(id)]));

    const setFieldValues = item => {
      Object.entries(fieldEls).forEach(([key, element]) => {
        if (!element) return;
        const defaultValue = Object.prototype.hasOwnProperty.call(config.defaults, key) ? config.defaults[key] : '';
        const value = Object.prototype.hasOwnProperty.call(item, key) ? item[key] : defaultValue;
        element.value = typeof value === 'boolean' ? (value ? '1' : '0') : String(value ?? '');
      });
    };

    const setViewValues = item => {
      Object.entries(viewEls).forEach(([key, element]) => {
        if (!element) return;
        const formatter = config.viewFormatters?.[key];
        const value = Object.prototype.hasOwnProperty.call(item, key) ? item[key] : null;
        element.textContent = formatter ? formatter(value, item) : String(value ?? '-');
      });
    };

    const setCreateMode = () => {
      form.action = config.storeUrl;
      methodInput.value = 'POST';
      titleEl.textContent = config.createTitle;
      submitBtn.textContent = config.createSubmitLabel;
      form.reset();
      setFieldValues(config.defaults);
    };

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

    document.querySelectorAll(config.editButtonSelector).forEach(button => {
      button.addEventListener('click', () => {
        const item = parsePayload(button.dataset.item || '');
        if (!item) return;
        form.action = `${config.updateBaseUrl}/${item.id}`;
        methodInput.value = 'PUT';
        titleEl.textContent = config.editTitle;
        submitBtn.textContent = config.editSubmitLabel;
        setFieldValues(item);
        editorModal?.show();
      });
    });

    document.querySelectorAll(config.viewButtonSelector).forEach(button => {
      button.addEventListener('click', () => {
        const item = parsePayload(button.dataset.item || '');
        if (!item) return;
        setViewValues(item);
        viewModal?.show();
      });
    });

    document.querySelectorAll(config.deleteButtonSelector).forEach(button => {
      button.addEventListener('click', () => {
        deleteForm.action = `${config.updateBaseUrl}/${button.dataset.id}`;
        deleteName.textContent = button.dataset.name || config.itemLabel;
        deleteModal?.show();
      });
    });
  };

  setupCatalogCrud({
    openCreateButtonId: 'btnOpenGroupGiftCreate',
    editorModalId: 'groupGiftEditorModal',
    viewModalId: 'groupGiftViewModal',
    deleteModalId: 'deleteGroupGiftModal',
    formId: 'groupGiftEditorForm',
    methodInputId: 'groupGiftMethod',
    editorTitleId: 'groupGiftEditorModalLabel',
    submitButtonId: 'groupGiftSubmitBtn',
    deleteFormId: 'deleteGroupGiftForm',
    deleteNameId: 'deleteGroupGiftName',
    storeUrl: @json(route('owner.settings.gifts.store')),
    updateBaseUrl: @json(url('/owner/configuracion/obsequios')),
    itemLabel: 'este obsequio',
    createTitle: 'Agregar obsequio',
    editTitle: 'Editar obsequio',
    createSubmitLabel: 'Guardar obsequio',
    editSubmitLabel: 'Guardar cambios',
    editButtonSelector: '.btn-edit-group-gift',
    viewButtonSelector: '.btn-view-group-gift',
    deleteButtonSelector: '.btn-delete-group-gift',
    defaults: {
      name: '',
      type: 'included',
      internal_cost: 0,
      base_price: 0,
      is_active: true,
      is_default: false,
      sort_order: 100,
    },
    formFields: {
      name: 'groupGiftName',
      type: 'groupGiftType',
      internal_cost: 'groupGiftInternalCost',
      base_price: 'groupGiftBasePrice',
      is_active: 'groupGiftIsActive',
      is_default: 'groupGiftIsDefault',
      sort_order: 'groupGiftSortOrder',
    },
    viewFields: {
      name: 'groupGiftViewName',
      type: 'groupGiftViewType',
      internal_cost: 'groupGiftViewInternalCost',
      base_price: 'groupGiftViewBasePrice',
      is_active: 'groupGiftViewStatus',
      is_default: 'groupGiftViewDefault',
      sort_order: 'groupGiftViewOrder',
    },
    viewFormatters: {
      type: value => value === 'additional' ? 'Adicional' : 'Incluido',
      internal_cost: value => formatCOP(value),
      base_price: value => formatCOP(value),
      is_active: value => value ? 'Activo' : 'Inactivo',
      is_default: value => value ? 'Sí' : 'No',
    },
  });

  setupCatalogCrud({
    openCreateButtonId: 'btnOpenGroupArtistCreate',
    editorModalId: 'groupArtistEditorModal',
    viewModalId: 'groupArtistViewModal',
    deleteModalId: 'deleteGroupArtistModal',
    formId: 'groupArtistEditorForm',
    methodInputId: 'groupArtistMethod',
    editorTitleId: 'groupArtistEditorModalLabel',
    submitButtonId: 'groupArtistSubmitBtn',
    deleteFormId: 'deleteGroupArtistForm',
    deleteNameId: 'deleteGroupArtistName',
    storeUrl: @json(route('owner.settings.artists.store')),
    updateBaseUrl: @json(url('/owner/configuracion/artistas')),
    itemLabel: 'este artista',
    createTitle: 'Agregar artista',
    editTitle: 'Editar artista',
    createSubmitLabel: 'Guardar artista',
    editSubmitLabel: 'Guardar cambios',
    editButtonSelector: '.btn-edit-group-artist',
    viewButtonSelector: '.btn-view-group-artist',
    deleteButtonSelector: '.btn-delete-group-artist',
    defaults: {
      name: '',
      type: 'included',
      internal_cost: 0,
      base_price: 0,
      is_active: true,
      sort_order: 100,
    },
    formFields: {
      name: 'groupArtistName',
      type: 'groupArtistType',
      internal_cost: 'groupArtistInternalCost',
      base_price: 'groupArtistBasePrice',
      is_active: 'groupArtistIsActive',
      sort_order: 'groupArtistSortOrder',
    },
    viewFields: {
      name: 'groupArtistViewName',
      type: 'groupArtistViewType',
      internal_cost: 'groupArtistViewInternalCost',
      base_price: 'groupArtistViewBasePrice',
      is_active: 'groupArtistViewStatus',
      sort_order: 'groupArtistViewOrder',
    },
    viewFormatters: {
      type: value => value === 'additional' ? 'Adicional' : 'Incluido',
      internal_cost: value => formatCOP(value),
      base_price: value => formatCOP(value),
      is_active: value => value ? 'Activo' : 'Inactivo',
    },
  });

  setupCatalogCrud({
    openCreateButtonId: 'btnOpenGroupOtherCostCreate',
    editorModalId: 'groupOtherCostEditorModal',
    viewModalId: 'groupOtherCostViewModal',
    deleteModalId: 'deleteGroupOtherCostModal',
    formId: 'groupOtherCostEditorForm',
    methodInputId: 'groupOtherCostMethod',
    editorTitleId: 'groupOtherCostEditorModalLabel',
    submitButtonId: 'groupOtherCostSubmitBtn',
    deleteFormId: 'deleteGroupOtherCostForm',
    deleteNameId: 'deleteGroupOtherCostName',
    storeUrl: @json(route('owner.settings.other-costs.store')),
    updateBaseUrl: @json(url('/owner/configuracion/otros-costos')),
    itemLabel: 'este costo',
    createTitle: 'Agregar costo',
    editTitle: 'Editar costo',
    createSubmitLabel: 'Guardar costo',
    editSubmitLabel: 'Guardar cambios',
    editButtonSelector: '.btn-edit-group-other-cost',
    viewButtonSelector: '.btn-view-group-other-cost',
    deleteButtonSelector: '.btn-delete-group-other-cost',
    defaults: {
      name: '',
      internal_cost: 0,
      base_price: 0,
      is_active: true,
      sort_order: 100,
    },
    formFields: {
      name: 'groupOtherCostName',
      internal_cost: 'groupOtherCostInternalCost',
      base_price: 'groupOtherCostBasePrice',
      is_active: 'groupOtherCostIsActive',
      sort_order: 'groupOtherCostSortOrder',
    },
    viewFields: {
      name: 'groupOtherCostViewName',
      internal_cost: 'groupOtherCostViewInternalCost',
      base_price: 'groupOtherCostViewBasePrice',
      is_active: 'groupOtherCostViewStatus',
      sort_order: 'groupOtherCostViewOrder',
    },
    viewFormatters: {
      internal_cost: value => formatCOP(value),
      base_price: value => formatCOP(value),
      is_active: value => value ? 'Activo' : 'Inactivo',
    },
  });
});
</script>
@endsection
