@extends('layouts.ownerLayout')

@section('title', 'Serenatas')

@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',
  'resources/assets/vendor/libs/flatpickr/flatpickr.scss',
  'resources/assets/vendor/libs/select2/select2.scss',
  'resources/assets/vendor/libs/@form-validation/form-validation.scss',
  'resources/assets/vendor/libs/notyf/notyf.scss'
])
@endsection

@section('vendor-script')
@vite([
  'resources/assets/vendor/libs/datatables-bs5/datatables-bootstrap5.js',
  'resources/assets/vendor/libs/flatpickr/flatpickr.js',
  'resources/assets/vendor/libs/select2/select2.js',
  'resources/assets/vendor/libs/@form-validation/popular.js',
  'resources/assets/vendor/libs/@form-validation/bootstrap5.js',
  'resources/assets/vendor/libs/@form-validation/auto-focus.js',
  'resources/assets/vendor/libs/notyf/notyf.js'
])
@endsection

@section('page-script')
@vite('resources/assets/js/owner-serenatas.js')
<script>
  window.__openAddSerenata = @json($errors->any());
  window.__toastData = {
    success: @json(session('status')),
    errors: @json($errors->all())
  };
  window.__googleMapsApiKey = @json($googleMapsApiKey ?? null);
  window.__googleMapsCountry = @json($googleMapsCountry ?? 'co');
  window.__aiParseUrl = @json(route('owner.serenatas.ai-parse'));
  window.__addressResolveUrl = @json(route('owner.serenatas.address-resolve'));
  window.__addressSuggestionsUrl = @json(route('owner.serenatas.address-suggestions'));
  window.__locationOptionsUrl = @json(route('owner.serenatas.location-options'));
  window.__locationOptionsSeed = @json($locationOptionsSeed ?? ['neighborhoods' => [], 'localities' => []]);
  window.__packageTemplateUrl = @json(route('owner.serenatas.package-template'));
  window.__mariachiGroupOptions = @json($mariachiGroupOptions ?? []);
  window.__serenataPackages = @json($packageOptions ?? []);
