@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',
    };
  };
  $serviceStatusLabel = $normalizeServiceStatus($serenata->service_status);
  $paymentBadge = match ((string) $serenata->payment_status) {
    'Pagado' => 'bg-label-success',
    'Abono parcial' => 'bg-label-info',
    'Cancelada sin cobro' => 'bg-label-danger',
    default => 'bg-label-warning',
  };
  $serviceBadge = match($serviceStatusLabel) {
    'Realizada' => 'bg-label-success',
    'Confirmada' => 'bg-label-success',
    'Pendiente' => 'bg-label-warning',
    'Cancelada' => 'bg-label-danger',
    default => 'bg-label-info',
  };
  $isEmbedded = $embedded ?? false;
  $effectiveCommission = (float) $serenata->commission_amount;
  if ($effectiveCommission <= 0) {
    $effectiveCommission = max(0, (float) $serenata->profit_amount);
  }
  $effectiveProfit = (float) $serenata->profit_amount;
  $formatCop = fn ($value) => '$' . number_format((float) $value, 0, ',', '.');
  $plannedPrefix = '[PLAN]';
  $actualCustomerCharge = $serenata->actual_customer_charge !== null
    ? (float) $serenata->actual_customer_charge
    : null;
  $effectiveCustomerCharge = $actualCustomerCharge ?? (float) $serenata->total_charged;
  $paymentRows = collect($payments ?? [])->map(function ($payment) use ($plannedPrefix) {
    $note = trim((string) ($payment->note ?? ''));
    $isRefund = str_contains($note, '[REFUND]');
    $isPlannedPayment = !$isRefund && str_starts_with($note, $plannedPrefix);

    return [
      'model' => $payment,
      'is_refund' => $isRefund,
      'is_planned' => $isPlannedPayment,
      'is_applied' => !$isRefund && !$isPlannedPayment,
    ];
  })->values();
  $totalPaid = (float) collect($payments ?? [])->filter(function ($payment) use ($plannedPrefix) {
    $note = trim((string) ($payment->note ?? ''));
    $isRefund = str_contains($note, '[REFUND]');
    return $note === '' || !str_starts_with($note, $plannedPrefix) || $isRefund;
  })->sum('amount');
  $appliedPaymentsCount = $paymentRows->where('is_applied', true)->count();
  $refundPaymentsCount = $paymentRows->where('is_refund', true)->count();
  $plannedPaymentsCount = $paymentRows->where('is_planned', true)->count();
  $pendingAmount = max(0, $effectiveCustomerCharge - $totalPaid);
  $paymentDiff = round($totalPaid - $effectiveCustomerCharge, 2);
  $hasPaymentMismatch = abs($paymentDiff) >= 1;
  $cededOverview = $cededOverview ?? [
    'status' => 'equilibrado',
    'label' => 'Sin excedente',
    'amount' => 0,
    'signed_amount' => 0,
  ];
  $externalPartnerMovements = collect($externalPartnerMovements ?? []);
  $externalMovementCount = $externalPartnerMovements->count();
  $externalPartnerBalanceSummary = $externalPartnerBalanceSummary ?? [];
  $externalPartnerMovementTypeOptions = $externalPartnerMovementTypeOptions ?? [];
  $externalPartnerMovementDirectionOptions = $externalPartnerMovementDirectionOptions ?? [];
  $externalPartnerMovementSettlementOptions = $externalPartnerMovementSettlementOptions ?? [];
  $externalPartnerNameLookup = collect($externalPartnerOptions ?? [])
    ->mapWithKeys(fn ($item) => [(int) ($item['id'] ?? 0) => (string) ($item['name'] ?? '')])
    ->merge(
      $externalPartnerMovements->mapWithKeys(function ($movement) {
        $partnerId = (int) ($movement->external_partner_id ?? 0);
        if ($partnerId <= 0) {
          return [];
        }

        return [
          $partnerId => (string) ($movement->externalPartner->name ?? ('Externo #' . $partnerId)),
        ];
      })
    )
    ->all();
  $savedCededBreakdown = collect(old('ceded_cost_breakdown')
    ? (json_decode((string) old('ceded_cost_breakdown'), true) ?: [])
    : ($serenata->ceded_cost_breakdown ?? []));
  $savedCededBreakdownLookup = $savedCededBreakdown
    ->filter(fn ($item) => is_array($item))
    ->mapWithKeys(function ($item) {
      $source = (string) ($item['source'] ?? '');
      $index = array_key_exists('index', $item) ? (string) $item['index'] : 'x';
      if ($source === '') {
        return [];
      }

      return [$source . ':' . $index => $item];
    });
  $giftItems = collect($serenata->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, ',', '.') . ')';
  };
  $activeLineItems = collect($lineItems ?? [])->filter(fn ($item) => empty($item['is_deleted']))->values();
  $deletedLineItemsCount = collect($lineItems ?? [])->filter(fn ($item) => !empty($item['is_deleted']))->count();
  $costCategorySummary = collect([
    [
      'key' => 'artist',
      'label' => 'Artistas',
      'icon' => 'tabler-music',
      'tone' => 'primary',
      'items' => $activeLineItems->where('source', 'artist'),
    ],
    [
      'key' => 'gift',
      'label' => 'Obsequios',
      'icon' => 'tabler-gift',
      'tone' => 'warning',
      'items' => $activeLineItems->where('source', 'gift'),
    ],
    [
      'key' => 'other_cost',
      'label' => 'Otros costos',
      'icon' => 'tabler-tool',
      'tone' => 'info',
      'items' => $activeLineItems->where('source', 'other_cost'),
    ],
  ])->map(function ($group) {
    $items = collect($group['items'] ?? []);

    return [
      'key' => $group['key'],
      'label' => $group['label'],
      'icon' => $group['icon'],
      'tone' => $group['tone'],
      'count' => $items->count(),
      'total' => (float) $items->sum(fn ($item) => (float) ($item['total'] ?? 0)),
    ];
  })->values();
  $includedText = $giftIncluded->isNotEmpty()
    ? $giftIncluded->map($formatGiftLine)->implode(', ')
    : 'Ninguno';
  $additionalText = $giftAdditional->isNotEmpty()
    ? $giftAdditional->map($formatGiftLine)->implode(', ')
    : 'Ninguno';
  $shareLines = [
    "SERVICIO {$serenata->code}",
    'Grupo: ' . ($serenata->mariachiGroup?->name ?: 'Sin grupo'),
    "Cliente: {$serenata->payer_name}",
    'Correo: ' . ($serenata->payer_email ?: '-'),
    "Teléfono 1: {$serenata->formatted_contact_phone_1}",
    'Teléfono 2: ' . ($serenata->formatted_contact_phone_2 ?: '-'),
    "Dirección: {$serenata->service_address}",
    'País: ' . ($serenata->service_country ?: 'Colombia'),
    'Departamento: ' . ($serenata->service_department ?: '-'),
    "Ciudad/Municipio: {$serenata->locality}",
    'Localidad: ' . ($serenata->service_locality ?: '-'),
    'Sector/UPZ: ' . ($serenata->service_sector ?: '-'),
    "Barrio: {$serenata->neighborhood}",
    'Fecha: ' . optional($serenata->event_date)->format('d/m/Y'),
    'Horario estimado: ' . $serenata->eventWindowLabel(),
    "De parte de: {$serenata->from_name}",
    "Para quién: {$serenata->to_name}",
    'Motivo: ' . ($serenata->reason ?: '-'),
    "Obsequios incluidos: {$includedText}",
    "Obsequios adicionales: {$additionalText}",
    'Precio total: $' . number_format((float) ($serenata->total_charged ?? 0), 0, ',', '.'),
  ];
  if (!empty($serenata->address_additional)) {
    $shareLines[] = "Dirección adicional: {$serenata->address_additional}";
  }
  if (!empty($serenata->service_private_note)) {
    $shareLines[] = "Nota para el servicio: {$serenata->service_private_note}";
  }
  $serenataShareText = implode("\n", $shareLines);
  $phoneDigits = $serenata->contact_phone_1_whatsapp_digits;
  $confirmMessage = implode("\n", [
    "Hola {$serenata->payer_name}, te habla Camila Serenatas.",
    'Queremos reconfirmar tu servicio:',
    'Fecha: ' . optional($serenata->event_date)->format('d/m/Y'),
    'Horario estimado: ' . $serenata->eventWindowLabel(),
    "Dirección: {$serenata->service_address}",
    'Localidad: ' . ($serenata->service_locality ?: '-'),
    'Sector: ' . ($serenata->service_sector ?: '-'),
    "Barrio: {$serenata->neighborhood}",
    "Ciudad/Municipio: {$serenata->locality}",
    '',
    '¿Todo sigue en pie? Muchas gracias.'
  ]);
  $waConfirmUrl = $phoneDigits !== ''
    ? 'https://wa.me/' . $phoneDigits . '?text=' . rawurlencode($confirmMessage)
    : null;
  $googleMapsQuery = implode(', ', array_filter([
    trim((string) ($serenata->service_address ?? '')),
    trim((string) ($serenata->address_additional ?? '')),
    trim((string) ($serenata->service_sector ?? '')),
    trim((string) ($serenata->service_locality ?? '')),
    trim((string) ($serenata->neighborhood ?? '')),
    trim((string) ($serenata->service_department ?? '')),
    trim((string) ($serenata->locality ?? '')),
    trim((string) ($serenata->service_country ?? 'Colombia')),
  ]));
  $googleMapsFallbackUrl = $googleMapsQuery !== ''
    ? 'https://www.google.com/maps/search/?api=1&query=' . rawurlencode($googleMapsQuery)
    : null;
  $googleMapsAddressUrl = !empty($googleMapsAddressUrl ?? '')
    ? $googleMapsAddressUrl
    : $googleMapsFallbackUrl;
  $addressShareText = $googleMapsAddressUrl ?: trim((string) ($serenata->service_address ?? ''));
  $currentExternalPartnerName = $serenata->externalPartner?->name ?: 'Sin externo asignado';
  $cededOverviewStatus = (string) ($cededOverview['status'] ?? 'equilibrado');
  $cededOverviewBadge = match ($cededOverviewStatus) {
    'por_cobrar' => 'bg-label-success',
    'yo_debo' => 'bg-label-warning',
    default => 'bg-label-secondary',
  };
  $eventDateHeadline = '-';
  if ($serenata->event_date) {
    $eventDateValue = $serenata->event_date->copy();
    $eventDateLabel = mb_strtoupper($eventDateValue->locale('es')->translatedFormat('d F'), 'UTF-8');
    $eventTimeLabel = $serenata->eventWindowLabel();

    if ((int) $eventDateValue->year !== (int) now()->year) {
      $eventDateLabel .= ' ' . $eventDateValue->format('Y');
    }

    $eventDateHeadline = trim($eventDateLabel . ($eventTimeLabel !== '' ? (((int) $eventDateValue->year !== (int) now()->year ? ' | ' : ' ') . $eventTimeLabel) : ''));
  }
  $cededBreakdownItems = collect($lineItems ?? [])
    ->filter(fn ($item) => empty($item['is_deleted']))
    ->values()
    ->map(function ($item) use ($savedCededBreakdownLookup) {
      $lookupKey = (string) ($item['source'] ?? '') . ':' . (string) ($item['index'] ?? '0');
      $saved = $savedCededBreakdownLookup->get($lookupKey, []);
      $quantity = max(1, (int) ($saved['quantity'] ?? $item['quantity'] ?? 1));
      $unitPrice = (float) ($saved['unit_price'] ?? $item['unit_price'] ?? 0);
      $included = array_key_exists('included', $saved) ? (bool) $saved['included'] : true;

      return [
        'source' => (string) ($item['source'] ?? ''),
        'index' => (int) ($item['index'] ?? 0),
        'name' => (string) ($saved['name'] ?? $item['name'] ?? 'Ítem'),
        'category' => (string) ($item['category'] ?? ''),
        'quantity' => $quantity,
        'unit_price' => $unitPrice,
        'included' => $included,
        'total' => $included ? ($quantity * $unitPrice) : 0,
      ];
    })
    ->values();
  $savedTransportItem = $savedCededBreakdown->first(fn ($item) => is_array($item) && (($item['source'] ?? '') === 'transport'));
  $cededTransportInitial = (float) old('ceded_transport_amount', $savedTransportItem['unit_price'] ?? $serenata->ceded_transport_amount);
  $cededBreakdownJson = $cededBreakdownItems
    ->push([
      'source' => 'transport',
      'index' => 0,
      'name' => 'Transporte manual',
      'category' => 'Transporte',
      'quantity' => 1,
      'unit_price' => $cededTransportInitial,
      'included' => $cededTransportInitial > 0,
      'total' => $cededTransportInitial > 0 ? $cededTransportInitial : 0,
    ])
    ->values()
    ->toJson(JSON_UNESCAPED_UNICODE);
@endphp

<textarea id="copy_serenata_detail_{{ $serenata->id }}" class="d-none">{{ $serenataShareText }}</textarea>
<textarea id="copy_serenata_address_{{ $serenata->id }}" class="d-none">{{ $addressShareText }}</textarea>