</script>
<style>
  .gm-address-suggestions {
    position: absolute;
    z-index: 1100;
    width: 100%;
    background: #fff;
    border: 1px solid #dbdade;
    border-radius: 0.375rem;
    box-shadow: 0 0.25rem 0.75rem rgba(47, 43, 61, 0.12);
    margin-top: 0.25rem;
    max-height: 220px;
    overflow-y: auto;
  }

  .gm-address-suggestion-item {
    padding: 0.5rem 0.75rem;
    font-size: 0.9375rem;
    color: #6f6b7d;
    cursor: pointer;
  }

  .gm-address-suggestion-item:hover,
  .gm-address-suggestion-item.active {
    background: #f4f5fb;
    color: #5d596c;
  }
  .address-input-group {
    position: relative;
  }
  .address-input-group > .address-input {
    padding-right: 2.6rem;
  }
  .address-map-btn {
    position: absolute;
    top: 1px;
    right: 1px;
    bottom: 1px;
    width: 38px;
    border: 0;
    border-radius: 0 .375rem .375rem 0;
    background: transparent;
    color: #8a8d98;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    z-index: 4;
    box-shadow: none;
  }
  .address-map-btn:hover,
  .address-map-btn:focus,
  .address-map-btn:active {
    color: #6f7281;
    background-color: rgba(111, 114, 129, 0.06) !important;
    box-shadow: none !important;
  }
  .phone-intl-field .iti {
    width: 100%;
    display: block;
  }
  .phone-intl-field .iti__tel-input {
    width: 100%;
  }
  .phone-intl-field .iti__selected-country {
    border-radius: .375rem 0 0 .375rem;
  }
  .phone-intl-field .iti__selected-country-primary {
    min-height: calc(1.5em + 0.844rem + 2px);
    padding-inline: .6rem .5rem;
  }
  .phone-intl-field .iti__selected-dial-code {
    font-size: .8125rem;
    color: #5d596c;
    margin-left: .35rem;
  }
  .phone-intl-field .iti__country-container {
    z-index: 6;
  }
  .phone-intl-field .iti__dropdown-content {
    z-index: 1100;
    border-color: #dbdade;
    box-shadow: 0 0.25rem 0.75rem rgba(47, 43, 61, 0.14);
  }
  .phone-intl-field .iti__search-input {
    color: #5d596c;
  }
  .phone-intl-field .iti__country-name {
    max-width: 13rem;
  }

  .ia-assist-overlay {
    position: absolute;
    inset: 0;
    z-index: 1060;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(47, 43, 61, 0.45);
    padding: 1rem;
  }

  .field-dot {
    display: inline-block;
    width: 0.45rem;
    height: 0.45rem;
    border-radius: 999px;
    margin-left: 0.35rem;
    vertical-align: middle;
  }

  .field-dot.required {
    background-color: #ff4c51;
  }

  .field-dot.optional {
    background-color: #a8aab4;
    opacity: 0.75;
  }

  .serenata-date-highlight-day {
    position: relative;
  }

  .serenata-date-highlight-day::after {
    content: '';
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: #28c76f;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    bottom: 4px;
  }

  .serenata-date-cell {
    line-height: 1.15;
  }

  .serenata-date-cell .serenata-date-day {
    display: block;
    font-weight: 700;
    color: #444050;
    letter-spacing: 0.03em;
  }

  .serenata-date-cell .serenata-date-time {
    display: block;
    margin-top: 0.2rem;
    font-size: 0.8125rem;
    font-weight: 600;
    color: #6f6b7d;
    letter-spacing: 0.08em;
  }

  .serenata-client-link {
    display: inline-flex;
    align-items: center;
    gap: 0.45rem;
    padding: 0.3rem 0.7rem;
    border-radius: 999px;
    background: rgba(115, 103, 240, 0.08);
    color: #5f59e1;
    font-weight: 600;
    text-decoration: none;
    transition: background-color 0.2s ease, color 0.2s ease, transform 0.2s ease;
  }

  .serenata-client-link:hover,
  .serenata-client-link:focus {
    background: rgba(115, 103, 240, 0.14);
    color: #4b45c6;
    transform: translateY(-1px);
    text-decoration: none;
  }

  .serenata-client-link .icon-base {
    font-size: 0.9rem;
  }

  #modalAddSerenata .flatpickr-calendar,
  .flatpickr-calendar {
    z-index: 3000 !important;
  }

  .time-input-group {
    position: relative;
  }
  .time-input-group > .time-input {
    padding-right: 2.4rem;
  }
  .time-picker-btn {
    position: absolute;
    top: 1px;
    right: 1px;
    bottom: 1px;
    width: 36px;
    border: 0;
    border-radius: 0 .375rem .375rem 0;
    background: transparent;
    color: #8a8d98;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    z-index: 4;
    box-shadow: none;
  }
  .time-picker-btn:hover,
  .time-picker-btn:focus,
  .time-picker-btn:active {
    color: #6f7281;
    background-color: rgba(111, 114, 129, 0.06) !important;
    box-shadow: none !important;
  }
  .event-window-mode-group {
    display: inline-flex;
    gap: 0.5rem;
    flex-wrap: wrap;
  }
  .event-window-mode-btn.active {
    background: rgba(255, 76, 81, 0.1);
    border-color: rgba(255, 76, 81, 0.28);
    color: #ff4c51;
  }
  .event-window-preview {
    border: 1px dashed rgba(111, 107, 125, 0.2);
    border-radius: 0.75rem;
    padding: 0.75rem 0.9rem;
    background: linear-gradient(180deg, rgba(255, 255, 255, 0.96), rgba(244, 245, 251, 0.96));
  }
  .event-window-preview strong {
    color: #444050;
    font-size: 0.95rem;
  }
  .event-clock-face {
    position: relative;
    width: 320px;
    height: 320px;
    margin: 0 auto;
    border-radius: 50%;
    background:
      radial-gradient(circle at center, rgba(255, 76, 81, 0.08) 0 52px, transparent 53px),
      radial-gradient(circle at center, #fff 0 100%, #fff 100%);
    border: 1px solid rgba(111, 107, 125, 0.15);
    box-shadow: inset 0 0 0 10px rgba(244, 245, 251, 0.9);
  }
  .event-clock-face::before {
    content: '';
    position: absolute;
    inset: 28px;
    border-radius: 50%;
    border: 1px dashed rgba(111, 107, 125, 0.14);
  }
  .event-clock-center {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 104px;
    text-align: center;
    z-index: 2;
  }
  .event-clock-center .badge {
    font-size: 0.72rem;
    letter-spacing: 0.04em;
  }
  .event-clock-hour {
    position: absolute;
    left: 50%;
    top: 50%;
    width: 52px;
    height: 52px;
    margin-left: -26px;
    margin-top: -26px;
    border-radius: 50%;
    border: 1px solid rgba(111, 107, 125, 0.16);
    background: #fff;
    color: #444050;
    display: inline-flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 0.05rem;
    box-shadow: 0 0.3rem 0.8rem rgba(47, 43, 61, 0.08);
    transform:
      rotate(calc(var(--slot) * 30deg))
      translateY(calc(var(--radius) * -1))
      rotate(calc(var(--slot) * -30deg));
    transition: transform 0.18s ease, box-shadow 0.18s ease, border-color 0.18s ease, background-color 0.18s ease;
  }
  .event-clock-hour:hover {
    transform:
      rotate(calc(var(--slot) * 30deg))
      translateY(calc(var(--radius) * -1))
      rotate(calc(var(--slot) * -30deg))
      scale(1.05);
    border-color: rgba(255, 76, 81, 0.3);
    box-shadow: 0 0.5rem 1rem rgba(47, 43, 61, 0.12);
  }
  .event-clock-hour.active {
    background: rgba(255, 76, 81, 0.12);
    border-color: rgba(255, 76, 81, 0.32);
    color: #ff4c51;
    box-shadow: 0 0.5rem 1rem rgba(255, 76, 81, 0.18);
  }
  .event-clock-hour small {
    font-size: 0.68rem;
    color: #8a8d98;
    line-height: 1;
  }
  .event-clock-hour.active small {
    color: inherit;
  }
  .event-clock-hour-inner {
    --radius: 76px;
    width: 46px;
    height: 46px;
    margin-left: -23px;
    margin-top: -23px;
    background: #f9fafc;
  }
  .event-clock-hour-outer {
    --radius: 132px;
  }
  .event-clock-summary {
    border-radius: 0.85rem;
    background: linear-gradient(135deg, rgba(255, 76, 81, 0.08), rgba(255, 255, 255, 0.96));
    border: 1px solid rgba(255, 76, 81, 0.12);
    padding: 0.9rem 1rem;
  }
  .event-clock-summary .event-clock-window {
    font-size: 1.05rem;
    font-weight: 700;
    color: #444050;
  }
  .event-clock-summary .event-clock-ref {
    font-size: 0.82rem;
    color: #6f6b7d;
  }
  @media (max-width: 575.98px) {
    .event-clock-face {
      width: 280px;
      height: 280px;
    }
    .event-clock-hour-outer {
      --radius: 114px;
    }
    .event-clock-hour-inner {
      --radius: 64px;
    }
  }

  .location-input-group {
    position: relative;
  }
  .location-select-wrap {
    min-width: 0;
  }
  .location-select-wrap > .select2-container {
    width: 100% !important;
    min-width: 0;
  }
  .location-select-wrap > .select2-container.location-select2 {
    flex: 1 1 auto;
  }
  .location-select-wrap > .select2-container .select2-selection--single {
    height: calc(1.5em + .5rem + 2px);
    padding-right: 2rem;
  }
  .location-select-wrap > .select2-container .select2-selection__rendered {
    line-height: calc(1.5em + .5rem);
    padding-left: 0.65rem;
    padding-right: 2.25rem;
  }
  .location-select-wrap > .select2-container .select2-selection__arrow {
    height: calc(1.5em + .5rem + 2px);
    right: 1.8rem;
  }
  .location-select-wrap > select.form-select {
    padding-right: 2.25rem;
  }
  .location-select-wrap > .location-text-input {
    padding-right: 2.25rem;
  }
  .location-lock-btn {
    position: absolute;
    top: 1px;
    right: 1px;
    bottom: 1px;
    min-width: 32px;
    width: 32px;
    padding: 0;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    height: auto;
    border: 0;
    border-radius: 0 .375rem .375rem 0;
    font-size: 0.875rem;
    line-height: 1;
    color: #8a8d98;
    background: transparent;
    box-shadow: none;
    z-index: 4;
  }
  .location-lock-btn:hover,
  .location-lock-btn:focus,
  .location-lock-btn:active {
    color: #6f7281;
    background-color: rgba(111, 114, 129, 0.06) !important;
    box-shadow: none !important;
  }
  .location-lock-btn.btn-outline-primary {
    color: #696cff;
    background-color: rgba(105, 108, 255, 0.08);
  }
  select.location-locked {
    pointer-events: none;
    background-color: #f4f5fb;
  }
  select.location-locked + .select2-container {
    pointer-events: none;
  }
  select.location-locked + .select2-container .select2-selection--single {
    background-color: #f4f5fb;
    cursor: not-allowed;
  }
  select.location-locked + .select2-container .select2-selection__rendered {
    color: #a8aab4;
  }
  select.location-locked + .select2-container .select2-selection__clear {
    display: none;
  }
  input.location-locked {
    background-color: #f4f5fb;
    cursor: not-allowed;
  }
</style>
@endsection

@section('content')
@php
  $serviceStatusOptions = ['Pendiente', 'Confirmada', 'Realizada', 'Cancelada'];
  $normalizeServiceStatus = function ($status) {
    return match ((string) $status) {
      'Confirmado', 'Confirmada' => 'Confirmada',
      'Completada', 'Realizada' => 'Realizada',
      'Cancelado', 'Cancelada' => 'Cancelada',
      'Cedida', 'Pendiente' => 'Pendiente',
      default => 'Pendiente',
    };
  };
  $paymentBadgeClass = function ($status) {
    return match ((string) $status) {
      'Pagado' => 'bg-label-success',
      'Abono parcial' => 'bg-label-info',
      'Cancelada sin cobro' => 'bg-label-danger',
      default => 'bg-label-warning',
    };
  };
@endphp
<div class="card mb-6">
  <div class="card-widget-separator-wrapper">
    <div class="card-body card-widget-separator">
      <div class="row gy-4 gy-sm-1">
        <div class="col-sm-6 col-lg-3">
          <div class="d-flex justify-content-between align-items-start card-widget-1 border-end pb-4 pb-sm-0">
            <div>
              <h4 class="mb-0">{{ $stats['pending'] }}</h4>
              <p class="mb-0">Por cobrar</p>
            </div>
            <span class="avatar me-sm-6">
              <span class="avatar-initial bg-label-secondary rounded text-heading">
                <i class="icon-base ti tabler-calendar-stats icon-26px text-heading"></i>
              </span>
            </span>
          </div>
          <hr class="d-none d-sm-block d-lg-none me-6" />
        </div>
        <div class="col-sm-6 col-lg-3">
          <div class="d-flex justify-content-between align-items-start card-widget-2 border-end pb-4 pb-sm-0">
            <div>
              <h4 class="mb-0">{{ $stats['completed'] }}</h4>
              <p class="mb-0">Realizadas</p>
            </div>
            <span class="avatar p-2 me-lg-6">
              <span class="avatar-initial bg-label-secondary rounded"><i class="icon-base ti tabler-checks icon-26px text-heading"></i></span>
            </span>
          </div>
          <hr class="d-none d-sm-block d-lg-none" />
        </div>
        <div class="col-sm-6 col-lg-3">
          <div class="d-flex justify-content-between align-items-start border-end pb-4 pb-sm-0 card-widget-3">
            <div>
              <h4 class="mb-0">{{ $stats['ceded'] }}</h4>
              <p class="mb-0">Cedidas</p>
            </div>
            <span class="avatar p-2 me-sm-6">
              <span class="avatar-initial bg-label-secondary rounded"><i class="icon-base ti tabler-wallet icon-26px text-heading"></i></span>
            </span>
          </div>
        </div>
        <div class="col-sm-6 col-lg-3">
          <div class="d-flex justify-content-between align-items-start">
            <div>
              <h4 class="mb-0">{{ $stats['cancelled'] }}</h4>
              <p class="mb-0">Canceladas</p>
            </div>
            <span class="avatar p-2">
              <span class="avatar-initial bg-label-secondary rounded"><i class="icon-base ti tabler-alert-octagon icon-26px text-heading"></i></span>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="card">
  <div class="card-header border-bottom">
    <h5 class="card-title">Filtros</h5>
    <div class="d-flex justify-content-between align-items-center row pt-4 gap-6 gap-md-0 g-md-6">
      <div class="col-md-3 serenata_date"></div>
      <div class="col-md-2 serenata_group"></div>
      <div class="col-md-2 serenata_status"></div>
      <div class="col-md-2 serenata_payment"></div>
      <div class="col-md-3 serenata_method"></div>
    </div>
  </div>

  <div class="card-datatable">
    <table class="datatables-owner-serenatas table border-top">
      <thead>
        <tr>
          <th>Serenata</th>
          <th>Fecha</th>
          <th>Grupo</th>
          <th>Cliente</th>
          <th>Pago</th>
          <th>Estado</th>
          <th>Método</th>
          <th>Acciones</th>
        </tr>
      </thead>
      <tbody>
        @foreach ($orders as $order)
          @php
            $giftItems = collect($order->gift_items ?? [])->filter(function ($item) {
              return !(bool) data_get($item, 'is_deleted', false);
            });
            $giftIncluded = $giftItems->filter(function ($item) {
              $type = strtolower((string) data_get($item, 'type', 'included'));
              return $type !== 'additional';
            })->values();
            $giftAdditional = $giftItems->filter(function ($item) {
              $type = strtolower((string) data_get($item, 'type', 'included'));
              return $type === 'additional';
            })->values();

            $formatGiftLine = function ($item): string {
              $name = (string) data_get($item, 'name', 'Obsequio');
              $qty = max(1, (int) data_get($item, 'quantity', 1));
              $unit = (float) data_get($item, 'unit_price', 0);
              return $name . " x{$qty} ($" . number_format($unit, 0, ',', '.') . ')';
            };

            $includedText = $giftIncluded->isNotEmpty()
              ? $giftIncluded->map($formatGiftLine)->implode(', ')
              : 'Ninguno';
            $additionalText = $giftAdditional->isNotEmpty()
              ? $giftAdditional->map($formatGiftLine)->implode(', ')
              : 'Ninguno';

            $phoneDigits = $order->contact_phone_1_whatsapp_digits;
            $confirmMessage = implode("\n", [
              "Hola {$order->payer_name}, te habla Camila Serenatas.",
              'Queremos reconfirmar tu servicio:',
              'Fecha: ' . optional($order->event_date)->format('d/m/Y'),
              'Horario estimado: ' . $order->eventWindowLabel(),
              "Dirección: {$order->service_address}",
              "Barrio: {$order->neighborhood}",
              '',
              '¿Todo sigue en pie? Muchas gracias.'
            ]);
            $waConfirmUrl = $phoneDigits !== ''
              ? 'https://wa.me/' . $phoneDigits . '?text=' . rawurlencode($confirmMessage)
              : null;

            $shareLines = [
              "SERVICIO {$order->code}",
              'Grupo: ' . (optional($order->mariachiGroup)->name ?: 'Sin grupo'),
              "Cliente: {$order->payer_name}",
              'Correo: ' . ($order->payer_email ?: '-'),
              "Teléfono 1: {$order->formatted_contact_phone_1}",
              'Teléfono 2: ' . ($order->formatted_contact_phone_2 ?: '-'),
              "Dirección: {$order->service_address}",
              'País: ' . ($order->service_country ?: 'Colombia'),
              'Departamento: ' . ($order->service_department ?: '-'),
              "Ciudad/Municipio: {$order->locality}",
              'Localidad: ' . ($order->service_locality ?: '-'),
              'Sector/UPZ: ' . ($order->service_sector ?: '-'),
              "Barrio: {$order->neighborhood}",
              'Fecha: ' . optional($order->event_date)->format('d/m/Y'),
              'Horario estimado: ' . $order->eventWindowLabel(),
              "De parte de: {$order->from_name}",
              "Para quién: {$order->to_name}",
              'Motivo: ' . ($order->reason ?: '-'),
              "Obsequios incluidos: {$includedText}",
              "Obsequios adicionales: {$additionalText}",
              'Precio total: $' . number_format((float) ($order->total_charged ?? 0), 0, ',', '.'),
            ];

            if (!empty($order->address_additional)) {
              $shareLines[] = "Dirección adicional: {$order->address_additional}";
            }
            if (!empty($order->service_private_note)) {
              $shareLines[] = "Nota para el servicio: {$order->service_private_note}";
            }
            $shareText = implode("\n", $shareLines);
            $displayDate = $order->event_date
              ? mb_strtoupper($order->event_date->locale('es')->translatedFormat('d F'), 'UTF-8')
              : '-';
            $displayTime = $order->eventWindowLabel() ?: '-';
          @endphp
          <tr>
            <td>
              <a
                href="{{ route('owner.serenatas.show', $order) }}"
                class="text-heading fw-semibold btn-open-serenata-view"
                data-view-url="{{ route('owner.serenatas.show', ['serenata' => $order, 'embed' => 1]) }}">
                {{ $order->code }}
              </a>
            </td>
            <td data-order="{{ optional($order->event_date)->format('Y-m-d') }} {{ $order->event_time }}">
              <div class="serenata-date-cell">
                <span class="serenata-date-day">{{ $displayDate }}</span>
                <span class="serenata-date-time">{{ $displayTime }}</span>
              </div>
            </td>
            <td>{{ optional($order->mariachiGroup)->name ?: 'Sin grupo' }}</td>
            <td>
              @if ($order->customer_id)
                <a href="{{ route('owner.clients.show', $order->customer_id) }}" class="serenata-client-link">
                  <i class="icon-base ti tabler-user-circle"></i>
                  <span>{{ $order->payer_name }}</span>
                </a>
              @else
                <span class="fw-semibold text-heading">{{ $order->payer_name }}</span>
              @endif
            </td>
            <td>
              <span class="badge {{ $paymentBadgeClass($order->payment_status) }}">
                {{ $order->payment_status }}
              </span>
            </td>
            <td>
              @php
                $serviceStatusLabel = $normalizeServiceStatus($order->service_status);
              @endphp
              <span class="badge {{
                in_array($serviceStatusLabel, ['Realizada', 'Confirmada'], true) ? 'bg-label-success' :
                ($serviceStatusLabel === 'Pendiente' ? 'bg-label-warning' :
                ($serviceStatusLabel === 'Cancelada' ? 'bg-label-danger' : 'bg-label-info'))
              }}">
                {{ $serviceStatusLabel }}
              </span>
            </td>
            <td>{{ $order->payment_method }}</td>
            <td>
              <textarea id="copy_serenata_{{ $order->id }}" class="d-none">{{ $shareText }}</textarea>
              <a
                href="{{ route('owner.serenatas.show', $order) }}"
                class="btn btn-text-secondary rounded-pill waves-effect btn-icon btn-open-serenata-view"
                data-view-url="{{ route('owner.serenatas.show', ['serenata' => $order, 'embed' => 1]) }}"
                title="Ver detalle">
                <i class="icon-base ti tabler-eye icon-22px"></i>
              </a>
              <button
                type="button"
                class="btn btn-text-secondary rounded-pill waves-effect btn-icon btn-copy-serenata"
                data-copy-target="copy_serenata_{{ $order->id }}"
                title="Copiar para WhatsApp">
                <i class="icon-base ti tabler-copy icon-22px"></i>
              </button>
              @if($waConfirmUrl)
                <a
                  href="{{ $waConfirmUrl }}"
                  target="_blank"
                  rel="noopener noreferrer"
                  class="btn btn-text-success rounded-pill waves-effect btn-icon"
                  title="Reconfirmar por WhatsApp">
                  <i class="icon-base ti tabler-brand-whatsapp icon-22px"></i>
                </a>
              @else
                <button type="button" class="btn btn-text-secondary rounded-pill waves-effect btn-icon" disabled title="Sin teléfono disponible">
                  <i class="icon-base ti tabler-brand-whatsapp icon-22px"></i>
                </button>
              @endif
            </td>
          </tr>
        @endforeach
      </tbody>
    </table>
  </div>

  <div class="modal fade" id="modalSerenataView" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-fullscreen">
      <div class="modal-content border-0">
        <div class="modal-header">
          <h5 class="modal-title">Detalle de serenata</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body p-0">
          <iframe
            id="serenataViewFrame"
            title="Detalle de serenata"
            class="w-100 border-0"
            style="height: calc(100vh - 64px);"
            src="about:blank"></iframe>
        </div>
      </div>
    </div>
  </div>

  <div class="modal fade" id="modalAddSerenata" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-fullscreen">
      <div class="modal-content">
        <div class="modal-body p-6">
          <button type="button" class="btn-close position-absolute top-0 end-0 m-4" data-bs-dismiss="modal" aria-label="Close"></button>

          <form class="add-new-serenata pt-0" id="addNewSerenataForm" method="POST" action="{{ route('owner.serenatas.store') }}">
            @csrf
            <input type="hidden" name="submission_token" value="{{ old('submission_token', (string) \Illuminate\Support\Str::uuid()) }}">
            @php
              $oldGiftItemsRaw = old('gift_items', '[]');
              $oldGiftItems = json_decode($oldGiftItemsRaw, true);
              if (!is_array($oldGiftItems)) {
                $oldGiftItems = [];
              }
              $oldGiftItemsByCode = collect($oldGiftItems)->keyBy('code');
              $oldArtistItemsRaw = old('artist_items', '[]');
              $oldArtistItems = json_decode($oldArtistItemsRaw, true);
              if (!is_array($oldArtistItems)) {
                $oldArtistItems = [];
              }
              $oldArtistItemsByCode = collect($oldArtistItems)->keyBy('code');
              $oldOtherCostItemsRaw = old('other_cost_items', '[]');
              $oldOtherCostItems = json_decode($oldOtherCostItemsRaw, true);
              if (!is_array($oldOtherCostItems)) {
                $oldOtherCostItems = [];
              }
              $oldOtherCostItemsByCode = collect($oldOtherCostItems)->keyBy('code');
              $defaultArtistCodes = ['cantante', 'vihuela', 'guitarron', 'trompeta'];
            @endphp

            <div class="app-ecommerce">
              <div class="d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center mb-4 row-gap-3">
                <div class="d-flex flex-column justify-content-center">
                  <h5 class="mb-1">Nueva serenata</h5>
                  <p class="mb-0 text-body-secondary">Registra la información del servicio y del pago.</p>
                </div>
                <div class="d-flex align-content-center flex-wrap gap-2">
                  <button type="button" class="btn btn-label-primary btn-sm" id="btnOpenIaAssist">
                    <i class="icon-base ti tabler-sparkles me-1"></i> Autocompletar con IA (beta)
                  </button>
                  <button type="reset" class="btn btn-label-secondary btn-sm">Limpiar</button>
                  <button type="submit" class="btn btn-primary btn-sm" data-submit-lock="default">Guardar serenata</button>
                </div>
              </div>

              <div class="row">
                <div class="col-12 col-lg-8">
                  <div class="card mb-4">
                    <div class="card-header">
                      <h6 class="card-title mb-0">Información de la serenata</h6>
                    </div>
                    <div class="card-body">
                      <div class="row g-3">
                        <div class="col-md-6 form-control-validation">
                          <label class="form-label mb-1" for="mariachi_group_id">Grupo musical <span class="field-dot required" title="Obligatorio"></span></label>
                          @php
                            $groupOptions = collect($mariachiGroupOptions ?? []);
                            $defaultGroupId = $selectedWorkspaceGroupId
                              ?? data_get($groupOptions->firstWhere('is_default', true), 'id')
                              ?? data_get($groupOptions->first(), 'id');
                          @endphp
                          <select class="form-select form-select-sm" id="mariachi_group_id" name="mariachi_group_id" required>
                            @foreach ($groupOptions as $group)
                              <option value="{{ $group['id'] }}" @selected((string) old('mariachi_group_id', $defaultGroupId) === (string) $group['id'])>{{ $group['name'] }}</option>
                            @endforeach
                          </select>
                        </div>
                        <div class="col-md-6">
                          <label class="form-label mb-1" for="serenata_package_id">Paquete (plantilla) <span class="field-dot optional" title="Opcional"></span></label>
                          @php
                            $packageOptionsCollection = collect($packageOptions ?? []);
                            $defaultPackageId = data_get(
                              $packageOptionsCollection->first(function ($package) use ($defaultGroupId) {
                                return (int) ($package['mariachi_group_id'] ?? 0) === (int) $defaultGroupId
                                  && !empty($package['is_default']);
                              }),
                              'id'
                            ) ?? data_get(
                              $packageOptionsCollection->first(function ($package) use ($defaultGroupId) {
                                return (int) ($package['mariachi_group_id'] ?? 0) === (int) $defaultGroupId;
                              }),
                              'id'
                            );
                          @endphp
                          <select class="form-select form-select-sm" id="serenata_package_id" name="serenata_package_id">
                            <option value="">Sin paquete</option>
                            @foreach ($packageOptionsCollection as $packageOption)
                              <option
                                value="{{ $packageOption['id'] }}"
                                data-city="{{ $packageOption['city'] }}"
                                data-mariachi-group-id="{{ $packageOption['mariachi_group_id'] ?? '' }}"
                                @selected((string) old('serenata_package_id', $defaultPackageId) === (string) $packageOption['id'])>
                                {{ $packageOption['name'] }} · {{ $packageOption['city'] }} · ${{ number_format((float) $packageOption['base_price'], 0, ',', '.') }}
                              </option>
                            @endforeach
                          </select>
                        </div>
                        <div class="col-md-6 form-control-validation">
                          <label class="form-label mb-1" for="payer_name">Nombre de quien realiza el pago <span class="field-dot required" title="Obligatorio"></span></label>
                          <input type="text" class="form-control form-control-sm" id="payer_name" name="payer_name" value="{{ old('payer_name') }}" required>
                        </div>
                        <div class="col-md-6 form-control-validation">
                          <label class="form-label mb-1" for="payer_email">Correo del cliente <span class="field-dot optional" title="Opcional"></span></label>
                          <input type="email" class="form-control form-control-sm" id="payer_email" name="payer_email" value="{{ old('payer_email') }}" placeholder="cliente@email.com">
                        </div>

                        <div class="col-md-8 form-control-validation">
                          <label class="form-label mb-1" for="service_address">Dirección del servicio <span class="field-dot required" title="Obligatorio"></span></label>
                          <div class="address-input-group position-relative">
                            <input type="text" class="form-control form-control-sm address-input" id="service_address" name="service_address" value="{{ old('service_address') }}" required autocomplete="off">
                            <button class="address-map-btn" type="button" id="btnOpenServiceAddressMap" title="Abrir en Google Maps">
                              <i class="icon-base ti tabler-map-pin-share"></i>
                            </button>
                          </div>
                        </div>
                        <div class="col-md-4 form-control-validation">
                          <label class="form-label mb-1" for="address_additional">Dirección adicional (casa/apto/interior) <span class="field-dot optional" title="Opcional"></span></label>
                          <input type="text" class="form-control form-control-sm" id="address_additional" name="address_additional" value="{{ old('address_additional') }}" placeholder="Ej: Apto 402, Casa 5, Torre B">
                        </div>
                        <div class="col-md-4 form-control-validation">
                          <label class="form-label mb-1" for="service_country">País <span class="field-dot required" title="Obligatorio"></span></label>
                          <div class="location-input-group">
                            <div class="location-select-wrap">
                              <input
                                type="text"
                                class="form-control form-control-sm location-text-input location-locked"
                                id="service_country"
                                name="service_country"
                                value="{{ old('service_country', 'Colombia') }}"
                                data-locked="1"
                                required>
                            </div>
                            <button class="btn btn-outline-secondary location-lock-btn" type="button" id="btnEditServiceCountry" title="Editar país">
                              <i class="icon-base ti tabler-lock"></i>
                            </button>
                          </div>
                        </div>
                        <div class="col-md-4 form-control-validation">
                          <label class="form-label mb-1" for="service_department">Departamento <span class="field-dot optional" title="Opcional"></span></label>
                          <div class="location-input-group">
                            <div class="location-select-wrap">
                              <input
                                type="text"
                                class="form-control form-control-sm location-text-input location-locked"
                                id="service_department"
                                name="service_department"
                                value="{{ old('service_department') }}"
                                list="service_department_options"
                                data-locked="1"
                                placeholder="Ej: Bogotá D.C., Cundinamarca">
                            </div>
                            <button class="btn btn-outline-secondary location-lock-btn" type="button" id="btnEditServiceDepartment" title="Editar departamento">
                              <i class="icon-base ti tabler-lock"></i>
                            </button>
                          </div>
                        </div>
                        <div class="col-md-4 form-control-validation">
                          <label class="form-label mb-1" for="locality">Ciudad / Municipio <span class="field-dot required" title="Obligatorio"></span></label>
                          <div class="location-input-group">
                            <div class="location-select-wrap">
                              <select
                                class="form-select form-select-sm location-select location-locked"
                                id="locality"
                                name="locality"
                                data-locked="1"
                                data-placeholder="Buscar o escribir ciudad/municipio"
                                required>
                                @if(old('locality'))
                                  <option value="{{ old('locality') }}" selected>{{ old('locality') }}</option>
                                @else
                                  <option value=""></option>
                                @endif
                                @foreach (($locationOptionsSeed['localities'] ?? []) as $localityOption)
                                  @if(old('locality') !== $localityOption)
                                    <option value="{{ $localityOption }}">{{ $localityOption }}</option>
                                  @endif
                                @endforeach
                              </select>
                            </div>
                            <button class="btn btn-outline-secondary location-lock-btn" type="button" id="btnEditLocality" title="Editar ciudad/municipio">
                              <i class="icon-base ti tabler-lock"></i>
                            </button>
                          </div>
                        </div>
                        <div class="col-md-4 form-control-validation">
                          <label class="form-label mb-1" for="service_locality">Localidad <span class="field-dot optional" title="Opcional"></span></label>
                          <div class="location-input-group">
                            <div class="location-select-wrap">
                              <input
                                type="text"
                                class="form-control form-control-sm location-text-input location-locked"
                                id="service_locality"
                                name="service_locality"
                                value="{{ old('service_locality') }}"
                                list="service_locality_options"
                                data-locked="1"
                                placeholder="Ej: Bosa, Kennedy, Suba">
                            </div>
                            <button class="btn btn-outline-secondary location-lock-btn" type="button" id="btnEditServiceLocality" title="Editar localidad">
                              <i class="icon-base ti tabler-lock"></i>
                            </button>
                          </div>
                        </div>
                        <div class="col-md-4 form-control-validation">
                          <label class="form-label mb-1" for="service_sector">Sector / UPZ / Urbanización <span class="field-dot optional" title="Opcional"></span></label>
                          <div class="location-input-group">
                            <div class="location-select-wrap">
                              <input
                                type="text"
                                class="form-control form-control-sm location-text-input location-locked"
                                id="service_sector"
                                name="service_sector"
                                value="{{ old('service_sector') }}"
                                list="service_sector_options"
                                data-locked="1"
                                placeholder="Ej: La Paz, Primavera, San Pablo">
                            </div>
                            <button class="btn btn-outline-secondary location-lock-btn" type="button" id="btnEditServiceSector" title="Editar sector o UPZ">
                              <i class="icon-base ti tabler-lock"></i>
                            </button>
                          </div>
                        </div>
                        <div class="col-md-4 form-control-validation">
                          <label class="form-label mb-1" for="neighborhood">Barrio <span class="field-dot required" title="Obligatorio"></span></label>
                          <div class="location-input-group">
                            <div class="location-select-wrap">
                              <select
                                class="form-select form-select-sm location-select location-locked"
                                id="neighborhood"
                                name="neighborhood"
                                data-locked="1"
                                data-placeholder="Buscar o escribir barrio"
                                required>
                                @if(old('neighborhood'))
                                  <option value="{{ old('neighborhood') }}" selected>{{ old('neighborhood') }}</option>
                                @else
                                  <option value=""></option>
                                @endif
                                @foreach (($locationOptionsSeed['neighborhoods'] ?? []) as $neighborhoodOption)
                                  @if(old('neighborhood') !== $neighborhoodOption)
                                    <option value="{{ $neighborhoodOption }}">{{ $neighborhoodOption }}</option>
                                  @endif
                                @endforeach
                              </select>
                            </div>
                            <button class="btn btn-outline-secondary location-lock-btn" type="button" id="btnEditNeighborhood" title="Editar barrio">
                              <i class="icon-base ti tabler-lock"></i>
                            </button>
                          </div>
                        </div>
                        <div class="col-md-4 form-control-validation phone-intl-field">
                          <label class="form-label mb-1" for="contact_phone_1_display">Número de contacto 1 <span class="field-dot required" title="Obligatorio"></span></label>
                          <input type="hidden" id="contact_phone_1" name="contact_phone_1" value="{{ old('contact_phone_1') }}">
                          <input
                            type="tel"
                            class="form-control form-control-sm"
                            id="contact_phone_1_display"
                            name="contact_phone_1_display"
                            value=""
                            inputmode="tel"
                            autocomplete="tel"
                            placeholder="300 123 4567"
                            required>
                        </div>
                        <datalist id="service_department_options">
                          @foreach (($locationOptionsSeed['departments'] ?? []) as $departmentOption)
                            <option value="{{ $departmentOption }}"></option>
                          @endforeach
                        </datalist>
                        <datalist id="service_locality_options">
                          @foreach (($locationOptionsSeed['service_localities'] ?? []) as $serviceLocalityOption)
                            <option value="{{ $serviceLocalityOption }}"></option>
                          @endforeach
                        </datalist>
                        <datalist id="service_sector_options">
                          @foreach (($locationOptionsSeed['service_sectors'] ?? []) as $serviceSectorOption)
                            <option value="{{ $serviceSectorOption }}"></option>
                          @endforeach
                        </datalist>
                        <div class="col-md-4 phone-intl-field">
                          <label class="form-label mb-1" for="contact_phone_2_display">Número de contacto 2 <span class="field-dot optional" title="Opcional"></span></label>
                          <input type="hidden" id="contact_phone_2" name="contact_phone_2" value="{{ old('contact_phone_2') }}">
                          <input
                            type="tel"
                            class="form-control form-control-sm"
                            id="contact_phone_2_display"
                            name="contact_phone_2_display"
                            value=""
                            inputmode="tel"
                            autocomplete="tel"
                            placeholder="Opcional">
                        </div>

                        <div class="col-md-6 form-control-validation">
                          <label class="form-label mb-1" for="reason">Motivo de la serenata <span class="field-dot required" title="Obligatorio"></span></label>
                          <input type="text" class="form-control form-control-sm" id="reason" name="reason" value="{{ old('reason') }}" required>
                        </div>
                        <div class="col-md-3 form-control-validation">
                          <label class="form-label mb-1" for="from_name">De parte de <span class="field-dot required" title="Obligatorio"></span></label>
                          <input type="text" class="form-control form-control-sm" id="from_name" name="from_name" value="{{ old('from_name') }}" required>
                        </div>
                        <div class="col-md-3 form-control-validation">
                          <label class="form-label mb-1" for="to_name">Para quién <span class="field-dot required" title="Obligatorio"></span></label>
                          <input type="text" class="form-control form-control-sm" id="to_name" name="to_name" value="{{ old('to_name') }}" required>
                        </div>

                        <div class="col-md-3 form-control-validation">
                          <label class="form-label mb-1" for="event_date">Fecha <span class="field-dot required" title="Obligatorio"></span></label>
                          <input type="date" class="form-control form-control-sm" id="event_date" name="event_date" value="{{ old('event_date') }}" required>
                        </div>
                        <div class="col-md-3 form-control-validation">
                          <label class="form-label mb-1" for="event_time">Horario <span class="field-dot required" title="Obligatorio"></span></label>
                          <div class="time-input-group">
                            <input type="hidden" id="event_time" name="event_time" value="{{ old('event_time') }}" required>
                            <input type="text" class="form-control form-control-sm time-input" id="event_time_display" name="event_time_display" value="{{ old('event_time') }}" placeholder="Ej: 18, 6 pm" autocomplete="off">
                            <button class="time-picker-btn" type="button" id="btnEventTimePicker" title="Seleccionar hora">
                              <i class="icon-base ti tabler-clock"></i>
                            </button>
                          </div>
                          <input type="hidden" id="event_time_window_mode" value="{{ old('event_time_window_mode', 'after') }}">
                          <div class="event-window-mode-group mt-2" id="eventTimeModeButtons">
                            <button type="button" class="btn btn-sm btn-label-secondary event-window-mode-btn" data-mode="after">Desde esta hora</button>
                            <button type="button" class="btn btn-sm btn-label-secondary event-window-mode-btn" data-mode="before">Hasta esta hora</button>
                          </div>
                          <div class="event-window-preview mt-2">
                            <div class="small text-body-secondary mb-1">Ventana estimada de llegada</div>
                            <strong id="event_time_window_preview">Selecciona una hora de referencia</strong>
                          </div>
                        </div>
                        <div class="col-md-6 form-control-validation">
                          <label class="form-label mb-1" for="client_notes">Notas al cliente <span class="field-dot optional" title="Opcional"></span></label>
                          <textarea class="form-control form-control-sm" id="client_notes" name="client_notes" rows="2" placeholder="Observaciones visibles para el cliente">{{ old('client_notes') }}</textarea>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="card mb-0">
                    <div class="card-header">
                      <h6 class="card-title mb-0">Obsequios incluidos</h6>
                    </div>
                    <div class="card-body">
                      <input type="hidden" id="gift_items" name="gift_items" value="{{ old('gift_items', '[]') }}">
                      <div class="row">
                        <div class="col-12 col-md-4 col-xl-3 border-end">
                          <div class="nav-align-left">
                            <ul class="nav nav-pills flex-column w-100" role="tablist">
                              <li class="nav-item mb-2">
                                <button
                                  class="nav-link active d-flex align-items-center justify-content-start"
                                  data-bs-toggle="tab"
                                  data-bs-target="#gift-included-tab"
                                  type="button"
                                  role="tab">
                                  <i class="icon-base ti tabler-gift me-2"></i> Incluidos
                                </button>
                              </li>
                              <li class="nav-item">
                                <button
                                  class="nav-link d-flex align-items-center justify-content-start"
                                  data-bs-toggle="tab"
                                  data-bs-target="#gift-additional-tab"
                                  type="button"
                                  role="tab">
                                  <i class="icon-base ti tabler-shopping-bag-plus me-2"></i> Adicionales
                                </button>
                              </li>
                              <li class="nav-item mt-2">
                                <button
                                  class="nav-link d-flex align-items-center justify-content-start"
                                  data-bs-toggle="tab"
                                  data-bs-target="#gift-artists-tab"
                                  type="button"
                                  role="tab">
                                  <i class="icon-base ti tabler-music me-2"></i> Artistas
                                </button>
                              </li>
                              <li class="nav-item mt-2">
                                <button
                                  class="nav-link d-flex align-items-center justify-content-start"
                                  data-bs-toggle="tab"
                                  data-bs-target="#gift-other-costs-tab"
                                  type="button"
                                  role="tab">
                                  <i class="icon-base ti tabler-truck-delivery me-2"></i> Otros Costos
                                </button>
                              </li>
                            </ul>
                          </div>
                        </div>
                        <div class="col-12 col-md-8 col-xl-9 pt-3 pt-md-0">
                          <div class="tab-content p-0" id="giftItemsList">
                            <div class="tab-pane fade show active gift-tab-panel" id="gift-included-tab" role="tabpanel" data-page-size="3">
                              <p class="text-body-secondary mb-3">Obsequios que pueden ir incluidos en el servicio.</p>
                              <div class="row g-2 gift-tab-list">
                                @foreach ($giftOptions as $giftOption)
                                  @continue(($giftOption['type'] ?? 'included') !== 'included')
                                  @php
                                    $giftCode = $giftOption['code'];
                                    $giftGroupId = (int) ($giftOption['mariachi_group_id'] ?? 0);
                                    $giftInputId = 'gift_' . $giftGroupId . '_' . $giftCode;
                                    $oldGiftItem = $oldGiftItemsByCode->get($giftCode, []);
                                    $isChecked = !empty($oldGiftItem) || (empty($oldGiftItems) && !empty($giftOption['is_default']));
                                    $oldQuantity = (int) data_get($oldGiftItem, 'quantity', 1);
                                    $quantity = $oldQuantity > 0 ? $oldQuantity : 1;
                                  @endphp
                                  <div class="col-12 col-md-6 col-xl-4 gift-item-col">
                                    <div
                                      class="border rounded p-2 h-100 d-flex flex-column gap-2 gift-item-row"
                                      data-gift-code="{{ $giftCode }}"
                                      data-mariachi-group-id="{{ $giftGroupId }}"
                                      data-gift-name="{{ $giftOption['name'] }}"
                                      data-gift-price="{{ $giftOption['price'] }}"
                                      data-gift-type="{{ $giftOption['type'] ?? 'included' }}">
                                      <div class="form-check m-0">
                                        <input
                                          class="form-check-input gift-item-check"
                                          type="checkbox"
                                          id="{{ $giftInputId }}"
                                          @checked($isChecked)>
                                        <label class="form-check-label small fw-medium" for="{{ $giftInputId }}">
                                          {{ $giftOption['name'] }}
                                          <span class="text-body-secondary">(${{ number_format($giftOption['price'], 0, ',', '.') }})</span>
                                        </label>
                                      </div>
                                      <input
                                        type="number"
                                        class="form-control form-control-sm gift-item-qty"
                                        min="1"
                                        max="50"
                                        value="{{ $quantity }}"
                                        @disabled(!$isChecked)>
                                    </div>
                                  </div>
                                @endforeach
                              </div>
                              <div class="d-flex justify-content-end align-items-center gap-2 mt-3 gift-pagination">
                                <button type="button" class="btn btn-sm btn-label-secondary gift-page-prev">Anterior</button>
                                <small class="text-body-secondary gift-page-info">1 / 1</small>
                                <button type="button" class="btn btn-sm btn-label-secondary gift-page-next">Siguiente</button>
                              </div>
                            </div>
                            <div class="tab-pane fade gift-tab-panel" id="gift-additional-tab" role="tabpanel" data-page-size="3">
                              <p class="text-body-secondary mb-3">Obsequios que se suman como adicional al precio.</p>
                              <div class="row g-2 gift-tab-list">
                                @foreach ($giftOptions as $giftOption)
                                  @continue(($giftOption['type'] ?? 'included') !== 'additional')
                                  @php
                                    $giftCode = $giftOption['code'];
                                    $giftGroupId = (int) ($giftOption['mariachi_group_id'] ?? 0);
                                    $giftInputId = 'gift_' . $giftGroupId . '_' . $giftCode;
                                    $oldGiftItem = $oldGiftItemsByCode->get($giftCode, []);
                                    $isChecked = !empty($oldGiftItem) || (empty($oldGiftItems) && !empty($giftOption['is_default']));
                                    $oldQuantity = (int) data_get($oldGiftItem, 'quantity', 1);
                                    $quantity = $oldQuantity > 0 ? $oldQuantity : 1;
                                  @endphp
                                  <div class="col-12 col-md-6 col-xl-4 gift-item-col">
                                    <div
                                      class="border rounded p-2 h-100 d-flex flex-column gap-2 gift-item-row"
                                      data-gift-code="{{ $giftCode }}"
                                      data-mariachi-group-id="{{ $giftGroupId }}"
                                      data-gift-name="{{ $giftOption['name'] }}"
                                      data-gift-price="{{ $giftOption['price'] }}"
                                      data-gift-type="{{ $giftOption['type'] ?? 'included' }}">
                                      <div class="form-check m-0">
                                        <input
                                          class="form-check-input gift-item-check"
                                          type="checkbox"
                                          id="{{ $giftInputId }}"
                                          @checked($isChecked)>
                                        <label class="form-check-label small fw-medium" for="{{ $giftInputId }}">
                                          {{ $giftOption['name'] }}
                                          <span class="text-body-secondary">(${{ number_format($giftOption['price'], 0, ',', '.') }})</span>
                                        </label>
                                      </div>
                                      <input
                                        type="number"
                                        class="form-control form-control-sm gift-item-qty"
                                        min="1"
                                        max="50"
                                        value="{{ $quantity }}"
                                        @disabled(!$isChecked)>
                                    </div>
                                  </div>
                                @endforeach
                              </div>
                              <div class="d-flex justify-content-end align-items-center gap-2 mt-3 gift-pagination">
                                <button type="button" class="btn btn-sm btn-label-secondary gift-page-prev">Anterior</button>
                                <small class="text-body-secondary gift-page-info">1 / 1</small>
                                <button type="button" class="btn btn-sm btn-label-secondary gift-page-next">Siguiente</button>
                              </div>
                            </div>
                            <div class="tab-pane fade" id="gift-artists-tab" role="tabpanel">
                              <p class="text-body-secondary mb-3">Selecciona artistas para esta serenata y ajusta precio cuando aplique.</p>
                              <input type="hidden" id="artist_items" name="artist_items" value="{{ old('artist_items', '[]') }}">
                              <div class="row g-2" id="artistItemsList">
                                @foreach ($artistOptions as $artistOption)
                                  @php
                                    $artistCode = $artistOption['code'];
                                    $artistGroupId = (int) ($artistOption['mariachi_group_id'] ?? 0);
                                    $artistInputId = 'artist_' . $artistGroupId . '_' . $artistCode;
                                    $artistPriceInputId = 'artist_price_' . $artistGroupId . '_' . $artistCode;
                                    $oldArtistItem = $oldArtistItemsByCode->get($artistCode, []);
                                    $isArtistChecked = !empty($oldArtistItem) || (empty($oldArtistItems) && in_array($artistCode, $defaultArtistCodes, true));
                                    $artistUnitPrice = (float) data_get($oldArtistItem, 'unit_price', $artistOption['price']);
                                  @endphp
                                  <div class="col-12 col-md-6 col-xl-4">
                                    <div
                                      class="border rounded p-2 h-100 d-flex flex-column gap-2 artist-item-row"
                                      data-artist-code="{{ $artistCode }}"
                                      data-mariachi-group-id="{{ $artistGroupId }}"
                                      data-artist-name="{{ $artistOption['name'] }}">
                                      <div class="d-flex justify-content-between align-items-start gap-2">
                                        <div>
                                          <h6 class="mb-1 d-flex align-items-center gap-2">
                                            <input
                                              class="form-check-input mt-0 artist-item-check"
                                              type="checkbox"
                                              id="{{ $artistInputId }}"
                                              @checked($isArtistChecked)>
                                            <label for="{{ $artistInputId }}" class="mb-0">{{ $artistOption['name'] }}</label>
                                          </h6>
                                          <small class="text-body-secondary">
                                            {{ ($artistOption['type'] ?? 'included') === 'additional' ? 'Adicional' : 'Incluido' }}
                                          </small>
                                        </div>
                                      </div>
                                      <div>
                                        <label class="form-label mb-1 small text-body-secondary" for="{{ $artistPriceInputId }}">Precio (COP)</label>
                                        <input
                                          type="text"
                                          inputmode="numeric"
                                          class="form-control form-control-sm artist-item-price"
                                          id="{{ $artistPriceInputId }}"
                                          value="{{ number_format($artistUnitPrice, 0, ',', '.') }}"
                                          @disabled(!$isArtistChecked)>
                                      </div>
                                    </div>
                                  </div>
                                @endforeach
                              </div>
                            </div>
                            <div class="tab-pane fade" id="gift-other-costs-tab" role="tabpanel">
                              <p class="text-body-secondary mb-3">Costos derivados del servicio (logística, transporte, etc.).</p>
                              <input type="hidden" id="other_cost_items" name="other_cost_items" value="{{ old('other_cost_items', '[]') }}">
                              <div class="row g-2" id="otherCostItemsList">
                                @foreach ($otherCostOptions as $otherCostOption)
                                  @php
                                    $otherCostCode = $otherCostOption['code'];
                                    $otherCostGroupId = (int) ($otherCostOption['mariachi_group_id'] ?? 0);
                                    $otherCostInputId = 'other_cost_' . $otherCostGroupId . '_' . $otherCostCode;
                                    $otherCostPriceInputId = 'other_cost_price_' . $otherCostGroupId . '_' . $otherCostCode;
                                    $oldOtherCostItem = $oldOtherCostItemsByCode->get($otherCostCode, []);
                                    $isOtherCostChecked = !empty($oldOtherCostItem) || (empty($oldOtherCostItems) && $otherCostCode === 'transporte');
                                    $otherCostUnitPrice = (float) data_get($oldOtherCostItem, 'unit_price', $otherCostOption['price']);
                                  @endphp
                                  <div class="col-12 col-md-6 col-xl-4">
                                    <div
                                      class="border rounded p-2 h-100 d-flex flex-column gap-2 other-cost-item-row"
                                      data-other-cost-code="{{ $otherCostCode }}"
                                      data-mariachi-group-id="{{ $otherCostGroupId }}"
                                      data-other-cost-name="{{ $otherCostOption['name'] }}">
                                      <div class="d-flex justify-content-between align-items-start gap-2">
                                        <div>
                                          <h6 class="mb-1 d-flex align-items-center gap-2">
                                            <input
                                              class="form-check-input mt-0 other-cost-item-check"
                                              type="checkbox"
                                              id="{{ $otherCostInputId }}"
                                              @checked($isOtherCostChecked)>
                                            <label for="{{ $otherCostInputId }}" class="mb-0">{{ $otherCostOption['name'] }}</label>
                                          </h6>
                                        </div>
                                      </div>
                                      <div>
                                        <label class="form-label mb-1 small text-body-secondary" for="{{ $otherCostPriceInputId }}">Precio (COP)</label>
                                        <input
                                          type="text"
                                          inputmode="numeric"
                                          class="form-control form-control-sm other-cost-item-price"
                                          id="{{ $otherCostPriceInputId }}"
                                          value="{{ number_format($otherCostUnitPrice, 0, ',', '.') }}"
                                          @disabled(!$isOtherCostChecked)>
                                      </div>
                                    </div>
                                  </div>
                                @endforeach
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div class="col-12 col-lg-4">
                  <div class="card mb-4">
                    <div class="card-body">
                      <button
                        type="button"
                        class="btn btn-label-secondary w-100 d-flex align-items-center justify-content-between"
                        data-bs-toggle="collapse"
                        data-bs-target="#internalNotesCollapse"
                        aria-expanded="false"
                        aria-controls="internalNotesCollapse"
                        id="internalNotesToggleBtn">
                        <span class="fw-medium">Notas internas</span>
                        <i class="icon-base ti tabler-plus" id="internalNotesToggleIcon"></i>
                      </button>
                      <div class="collapse mt-3" id="internalNotesCollapse">
                        <div class="form-control-validation">
                          <label class="form-label mb-1" for="internal_notes">Notas internas <span class="field-dot optional" title="Opcional"></span></label>
                          <textarea class="form-control form-control-sm" id="internal_notes" name="internal_notes" rows="3" placeholder="Solo para tu equipo interno">{{ old('internal_notes') }}</textarea>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="card mb-4">
                    <div class="card-header">
                      <h6 class="card-title mb-0">Estado y método de pago</h6>
                    </div>
                    <div class="card-body">
                      <input type="hidden" name="payment_status" value="Pendiente">
                      <div class="row g-3">
                        <div class="col-12 form-control-validation">
                          <label class="form-label mb-1">Estado de pago inicial</label>
                          <input type="text" class="form-control form-control-sm bg-label-secondary" value="Pendiente" readonly>
                          <small class="text-body-secondary">El cobro nace pendiente y se actualiza con pagos reales.</small>
                        </div>
                        <div class="col-12 form-control-validation">
                          <label class="form-label mb-1" for="service_status">Estado de servicio <span class="field-dot required" title="Obligatorio"></span></label>
                          <select class="form-select form-select-sm" id="service_status" name="service_status" required>
                            @foreach ($serviceStatusOptions as $status)
                              <option value="{{ $status }}" @selected(old('service_status', 'Pendiente') === $status)>{{ $status }}</option>
                            @endforeach
                          </select>
                        </div>
                        <div class="col-12 form-control-validation d-none" id="cancellationReasonWrap">
                          <label class="form-label mb-1" for="cancellation_reason">Motivo de cancelación <span class="field-dot required" title="Obligatorio"></span></label>
                          <textarea class="form-control form-control-sm" id="cancellation_reason" name="cancellation_reason" rows="2" placeholder="Explica la razón de la cancelación">{{ old('cancellation_reason') }}</textarea>
                        </div>
                        <div class="col-12 form-control-validation">
                          <label class="form-label mb-1" for="payment_method">Método de pago <span class="field-dot required" title="Obligatorio"></span></label>
                          @php
                            $methodOptions = collect($paymentMethodOptions ?? []);
                            $defaultMethod = data_get($methodOptions->firstWhere('is_default', true), 'name')
                              ?? data_get($methodOptions->first(), 'name')
                              ?? '';
                          @endphp
                          <select class="form-select form-select-sm" id="payment_method" name="payment_method" required @disabled($methodOptions->isEmpty())>
                            @if($methodOptions->isNotEmpty())
                              @foreach ($methodOptions as $method)
                                <option value="{{ $method['name'] }}" @selected(old('payment_method', $defaultMethod) === $method['name'])>{{ $method['name'] }}</option>
                              @endforeach
                            @else
                              <option value="" selected disabled>Configura métodos en Configuración > Pagos</option>
                            @endif
                          </select>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="card mb-0">
                    <div class="card-header">
                      <h6 class="card-title mb-0">Precios</h6>
                    </div>
                    <div class="card-body">
                      <div class="row g-3 mb-3">
                        <div class="col-md-6 form-control-validation">
                          <label class="form-label mb-1 d-flex align-items-center gap-1" for="base_price">
                            Yo cobro al cliente <span class="field-dot required" title="Obligatorio"></span>
                            <i class="icon-base ti tabler-info-circle text-body-secondary"
                               data-bs-toggle="tooltip"
                               title="Monto final pactado con el cliente, antes del descuento."></i>
                          </label>
                          <input type="text" inputmode="numeric" class="form-control form-control-sm fw-semibold" id="base_price" name="base_price" value="{{ old('base_price', 0) ? number_format((float) old('base_price', 0), 0, ',', '.') : '0' }}" required>
                          <small class="text-body-secondary">Este es el valor que tú vendiste.</small>
                        </div>
                        <div class="col-md-6">
                          <label class="form-label mb-1 d-flex align-items-center gap-1" for="discount_amount">
                            Descuento al cliente <span class="field-dot optional" title="Opcional"></span>
                            <i class="icon-base ti tabler-info-circle text-body-secondary"
                               data-bs-toggle="tooltip"
                               title="Valor que se resta al precio cobrado al cliente."></i>
                          </label>
                          <input type="text" inputmode="numeric" class="form-control form-control-sm" id="discount_amount" name="discount_amount" value="{{ old('discount_amount', 0) ? number_format((float) old('discount_amount', 0), 0, ',', '.') : '0' }}">
                          <small class="text-body-secondary">Déjalo en `0` si no hay descuento.</small>
                        </div>
                        <div class="col-md-6">
                          <label class="form-label mb-1 d-flex align-items-center gap-1" for="base_cost_preview">
                            Me cuesta este servicio
                            <i class="icon-base ti tabler-info-circle text-body-secondary"
                               data-bs-toggle="tooltip"
                               title="Costo total automático del servicio = artistas + obsequios + otros costos."></i>
                          </label>
                          <input type="text" class="form-control form-control-sm bg-label-secondary fw-semibold" id="base_cost_preview" value="0" readonly>
                          <small class="text-body-secondary">Esto es lo que te cuesta hacerlo.</small>
                        </div>
                        <div class="col-md-6">
                          <label class="form-label mb-1 d-flex align-items-center gap-1" for="profit_preview">
                            Yo gano aproximadamente
                            <i class="icon-base ti tabler-info-circle text-body-secondary"
                               data-bs-toggle="tooltip"
                               title="Ganancia = Total cobrado real - Costo del servicio."></i>
                          </label>
                          <input type="text" class="form-control form-control-sm bg-label-secondary fw-semibold" id="profit_preview" value="0" readonly>
                          <small class="text-body-secondary">Se actualiza solo con los valores de arriba.</small>
                        </div>
                        <div class="col-md-6">
                          <label class="form-label mb-1 d-flex align-items-center gap-1" for="total_price_preview">
                            Total cobrado real
                            <i class="icon-base ti tabler-info-circle text-body-secondary"
                               data-bs-toggle="tooltip"
                               title="Total cobrado real = Precio cobrado al cliente - Descuento."></i>
                          </label>
                          <input type="text" class="form-control form-control-sm bg-label-secondary fw-semibold" id="total_price_preview" value="0" readonly>
                          <small class="text-body-secondary">Esto es lo que realmente entra después del descuento.</small>
                        </div>
                        <div class="col-md-6 d-none">
                          <label class="form-label mb-1" for="gift_amount">Obsequios</label>
                          <input type="hidden" id="gift_amount" name="gift_amount" value="{{ old('gift_amount', 0) }}">
                        </div>
                      </div>

                      <div class="border rounded p-3">
                        <div class="d-flex justify-content-between align-items-center gap-2 mb-3">
                          <div>
                            <h6 class="mb-1">Cómo se calcula lo que me cuesta</h6>
                            <small class="text-body-secondary">Estos valores salen de artistas, obsequios y otros costos seleccionados. No hace falta editarlos aquí.</small>
                          </div>
                        </div>

                        <div class="row g-3">
                          <div class="col-md-6 form-control-validation">
                            <label class="form-label mb-1 d-flex align-items-center gap-1" for="artist_amount">
                              Artistas
                              <i class="icon-base ti tabler-info-circle text-body-secondary"
                                 data-bs-toggle="tooltip"
                                 title="Costo total de artistas seleccionados."></i>
                            </label>
                            <input type="text" inputmode="numeric" class="form-control form-control-sm bg-label-secondary" id="artist_amount" name="artist_amount" value="{{ old('artist_amount', 0) ? number_format((float) old('artist_amount', 0), 0, ',', '.') : '0' }}" readonly>
                          </div>

                          <div class="col-md-6">
                            <label class="form-label mb-1 d-flex align-items-center gap-1" for="other_cost_amount">
                              Otros costos
                              <i class="icon-base ti tabler-info-circle text-body-secondary"
                                 data-bs-toggle="tooltip"
                                 title="Costos derivados como transporte, logística u otros cargos seleccionados."></i>
                            </label>
                            <input type="text" inputmode="numeric" class="form-control form-control-sm bg-label-secondary" id="other_cost_amount" name="other_cost_amount" value="{{ old('other_cost_amount', 0) ? number_format((float) old('other_cost_amount', 0), 0, ',', '.') : '0' }}" readonly>
                          </div>

                          <div class="col-md-6">
                            <label class="form-label mb-1 d-flex align-items-center gap-1" for="gift_included_amount_preview">
                              Obsequios incluidos
                              <i class="icon-base ti tabler-info-circle text-body-secondary"
                                 data-bs-toggle="tooltip"
                                 title="Costo de obsequios marcados como incluidos."></i>
                            </label>
                            <input type="text" class="form-control form-control-sm bg-label-secondary" id="gift_included_amount_preview" value="0" readonly>
                          </div>

                          <div class="col-md-6">
                            <label class="form-label mb-1 d-flex align-items-center gap-1" for="gift_additional_amount_preview">
                              Obsequios adicionales
                              <i class="icon-base ti tabler-info-circle text-body-secondary"
                                 data-bs-toggle="tooltip"
                                 title="Costo de obsequios marcados como adicionales."></i>
                            </label>
                            <input type="text" class="form-control form-control-sm bg-label-secondary" id="gift_additional_amount_preview" value="0" readonly>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </form>
          <div class="modal fade" id="modalEventTimeWindowPicker" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
              <div class="modal-content">
                <div class="modal-header">
                  <div>
                    <h5 class="modal-title mb-0">Franja de llegada</h5>
                    <small class="text-body-secondary">Selecciona una hora de referencia. El sistema arma automáticamente un lapso de 1 hora.</small>
                  </div>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                  <div class="event-window-mode-group justify-content-center mb-3" id="modalEventTimeModeButtons">
                    <button type="button" class="btn btn-sm btn-label-secondary event-window-mode-btn" data-mode="after">Llegamos desde esta hora</button>
                    <button type="button" class="btn btn-sm btn-label-secondary event-window-mode-btn" data-mode="before">Llegamos máximo a esta hora</button>
                  </div>
                  <div class="event-clock-summary text-center mb-4">
                    <div class="small text-body-secondary mb-1">Ventana seleccionada</div>
                    <div class="event-clock-window" id="modalEventTimeWindowPreview">08:00 PM - 09:00 PM</div>
                    <div class="event-clock-ref mt-1">Referencia: <span id="modalEventTimeReferenceLabel">08:00 PM</span> · <span class="badge bg-label-secondary" id="modalEventTimeMeridiem">PM</span></div>
                  </div>
                  <div class="event-clock-face">
                    <div class="event-clock-center">
                      <div class="small text-body-secondary">Selecciona la hora</div>
                      <div class="fw-semibold" id="modalEventTimeCenterLabel">08:00 PM</div>
                    </div>
                    @php
                      $outerClockHours = [
                        ['value' => 0, 'label' => '12', 'sub' => '00'],
                        ['value' => 1, 'label' => '1', 'sub' => '01'],
                        ['value' => 2, 'label' => '2', 'sub' => '02'],
                        ['value' => 3, 'label' => '3', 'sub' => '03'],
                        ['value' => 4, 'label' => '4', 'sub' => '04'],
                        ['value' => 5, 'label' => '5', 'sub' => '05'],
                        ['value' => 6, 'label' => '6', 'sub' => '06'],
                        ['value' => 7, 'label' => '7', 'sub' => '07'],
                        ['value' => 8, 'label' => '8', 'sub' => '08'],
                        ['value' => 9, 'label' => '9', 'sub' => '09'],
                        ['value' => 10, 'label' => '10', 'sub' => '10'],
                        ['value' => 11, 'label' => '11', 'sub' => '11'],
                      ];
                      $innerClockHours = [
                        ['value' => 12, 'label' => '12', 'sub' => '12'],
                        ['value' => 13, 'label' => '1', 'sub' => '13'],
                        ['value' => 14, 'label' => '2', 'sub' => '14'],
                        ['value' => 15, 'label' => '3', 'sub' => '15'],
                        ['value' => 16, 'label' => '4', 'sub' => '16'],
                        ['value' => 17, 'label' => '5', 'sub' => '17'],
                        ['value' => 18, 'label' => '6', 'sub' => '18'],
                        ['value' => 19, 'label' => '7', 'sub' => '19'],
                        ['value' => 20, 'label' => '8', 'sub' => '20'],
                        ['value' => 21, 'label' => '9', 'sub' => '21'],
                        ['value' => 22, 'label' => '10', 'sub' => '22'],
                        ['value' => 23, 'label' => '11', 'sub' => '23'],
                      ];
                    @endphp
                    @foreach ($outerClockHours as $slot => $hour)
                      <button type="button" class="event-clock-hour event-clock-hour-outer js-event-clock-hour" data-hour="{{ $hour['value'] }}" style="--slot: {{ $slot }};">
                        <span>{{ $hour['label'] }}</span>
                        <small>{{ $hour['sub'] }}</small>
                      </button>
                    @endforeach
                    @foreach ($innerClockHours as $slot => $hour)
                      <button type="button" class="event-clock-hour event-clock-hour-inner js-event-clock-hour" data-hour="{{ $hour['value'] }}" style="--slot: {{ $slot }};">
                        <span>{{ $hour['label'] }}</span>
                        <small>{{ $hour['sub'] }}</small>
                      </button>
                    @endforeach
                  </div>
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cerrar</button>
                  <button type="button" class="btn btn-primary" id="btnApplyEventTimeWindow">Usar esta franja</button>
                </div>
              </div>
            </div>
          </div>
          <div id="iaAssistOverlay" class="ia-assist-overlay d-none">
            <div class="card mb-0 w-100" style="max-width: 760px;">
              <div class="card-header d-flex justify-content-between align-items-center">
                <div>
                  <h5 class="mb-0">Autocompletar con IA (beta)</h5>
                  <small class="text-body-secondary">Pega mensaje de WhatsApp o formulario libre y extraemos campos básicos.</small>
                </div>
                <button type="button" class="btn-close" id="btnCloseIaAssistOverlay" aria-label="Close"></button>
              </div>
              <div class="card-body">
                <div class="mb-4">
                  <textarea id="ia_raw_text" class="form-control" rows="8" placeholder="Nombre Angely Martínez..."></textarea>
                </div>
                <div class="d-flex justify-content-end gap-2">
                  <button type="button" class="btn btn-label-secondary" id="btnCancelIaAssistOverlay">Cancelar</button>
                  <button type="button" class="btn btn-primary" id="btnApplyIaParse">Aplicar al formulario</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
@endsection