<div class="serenata-hero mb-6">
  <div class="serenata-hero__content">
    <div class="serenata-hero__summary">
      <span class="serenata-hero__eyebrow">Detalle de serenata</span>
      <div class="d-flex flex-wrap align-items-center gap-3">
        <h2 class="serenata-hero__title mb-0">Serenata {{ $serenata->code }}</h2>
        @if($serenata->mariachiGroup)
          <span class="serenata-hero__group">{{ $serenata->mariachiGroup->name }}</span>
        @endif
      </div>

      <div class="serenata-hero__chips">
        <span class="badge {{ $paymentBadge }}">{{ $serenata->payment_status }}</span>
        <span class="badge {{ $serviceBadge }}">{{ $serviceStatusLabel }}</span>
        @if($serenata->is_ceded)
          <span class="badge bg-label-info">Cedida</span>
          @if(($cededOverview['status'] ?? 'equilibrado') !== 'equilibrado')
            <span class="badge {{ $cededOverview['status'] === 'por_cobrar' ? 'bg-label-success' : 'bg-label-warning' }}">
              {{ $cededOverview['label'] }}: ${{ number_format((float) ($cededOverview['amount'] ?? 0), 0, ',', '.') }}
            </span>
          @endif
        @endif
      </div>

      <div class="serenata-hero__meta">
        <div class="serenata-hero__meta-item">
          <span class="serenata-hero__meta-icon">
            <i class="icon-base ti tabler-calendar-event"></i>
          </span>
          <div>
            <span class="serenata-hero__meta-label">Evento</span>
            <strong>{{ $eventDateHeadline }}</strong>
          </div>
        </div>
        <div class="serenata-hero__meta-item">
          <span class="serenata-hero__meta-icon">
            <i class="icon-base ti tabler-clock-hour-4"></i>
          </span>
          <div>
            <span class="serenata-hero__meta-label">Creado</span>
            <strong>{{ $serenata->created_at?->format('d/m/Y H:i') }}</strong>
          </div>
        </div>
      </div>

      @if($serviceStatusLabel === 'Cancelada')
        <button
          type="button"
          class="serenata-cancel-note"
          data-bs-toggle="modal"
          data-bs-target="#modalQuickCancelReason"
          data-cancel-edit="1"
          title="{{ $serenata->cancellation_reason ? 'Editar motivo de cancelación' : 'Añadir motivo de cancelación' }}">
          <span class="serenata-cancel-note__icon">
            <i class="icon-base ti {{ $serenata->cancellation_reason ? 'tabler-pencil-heart' : 'tabler-message-circle-plus' }}"></i>
          </span>
          <span class="serenata-cancel-note__content">
            <span class="serenata-cancel-note__label">Motivo de cancelación</span>
            <span class="serenata-cancel-note__text">{{ $serenata->cancellation_reason ?: 'Añadir motivo' }}</span>
          </span>
          <span class="serenata-cancel-note__action">
            <i class="icon-base ti tabler-chevron-right"></i>
          </span>
        </button>
      @endif
    </div>

    <div class="serenata-hero__side">
      <div class="serenata-hero__actions">
        <button
          type="button"
          class="btn btn-label-primary btn-sm btn-copy-serenata"
          data-copy-target="copy_serenata_detail_{{ $serenata->id }}">
          <i class="icon-base ti tabler-copy me-1"></i>Copiar WhatsApp
        </button>
        @if($waConfirmUrl)
          <a
            href="{{ $waConfirmUrl }}"
            target="_blank"
            rel="noopener noreferrer"
            class="btn btn-label-success btn-sm">
            <i class="icon-base ti tabler-brand-whatsapp me-1"></i>Reconfirmar
          </a>
        @else
          <button type="button" class="btn btn-label-secondary btn-sm" disabled>
            <i class="icon-base ti tabler-brand-whatsapp me-1"></i>Sin teléfono
          </button>
        @endif
        <button type="button" class="btn btn-label-danger btn-sm" data-bs-toggle="modal" data-bs-target="#modalRefundPayment">
          Reembolso parcial
        </button>
        @unless($isEmbedded)
          <a href="{{ route('owner.serenatas.index') }}" class="btn btn-label-secondary btn-sm">Volver</a>
        @endunless
      </div>

      <div class="serenata-hero__status-panel">
        <div>
          <span class="serenata-hero__status-label">Estado del servicio</span>
          <p class="serenata-hero__status-help mb-0">Actualiza aquí el seguimiento operativo de la serenata.</p>
        </div>
        <form
          id="quickStatusForm"
          method="POST"
          action="{{ route('owner.serenatas.update-status', $serenata) }}"
          class="serenata-hero__status-form"
          data-current-status="{{ $serviceStatusLabel }}">
          @csrf
          @method('PATCH')
          <select class="form-select form-select-sm" id="quick_service_status" name="service_status">
            @foreach ($serviceStatusOptions as $status)
              <option value="{{ $status }}" @selected($serviceStatusLabel === $status)>{{ $status }}</option>
            @endforeach
          </select>
          <input
            type="hidden"
            id="quick_cancellation_reason"
            name="cancellation_reason"
            value="{{ old('cancellation_reason', $serviceStatusLabel === 'Cancelada' ? $serenata->cancellation_reason : '') }}">
          <button type="submit" class="btn btn-primary btn-sm">Guardar estado</button>
        </form>
      </div>
    </div>
  </div>
</div>

@if (session('status'))
  <div class="alert alert-success mb-6">{{ session('status') }}</div>
@endif

@if ($errors->any())
  <div class="alert alert-danger mb-6">
    <ul class="mb-0 ps-3">
      @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
      @endforeach
    </ul>
  </div>
@endif

@if($hasPaymentMismatch)
  <div class="alert alert-warning mb-6">
    <div class="d-flex align-items-center gap-2 flex-wrap">
      <i class="icon-base ti tabler-alert-triangle"></i>
      <strong>Advertencia:</strong>
      <span>registrado ${{ number_format($totalPaid, 0, ',', '.') }} frente a un cobro real esperado de ${{ number_format($effectiveCustomerCharge, 0, ',', '.') }}.</span>
      @if($paymentDiff > 0)
        <span class="badge bg-label-danger">Excedente: ${{ number_format($paymentDiff, 0, ',', '.') }}</span>
      @else
        <span class="badge bg-label-warning">Pendiente: ${{ number_format(abs($paymentDiff), 0, ',', '.') }}</span>
      @endif
    </div>
  </div>
@endif

<div class="nav-align-top mb-4">
  <ul class="nav nav-pills flex-row gap-2" role="tablist">
    <li class="nav-item" role="presentation">
      <button class="nav-link active js-serenata-main-tab" data-main-target="serenata-detalles-tab" type="button" role="tab">
        <i class="icon-base ti tabler-list-details me-1"></i> Detalles
      </button>
    </li>
    <li class="nav-item" role="presentation">
      <button class="nav-link js-serenata-main-tab" data-main-target="serenata-pago-tab" type="button" role="tab">
        <i class="icon-base ti tabler-cash me-1"></i> Pago
      </button>
    </li>
    <li class="nav-item" role="presentation">
      <button class="nav-link js-serenata-main-tab" data-main-target="serenata-cedida-tab" type="button" role="tab">
        <i class="icon-base ti tabler-arrows-right-left me-1"></i> Cedida y cambios
      </button>
    </li>
    <li class="nav-item" role="presentation">
      <button class="nav-link js-serenata-main-tab" data-main-target="serenata-actividad-tab" type="button" role="tab">
        <i class="icon-base ti tabler-activity me-1"></i> Actividad y logs
      </button>
    </li>
  </ul>
</div>

<div class="tab-content p-0">
  <div class="tab-pane show active serenata-main-pane" id="serenata-detalles-tab" role="tabpanel">
<div class="row g-4 mb-6">
  <div class="col-6 col-xl-3">
    <div class="serenata-stat-card">
      <span class="serenata-stat-card__label">Precio pactado</span>
      <strong class="serenata-stat-card__value">{{ $formatCop($serenata->total_charged) }}</strong>
      <span class="serenata-stat-card__hint">Valor cotizado al cliente</span>
    </div>
  </div>
  <div class="col-6 col-xl-3">
    <div class="serenata-stat-card">
      <span class="serenata-stat-card__label">Cobro real</span>
      <strong class="serenata-stat-card__value">{{ $formatCop($effectiveCustomerCharge) }}</strong>
      <span class="serenata-stat-card__hint">Base actual del ingreso</span>
    </div>
  </div>
  <div class="col-6 col-xl-3">
    <div class="serenata-stat-card">
      <span class="serenata-stat-card__label">Me costó</span>
      <strong class="serenata-stat-card__value">{{ $formatCop($serenata->base_cost) }}</strong>
      <span class="serenata-stat-card__hint">Costo interno del servicio</span>
    </div>
  </div>
  <div class="col-6 col-xl-3">
    <div class="serenata-stat-card {{ $effectiveProfit < 0 ? 'is-negative' : 'is-positive' }}">
      <span class="serenata-stat-card__label">Me quedó</span>
      <strong class="serenata-stat-card__value">
        {{ $effectiveProfit < 0 ? '- ' : '' }}{{ $formatCop(abs($effectiveProfit)) }}
      </strong>
      <span class="serenata-stat-card__hint">
        {{ $effectiveProfit < 0 ? 'El servicio quedó por debajo del costo' : 'Margen actual de la serenata' }}
      </span>
    </div>
  </div>
</div>

<div class="row g-6">
  <div class="col-12 col-lg-4 order-1 order-lg-0">
    <div class="card mb-6">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">Información de la serenata</h5>
        <button
          type="button"
          class="btn btn-sm btn-icon btn-text-secondary"
          data-bs-toggle="modal"
          data-bs-target="#modalEditSerenataInfo"
          title="Editar información de la serenata">
          <i class="icon-base ti tabler-pencil icon-18px"></i>
        </button>
      </div>
      <div class="card-body">
        <div class="serenata-info-grid">
          <div class="serenata-info-grid__item">
            <span class="serenata-info-grid__label">Fecha y hora</span>
            <strong class="serenata-info-grid__value">{{ $eventDateHeadline }}</strong>
          </div>
          <div class="serenata-info-grid__item">
            <span class="serenata-info-grid__label">Estado</span>
            <span class="badge {{ $serviceBadge }}">{{ $serviceStatusLabel }}</span>
          </div>
          <div class="serenata-info-grid__item">
            <span class="serenata-info-grid__label">Grupo</span>
            <strong class="serenata-info-grid__value">{{ $serenata->mariachiGroup?->name ?: 'Sin grupo' }}</strong>
          </div>
          <div class="serenata-info-grid__item">
            <span class="serenata-info-grid__label">De parte de</span>
            <strong class="serenata-info-grid__value">{{ $serenata->from_name }}</strong>
          </div>
          <div class="serenata-info-grid__item">
            <span class="serenata-info-grid__label">Para quién</span>
            <strong class="serenata-info-grid__value">{{ $serenata->to_name }}</strong>
          </div>
          <div class="serenata-info-grid__item serenata-info-grid__item--full">
            <span class="serenata-info-grid__label">Motivo</span>
            <strong class="serenata-info-grid__value">{{ $serenata->reason ?: '-' }}</strong>
          </div>
        </div>
      </div>
    </div>

    <div class="card mb-6">
      <div class="card-header">
        <h5 class="card-title mb-0">Cliente</h5>
      </div>
      <div class="card-body">
        <div class="serenata-customer-hero mb-3">
          <div class="d-flex align-items-center gap-3 min-w-0">
            <div class="avatar avatar-lg">
              <span class="avatar-initial rounded-circle bg-label-primary">{{ strtoupper(mb_substr($serenata->payer_name, 0, 1)) }}</span>
            </div>
            <div class="min-w-0">
              <h6 class="mb-1">{{ $serenata->payer_name }}</h6>
              <div class="d-flex flex-wrap gap-2">
                <span class="serenata-mini-chip">Código {{ $serenata->code }}</span>
                <span class="serenata-mini-chip">Servicio para {{ $serenata->to_name }}</span>
              </div>
            </div>
          </div>
          <div class="serenata-customer-actions">
            @if(!empty($serenata->customer_id))
              <a href="{{ route('owner.clients.show', $serenata->customer_id) }}" class="btn btn-label-primary btn-sm" target="_blank" rel="noopener noreferrer">
                <i class="icon-base ti tabler-user me-1"></i>Ver ficha
              </a>
            @endif
            @if(!empty($serenata->formatted_contact_phone_1))
              <span class="serenata-customer-actions__hint">
                <i class="icon-base ti tabler-phone-call me-1"></i>{{ $serenata->formatted_contact_phone_1 }}
              </span>
            @endif
          </div>
        </div>

        <div class="serenata-contact-grid mb-3">
          <div class="serenata-contact-card">
            <span class="serenata-contact-card__label">Contacto principal</span>
            <strong class="serenata-contact-card__value">{{ $serenata->formatted_contact_phone_1 }}</strong>
            <span class="serenata-contact-card__meta">Principal</span>
          </div>
          <div class="serenata-contact-card">
            <span class="serenata-contact-card__label">Contacto alterno</span>
            <strong class="serenata-contact-card__value">{{ $serenata->formatted_contact_phone_2 ?: '-' }}</strong>
            <span class="serenata-contact-card__meta">Respaldo</span>
          </div>
          <div class="serenata-contact-card serenata-contact-card--wide">
            <span class="serenata-contact-card__label">Correo</span>
            <strong class="serenata-contact-card__value">{{ $serenata->payer_email ?: '-' }}</strong>
            <span class="serenata-contact-card__meta">Seguimiento</span>
          </div>
        </div>

        <div class="serenata-soft-panel">
          <button
            class="btn btn-sm btn-label-secondary w-100 d-flex align-items-center justify-content-between"
            type="button"
            data-bs-toggle="collapse"
            data-bs-target="#servicePrivateNoteCollapse"
            aria-expanded="{{ $errors->has('service_private_note') || old('service_private_note') !== null ? 'true' : 'false' }}"
            aria-controls="servicePrivateNoteCollapse">
            <span>Nota Privada para el cliente</span>
            <i id="servicePrivateNoteToggleIcon" class="icon-base ti {{ $errors->has('service_private_note') || old('service_private_note') !== null ? 'tabler-minus' : 'tabler-plus' }} icon-18px"></i>
          </button>

          <div class="collapse mt-4 {{ $errors->has('service_private_note') || old('service_private_note') !== null ? 'show' : '' }}" id="servicePrivateNoteCollapse">
            <form method="POST" action="{{ route('owner.serenatas.update-service-note', $serenata) }}">
              @csrf
              @method('PATCH')
              <textarea
                class="form-control mb-3"
                name="service_private_note"
                rows="3"
                maxlength="1200"
                placeholder="Añade una nota privada sobre este cliente/servicio.">{{ old('service_private_note', $serenata->service_private_note) }}</textarea>
              <div class="d-flex justify-content-end">
                <button type="submit" class="btn btn-primary btn-sm">Guardar</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <div class="card mb-6">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">Dirección</h5>
        <div class="d-flex align-items-center gap-2">
          <button
            type="button"
            class="btn btn-sm btn-label-secondary btn-copy-address-share"
            data-copy-target="copy_serenata_address_{{ $serenata->id }}">
            <i class="icon-base ti tabler-copy me-1"></i>Copiar ubicación
          </button>
          <div class="dropdown">
            <button class="btn btn-sm btn-icon btn-text-secondary" type="button" data-bs-toggle="dropdown" aria-expanded="false">
              <i class="icon-base ti tabler-dots-vertical icon-18px"></i>
            </button>
            <ul class="dropdown-menu dropdown-menu-end">
              <li>
                <button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#modalEditServiceAddress">
                  <i class="icon-base ti tabler-edit me-2"></i>Editar dirección existente
                </button>
              </li>
              <li>
                <button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#modalSelectServiceAddress">
                  <i class="icon-base ti tabler-map-pin me-2"></i>Seleccionar otra dirección
                </button>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div class="card-body">
        <div class="serenata-address-hero mb-3">
          <div>
            <span class="serenata-address-hero__label">Ubicación principal</span>
            @if($googleMapsAddressUrl)
              <a
                href="{{ $googleMapsAddressUrl }}"
                target="_blank"
                rel="noopener noreferrer"
                class="serenata-address-hero__link">
                {{ $serenata->service_address }}
              </a>
            @else
              <span class="serenata-address-hero__link">{{ $serenata->service_address }}</span>
            @endif
          </div>
          <div class="serenata-address-hero__actions">
            <span class="serenata-mini-chip">Barrio {{ $serenata->neighborhood }}</span>
            <span class="serenata-mini-chip">{{ $serenata->locality }}</span>
          </div>
        </div>

        <div class="serenata-address-grid">
          <div class="serenata-address-grid__item">
            <span class="serenata-info-grid__label">País</span>
            <strong class="serenata-info-grid__value">{{ $serenata->service_country ?: 'Colombia' }}</strong>
          </div>
          <div class="serenata-address-grid__item">
            <span class="serenata-info-grid__label">Departamento</span>
            <strong class="serenata-info-grid__value">{{ $serenata->service_department ?: '-' }}</strong>
          </div>
          <div class="serenata-address-grid__item">
            <span class="serenata-info-grid__label">Ciudad/Municipio</span>
            <strong class="serenata-info-grid__value">{{ $serenata->locality }}</strong>
          </div>
          @if(!empty($serenata->service_locality))
            <div class="serenata-address-grid__item">
              <span class="serenata-info-grid__label">Localidad</span>
              <strong class="serenata-info-grid__value">{{ $serenata->service_locality }}</strong>
            </div>
          @endif
          @if(!empty($serenata->service_sector))
            <div class="serenata-address-grid__item">
              <span class="serenata-info-grid__label">Sector / UPZ</span>
              <strong class="serenata-info-grid__value">{{ $serenata->service_sector }}</strong>
            </div>
          @endif
          <div class="serenata-address-grid__item">
            <span class="serenata-info-grid__label">Barrio</span>
            <strong class="serenata-info-grid__value">{{ $serenata->neighborhood }}</strong>
          </div>
          @if(!empty($serenata->address_additional))
            <div class="serenata-address-grid__item serenata-address-grid__item--full">
              <span class="serenata-info-grid__label">Adicional</span>
              <strong class="serenata-info-grid__value">{{ $serenata->address_additional }}</strong>
            </div>
          @endif
        </div>
      </div>
    </div>

    <div class="card mb-6">
      <div class="card-header">
        <h5 class="card-title mb-0">Nota Interna</h5>
      </div>
      <div class="card-body">
        <button
          class="btn btn-sm btn-label-secondary w-100 d-flex align-items-center justify-content-between"
          type="button"
          data-bs-toggle="collapse"
          data-bs-target="#internalNoteCollapse"
          aria-expanded="{{ $errors->has('internal_notes') || old('internal_notes') !== null ? 'true' : 'false' }}"
          aria-controls="internalNoteCollapse">
          <span>Nota Interna</span>
          <i id="internalNoteToggleIcon" class="icon-base ti {{ $errors->has('internal_notes') || old('internal_notes') !== null ? 'tabler-minus' : 'tabler-plus' }} icon-18px"></i>
        </button>

        <div class="collapse mt-4 {{ $errors->has('internal_notes') || old('internal_notes') !== null ? 'show' : '' }}" id="internalNoteCollapse">
          <div class="border-top pt-3">
            <form method="POST" action="{{ route('owner.serenatas.update-notes', $serenata) }}">
              @csrf
              @method('PATCH')
              <div class="mb-3">
                <textarea
                  id="notes_internal"
                  class="form-control"
                  name="internal_notes"
                  rows="4"
                  maxlength="1200"
                  placeholder="Sin nota interna.">{{ old('internal_notes', $serenata->internal_notes) }}</textarea>
              </div>
              <div class="d-flex justify-content-end">
                <button type="submit" class="btn btn-primary btn-sm">Guardar</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12 col-lg-8 order-0 order-lg-1">
    <div class="card mb-6">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title m-0">Detalle de costos</h5>
        <div class="d-flex align-items-center gap-2">
          <button type="button" class="btn btn-sm btn-icon btn-label-secondary" id="btnToggleCostActions" title="Editar detalle de costos">
            <i class="icon-base ti tabler-pencil icon-18px"></i>
          </button>
          <button type="button" class="btn btn-sm btn-icon btn-label-primary d-none" id="btnToggleCostEditor" data-bs-toggle="collapse" data-bs-target="#costEditorCollapse" aria-expanded="false" aria-controls="costEditorCollapse" title="Agregar ítem">
            <i class="icon-base ti tabler-shopping-cart-plus icon-18px"></i>
          </button>
        </div>
      </div>
      <div class="card-body pt-0">
        <div class="serenata-cost-overview">
          @foreach($costCategorySummary as $group)
            <div class="serenata-cost-overview__card serenata-cost-overview__card--{{ $group['tone'] }}">
              <span class="serenata-cost-overview__icon">
                <i class="icon-base ti {{ $group['icon'] }}"></i>
              </span>
              <div class="serenata-cost-overview__content">
                <span class="serenata-cost-overview__label">{{ $group['label'] }}</span>
                <strong class="serenata-cost-overview__value">{{ $formatCop($group['total']) }}</strong>
                <span class="serenata-cost-overview__meta">{{ $group['count'] }} {{ \Illuminate\Support\Str::plural('ítem', $group['count']) }}</span>
              </div>
            </div>
          @endforeach
          <div class="serenata-cost-overview__card serenata-cost-overview__card--dark">
            <span class="serenata-cost-overview__icon">
              <i class="icon-base ti tabler-receipt-2"></i>
            </span>
            <div class="serenata-cost-overview__content">
              <span class="serenata-cost-overview__label">Total activo</span>
              <strong class="serenata-cost-overview__value">{{ $formatCop($serenata->base_cost) }}</strong>
              <span class="serenata-cost-overview__meta">{{ $activeLineItems->count() }} {{ \Illuminate\Support\Str::plural('ítem', $activeLineItems->count()) }}</span>
            </div>
          </div>
        </div>
        @if($deletedLineItemsCount > 0)
          <div class="serenata-cost-inline-note">
            <i class="icon-base ti tabler-history-toggle"></i>
            <span>{{ $deletedLineItemsCount }} {{ \Illuminate\Support\Str::plural('ítem eliminado', $deletedLineItemsCount) }} aún visible en la tabla para trazabilidad.</span>
          </div>
        @endif
      </div>
      <div class="serenata-cost-table-wrap table-responsive">
        <table class="table serenata-cost-table mb-0 w-100">
          <thead>
            <tr>
              <th>Categoría</th>
              <th>Ítem</th>
              <th>Precio</th>
              <th>Cant.</th>
              <th>Total</th>
              <th class="text-end cost-actions-col d-none">Acciones</th>
            </tr>
          </thead>
          <tbody
            id="costItemsTableBody"
            data-remove-url="{{ route('owner.serenatas.remove-cost-item', $serenata) }}"
            data-restore-url="{{ route('owner.serenatas.restore-cost-item', $serenata) }}"
            data-update-url="{{ route('owner.serenatas.update-cost-item', $serenata) }}">
            @forelse($lineItems as $item)
              <tr
                class="{{ !empty($item['is_deleted']) ? 'table-secondary text-body-secondary' : '' }}"
                data-source="{{ $item['source'] }}"
                data-index="{{ $item['index'] }}"
                data-category="{{ $item['category'] }}"
                data-name="{{ $item['name'] }}"
                data-unit-price="{{ number_format((float) $item['unit_price'], 2, '.', '') }}"
                data-quantity="{{ $item['quantity'] }}"
                data-total="{{ number_format((float) $item['total'], 2, '.', '') }}">
                <td class="cost-col-category">
                  <span class="serenata-table-chip serenata-table-chip--{{ $item['source'] }}">
                    {{ $item['category'] }}
                  </span>
                </td>
                <td class="cost-col-item">
                  @if(!empty($item['is_deleted']))
                    <span class="text-decoration-line-through">{{ $item['name'] }}</span>
                    <span class="badge bg-label-secondary ms-1">Eliminado</span>
                    @if(!empty($item['delete_reason']))
                      <div class="small mt-1">Motivo: {{ $item['delete_reason'] }}</div>
                    @endif
                  @else
                    {{ $item['name'] }}
                  @endif
                </td>
                <td class="cost-col-unit-price">${{ number_format((float) $item['unit_price'], 0, ',', '.') }}</td>
                <td class="cost-col-quantity">{{ $item['quantity'] }}</td>
                <td class="cost-col-total">
                  <strong>${{ number_format((float) $item['total'], 0, ',', '.') }}</strong>
                </td>
                <td class="text-end cost-actions-col d-none">
                  @if(empty($item['is_deleted']))
                    <button
                      type="button"
                      class="btn btn-sm btn-icon btn-text-secondary me-1 btn-inline-save-cost-item"
                      data-source="{{ $item['source'] }}"
                      data-index="{{ $item['index'] }}"
                      data-name="{{ $item['name'] }}"
                      data-quantity="{{ $item['quantity'] }}"
                      data-unit-price="{{ number_format((float) $item['unit_price'], 2, '.', '') }}"
                      title="Guardar cambios">
                      <i class="icon-base ti tabler-pencil icon-18px"></i>
                    </button>
                    <form method="POST" action="{{ route('owner.serenatas.remove-cost-item', $serenata) }}" class="d-inline-block text-start form-remove-cost-item">
                      @csrf
                      @method('PATCH')
                      <input type="hidden" name="source" value="{{ $item['source'] }}">
                      <input type="hidden" name="index" value="{{ $item['index'] }}">
                      <input type="hidden" name="reason" value="">
                      <button type="button" class="btn btn-sm btn-icon btn-text-danger btn-show-remove-cost-confirm" title="Eliminar">
                        <i class="icon-base ti tabler-x icon-18px"></i>
                      </button>
                      <div class="remove-cost-confirmation d-none mt-2 p-2 border rounded bg-body" style="min-width: 280px;">
                        <div class="small text-body-secondary mb-2">Confirma eliminación del ítem.</div>
                        <input
                          type="text"
                          class="form-control form-control-sm mb-2 remove-cost-reason-input"
                          maxlength="120"
                          placeholder="Motivo (opcional)">
                        <div class="d-flex justify-content-end gap-2">
                          <button type="button" class="btn btn-label-secondary btn-sm btn-cancel-remove-cost-item">Cancelar</button>
                          <button type="submit" class="btn btn-danger btn-sm">Eliminar</button>
                        </div>
                      </div>
                    </form>
                  @else
                    <form method="POST" action="{{ route('owner.serenatas.restore-cost-item', $serenata) }}" class="d-inline-block form-restore-cost-item">
                      @csrf
                      @method('PATCH')
                      <input type="hidden" name="source" value="{{ $item['source'] }}">
                      <input type="hidden" name="index" value="{{ $item['index'] }}">
                      <button type="submit" class="btn btn-sm btn-icon btn-text-success" title="Revertir eliminación">
                        <i class="icon-base ti tabler-arrow-back-up icon-18px"></i>
                      </button>
                    </form>
                  @endif
                </td>
              </tr>
            @empty
              <tr>
                <td colspan="6" class="text-center text-body-secondary py-5">Sin ítems seleccionados en esta serenata.</td>
              </tr>
            @endforelse
          </tbody>
        </table>
      </div>
      <div class="collapse border-top mt-3" id="costEditorCollapse">
        <div class="card-body pt-4 pb-6">
          <div class="row g-4 mb-2">
            <div class="col-12 col-lg-4">
              <div class="nav-align-left">
                <ul class="nav nav-pills flex-column gap-2" role="tablist">
                  <li class="nav-item">
                    <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tabAddGiftIncluded" type="button">
                      <i class="icon-base ti tabler-gift me-2"></i>Incluidos
                    </button>
                  </li>
                  <li class="nav-item">
                    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabAddGiftAdditional" type="button">
                      <i class="icon-base ti tabler-shopping-bag-plus me-2"></i>Adicionales
                    </button>
                  </li>
                  <li class="nav-item">
                    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabAddArtist" type="button">
                      <i class="icon-base ti tabler-music me-2"></i>Artistas
                    </button>
                  </li>
                  <li class="nav-item">
                    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabAddOtherCost" type="button">
                      <i class="icon-base ti tabler-truck me-2"></i>Otros costos
                    </button>
                  </li>
                </ul>
              </div>
            </div>
            <div class="col-12 col-lg-8">
              <div class="tab-content p-0">
                <div class="tab-pane fade show active" id="tabAddGiftIncluded">
                  <p class="text-body-secondary mb-3">Obsequios que pueden ir incluidos en el servicio.</p>
                  <form method="POST" action="{{ route('owner.serenatas.add-service-adjustment', $serenata) }}" class="row g-3 cost-pick-form">
                    @csrf
                    <div class="col-12">
                      <input type="hidden" name="item_key" required>
                      <input type="hidden" name="quantity" value="1">
                      <input type="hidden" name="unit_price" value="0">
                      <div class="row g-2">
                        @foreach(($giftOptions ?? []) as $gift)
                          @if(($gift['type'] ?? 'included') === 'included')
                            <div class="col-12 col-md-6 col-xl-4">
                              <div class="border rounded p-2 h-100 d-flex flex-column gap-2 cost-pick-card" data-item-key="gift:{{ $gift['code'] }}" data-default-price="{{ number_format((float) ($gift['price'] ?? 0), 2, '.', '') }}">
                                <div class="d-flex align-items-center justify-content-between gap-2">
                                  <span class="fw-medium">{{ $gift['name'] }}</span>
                                  <button type="button" class="btn btn-sm btn-icon btn-label-primary cost-pick-add-btn" title="Agregar">
                                    <i class="icon-base ti tabler-shopping-cart-plus"></i>
                                  </button>
                                </div>
                                <small class="text-body-secondary">${{ number_format((float) ($gift['price'] ?? 0), 0, ',', '.') }}</small>
                                <div class="d-flex align-items-center gap-2 mt-auto cost-pick-qty-controls">
                                  <button type="button" class="btn btn-sm btn-icon btn-label-secondary cost-pick-qty-minus" title="Restar">
                                    <i class="icon-base ti tabler-minus"></i>
                                  </button>
                                  <input type="number" min="1" step="1" value="1" class="form-control form-control-sm text-center cost-pick-qty-input" style="max-width:72px;">
                                  <button type="button" class="btn btn-sm btn-icon btn-label-secondary cost-pick-qty-plus" title="Sumar">
                                    <i class="icon-base ti tabler-plus"></i>
                                  </button>
                                </div>
                              </div>
                            </div>
                          @endif
                        @endforeach
                      </div>
                    </div>
                  </form>
                </div>
                <div class="tab-pane fade" id="tabAddGiftAdditional">
                  <p class="text-body-secondary mb-3">Obsequios que se suman como adicional al servicio.</p>
                  <form method="POST" action="{{ route('owner.serenatas.add-service-adjustment', $serenata) }}" class="row g-3 cost-pick-form">
                    @csrf
                    <div class="col-12">
                      <input type="hidden" name="item_key" required>
                      <input type="hidden" name="quantity" value="1">
                      <input type="hidden" name="unit_price" value="0">
                      <div class="row g-2">
                        @foreach(($giftOptions ?? []) as $gift)
                          @if(($gift['type'] ?? 'included') !== 'included')
                            <div class="col-12 col-md-6 col-xl-4">
                              <div class="border rounded p-2 h-100 d-flex flex-column gap-2 cost-pick-card" data-item-key="gift:{{ $gift['code'] }}" data-default-price="{{ number_format((float) ($gift['price'] ?? 0), 2, '.', '') }}">
                                <div class="d-flex align-items-center justify-content-between gap-2">
                                  <span class="fw-medium">{{ $gift['name'] }}</span>
                                  <button type="button" class="btn btn-sm btn-icon btn-label-primary cost-pick-add-btn" title="Agregar">
                                    <i class="icon-base ti tabler-shopping-cart-plus"></i>
                                  </button>
                                </div>
                                <small class="text-body-secondary">${{ number_format((float) ($gift['price'] ?? 0), 0, ',', '.') }}</small>
                                <div class="d-flex align-items-center gap-2 mt-auto cost-pick-qty-controls">
                                  <button type="button" class="btn btn-sm btn-icon btn-label-secondary cost-pick-qty-minus" title="Restar">
                                    <i class="icon-base ti tabler-minus"></i>
                                  </button>
                                  <input type="number" min="1" step="1" value="1" class="form-control form-control-sm text-center cost-pick-qty-input" style="max-width:72px;">
                                  <button type="button" class="btn btn-sm btn-icon btn-label-secondary cost-pick-qty-plus" title="Sumar">
                                    <i class="icon-base ti tabler-plus"></i>
                                  </button>
                                </div>
                              </div>
                            </div>
                          @endif
                        @endforeach
                      </div>
                    </div>
                  </form>
                </div>
                <div class="tab-pane fade" id="tabAddArtist">
                  <p class="text-body-secondary mb-3">Selecciona artistas para esta serenata y ajusta precio cuando aplique.</p>
                  <form method="POST" action="{{ route('owner.serenatas.add-service-adjustment', $serenata) }}" class="row g-3 cost-pick-form">
                    @csrf
                    <div class="col-12">
                      <input type="hidden" name="item_key" required>
                      <input type="hidden" name="quantity" value="1">
                      <input type="hidden" name="unit_price" value="0">
                      <div class="row g-2">
                        @foreach(($artistOptions ?? []) as $artist)
                          <div class="col-12 col-md-6 col-xl-4">
                            <div class="border rounded p-2 h-100 d-flex flex-column gap-2 cost-pick-card" data-item-key="artist:{{ $artist['code'] }}" data-default-price="{{ number_format((float) ($artist['price'] ?? 0), 2, '.', '') }}">
                              <div class="d-flex align-items-center justify-content-between gap-2">
                                <span class="fw-medium">{{ $artist['name'] }}</span>
                                <button type="button" class="btn btn-sm btn-icon btn-label-primary cost-pick-add-btn" title="Agregar">
                                  <i class="icon-base ti tabler-shopping-cart-plus"></i>
                                </button>
                              </div>
                              <small class="text-body-secondary">${{ number_format((float) ($artist['price'] ?? 0), 0, ',', '.') }}</small>
                              <div class="d-flex align-items-center gap-2 mt-auto cost-pick-qty-controls">
                                <button type="button" class="btn btn-sm btn-icon btn-label-secondary cost-pick-qty-minus" title="Restar">
                                  <i class="icon-base ti tabler-minus"></i>
                                </button>
                                <input type="number" min="1" step="1" value="1" class="form-control form-control-sm text-center cost-pick-qty-input" style="max-width:72px;">
                                <button type="button" class="btn btn-sm btn-icon btn-label-secondary cost-pick-qty-plus" title="Sumar">
                                  <i class="icon-base ti tabler-plus"></i>
                                </button>
                              </div>
                            </div>
                          </div>
                        @endforeach
                      </div>
                    </div>
                  </form>
                </div>
                <div class="tab-pane fade" id="tabAddOtherCost">
                  <p class="text-body-secondary mb-3">Agrega otros costos del servicio.</p>
                  <form method="POST" action="{{ route('owner.serenatas.add-service-adjustment', $serenata) }}" class="row g-3 cost-pick-form">
                    @csrf
                    <div class="col-12">
                      <input type="hidden" name="item_key" required>
                      <input type="hidden" name="quantity" value="1">
                      <input type="hidden" name="unit_price" value="0">
                      <div class="row g-2">
                        @foreach(($otherCostOptions ?? []) as $cost)
                          <div class="col-12 col-md-6 col-xl-4">
                            <div class="border rounded p-2 h-100 d-flex flex-column gap-2 cost-pick-card" data-item-key="other_cost:{{ $cost['code'] }}" data-default-price="{{ number_format((float) ($cost['price'] ?? 0), 2, '.', '') }}">
                              <div class="d-flex align-items-center justify-content-between gap-2">
                                <span class="fw-medium">{{ $cost['name'] }}</span>
                                <button type="button" class="btn btn-sm btn-icon btn-label-primary cost-pick-add-btn" title="Agregar">
                                  <i class="icon-base ti tabler-shopping-cart-plus"></i>
                                </button>
                              </div>
                              <small class="text-body-secondary">${{ number_format((float) ($cost['price'] ?? 0), 0, ',', '.') }}</small>
                              <div class="d-flex align-items-center gap-2 mt-auto cost-pick-qty-controls">
                                <button type="button" class="btn btn-sm btn-icon btn-label-secondary cost-pick-qty-minus" title="Restar">
                                  <i class="icon-base ti tabler-minus"></i>
                                </button>
                                <input type="number" min="1" step="1" value="1" class="form-control form-control-sm text-center cost-pick-qty-input" style="max-width:72px;">
                                <button type="button" class="btn btn-sm btn-icon btn-label-secondary cost-pick-qty-plus" title="Sumar">
                                  <i class="icon-base ti tabler-plus"></i>
                                </button>
                              </div>
                            </div>
                          </div>
                        @endforeach
                      </div>
                    </div>
                  </form>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="card-body border-top pt-5">
        <div class="serenata-cost-summary mb-4">
          <div class="serenata-cost-summary__item">
            <span class="serenata-cost-summary__label">Precio base</span>
            <strong class="serenata-cost-summary__value" id="summary_base_price">{{ $formatCop($serenata->base_price) }}</strong>
          </div>
          <div class="serenata-cost-summary__item">
            <span class="serenata-cost-summary__label">Costo del servicio</span>
            <strong class="serenata-cost-summary__value" id="summary_base_cost">{{ $formatCop($serenata->base_cost) }}</strong>
          </div>
          <div class="serenata-cost-summary__item">
            <span class="serenata-cost-summary__label">Descuento</span>
            <strong class="serenata-cost-summary__value {{ (float) $serenata->discount_amount > 0 ? 'text-danger' : '' }}" id="summary_discount">
              @if((float) $serenata->discount_amount > 0)
                - {{ $formatCop($serenata->discount_amount) }}
              @else
                $0
              @endif
            </strong>
          </div>
          <div class="serenata-cost-summary__item {{ $effectiveProfit < 0 ? 'is-negative' : 'is-positive' }}">
            <span class="serenata-cost-summary__label">Me quedó</span>
            <strong class="serenata-cost-summary__value" id="summary_profit_amount">
              {{ $effectiveProfit < 0 ? '- ' : '' }}{{ $formatCop(abs($effectiveProfit)) }}
            </strong>
          </div>
          <div class="serenata-cost-summary__item">
            <span class="serenata-cost-summary__label">Pactado final</span>
            <strong class="serenata-cost-summary__value" id="summary_total_charged">{{ $formatCop($serenata->total_charged) }}</strong>
          </div>
          @if((float) ($serenata->commission_rate ?? 0) > 0)
            <div class="serenata-cost-summary__item">
              <span class="serenata-cost-summary__label">Comisión</span>
              <strong class="serenata-cost-summary__value" id="summary_commission">{{ $formatCop($effectiveCommission) }}</strong>
            </div>
          @endif
        </div>
        <div class="d-flex justify-content-end mb-3">
          <button type="button" class="btn btn-sm btn-label-secondary" data-bs-toggle="modal" data-bs-target="#modalEditPricingSummary">
            <i class="icon-base ti tabler-pencil me-1"></i>Editar valores
          </button>
        </div>
        <div class="d-flex justify-content-end mt-4">
          <button type="button" class="btn btn-label-primary btn-sm" data-bs-toggle="modal" data-bs-target="#modalAddDiscount">
            <i class="icon-base ti tabler-ticket me-1"></i>Añadir un descuento
          </button>
        </div>
        @if((float) $serenata->discount_amount > 0)
          <div class="table-responsive mt-4">
            <table class="table table-sm mb-0">
              <thead>
                <tr>
                  <th>Nombre</th>
                  <th class="text-end">Valor</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>Descuento aplicado</td>
                  <td class="text-end text-danger fw-medium">- ${{ number_format((float) $serenata->discount_amount, 0, ',', '.') }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        @endif
      </div>
    </div>

    <div class="card mb-6">
      <div class="card-header">
        <h5 class="card-title mb-0">Historial del servicio</h5>
      </div>
      <div class="card-body">
        <div class="serenata-history-overview mb-4">
          <div class="serenata-history-overview__item">
            <span class="serenata-history-overview__label">Estado actual</span>
            <span class="badge {{ $serviceBadge }}">{{ $serviceStatusLabel }}</span>
          </div>
          <div class="serenata-history-overview__item">
            <span class="serenata-history-overview__label">Pago</span>
            <span class="badge {{ $paymentBadge }}">{{ $serenata->payment_status }}</span>
          </div>
          @if(!empty($serenata->cancellation_reason))
            <div class="serenata-history-overview__item serenata-history-overview__item--full">
              <span class="serenata-history-overview__label">Motivo de cancelación</span>
              <strong>{{ $serenata->cancellation_reason }}</strong>
            </div>
          @endif
        </div>

        <div class="table-responsive">
          <table class="table table-sm">
            <thead>
              <tr>
                <th>Cambio</th>
                <th>Usuario</th>
                <th>Fecha</th>
              </tr>
            </thead>
            <tbody>
              @forelse(($serviceStatusHistories ?? collect()) as $history)
                <tr>
                  <td>
                    <span class="badge bg-label-primary">{{ $history->to_service_status ? $normalizeServiceStatus($history->to_service_status) : '-' }}</span>
                  </td>
                  <td>{{ $history->changedByUser->name ?? 'Sistema' }}</td>
                  <td>{{ $history->created_at?->format('d/m/Y H:i:s') }}</td>
                </tr>
              @empty
                <tr>
                  <td>
                    <span class="badge bg-label-primary">{{ $serviceStatusLabel }}</span>
                  </td>
                  <td>Sistema</td>
                  <td>{{ $serenata->created_at?->format('d/m/Y H:i:s') }}</td>
                </tr>
              @endforelse
            </tbody>
          </table>
        </div>
      </div>
    </div>

  </div>
  </div>
  </div>

  <div class="tab-pane serenata-main-pane d-none" id="serenata-pago-tab" role="tabpanel">
    <div class="card mb-6">
      <div class="card-header">
        <h5 class="card-title m-0">Pago ({{ $paymentRows->count() }})</h5>
      </div>
      <div class="card-body">
        <div class="serenata-payment-overview mb-4">
          <div class="serenata-payment-overview__card">
            <span class="serenata-payment-overview__label">Estado de pago</span>
            <div class="d-flex align-items-center gap-2 flex-wrap">
              <span class="badge {{ $paymentBadge }}">{{ $serenata->payment_status }}</span>
              <span class="serenata-payment-overview__meta">{{ $appliedPaymentsCount }} aplicados</span>
            </div>
          </div>
          <div class="serenata-payment-overview__card">
            <span class="serenata-payment-overview__label">Cobro real esperado</span>
            <strong class="serenata-payment-overview__value">{{ $formatCop($effectiveCustomerCharge) }}</strong>
            <span class="serenata-payment-overview__meta">Base actual del servicio</span>
          </div>
          <div class="serenata-payment-overview__card">
            <span class="serenata-payment-overview__label">Cobrado neto</span>
            <strong class="serenata-payment-overview__value">{{ $formatCop($totalPaid) }}</strong>
            <span class="serenata-payment-overview__meta">{{ $refundPaymentsCount }} reembolsos registrados</span>
          </div>
          <div class="serenata-payment-overview__card {{ $pendingAmount > 0 ? 'is-warning' : 'is-success' }}">
            <span class="serenata-payment-overview__label">Pendiente</span>
            <strong class="serenata-payment-overview__value">{{ $formatCop($pendingAmount) }}</strong>
            <span class="serenata-payment-overview__meta">{{ $plannedPaymentsCount }} movimientos planeados</span>
          </div>
        </div>

        <div class="row g-4">
          <div class="col-12 col-xl-5">
            <div class="serenata-payment-panel mb-4">
              <div class="serenata-payment-panel__header">
                <div>
                  <h6 class="mb-1">Cobro real al cliente</h6>
                  <p class="text-body-secondary mb-0">Úsalo solo si el cliente terminó pagando distinto a lo pactado.</p>
                </div>
              </div>
              <form method="POST" action="{{ route('owner.serenatas.update-actual-customer-charge', $serenata) }}">
                @csrf
                @method('PATCH')
                <div class="row g-3 align-items-end">
                  <div class="col-12">
                    <label class="form-label">Cobro real</label>
                    <input
                      type="text"
                      inputmode="numeric"
                      class="form-control js-cop-mask"
                      name="actual_customer_charge"
                      value="{{ old('actual_customer_charge', $actualCustomerCharge !== null ? number_format($actualCustomerCharge, 0, ',', '.') : '') }}"
                      placeholder="{{ number_format((float) $serenata->total_charged, 0, ',', '.') }}">
                    <small class="text-body-secondary d-block mt-1">Si lo dejas vacío, usamos el precio pactado.</small>
                  </div>
                  <div class="col-12">
                    <label class="form-label">Nota del ajuste</label>
                    <textarea
                      class="form-control"
                      name="actual_customer_charge_notes"
                      rows="3"
                      maxlength="1200"
                      placeholder="Ejemplo: el cliente pagó menos por incidencia con obsequios o demora">{{ old('actual_customer_charge_notes', $serenata->actual_customer_charge_notes) }}</textarea>
                  </div>
                  <div class="col-12 d-flex justify-content-between align-items-center flex-wrap gap-2">
                    @if($serenata->actual_customer_charge_recorded_at)
                      <span class="text-body-secondary small">Última actualización: {{ $serenata->actual_customer_charge_recorded_at?->format('d/m/Y H:i') }}</span>
                    @else
                      <span class="text-body-secondary small">Sin ajustes manuales aún.</span>
                    @endif
                    <button type="submit" class="btn btn-primary btn-sm">Guardar cobro real</button>
                  </div>
                </div>
              </form>
            </div>

            <div class="serenata-payment-panel">
              <div class="serenata-payment-panel__header">
                <div>
                  <h6 class="mb-1">Registrar movimiento</h6>
                  <p class="text-body-secondary mb-0">Añade aquí un pago real que sí entró o quedó registrado.</p>
                </div>
              </div>
              <form method="POST" action="{{ route('owner.serenatas.add-payment', $serenata) }}">
                @csrf
                <div class="mb-3">
                  <label class="form-label">Método actual del servicio</label>
                  <div class="serenata-payment-method-row">
                    <select class="form-select" name="payment_method_id" form="updateSerenataPaymentMethodForm">
                      @php
                        $currentMethodId = collect($paymentMethodOptions ?? [])
                          ->first(fn ($item) => mb_strtolower((string) ($item['name'] ?? ''), 'UTF-8') === mb_strtolower((string) $serenata->payment_method, 'UTF-8'))['id'] ?? null;
                      @endphp
                      @forelse (($paymentMethodOptions ?? []) as $method)
                        <option value="{{ $method['id'] }}" @selected((int) $currentMethodId === (int) $method['id'])>{{ $method['name'] }}</option>
                      @empty
                        <option value="" selected disabled>Sin métodos activos (Configura en Configuración > Pagos)</option>
                      @endforelse
                    </select>
                    <button type="submit" form="updateSerenataPaymentMethodForm" class="btn btn-label-primary btn-sm" @disabled(empty($paymentMethodOptions))>Actualizar</button>
                  </div>
                </div>

                <div class="row g-3">
                  <div class="col-md-6">
                    <label class="form-label">Fecha</label>
                    <input type="datetime-local" class="form-control" name="paid_at" value="{{ old('paid_at', now()->format('Y-m-d\TH:i')) }}" required>
                  </div>
                  <div class="col-md-6">
                    <label class="form-label">Método para este movimiento</label>
                    <select class="form-select" name="payment_method_id">
                      <option value="">Usar actual ({{ $serenata->payment_method }})</option>
                      @foreach (($paymentMethodOptions ?? []) as $method)
                        <option value="{{ $method['id'] }}">{{ $method['name'] }}</option>
                      @endforeach
                    </select>
                  </div>
                  <div class="col-md-6">
                    <label class="form-label">Importe</label>
                    <input
                      type="text"
                      inputmode="numeric"
                      class="form-control js-cop-mask"
                      name="amount"
                      value="{{ old('amount', $pendingAmount > 0 ? number_format($pendingAmount, 0, ',', '.') : '0') }}"
                      required>
                  </div>
                  <div class="col-md-6">
                    <label class="form-label">Referencia</label>
                    <input type="text" class="form-control" name="transaction_reference" maxlength="190" value="{{ old('transaction_reference') }}">
                  </div>
                  <div class="col-12 d-flex justify-content-end">
                    <button type="submit" class="btn btn-primary">Añadir pago</button>
                  </div>
                </div>
              </form>
            </div>
          </div>

          <div class="col-12 col-xl-7">
            <div class="serenata-payment-panel h-100">
              <div class="serenata-payment-panel__header">
                <div>
                  <h6 class="mb-1">Historial de movimientos</h6>
                  <p class="text-body-secondary mb-0">Resumen de pagos aplicados, pendientes planeados y reembolsos.</p>
                </div>
              </div>

              <div class="serenata-payment-ledger table-responsive">
                <table class="table table-sm mb-0">
                  <thead>
                    <tr>
                      <th>Fecha</th>
                      <th>Método</th>
                      <th>Estado</th>
                      <th>Referencia</th>
                      <th>Importe</th>
                      <th>Registrado por</th>
                    </tr>
                  </thead>
                  <tbody>
                    @forelse($paymentRows as $paymentRow)
                      @php
                        $payment = $paymentRow['model'];
                        $isRefund = (bool) $paymentRow['is_refund'];
                        $isPlannedPayment = (bool) $paymentRow['is_planned'];
                      @endphp
                      <tr class="{{ $isRefund ? 'serenata-payment-ledger__row--refund' : ($isPlannedPayment ? 'serenata-payment-ledger__row--planned' : '') }}">
                        <td>{{ $payment->paid_at?->format('d/m/Y H:i') }}</td>
                        <td>{{ $payment->payment_method_name }}</td>
                        <td>
                          @if($isRefund)
                            <span class="badge bg-label-danger">Reembolso</span>
                          @elseif($isPlannedPayment)
                            <span class="badge bg-label-warning">Pendiente</span>
                          @else
                            <span class="badge bg-label-success">Aplicado</span>
                          @endif
                        </td>
                        <td>{{ $payment->transaction_reference ?: '-' }}</td>
                        <td class="fw-semibold">{{ $formatCop($payment->amount) }}</td>
                        <td>{{ $payment->registeredBy->name ?? 'Sistema' }}</td>
                      </tr>
                    @empty
                      <tr>
                        <td colspan="6" class="text-center text-body-secondary py-4">Aún no hay pagos registrados.</td>
                      </tr>
                    @endforelse
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
        <form id="updateSerenataPaymentMethodForm" method="POST" action="{{ route('owner.serenatas.update-payment-method', $serenata) }}">
          @csrf
          @method('PATCH')
        </form>
      </div>
    </div>
  </div>

  <div class="tab-pane serenata-main-pane d-none" id="serenata-actividad-tab" role="tabpanel">
    <div class="card mb-6">
      <div class="card-header">
        <h5 class="card-title m-0">Actividad y logs</h5>
      </div>
      <div class="card-body pt-2">
        <div class="nav-align-top mb-4">
          <ul class="nav nav-pills flex-row gap-2" role="tablist">
            <li class="nav-item" role="presentation">
              <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#service-activity-tab" type="button" role="tab" aria-selected="true">
                <i class="icon-base ti tabler-activity me-1"></i> Actividad
              </button>
            </li>
            <li class="nav-item" role="presentation">
              <button class="nav-link" data-bs-toggle="tab" data-bs-target="#service-logs-tab" type="button" role="tab" aria-selected="false">
                <i class="icon-base ti tabler-list-details me-1"></i> Logs ({{ $statusHistories->count() }})
              </button>
            </li>
          </ul>
        </div>

        <div class="tab-content p-0">
          <div class="tab-pane fade show active" id="service-activity-tab" role="tabpanel">
            <ul class="timeline pb-0 mb-0">
              <li class="timeline-item timeline-item-transparent border-primary">
                <span class="timeline-point timeline-point-primary"></span>
                <div class="timeline-event">
                  <div class="timeline-header">
                    <h6 class="mb-0">Serenata creada ({{ $serenata->code }})</h6>
                    <small class="text-body-secondary">{{ $serenata->created_at?->format('d/m/Y H:i') }}</small>
                  </div>
                  <p class="mt-2 mb-0">Registro inicial en el sistema.</p>
                </div>
              </li>
              <li class="timeline-item timeline-item-transparent border-primary">
                <span class="timeline-point timeline-point-primary"></span>
                <div class="timeline-event">
                  <div class="timeline-header">
                    <h6 class="mb-0">Evento programado</h6>
                    <small class="text-body-secondary">{{ optional($serenata->event_date)->format('d/m/Y') }} {{ $serenata->eventWindowLabel() }}</small>
                  </div>
                  <p class="mt-2 mb-0">Motivo: {{ $serenata->reason }}</p>
                </div>
              </li>
              <li class="timeline-item timeline-item-transparent border-transparent pb-0">
                <span class="timeline-point {{ $serviceStatusLabel === 'Realizada' ? 'timeline-point-success' : 'timeline-point-warning' }}"></span>
                <div class="timeline-event pb-0">
                  <div class="timeline-header">
                    <h6 class="mb-0">Estado actual: {{ $serviceStatusLabel }}</h6>
                    <small class="text-body-secondary">{{ $serenata->updated_at?->format('d/m/Y H:i') }}</small>
                  </div>
                  @if(!empty($serenata->cancellation_reason))
                    <p class="mt-2 mb-0">Motivo cancelación: {{ $serenata->cancellation_reason }}</p>
                  @elseif($serenata->is_ceded)
                    <p class="mt-2 mb-0">
                      {{ $cededOverview['label'] ?? 'Sin excedente' }}:
                      ${{ number_format((float) ($cededOverview['amount'] ?? 0), 0, ',', '.') }}
                    </p>
                  @endif
                </div>
              </li>
            </ul>
          </div>

          <div class="tab-pane fade" id="service-logs-tab" role="tabpanel">
            <div class="table-responsive">
              <table class="table table-sm mb-0">
                <thead>
                  <tr>
                    <th>Movimiento</th>
                    <th>Usuario</th>
                    <th>Fecha</th>
                  </tr>
                </thead>
                <tbody>
                  @forelse($statusHistories->take(50) as $history)
                    <tr>
                      <td>{{ $history->note ?: 'Cambio de estado' }}</td>
                      <td>{{ $history->changedByUser->name ?? 'Sistema' }}</td>
                      <td>{{ $history->created_at?->format('d/m/Y H:i:s') }}</td>
                    </tr>
                  @empty
                    <tr>
                      <td colspan="3" class="text-center text-body-secondary">Sin movimientos registrados.</td>
                    </tr>
                  @endforelse
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="tab-pane serenata-main-pane d-none" id="serenata-cedida-tab" role="tabpanel">
    <div class="card mb-6">
      <div class="card-header">
        <h5 class="card-title mb-0">Cesión operativa</h5>
      </div>
      <div class="card-body">
        <div class="serenata-ceded-overview mb-4">
          <div class="serenata-ceded-overview__card">
            <span class="serenata-ceded-overview__label">Estado</span>
            <div class="d-flex align-items-center gap-2 flex-wrap">
              <span class="badge {{ $serenata->is_ceded ? 'bg-label-info' : 'bg-label-secondary' }}">{{ $serenata->is_ceded ? 'Cedida activa' : 'No cedida' }}</span>
              @if($serenata->is_ceded)
                <span class="badge {{ $cededOverviewBadge }}">{{ $cededOverview['label'] ?? 'Sin excedente' }}</span>
              @endif
            </div>
          </div>
          <div class="serenata-ceded-overview__card">
            <span class="serenata-ceded-overview__label">Externo actual</span>
            <strong class="serenata-ceded-overview__value">{{ $currentExternalPartnerName }}</strong>
            <span class="serenata-ceded-overview__meta">Responsable operativo</span>
          </div>
          <div class="serenata-ceded-overview__card">
            <span class="serenata-ceded-overview__label">Tarifa externa</span>
            <strong class="serenata-ceded-overview__value">{{ $formatCop($serenata->ceded_total_cost) }}</strong>
            <span class="serenata-ceded-overview__meta">Valor acordado actual</span>
          </div>
          <div class="serenata-ceded-overview__card">
            <span class="serenata-ceded-overview__label">Ganancia / ajuste</span>
            <strong class="serenata-ceded-overview__value">{{ $formatCop((float) ($cededOverview['amount'] ?? 0)) }}</strong>
            <span class="serenata-ceded-overview__meta">Base: {{ $formatCop($effectiveCustomerCharge) }}</span>
          </div>
        </div>

        <form method="POST" action="{{ route('owner.serenatas.update-cedida', $serenata) }}" id="cededFlowForm">
          @csrf
          @method('PATCH')

          <div class="serenata-ceded-panel mb-4">
            <div class="form-check form-switch mb-0">
              <input class="form-check-input" type="checkbox" id="is_ceded" name="is_ceded" value="1" @checked((bool) old('is_ceded', $serenata->is_ceded))>
              <label class="form-check-label fw-medium" for="is_ceded">Esta serenata se entregó a un externo para su ejecución</label>
            </div>
            <p class="text-body-secondary small mb-0 mt-2">Activa este flujo cuando otra agrupación realiza el servicio y necesitas controlar tarifa, ajuste y conciliación.</p>
          </div>

          <div id="cededFieldsWrap" class="{{ (bool) old('is_ceded', $serenata->is_ceded) ? '' : 'd-none' }}">
            <div class="row g-4 mb-4">
              <div class="col-md-6 form-control-validation">
                <label class="form-label">Externo asignado</label>
                <select class="form-select" name="external_partner_id" id="external_partner_id">
                  <option value="">Selecciona externo</option>
                  @foreach(($externalPartnerOptions ?? []) as $partner)
                    <option value="{{ $partner['id'] }}" @selected((int) old('external_partner_id', $serenata->external_partner_id) === (int) $partner['id'])>
                      {{ $partner['name'] }}{{ !empty($partner['city']) ? " ({$partner['city']})" : '' }}
                    </option>
                  @endforeach
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">Estado de excedente</label>
                <input type="text" class="form-control" id="ceded_excess_label" value="{{ $cededOverview['label'] ?? 'Sin excedente' }}" readonly>
              </div>
            </div>

            <input type="hidden" name="ceded_artist_amount" id="ceded_artist_amount" value="{{ old('ceded_artist_amount', (float) $serenata->ceded_artist_amount) }}">
            <input type="hidden" name="ceded_gift_amount" id="ceded_gift_amount" value="{{ old('ceded_gift_amount', (float) $serenata->ceded_gift_amount) }}">
            <input type="hidden" name="ceded_transport_amount" id="ceded_transport_amount" value="{{ old('ceded_transport_amount', (float) $serenata->ceded_transport_amount) }}">
            <input type="hidden" name="ceded_other_cost_amount" id="ceded_other_cost_amount" value="{{ old('ceded_other_cost_amount', (float) $serenata->ceded_other_cost_amount) }}">
            <input type="hidden" name="ceded_cost_breakdown" id="ceded_cost_breakdown" value='{{ old('ceded_cost_breakdown', $cededBreakdownJson) }}'>

            <div class="serenata-ceded-panel" id="cededBreakdownEditor">
              <div class="d-flex flex-column flex-lg-row justify-content-between align-items-start gap-3 mb-4">
                <div>
                  <h6 class="mb-1">Mismos costos de la serenata, con ajustes rápidos</h6>
                  <p class="text-body-secondary mb-0">Tomamos artistas, obsequios y otros costos del servicio actual. Solo cambias lo que Patricia te cobre distinto.</p>
                </div>
              </div>

              <div class="serenata-ceded-kpis mb-4">
                <div class="col-md-3">
                  <div class="serenata-ceded-kpi">
                    <div class="small text-body-secondary">Artistas</div>
                    <div class="fs-5 fw-semibold" id="ceded_artist_amount_preview">$0</div>
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="serenata-ceded-kpi">
                    <div class="small text-body-secondary">Obsequios</div>
                    <div class="fs-5 fw-semibold" id="ceded_gift_amount_preview">$0</div>
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="serenata-ceded-kpi">
                    <div class="small text-body-secondary">Otros costos</div>
                    <div class="fs-5 fw-semibold" id="ceded_other_cost_amount_preview">$0</div>
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="serenata-ceded-kpi">
                    <div class="small text-body-secondary">Transporte manual</div>
                    <div class="fs-5 fw-semibold" id="ceded_transport_amount_preview">$0</div>
                  </div>
                </div>
              </div>

              <div class="row g-4">
                <div class="col-12 col-lg-3">
                  <div class="nav-align-left">
                    <ul class="nav nav-pills flex-column gap-2" role="tablist">
                      <li class="nav-item">
                        <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#cededTabArtists" type="button">
                          <i class="icon-base ti tabler-music me-2"></i>Artistas
                        </button>
                      </li>
                      <li class="nav-item">
                        <button class="nav-link" data-bs-toggle="tab" data-bs-target="#cededTabGifts" type="button">
                          <i class="icon-base ti tabler-gift me-2"></i>Obsequios
                        </button>
                      </li>
                      <li class="nav-item">
                        <button class="nav-link" data-bs-toggle="tab" data-bs-target="#cededTabOthers" type="button">
                          <i class="icon-base ti tabler-package me-2"></i>Otros costos
                        </button>
                      </li>
                      <li class="nav-item">
                        <button class="nav-link" data-bs-toggle="tab" data-bs-target="#cededTabTransport" type="button">
                          <i class="icon-base ti tabler-truck me-2"></i>Transporte
                        </button>
                      </li>
                    </ul>
                  </div>
                </div>
                <div class="col-12 col-lg-9">
                  <div class="tab-content p-0">
                    @php
                      $artistBreakdownItems = $cededBreakdownItems->where('source', 'artist')->values();
                      $giftBreakdownItems = $cededBreakdownItems->where('source', 'gift')->values();
                      $otherBreakdownItems = $cededBreakdownItems->where('source', 'other_cost')->values();
                    @endphp
                    <div class="tab-pane fade show active" id="cededTabArtists">
                      <p class="text-body-secondary mb-3">Ajusta solo los músicos cuyo valor cambie con el externo.</p>
                      <div class="row g-3">
                        @forelse($artistBreakdownItems as $item)
                          <div class="col-md-6">
                            <div class="border rounded p-3 js-ceded-breakdown-item" data-source="{{ $item['source'] }}" data-index="{{ $item['index'] }}" data-name="{{ $item['name'] }}">
                              <div class="form-check mb-2">
                                <input class="form-check-input js-ceded-item-included" type="checkbox" @checked($item['included'])>
                                <label class="form-check-label fw-medium">{{ $item['name'] }}</label>
                              </div>
                              <div class="row g-2">
                                <div class="col-5">
                                  <label class="form-label small">Cant.</label>
                                  <input type="number" min="1" step="1" class="form-control js-ceded-item-quantity" value="{{ $item['quantity'] }}">
                                </div>
                                <div class="col-7">
                                  <label class="form-label small">Precio externo</label>
                                  <input type="text" inputmode="numeric" class="form-control js-cop-mask js-ceded-item-unit-price" value="{{ number_format((float) $item['unit_price'], 0, ',', '.') }}">
                                </div>
                                <div class="col-12">
                                  <div class="small text-body-secondary">Total: <strong class="js-ceded-item-total">${{ number_format((float) $item['total'], 0, ',', '.') }}</strong></div>
                                </div>
                              </div>
                            </div>
                          </div>
                        @empty
                          <div class="col-12 text-body-secondary">No hay artistas activos en esta serenata.</div>
                        @endforelse
                      </div>
                    </div>
                    <div class="tab-pane fade" id="cededTabGifts">
                      <p class="text-body-secondary mb-3">Si el externo mantiene los mismos obsequios, no cambias nada. Si algo sube o se quita, lo ajustas aquí.</p>
                      <div class="row g-3">
                        @forelse($giftBreakdownItems as $item)
                          <div class="col-md-6">
                            <div class="border rounded p-3 js-ceded-breakdown-item" data-source="{{ $item['source'] }}" data-index="{{ $item['index'] }}" data-name="{{ $item['name'] }}">
                              <div class="form-check mb-2">
                                <input class="form-check-input js-ceded-item-included" type="checkbox" @checked($item['included'])>
                                <label class="form-check-label fw-medium">{{ $item['name'] }}</label>
                              </div>
                              <div class="row g-2">
                                <div class="col-5">
                                  <label class="form-label small">Cant.</label>
                                  <input type="number" min="1" step="1" class="form-control js-ceded-item-quantity" value="{{ $item['quantity'] }}">
                                </div>
                                <div class="col-7">
                                  <label class="form-label small">Precio externo</label>
                                  <input type="text" inputmode="numeric" class="form-control js-cop-mask js-ceded-item-unit-price" value="{{ number_format((float) $item['unit_price'], 0, ',', '.') }}">
                                </div>
                                <div class="col-12">
                                  <div class="small text-body-secondary">Total: <strong class="js-ceded-item-total">${{ number_format((float) $item['total'], 0, ',', '.') }}</strong></div>
                                </div>
                              </div>
                            </div>
                          </div>
                        @empty
                          <div class="col-12 text-body-secondary">No hay obsequios activos en esta serenata.</div>
                        @endforelse
                      </div>
                    </div>
                    <div class="tab-pane fade" id="cededTabOthers">
                      <p class="text-body-secondary mb-3">Aquí entran costos extras del servicio que el externo te cobre también.</p>
                      <div class="row g-3">
                        @forelse($otherBreakdownItems as $item)
                          <div class="col-md-6">
                            <div class="border rounded p-3 js-ceded-breakdown-item" data-source="{{ $item['source'] }}" data-index="{{ $item['index'] }}" data-name="{{ $item['name'] }}">
                              <div class="form-check mb-2">
                                <input class="form-check-input js-ceded-item-included" type="checkbox" @checked($item['included'])>
                                <label class="form-check-label fw-medium">{{ $item['name'] }}</label>
                              </div>
                              <div class="row g-2">
                                <div class="col-5">
                                  <label class="form-label small">Cant.</label>
                                  <input type="number" min="1" step="1" class="form-control js-ceded-item-quantity" value="{{ $item['quantity'] }}">
                                </div>
                                <div class="col-7">
                                  <label class="form-label small">Precio externo</label>
                                  <input type="text" inputmode="numeric" class="form-control js-cop-mask js-ceded-item-unit-price" value="{{ number_format((float) $item['unit_price'], 0, ',', '.') }}">
                                </div>
                                <div class="col-12">
                                  <div class="small text-body-secondary">Total: <strong class="js-ceded-item-total">${{ number_format((float) $item['total'], 0, ',', '.') }}</strong></div>
                                </div>
                              </div>
                            </div>
                          </div>
                        @empty
                          <div class="col-12 text-body-secondary">No hay otros costos activos en esta serenata.</div>
                        @endforelse
                      </div>
                    </div>
                    <div class="tab-pane fade" id="cededTabTransport">
                      <p class="text-body-secondary mb-3">Si el externo te cobra transporte aparte y no está en los ítems del servicio, lo registras aquí.</p>
                      <div class="border rounded p-3">
                        <label class="form-label">Transporte manual / ajuste</label>
                        <input type="text" inputmode="numeric" class="form-control js-cop-mask" id="ceded_transport_manual" value="{{ number_format((float) $cededTransportInitial, 0, ',', '.') }}">
                        <small class="text-body-secondary d-block mt-2">Ejemplo: si todo sigue igual pero Patricia te subió $10.000 de transporte, lo pones aquí.</small>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="row g-4 mt-1">
              <div class="col-md-4">
                <label class="form-label">Tarifa final acordada con el externo</label>
                <input type="text" inputmode="numeric" class="form-control js-cop-mask" name="ceded_total_cost" id="ceded_total_cost" value="{{ number_format((float) old('ceded_total_cost', $serenata->ceded_total_cost), 0, ',', '.') }}">
                <small class="text-body-secondary">Si la dejas en 0, usamos la suma automática de los ítems de arriba.</small>
              </div>
              <div class="col-md-4">
                <label class="form-label">Base actual para liquidar</label>
                <input type="text" class="form-control" id="ceded_total_charged_preview" value="{{ number_format($effectiveCustomerCharge, 0, ',', '.') }}" readonly>
              </div>
              <div class="col-md-4">
                <label class="form-label">Ganancia / ajuste actual</label>
                <input type="text" class="form-control" id="ceded_excess_amount_preview" value="{{ number_format((float) ($cededOverview['amount'] ?? 0), 0, ',', '.') }}" readonly>
              </div>
            </div>

            <div class="row g-4 mt-1">
              <div class="col-12">
                <label class="form-label">Notas de cesión</label>
                <textarea class="form-control" name="ceded_notes" rows="3" maxlength="1200" placeholder="Observaciones del acuerdo con el externo">{{ old('ceded_notes', $serenata->ceded_notes) }}</textarea>
              </div>
              <div class="col-12">
                <div class="form-check form-switch">
                  <input class="form-check-input" type="checkbox" id="ceded_mark_settled" name="ceded_mark_settled" value="1" @checked((bool) old('ceded_mark_settled', !empty($serenata->ceded_settled_at)))>
                  <label class="form-check-label" for="ceded_mark_settled">Excedente ya conciliado</label>
                </div>
                @if(!empty($serenata->ceded_settled_at))
                  <small class="text-body-secondary d-block mt-1">Última conciliación: {{ $serenata->ceded_settled_at?->format('d/m/Y H:i') }}</small>
                @endif
              </div>
            </div>
          </div>

          <div class="d-flex justify-content-end mt-4">
            <button type="submit" class="btn btn-primary">Guardar flujo cedida</button>
          </div>
        </form>
      </div>
    </div>

    <div class="card mb-6">
      <div class="card-header d-flex flex-column flex-lg-row align-items-lg-center justify-content-between gap-3">
        <div>
          <h5 class="card-title mb-1">Movimientos y saldos con externos</h5>
          <p class="text-body-secondary mb-0">Aquí registras cesiones, cambios pendientes, compensaciones con serenata, ajustes en efectivo y penalidades.</p>
        </div>
      </div>
      <div class="card-body">
        @if(!empty($externalPartnerBalanceSummary))
          <div class="serenata-ceded-balance-grid mb-4">
            @foreach($externalPartnerBalanceSummary as $partnerId => $summary)
              @php
                $balanceStatus = (string) ($summary['status'] ?? 'equilibrado');
                $balanceBadge = match ($balanceStatus) {
                  'a_favor' => 'bg-label-success',
                  'en_contra' => 'bg-label-danger',
                  default => 'bg-label-secondary',
                };
              @endphp
              <div class="col-md-4">
                <div class="serenata-ceded-balance-card h-100">
                  <div class="d-flex justify-content-between align-items-start gap-3">
                    <div>
                      <div class="fw-medium">{{ $externalPartnerNameLookup[(int) $partnerId] ?? ('Externo #' . $partnerId) }}</div>
                      <div class="small text-body-secondary">Saldo global con este externo</div>
                    </div>
                    <span class="badge {{ $balanceBadge }}">{{ $summary['label'] ?? 'Saldo' }}</span>
                  </div>
                  <div class="fs-5 fw-semibold mt-3">
                    ${{ number_format((float) ($summary['amount'] ?? 0), 0, ',', '.') }}
                  </div>
                </div>
              </div>
            @endforeach
          </div>
        @endif

        <div class="row g-4">
          <div class="col-12 col-xl-5">
            <form method="POST" action="{{ route('owner.serenatas.add-external-movement', $serenata) }}" class="serenata-ceded-panel mb-4">
          @csrf
              <div class="serenata-ceded-panel__header">
                <div>
                  <h6 class="mb-1">Registrar movimiento con externo</h6>
                  <p class="text-body-secondary mb-0">Controla aquí deudas, compensaciones y ajustes de una forma separada a la cesión principal.</p>
                </div>
              </div>
              <div class="row g-3">
                <div class="col-md-6">
                  <label class="form-label">Externo</label>
                  <select class="form-select" name="external_partner_id" id="external_movement_partner_id" required>
                    <option value="">Selecciona externo</option>
                    @foreach(($externalPartnerOptions ?? []) as $partner)
                      <option value="{{ $partner['id'] }}" @selected((int) old('external_partner_id', $serenata->external_partner_id) === (int) $partner['id'])>
                        {{ $partner['name'] }}{{ !empty($partner['city']) ? " ({$partner['city']})" : '' }}
                      </option>
                    @endforeach
                  </select>
                </div>
                <div class="col-md-6">
                  <label class="form-label">Tipo de movimiento</label>
                  <select class="form-select" name="movement_type" required>
                    @foreach($externalPartnerMovementTypeOptions as $value => $label)
                      <option value="{{ $value }}" @selected(old('movement_type', 'cedida') === $value)>{{ $label }}</option>
                    @endforeach
                  </select>
                </div>
                <div class="col-12">
                  <label class="form-label">Quién le debe a quién</label>
                  <select class="form-select" name="direction" id="external_movement_direction" required>
                    @foreach($externalPartnerMovementDirectionOptions as $value => $label)
                      <option value="{{ $value }}" @selected(old('direction', 'a_favor_mio') === $value)>{{ $label }}</option>
                    @endforeach
                  </select>
                  <small class="text-body-secondary d-block mt-1" id="external_movement_direction_hint">Selecciona el externo y el sistema te lo mostrará en lenguaje simple.</small>
                </div>
                <div class="col-md-6">
                  <label class="form-label">Valor</label>
                  <input type="text" inputmode="numeric" class="form-control js-cop-mask" name="amount" value="{{ old('amount') !== null ? number_format((float) old('amount'), 0, ',', '.') : '' }}" required>
                </div>
                <div class="col-md-6">
                  <label class="form-label">Cómo se compensa</label>
                  <select class="form-select" name="settlement_kind" id="external_movement_settlement_kind" required>
                    @foreach($externalPartnerMovementSettlementOptions as $value => $label)
                      <option value="{{ $value }}" @selected(old('settlement_kind', 'pendiente') === $value)>{{ $label }}</option>
                    @endforeach
                  </select>
                </div>
                <div class="col-md-6">
                  <label class="form-label">Fecha promesa</label>
                  <input type="date" class="form-control" name="due_date" value="{{ old('due_date') }}">
                </div>
                <div class="col-md-6">
                  <label class="form-label">Referencia</label>
                  <input type="text" class="form-control" name="counterpart_reference" maxlength="120" value="{{ old('counterpart_reference') }}" placeholder="Ej: Nequi, SRA-2201">
                </div>
                <div class="col-12">
                  <label class="form-label">Notas</label>
                  <textarea class="form-control" name="notes" rows="3" maxlength="1200" placeholder="Ej: Patricia recibe hoy la serenata y la compensa con otra la próxima semana.">{{ old('notes') }}</textarea>
                </div>
                <div class="col-12 d-flex justify-content-end">
                  <button type="submit" class="btn btn-primary">Registrar movimiento</button>
                </div>
              </div>
            </form>
          </div>

          <div class="col-12 col-xl-7">
            <div class="serenata-ceded-panel h-100">
              <div class="serenata-ceded-panel__header">
                <div>
                  <h6 class="mb-1">Historial de movimientos</h6>
                  <p class="text-body-secondary mb-0">{{ $externalMovementCount }} registros vinculados a esta serenata.</p>
                </div>
              </div>

              <div class="serenata-ceded-ledger table-responsive">
                <table class="table table-sm align-middle mb-0">
                  <thead>
                    <tr>
                      <th>Fecha</th>
                      <th>Externo</th>
                      <th>Movimiento</th>
                      <th>Dirección</th>
                      <th>Valor</th>
                      <th>Compensación</th>
                      <th>Promesa</th>
                      <th>Referencia</th>
                      <th>Nota</th>
                    </tr>
                  </thead>
                  <tbody>
                    @forelse($externalPartnerMovements as $movement)
                      <tr>
                        <td>{{ $movement->created_at?->format('d/m/Y H:i') }}</td>
                        <td>{{ $movement->externalPartner->name ?? 'Sin externo' }}</td>
                        <td>{{ $externalPartnerMovementTypeOptions[$movement->movement_type] ?? ucfirst(str_replace('_', ' ', (string) $movement->movement_type)) }}</td>
                        <td>
                          <span class="badge {{ $movement->direction === 'yo_debo' ? 'bg-label-danger' : 'bg-label-success' }}">
                            {{ $externalPartnerMovementDirectionOptions[$movement->direction] ?? $movement->direction }}
                          </span>
                        </td>
                        <td class="fw-semibold">${{ number_format((float) $movement->amount, 0, ',', '.') }}</td>
                        <td>{{ $externalPartnerMovementSettlementOptions[$movement->settlement_kind] ?? ucfirst((string) $movement->settlement_kind) }}</td>
                        <td>{{ $movement->due_date?->format('d/m/Y') ?: '-' }}</td>
                        <td>{{ $movement->counterpart_reference ?: '-' }}</td>
                        <td>{{ $movement->notes ?: '-' }}</td>
                      </tr>
                    @empty
                      <tr>
                        <td colspan="9" class="text-center text-body-secondary py-4">Todavía no hay movimientos registrados para esta serenata.</td>
                      </tr>
                    @endforelse
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="modalEditCostItem" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-end">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Editar ítem</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form method="POST" action="{{ route('owner.serenatas.update-cost-item', $serenata) }}">
        @csrf
        @method('PATCH')
        <div class="modal-body">
          <input type="hidden" name="source" id="edit_cost_item_source">
          <input type="hidden" name="index" id="edit_cost_item_index">
          <div class="mb-3">
            <label class="form-label">Ítem</label>
            <input type="text" class="form-control" id="edit_cost_item_name" readonly>
          </div>
          <div class="row g-3">
            <div class="col-md-4">
              <label class="form-label">Cantidad</label>
              <input type="number" min="1" step="1" class="form-control" name="quantity" id="edit_cost_item_quantity" required>
            </div>
            <div class="col-md-8">
              <label class="form-label">Costo unitario</label>
              <input type="text" class="form-control" name="unit_price" id="edit_cost_item_unit_price" required>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" class="btn btn-primary">Guardar cambios</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="modalQuickCancelReason" 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" id="quickCancelReasonModalTitle">Motivo de cancelación</h5>
          <small class="text-body-secondary" id="quickCancelReasonModalSubtitle">Confirma por qué esta serenata queda cancelada.</small>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>
      <div class="modal-body">
        <label for="quick_cancel_reason_input" class="form-label">Escribe el motivo</label>
        <textarea
          id="quick_cancel_reason_input"
          class="form-control"
          rows="3"
          maxlength="600"
          placeholder="Ej: cliente canceló por cambio de fecha"></textarea>
        <div class="small text-body-secondary mt-2" id="quickCancelReasonCurrentTextWrap">
          <span class="fw-medium">Motivo actual:</span>
          <span id="quickCancelReasonCurrentText">{{ $serenata->cancellation_reason ?: 'Sin motivo registrado.' }}</span>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cancelar</button>
        <button type="button" class="btn btn-primary" id="quickCancelReasonConfirmBtn">Confirmar</button>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="modalAddDiscount" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-end">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Añadir descuento</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form method="POST" action="{{ route('owner.serenatas.update-discount', $serenata) }}">
        @csrf
        @method('PATCH')
        <div class="modal-body">
          <div class="mb-3">
            <label class="form-label">Nombre</label>
            <input
              type="text"
              class="form-control"
              name="discount_name"
              maxlength="120"
              placeholder="Ej: Descuento cliente frecuente"
              value="{{ old('discount_name') }}">
          </div>
          <div class="row g-3">
            <div class="col-md-4">
              <label class="form-label">Tipo</label>
              <select class="form-select" name="discount_type" required>
                <option value="amount" @selected(old('discount_type', 'amount') === 'amount')>Importe</option>
                <option value="percent" @selected(old('discount_type') === 'percent')>Porcentaje</option>
              </select>
            </div>
            <div class="col-md-8">
              <label class="form-label">Valor</label>
              <input
                type="number"
                class="form-control"
                name="discount_value"
                min="0"
                step="0.01"
                required
                value="{{ old('discount_value', (float) $serenata->discount_amount) }}">
              <small class="text-body-secondary">Si usas porcentaje, aplica sobre Precio base.</small>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" class="btn btn-primary">Guardar descuento</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="modalEditPricingSummary" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Editar resumen económico</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>
      <form method="POST" action="{{ route('owner.serenatas.update-pricing', $serenata) }}">
        @csrf
        @method('PATCH')
        <div
          class="modal-body"
          data-pricing-base-cost="{{ (float) $serenata->base_cost }}"
          data-pricing-base-price="{{ (float) $serenata->base_price }}"
          data-pricing-discount="{{ (float) $serenata->discount_amount }}">
          <div class="mb-3">
            <label class="form-label">Yo cobré al cliente</label>
            <input
              type="text"
              inputmode="numeric"
              class="form-control js-cop-mask"
              id="pricing_summary_base_price_input"
              name="base_price"
              value="{{ number_format((float) old('base_price', $serenata->base_price), 0, ',', '.') }}"
              required>
          </div>
          <div class="mb-3">
            <label class="form-label">Descuento</label>
            <input
              type="text"
              inputmode="numeric"
              class="form-control js-cop-mask"
              id="pricing_summary_discount_input"
              name="discount_amount"
              value="{{ number_format((float) old('discount_amount', $serenata->discount_amount), 0, ',', '.') }}">
          </div>
          <div class="row g-3">
            <div class="col-sm-6">
              <small class="text-body-secondary d-block">Me costó el servicio</small>
              <strong id="pricing_summary_base_cost_preview">{{ $formatCop($serenata->base_cost) }}</strong>
            </div>
            <div class="col-sm-6">
              <small class="text-body-secondary d-block">Me queda con este cambio</small>
              <strong
                id="pricing_summary_profit_preview"
                class="{{ $effectiveProfit < 0 ? 'text-danger' : 'text-success' }}">
                {{ $effectiveProfit < 0 ? '- ' : '' }}{{ $formatCop(abs($effectiveProfit)) }}
              </strong>
            </div>
            <div class="col-12">
              <small class="text-body-secondary d-block">Precio pactado final</small>
              <strong id="pricing_summary_total_preview">{{ $formatCop($serenata->total_charged) }}</strong>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" class="btn btn-primary">Guardar cambios</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="modalRefundPayment" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-end">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Reembolso parcial</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form method="POST" action="{{ route('owner.serenatas.add-refund', $serenata) }}">
        @csrf
        <div class="modal-body">
          <div class="mb-3">
            <label class="form-label">Fecha</label>
            <input type="datetime-local" class="form-control" name="refunded_at" value="{{ now()->format('Y-m-d\TH:i') }}" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Método</label>
            <select class="form-select" name="payment_method_id">
              <option value="">Usar actual ({{ $serenata->payment_method }})</option>
              @foreach (($paymentMethodOptions ?? []) as $method)
                <option value="{{ $method['id'] }}">{{ $method['name'] }}</option>
              @endforeach
            </select>
          </div>
          <div class="mb-3">
            <label class="form-label">Importe a reembolsar</label>
            <input
              type="text"
              inputmode="numeric"
              class="form-control js-cop-mask"
              name="amount"
              value="{{ old('amount') !== null ? number_format((float) old('amount'), 0, ',', '.') : '' }}"
              required>
          </div>
          <div class="mb-0">
            <label class="form-label">Motivo</label>
            <textarea class="form-control" name="reason" rows="3" maxlength="600" placeholder="Motivo del reembolso (opcional)"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" class="btn btn-danger">Registrar reembolso</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="modalEditSerenataInfo" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Editar información de la serenata</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>
      <form method="POST" action="{{ route('owner.serenatas.update-event-info', $serenata) }}">
        @csrf
        @method('PATCH')
        <div class="modal-body">
          <div class="row g-3">
            <div class="col-12">
              <label class="form-label mb-1" for="edit_reason">Motivo de la serenata</label>
              <input
                type="text"
                class="form-control form-control-sm"
                id="edit_reason"
                name="reason"
                value="{{ old('reason', $serenata->reason) }}"
                required>
            </div>
            <div class="col-md-6">
              <label class="form-label mb-1" for="edit_from_name">De parte de</label>
              <input
                type="text"
                class="form-control form-control-sm"
                id="edit_from_name"
                name="from_name"
                value="{{ old('from_name', $serenata->from_name) }}"
                required>
            </div>
            <div class="col-md-6">
              <label class="form-label mb-1" for="edit_to_name">Para quién</label>
              <input
                type="text"
                class="form-control form-control-sm"
                id="edit_to_name"
                name="to_name"
                value="{{ old('to_name', $serenata->to_name) }}"
                required>
            </div>
            <div class="col-md-6">
              <label class="form-label mb-1" for="edit_event_date">Fecha</label>
              <input
                type="date"
                class="form-control form-control-sm"
                id="edit_event_date"
                name="event_date"
                value="{{ old('event_date', optional($serenata->event_date)->format('Y-m-d')) }}"
                required>
            </div>
            <div class="col-md-6">
              <label class="form-label mb-1" for="edit_event_time">Horario</label>
              <div class="time-input-group">
                <input
                  type="hidden"
                  id="edit_event_time"
                  name="event_time"
                  value="{{ old('event_time', $serenata->event_time) }}"
                  required>
                <input
                  type="text"
                  class="form-control form-control-sm time-input"
                  id="edit_event_time_display"
                  value="{{ old('event_time', $serenata->event_time) }}"
                  placeholder="Ej: 18, 6 pm"
                  autocomplete="off">
                <button class="time-picker-btn" type="button" id="btnEditEventTimePicker" title="Seleccionar hora">
                  <i class="icon-base ti tabler-clock"></i>
                </button>
              </div>
              <input type="hidden" id="edit_event_time_window_mode" value="after">
              <div class="event-window-mode-group mt-2" id="editEventTimeModeButtons">
                <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="edit_event_time_window_preview">Selecciona una hora de referencia</strong>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" class="btn btn-primary">Guardar cambios</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="modalEditEventTimeWindowPicker" 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 y el sistema crea el 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="modalEditEventTimeModeButtons">
          <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="modalEditEventTimeWindowPreview">08:00 PM - 09:00 PM</div>
          <div class="event-clock-ref mt-1">Referencia: <span id="modalEditEventTimeReferenceLabel">08:00 PM</span> · <span class="badge bg-label-secondary" id="modalEditEventTimeMeridiem">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="modalEditEventTimeCenterLabel">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-edit-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-edit-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="btnApplyEditEventTimeWindow">Usar esta franja</button>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="modalEditServiceAddress" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Editar dirección del servicio</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form method="POST" action="{{ route('owner.serenatas.update-address', $serenata) }}">
        @csrf
        @method('PATCH')
        <div class="modal-body">
          <div class="mb-3 position-relative">
            <label class="form-label" for="edit_service_address">Dirección</label>
            <input
              type="text"
              class="form-control"
              id="edit_service_address"
              name="service_address"
              value="{{ old('service_address', $serenata->service_address) }}"
              required>
            <div id="editServiceAddressSuggestions" class="gm-address-suggestions d-none"></div>
          </div>
          <div class="mb-3">
            <label class="form-label" for="edit_address_additional">Dirección adicional</label>
            <input
              type="text"
              class="form-control"
              id="edit_address_additional"
              name="address_additional"
              value="{{ old('address_additional', $serenata->address_additional) }}"
              placeholder="Apto, torre, interior...">
          </div>
          <div class="row g-3">
            <div class="col-6">
              <label class="form-label" for="edit_service_country">País</label>
              <input
                type="text"
                class="form-control"
                id="edit_service_country"
                name="service_country"
                value="{{ old('service_country', $serenata->service_country ?: 'Colombia') }}"
                required>
            </div>
            <div class="col-6">
              <label class="form-label" for="edit_service_department">Departamento</label>
              <input
                type="text"
                class="form-control"
                id="edit_service_department"
                name="service_department"
                value="{{ old('service_department', $serenata->service_department) }}">
            </div>
            <div class="col-6">
              <label class="form-label" for="edit_neighborhood">Barrio</label>
              <input
                type="text"
                class="form-control"
                id="edit_neighborhood"
                name="neighborhood"
                value="{{ old('neighborhood', $serenata->neighborhood) }}"
                required>
            </div>
            <div class="col-6">
              <label class="form-label" for="edit_locality">Ciudad/Municipio</label>
              <input
                type="text"
                class="form-control"
                id="edit_locality"
                name="locality"
                value="{{ old('locality', $serenata->locality) }}"
                required>
            </div>
            <div class="col-6">
              <label class="form-label" for="edit_service_locality">Localidad</label>
              <input
                type="text"
                class="form-control"
                id="edit_service_locality"
                name="service_locality"
                value="{{ old('service_locality', $serenata->service_locality) }}">
            </div>
            <div class="col-6">
              <label class="form-label" for="edit_service_sector">Sector / UPZ / Urbanización</label>
              <input
                type="text"
                class="form-control"
                id="edit_service_sector"
                name="service_sector"
                value="{{ old('service_sector', $serenata->service_sector) }}">
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" class="btn btn-primary">Guardar dirección</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="modalSelectServiceAddress" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Seleccionar otra dirección</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form method="POST" action="{{ route('owner.serenatas.update-address', $serenata) }}" id="selectAddressForm">
        @csrf
        @method('PATCH')
        <div class="modal-body">
          <div class="mb-3">
            <label class="form-label" for="selected_address_option">Direcciones registradas del cliente</label>
            <select class="form-select" id="selected_address_option">
              <option value="">Selecciona una dirección</option>
              @foreach(($addressOptions ?? []) as $idx => $address)
                <option
                  value="{{ $idx }}"
                  data-service-address="{{ $address['service_address'] }}"
                  data-address-additional="{{ $address['address_additional'] }}"
                  data-service-country="{{ $address['service_country'] }}"
                  data-service-department="{{ $address['service_department'] }}"
                  data-neighborhood="{{ $address['neighborhood'] }}"
                  data-locality="{{ $address['city'] }}"
                  data-service-locality="{{ $address['service_locality'] }}"
                  data-service-sector="{{ $address['service_sector'] }}">
                  {{ $address['label'] }}
                </option>
              @endforeach
            </select>
          </div>

          <div id="selectedAddressPreview" class="small text-body-secondary">
            Selecciona una dirección para ver el detalle.
          </div>

          <input type="hidden" name="service_address" id="selected_service_address" value="{{ $serenata->service_address }}">
          <input type="hidden" name="address_additional" id="selected_address_additional" value="{{ $serenata->address_additional }}">
          <input type="hidden" name="service_country" id="selected_service_country" value="{{ $serenata->service_country ?: 'Colombia' }}">
          <input type="hidden" name="service_department" id="selected_service_department" value="{{ $serenata->service_department }}">
          <input type="hidden" name="neighborhood" id="selected_neighborhood" value="{{ $serenata->neighborhood }}">
          <input type="hidden" name="locality" id="selected_locality" value="{{ $serenata->locality }}">
          <input type="hidden" name="service_locality" id="selected_service_locality" value="{{ $serenata->service_locality }}">
          <input type="hidden" name="service_sector" id="selected_service_sector" value="{{ $serenata->service_sector }}">
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" class="btn btn-primary">Usar esta dirección</button>
        </div>
      </form>
    </div>
  </div>
</div>
