@php
$pageConfigs = ['navbarType' => 'hidden', 'contentLayout' => 'wide'];
$configData = Helper::appClasses();
$statusMap = [
  'pending' => ['Pendiente', 'warning'],
  'confirmed' => ['Confirmado', 'info'],
  'at_restaurant' => ['En restaurante', 'primary'],
  'en_route' => ['En camino', 'primary'],
  'delivered' => ['Entregado', 'success'],
  'cancelled' => ['Cancelado', 'danger'],
];
@endphp

@extends('layouts/layoutMaster')

@section('title', 'Repartidor')

@section('content')
<div class="courier-dashboard">
  @php
    $isActive = $courier && $courier->is_active;
    $isOnline = $isActive && $courier->is_online;
  @endphp
  @if (session('success'))
    <div class="alert alert-success">{{ session('success') }}</div>
  @endif

  <div class="courier-desktop">
    <div class="card mb-3">
      <div class="card-body d-flex align-items-center justify-content-between flex-wrap gap-2">
        <div class="d-flex align-items-center gap-2">
          <i class="icon-base ti tabler-bike"></i>
          <span class="fw-medium">Mis entregas</span>
        </div>
        <div class="d-flex align-items-center gap-2">
          <span class="badge {{ $isActive ? ($isOnline ? 'bg-label-success' : 'bg-label-secondary') : 'bg-label-danger' }}">
            {{ !$isActive ? 'Desactivado' : ($isOnline ? 'En línea' : 'Desconectado') }}
          </span>
          <button class="btn btn-outline-primary btn-sm" type="button" id="enable-alerts-btn">
            Activar alertas
          </button>
          <button class="btn btn-outline-secondary btn-sm d-none" type="button" id="install-app-btn">
            Instalar app
          </button>
        </div>
      </div>
    </div>

    <div class="row g-3">
      <div class="col-lg-4">
        <div class="card h-100">
          <div class="card-body">
            <div class="d-flex align-items-center gap-2 mb-3">
              <button class="btn btn-dark btn-sm rounded-pill">
                Pendiente <span class="badge bg-warning text-dark ms-1">{{ $statusCounts['pending'] }}</span>
              </button>
              <button class="btn btn-label-secondary btn-sm rounded-pill">
                Confirmado <span class="badge bg-info text-white ms-1">{{ $statusCounts['confirmed'] }}</span>
              </button>
              <button class="btn btn-label-secondary btn-sm rounded-pill">
                En restaurante <span class="badge bg-primary text-white ms-1">{{ $statusCounts['at_restaurant'] }}</span>
              </button>
              <button class="btn btn-label-secondary btn-sm rounded-pill">
                En camino <span class="badge bg-primary text-white ms-1">{{ $statusCounts['en_route'] }}</span>
              </button>
              <button class="btn btn-label-secondary btn-sm rounded-pill">
                Entregado <span class="badge bg-success text-white ms-1">{{ $statusCounts['delivered'] }}</span>
              </button>
            </div>

            @php
              $currentDelivery = $pendingDelivery ?? null;
            @endphp
            @if (!$isActive)
              <div class="text-center text-muted py-4">
                El repartidor está desactivado. No puede recibir pedidos.
              </div>
            @elseif (!$isOnline)
              <div class="text-center text-muted py-4">
                Estás desconectado. Activa el estado en línea para recibir pedidos.
              </div>
    @elseif ($currentDelivery)
              <div class="courier-sheet shadow-sm border rounded-3">
                <div class="sheet-header">
                  <h5>Nuevo pedido</h5>
                  <span class="badge bg-label-primary">#{{ $currentDelivery->id }}</span>
                </div>
                <div class="auto-decline" data-assigned-at="{{ ($currentDelivery->assigned_at ?? $currentDelivery->updated_at)->toIso8601String() }}">
                  <span class="auto-decline-text">20 segundos para auto-rechazar</span>
                  <div class="auto-decline-bar"></div>
                </div>
                @php
                  $origin = $currentDelivery->restaurant?->address ?? '';
                  $destination = $currentDelivery->delivery_address ?? '';
                  $navApp = auth()->user()->nav_app ?? 'maps';
                  $navUrl = $navApp === 'waze'
                    ? 'https://waze.com/ul?q=' . urlencode($destination) . '&navigate=yes'
                    : 'https://www.google.com/maps/dir/?api=1&origin=' . urlencode($origin) . '&destination=' . urlencode($destination);
                @endphp
                <div class="sheet-body">
                  <div class="sheet-row">
                    <i class="icon-base ti tabler-building-store"></i>
                    <div>
                      <div class="fw-medium">Recogida</div>
                      <small class="text-muted">{{ $currentDelivery->restaurant?->address ?? 'Restaurante' }}</small>
                    </div>
                    <a class="sheet-nav" href="{{ $navUrl }}" target="_blank" rel="noopener" title="Abrir navegación">
                      <i class="icon-base ti tabler-navigation"></i>
                    </a>
                  </div>
                  <div class="sheet-row">
                    <i class="icon-base ti tabler-map-pin"></i>
                    <div>
                      <div class="fw-medium">Entrega</div>
                      <small class="text-muted">{{ $currentDelivery->delivery_address }}</small>
                    </div>
                    <a class="sheet-nav" href="{{ $navUrl }}" target="_blank" rel="noopener" title="Abrir navegación">
                      <i class="icon-base ti tabler-navigation"></i>
                    </a>
                  </div>
                </div>
                <div class="sheet-actions">
                  <form method="POST" action="{{ route('courier.deliveries.status', $currentDelivery) }}">
                    @csrf
                    <input type="hidden" name="status" value="confirmed" />
                    <button class="btn btn-success w-100" type="submit">Aceptar pedido</button>
                  </form>
                  <div class="reject-wrapper">
                    <button class="btn btn-outline-danger w-100" type="button" data-bs-toggle="dropdown">
                      <i class="icon-base ti tabler-x"></i> Rechazar
                    </button>
                    <div class="dropdown-menu w-100">
                      <button class="dropdown-item" type="button" data-reason="Me encuentro ocupado">Me encuentro ocupado</button>
                      <button class="dropdown-item" type="button" data-reason="Me encuentro lejos">Me encuentro lejos</button>
                    </div>
                  </div>
                </div>
              </div>
            @else
              <div class="text-center text-muted py-4">
                No hay pedidos nuevos por ahora.
              </div>
            @endif
          </div>
        </div>
      </div>

      <div class="col-lg-8">
        <div class="card h-100">
          <div class="card-body">
            <div class="d-flex align-items-center justify-content-between mb-3">
              <h5 class="mb-0">Ubicación</h5>
              <span class="text-muted" id="location-status">Esperando GPS…</span>
            </div>
            <div id="courier-map-desktop" class="courier-map"></div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="courier-mobile">
    <div class="courier-mobile-map">
      <div id="courier-map-mobile"></div>
      <div class="courier-pill">
        <span>Estado</span>
        <strong>{{ !$isActive ? 'Desactivado' : ($isOnline ? 'En línea' : 'Desconectado') }}</strong>
        <span class="dot {{ $isOnline ? 'dot-online' : 'dot-offline' }}"></span>
        <button class="btn btn-icon btn-sm courier-pill-install d-none" type="button" id="install-app-fab" title="Instalar app">
          <i class="icon-base ti tabler-download"></i>
        </button>
        <button class="btn btn-icon btn-sm courier-pill-alert" type="button" id="enable-alerts-fab" title="Activar alertas">
          <i class="icon-base ti tabler-bell"></i>
        </button>
      </div>
    </div>

    @php
      $currentDelivery = $pendingDelivery ?? null;
    @endphp
    @if (false)
      <div class="courier-hint">
        Pedido aceptado. Revisa los detalles en la pestaña <strong>Pedidos</strong>.
      </div>
    @endif

    @if ($isActive && $isOnline && $currentDelivery)
      <div class="courier-sheet">
        <div class="sheet-header">
          <h5>Nuevo pedido</h5>
          <span class="badge bg-label-primary">#{{ $currentDelivery->id }}</span>
        </div>
        <div class="auto-decline" data-assigned-at="{{ ($currentDelivery->assigned_at ?? $currentDelivery->updated_at)->toIso8601String() }}">
          <span class="auto-decline-text">20 segundos para auto-rechazar</span>
          <div class="auto-decline-bar"></div>
        </div>
        @php
          $origin = $currentDelivery->restaurant?->address ?? '';
          $destination = $currentDelivery->delivery_address ?? '';
          $navApp = auth()->user()->nav_app ?? 'maps';
          $navUrl = $navApp === 'waze'
            ? 'https://waze.com/ul?q=' . urlencode($destination) . '&navigate=yes'
            : 'https://www.google.com/maps/dir/?api=1&origin=' . urlencode($origin) . '&destination=' . urlencode($destination);
        @endphp
        <div class="sheet-body">
          <div class="sheet-row">
            <i class="icon-base ti tabler-building-store"></i>
            <div>
              <div class="fw-medium">Recogida</div>
              <small class="text-muted">{{ $currentDelivery->restaurant?->address ?? 'Restaurante' }}</small>
            </div>
            <a class="sheet-nav" href="{{ $navUrl }}" target="_blank" rel="noopener" title="Abrir navegación">
              <i class="icon-base ti tabler-navigation"></i>
            </a>
          </div>
          <div class="sheet-row">
            <i class="icon-base ti tabler-map-pin"></i>
            <div>
              <div class="fw-medium">Entrega</div>
              <small class="text-muted">{{ $currentDelivery->delivery_address }}</small>
            </div>
            <a class="sheet-nav" href="{{ $navUrl }}" target="_blank" rel="noopener" title="Abrir navegación">
              <i class="icon-base ti tabler-navigation"></i>
            </a>
          </div>
        </div>
        <div class="sheet-actions">
          <form method="POST" action="{{ route('courier.deliveries.status', $currentDelivery) }}">
            @csrf
            <input type="hidden" name="status" value="confirmed" />
            <button class="btn btn-success w-100" type="submit">Aceptar pedido</button>
          </form>
          <div class="reject-wrapper">
            <button class="btn btn-outline-danger w-100" type="button" data-bs-toggle="dropdown">
              <i class="icon-base ti tabler-x"></i> Rechazar
            </button>
            <div class="dropdown-menu w-100">
              <button class="dropdown-item" type="button" data-reason="Me encuentro ocupado">Me encuentro ocupado</button>
              <button class="dropdown-item" type="button" data-reason="Me encuentro lejos">Me encuentro lejos</button>
            </div>
          </div>
        </div>
      </div>
    @elseif ($isActive && $isOnline)
      <div class="courier-sheet">
        <div class="sheet-empty">
          <h5>Buscando pedidos…</h5>
          <p class="text-muted mb-0">Activa tu ubicación y espera nuevas entregas.</p>
        </div>
      </div>
    @elseif (!$isActive)
      <div class="courier-sheet">
        <div class="sheet-empty">
          <h5>Cuenta desactivada</h5>
          <p class="text-muted mb-0">Contacta al administrador para habilitar el acceso.</p>
        </div>
      </div>
    @else
      <div class="courier-sheet">
        <div class="sheet-empty">
          <h5>Estás desconectado</h5>
          <p class="text-muted mb-0">Activa el estado en línea para recibir pedidos.</p>
        </div>
      </div>
    @endif

    <nav class="courier-bottom-nav">
      <a class="active" href="{{ route('courier.dashboard') }}">
        <i class="icon-base ti tabler-map"></i>
      </a>
      <a href="{{ route('courier.orders.index') }}">
        <i class="icon-base ti tabler-clipboard-text"></i>
      </a>
      <a href="{{ route('courier.records.index') }}">
        <i class="icon-base ti tabler-history"></i>
      </a>
      <a href="{{ route('courier.profile.edit') }}">
        <i class="icon-base ti tabler-user"></i>
      </a>
    </nav>
  </div>
</div>
@endsection

@section('page-style')
  <style>
    .courier-dashboard {
      min-height: 100vh;
      display: flex;
      flex-direction: column;
    }
    .courier-map {
      height: calc(100vh - 220px);
      border-radius: 14px;
      background: #141622;
    }
    .delivery-list {
      overflow-y: auto;
      padding-right: 4px;
    }
    .delivery-item {
      border: 1px solid rgba(15, 20, 34, 0.08);
      border-radius: 14px;
      padding: 16px;
      background: #fff;
    }
    .courier-mobile {
      display: none;
      min-height: 100vh;
      flex-direction: column;
      padding-bottom: 70px;
      margin: 0;
      height: 100vh;
    }
    .courier-mobile-map {
      position: relative;
      flex: 1 1 auto;
      min-height: 45vh;
      border-radius: 0;
      overflow: hidden;
      background: #f5f5f7;
      margin: 0;
      padding: 0;
      width: 100vw;
    }
    #courier-map-mobile {
      height: 100%;
      width: 100%;
    }
    #courier-map-mobile iframe,
    #courier-map-desktop iframe {
      border: 0;
      width: 100%;
      height: 100%;
    }
    .courier-mobile-map .gm-style,
    .courier-mobile-map .gm-style > div {
      border-radius: 0 !important;
    }
    .courier-mobile-map .gm-style .gm-control-active,
    .courier-mobile-map .gm-style .gmnoprint,
    .courier-mobile-map .gm-style .gm-style-cc,
    .courier-mobile-map .gm-style .gm-fullscreen-control,
    .courier-mobile-map .gm-style .gm-svpc,
    .courier-mobile-map .gm-style .gm-bundled-control {
      display: none !important;
    }
    .courier-pill {
      position: absolute;
      top: 16px;
      left: 50%;
      transform: translateX(-50%);
      background: #fff;
      border-radius: 999px;
      padding: 6px 16px;
      display: flex;
      align-items: center;
      gap: 8px;
      box-shadow: 0 8px 20px rgba(15, 20, 34, 0.15);
      font-weight: 600;
    }
    .courier-pill .dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: #28c76f;
    }
    .courier-pill .dot-online {
      background: #28c76f;
    }
    .courier-pill .dot-offline {
      background: #a8aaae;
    }
    .courier-pill-alert {
      border: none;
      background: #f1f3f5;
      color: #a8aaae;
      width: 28px;
      height: 28px;
      border-radius: 50%;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      padding: 0;
      margin-left: 4px;
    }
    .courier-pill-install {
      border: none;
      background: #f1f3f5;
      color: #5e5f64;
      width: 28px;
      height: 28px;
      border-radius: 50%;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      padding: 0;
      margin-left: 4px;
    }
    .courier-pill-alert i {
      font-size: 14px;
    }
    .courier-pill-alert.is-active {
      background: rgba(40, 199, 111, 0.18);
      color: #28c76f;
    }
    #install-app-btn {
      white-space: nowrap;
    }
    #enable-alerts-btn.is-active {
      border-color: rgba(40, 199, 111, 0.45);
      color: #28c76f;
    }
    .courier-fab {
      position: absolute;
      right: 16px;
      bottom: 16px;
      width: 44px;
      height: 44px;
      border-radius: 50%;
      border: none;
      background: #fff;
      box-shadow: 0 8px 20px rgba(15, 20, 34, 0.2);
      display: inline-flex;
      align-items: center;
      justify-content: center;
    }
    .courier-sheet {
      background: #fff;
      border-radius: 18px 18px 0 0;
      padding: 16px;
      box-shadow: 0 -10px 25px rgba(15, 20, 34, 0.12);
      margin-top: -18px;
      z-index: 5;
      flex: none;
      max-height: 46vh;
      overflow-y: auto;
    }
    .courier-hint {
      margin: -12px 16px 8px;
      background: rgba(40, 199, 111, 0.12);
      color: #1c7f4c;
      border-radius: 12px;
      padding: 10px 14px;
      font-size: 13px;
      text-align: center;
      font-weight: 600;
    }
    .sheet-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;
    }
    .sheet-row {
      display: flex;
      gap: 12px;
      padding: 10px 0;
      border-bottom: 1px solid rgba(15, 20, 34, 0.06);
      align-items: center;
    }
    .sheet-row:last-child {
      border-bottom: none;
    }
    .sheet-actions {
      display: grid;
      grid-template-columns: 1fr;
      gap: 10px;
      margin-top: 12px;
    }
    .auto-decline {
      font-size: 12px;
      color: #6f6b7d;
      margin: 8px 0 12px;
    }
    .auto-decline-bar {
      height: 4px;
      border-radius: 999px;
      background: #28c76f;
      margin-top: 6px;
      width: 100%;
      transition: width 0.25s linear;
    }
    .reject-wrapper .dropdown-menu {
      border-radius: 12px;
      padding: 6px;
    }
    .sheet-nav {
      margin-left: auto;
      width: 34px;
      height: 34px;
      border-radius: 50%;
      border: 1px solid rgba(15, 20, 34, 0.08);
      display: inline-flex;
      align-items: center;
      justify-content: center;
      color: #28c76f;
      text-decoration: none;
      background: #f7f7fb;
    }
    .sheet-empty {
      text-align: center;
      padding: 16px 4px;
    }
    .courier-bottom-nav {
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      background: #fff;
      border-top: 1px solid rgba(15, 20, 34, 0.08);
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      padding: 8px 14px 12px;
      z-index: 20;
    }
    .courier-bottom-nav a {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 2px;
      color: #6f6b7d;
      font-size: 12px;
      text-decoration: none;
    }
    .courier-bottom-nav a i {
      font-size: 20px;
    }
    .courier-bottom-nav a.active {
      color: #28c76f;
      font-weight: 600;
    }
    @media (max-width: 991px) {
      .courier-desktop {
        display: none;
      }
      .courier-mobile {
        display: flex;
      }
      #layout-menu,
      .layout-navbar,
      .layout-menu-toggle,
      .content-footer {
        display: none !important;
      }
      html,
      body {
        height: 100% !important;
      }
      body,
      .layout-wrapper,
      .layout-page,
      .layout-content,
      .content-wrapper,
      .content-wrapper > * {
        margin: 0 !important;
        padding: 0 !important;
        height: 100%;
      }
      .layout-page {
        margin-top: 0 !important;
        padding-top: 0 !important;
      }
      .content-wrapper > .container-xxl,
      .content-wrapper > .container-xl,
      .content-wrapper > .container-lg,
      .content-wrapper > .container-md,
      .content-wrapper > .container-sm,
      .content-wrapper > .container {
        padding-top: 0 !important;
      }
      .layout-content {
        padding: 0 !important;
      }
      .content-wrapper {
        padding: 0 !important;
      }
      .container-p-y {
        padding: 0 !important;
        padding-top: 0 !important;
        padding-bottom: 0 !important;
        padding-block-start: 0 !important;
        padding-block-end: 0 !important;
      }
      .layout-page .content-wrapper .container-p-y:not([class^=pb-], [class*=" pb-"]) {
        padding-block-end: 0 !important;
      }
      .layout-page .content-wrapper .container-p-y:not([class^=pt-], [class*=" pt-"]) {
        padding-block-start: 0 !important;
      }
      .layout-page {
        padding: 0 !important;
      }
      .container-xxl,
      .container-xl,
      .container-lg,
      .container-md,
      .container-sm,
      .container {
        --bs-gutter-x: 0 !important;
        max-width: 100% !important;
        padding: 0 !important;
        margin: 0 !important;
      }
    }
  </style>
@endsection

@section('page-script')
  <script>
    const courierLocationStatus = document.getElementById('location-status');
    let courierMap = null;
    let courierMarker = null;
    let pickupMarker = null;
    let dropoffMarker = null;
    let mapReady = false;

    const currentDelivery = @json($currentDeliveryData);

    function pickMapElement() {
      const mobileEl = document.getElementById('courier-map-mobile');
      const desktopEl = document.getElementById('courier-map-desktop');
      if (mobileEl && mobileEl.offsetParent && mobileEl.clientWidth > 0 && mobileEl.clientHeight > 0) {
        return mobileEl;
      }
      if (desktopEl && desktopEl.offsetParent && desktopEl.clientWidth > 0 && desktopEl.clientHeight > 0) {
        return desktopEl;
      }
      return mobileEl || desktopEl;
    }

    function initCourierMapInternal() {
      const mapEl = pickMapElement();
      if (!mapEl || !window.google) {
        return;
      }
      if (mapEl.clientWidth === 0 || mapEl.clientHeight === 0) {
        setTimeout(initCourierMapInternal, 150);
        return;
      }
      courierMap = new google.maps.Map(mapEl, {
        center: { lat: 42.2673, lng: 2.9617 },
        zoom: 13,
        mapTypeControl: false,
        fullscreenControl: false,
        streetViewControl: false,
        zoomControl: false,
        rotateControl: false,
        scaleControl: false,
        gestureHandling: 'greedy',
      });
      google.maps.event.addListenerOnce(courierMap, 'tilesloaded', () => {
        mapReady = true;
      });
      google.maps.event.addListenerOnce(courierMap, 'idle', () => {
        google.maps.event.trigger(courierMap, 'resize');
      });
      setTimeout(() => {
        if (courierMap) {
          google.maps.event.trigger(courierMap, 'resize');
          courierMap.setCenter(courierMap.getCenter());
        }
      }, 500);

      updateRouteMarkers(currentDelivery);
    }

    function centerOnCourier() {
      if (courierMap && courierMarker) {
        courierMap.setCenter(courierMarker.getPosition());
      }
    }

    function updateRouteMarkers(delivery) {
      if (!courierMap || !delivery) {
        return;
      }
      const pickupLat = delivery?.pickup?.lat;
      const pickupLng = delivery?.pickup?.lng;
      const dropLat = delivery?.dropoff?.lat;
      const dropLng = delivery?.dropoff?.lng;

      if (pickupLat && pickupLng) {
        const pos = { lat: parseFloat(pickupLat), lng: parseFloat(pickupLng) };
        if (!pickupMarker) {
          pickupMarker = new google.maps.Marker({ map: courierMap, position: pos, label: 'P' });
        } else {
          pickupMarker.setPosition(pos);
        }
      }
      if (dropLat && dropLng) {
        const pos = { lat: parseFloat(dropLat), lng: parseFloat(dropLng) };
        if (!dropoffMarker) {
          dropoffMarker = new google.maps.Marker({ map: courierMap, position: pos, label: 'D' });
        } else {
          dropoffMarker.setPosition(pos);
        }
      }
      if (pickupLat && pickupLng && dropLat && dropLng) {
        const bounds = new google.maps.LatLngBounds();
        bounds.extend({ lat: parseFloat(pickupLat), lng: parseFloat(pickupLng) });
        bounds.extend({ lat: parseFloat(dropLat), lng: parseFloat(dropLng) });
        courierMap.fitBounds(bounds);
      }
    }

    function updateLocation() {
      if (!navigator.geolocation) {
        setFallbackLocation();
        return;
      }

      navigator.geolocation.getCurrentPosition((position) => {
        const lat = position.coords.latitude;
        const lng = position.coords.longitude;

        if (courierLocationStatus) {
          courierLocationStatus.textContent = 'Ubicación actualizada';
        }

        if (courierMap) {
          const pos = { lat, lng };
          if (!courierMarker) {
            courierMarker = new google.maps.Marker({ map: courierMap, position: pos });
          } else {
            courierMarker.setPosition(pos);
          }
          courierMap.setCenter(pos);
        }

        fetch('{{ route('courier.location.store') }}', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
          },
          body: JSON.stringify({ lat, lng }),
        }).catch(() => {});
      }, () => {
        setFallbackLocation();
      });
    }

    function setFallbackLocation() {
      const lat = 42.2673;
      const lng = 2.9617;
      if (courierLocationStatus) {
        courierLocationStatus.textContent = 'Ubicación simulada (Figueres)';
      }

      if (courierMap) {
        const pos = { lat, lng };
        if (!courierMarker) {
          courierMarker = new google.maps.Marker({ map: courierMap, position: pos });
        } else {
          courierMarker.setPosition(pos);
        }
        courierMap.setCenter(pos);
      }

      fetch('{{ route('courier.location.store') }}', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
        },
        body: JSON.stringify({ lat, lng }),
      }).catch(() => {});
    }

    (function loadCourierMapScript() {
      if (window.google && window.google.maps) {
        initCourierMapInternal();
        updateLocation();
        setInterval(updateLocation, 120000);
        setTimeout(showMapFallback, 3000);
        return;
      }
      const script = document.createElement('script');
      script.src = 'https://maps.googleapis.com/maps/api/js?key={{ config('services.google.maps_key') ?: env('GOOGLE_MAPS_API_KEY') }}&loading=async&callback=initCourierMap';
      script.async = true;
      script.defer = true;
      window.initCourierMap = function () {
        initCourierMapInternal();
        updateLocation();
        setInterval(updateLocation, 120000);
        setTimeout(showMapFallback, 3000);
      };
      document.head.appendChild(script);
    })();

    function showMapFallback() {
      if (mapReady) {
        return;
      }
      const mapEl = pickMapElement();
      if (!mapEl) {
        return;
      }
      if (document.getElementById('courier-map-fallback')) {
        return;
      }
      const iframe = document.createElement('iframe');
      iframe.id = 'courier-map-fallback';
      iframe.loading = 'lazy';
      iframe.src = 'https://www.google.com/maps?q=Figueres,Spain&z=13&output=embed';
      mapEl.innerHTML = '';
      mapEl.appendChild(iframe);
    }

    window.addEventListener('resize', () => {
      if (courierMap) {
        google.maps.event.trigger(courierMap, 'resize');
      }
    });
    window.addEventListener('orientationchange', () => {
      if (courierMap) {
        google.maps.event.trigger(courierMap, 'resize');
      }
    });

    (function initRejectionFlow() {
      const deliveryId = {{ $currentDelivery?->id ?? 'null' }};
      if (!deliveryId) {
        return;
      }

      const autoDeclineEls = Array.from(document.querySelectorAll('.auto-decline'));
      if (!autoDeclineEls.length) {
        return;
      }

      const assignedAtRaw = autoDeclineEls[0].getAttribute('data-assigned-at');
      const assignedAt = assignedAtRaw ? Date.parse(assignedAtRaw) : Date.now();
      const elapsedSeconds = Math.floor((Date.now() - assignedAt) / 1000);
      let remaining = Math.max(0, 20 - elapsedSeconds);
      let interval = null;
      let rejected = false;

      const updateUi = () => {
        const percent = Math.max(0, (remaining / 20) * 100);
        autoDeclineEls.forEach((el) => {
          const countdownEl = el.querySelector('.auto-decline-text');
          const barEl = el.querySelector('.auto-decline-bar');
          if (countdownEl) {
            countdownEl.textContent = `${remaining} segundos para auto-rechazar`;
          }
          if (barEl) {
            barEl.style.width = `${percent}%`;
          }
        });
      };

      const tick = () => {
        remaining -= 1;
        updateUi();
        if (remaining <= 0) {
          rejectDelivery('timeout');
        }
      };

      if (remaining <= 0) {
        rejectDelivery('timeout');
        return;
      }

      updateUi();
      interval = setInterval(tick, 1000);

      document.querySelectorAll('.dropdown-item[data-reason]').forEach((item) => {
        item.addEventListener('click', () => {
          const reason = item.getAttribute('data-reason');
          rejectDelivery(reason);
        });
      });

      function rejectDelivery(reason) {
        if (rejected) {
          return;
        }
        rejected = true;
        if (interval) {
          clearInterval(interval);
        }
        fetch('{{ route('courier.deliveries.reject', $currentDelivery ?? 0) }}', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
          },
          body: JSON.stringify({ reason }),
        }).then(() => {
          window.location.reload();
        }).catch(() => {
          window.location.reload();
        });
      }
    })();

    (function initCourierAlerts() {
      const currentDeliveryId = {{ $pendingDelivery?->id ?? 'null' }};
      const lastDeliveryId = localStorage.getItem('courier_last_delivery_id');
      const enableBtn = document.getElementById('enable-alerts-btn');
      const enableFab = document.getElementById('enable-alerts-fab');
      const installBtn = document.getElementById('install-app-btn');
      const installFab = document.getElementById('install-app-fab');
      const alertsKey = 'courier_alerts_enabled';
      let deferredInstallPrompt = null;
      let loopTimer = null;

      const setAlertUi = (enabled) => {
        const method = enabled ? 'add' : 'remove';
        if (enableBtn) enableBtn.classList[method]('is-active');
        if (enableFab) enableFab.classList[method]('is-active');
        if (enableBtn) enableBtn.textContent = enabled ? 'Alertas activas' : 'Activar alertas';
        if (enableFab) enableFab.title = enabled ? 'Alertas activas' : 'Activar alertas';
      };

      setAlertUi(localStorage.getItem(alertsKey) === '1');

      const setInstallUi = (available) => {
        const method = available ? 'remove' : 'add';
        if (installBtn) installBtn.classList[method]('d-none');
        if (installFab) installFab.classList[method]('d-none');
      };

      const isStandalone = () => {
        return window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone === true;
      };

      const unlockAudio = () => {
        try {
          const ctx = new (window.AudioContext || window.webkitAudioContext)();
          const osc = ctx.createOscillator();
          const gain = ctx.createGain();
          osc.type = 'square';
          osc.frequency.value = 880;
          gain.gain.value = 0.0001;
          osc.connect(gain);
          gain.connect(ctx.destination);
          osc.start();
          osc.stop(ctx.currentTime + 0.02);
          ctx.resume().then(() => {
            localStorage.setItem('courier_audio_unlocked', '1');
            localStorage.setItem(alertsKey, '1');
            setAlertUi(true);
          }).catch(() => {});
        } catch (e) {}
      };

      const requestNotifications = async () => {
        if (!('Notification' in window)) return;
        if (Notification.permission === 'default') {
          try {
            await Notification.requestPermission();
          } catch (e) {}
        }
      };

      const urlBase64ToUint8Array = (base64String) => {
        const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
        const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
        const rawData = window.atob(base64);
        const outputArray = new Uint8Array(rawData.length);
        for (let i = 0; i < rawData.length; ++i) {
          outputArray[i] = rawData.charCodeAt(i);
        }
        return outputArray;
      };

      const registerPush = async () => {
        if (!('serviceWorker' in navigator) || !('PushManager' in window)) return;
        const publicKey = '{{ config('webpush.vapid.public_key') }}';
        if (!publicKey) return;

        const registration = await navigator.serviceWorker.register('/service-worker.js');
        let subscription = await registration.pushManager.getSubscription();
        if (!subscription) {
          subscription = await registration.pushManager.subscribe({
            userVisibleOnly: true,
            applicationServerKey: urlBase64ToUint8Array(publicKey),
          });
        }

        await fetch('{{ route('courier.push.subscribe') }}', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name=\"csrf-token\"]').content,
          },
          body: JSON.stringify(subscription),
        });
      };

      const playAlertSound = () => {
        if (localStorage.getItem('courier_audio_unlocked') !== '1') {
          return;
        }
        try {
          const ctx = new (window.AudioContext || window.webkitAudioContext)();
          const osc = ctx.createOscillator();
          const gain = ctx.createGain();
          osc.type = 'square';
          osc.frequency.value = 880;
          gain.gain.value = 0.08;
          osc.connect(gain);
          gain.connect(ctx.destination);
          osc.start();
          osc.stop(ctx.currentTime + 0.35);
        } catch (e) {}
      };

      const startAlertLoop = (maxMs) => {
        if (loopTimer) {
          clearInterval(loopTimer);
          loopTimer = null;
        }
        const endAt = Date.now() + (maxMs || 20000);
        const tick = () => {
          if (localStorage.getItem(alertsKey) !== '1') return;
          if (Date.now() >= endAt) {
            clearInterval(loopTimer);
            loopTimer = null;
            return;
          }
          playAlertSound();
          if (navigator.vibrate) {
            try { navigator.vibrate([80, 60, 80]); } catch (e) {}
          }
        };
        tick();
        loopTimer = setInterval(tick, 2000);
      };

      const showNotification = () => {
        if (!('Notification' in window)) return;
        if (Notification.permission !== 'granted') return;
        new Notification('Nuevo pedido', {
          body: 'Tienes un pedido pendiente por aceptar.',
          icon: '{{ asset('assets/img/favicon/favicon.ico') }}',
          tag: currentDeliveryId ? ('delivery-' + String(currentDeliveryId)) : 'courier-new-order',
        });
      };

      const enableAlerts = async () => {
        unlockAudio();
        await requestNotifications();
        if (Notification.permission === 'granted') {
          registerPush();
        }
      };

      const disableAlerts = async () => {
        localStorage.setItem(alertsKey, '0');
        setAlertUi(false);
        if (loopTimer) {
          clearInterval(loopTimer);
          loopTimer = null;
        }
        if (!('serviceWorker' in navigator) || !('PushManager' in window)) return;
        try {
          const registration = await navigator.serviceWorker.getRegistration();
          if (!registration) return;
          const subscription = await registration.pushManager.getSubscription();
          if (!subscription) return;
          await fetch('{{ route('courier.push.unsubscribe') }}', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-CSRF-TOKEN': document.querySelector('meta[name=\"csrf-token\"]').content,
            },
            body: JSON.stringify(subscription),
          });
          await subscription.unsubscribe();
        } catch (e) {}
      };

      const toggleAlerts = () => {
        const enabled = localStorage.getItem(alertsKey) === '1';
        if (enabled) {
          disableAlerts();
        } else {
          enableAlerts();
        }
      };

      if (enableBtn) enableBtn.addEventListener('click', () => toggleAlerts());
      if (enableFab) enableFab.addEventListener('click', () => toggleAlerts());

      // PWA install prompt (Android/Chrome). Hidden unless the browser provides an install event.
      setInstallUi(false);
      window.addEventListener('beforeinstallprompt', (e) => {
        e.preventDefault();
        deferredInstallPrompt = e;
        if (!isStandalone()) {
          setInstallUi(true);
        }
      });
      const promptInstall = async () => {
        if (!deferredInstallPrompt) return;
        try {
          deferredInstallPrompt.prompt();
          await deferredInstallPrompt.userChoice;
        } catch (e) {}
        deferredInstallPrompt = null;
        setInstallUi(false);
      };
      if (installBtn) installBtn.addEventListener('click', promptInstall);
      if (installFab) installFab.addEventListener('click', promptInstall);

      if (Notification.permission === 'granted' && localStorage.getItem(alertsKey) === '1') {
        registerPush();
      }

      if (currentDeliveryId && String(currentDeliveryId) !== String(lastDeliveryId)) {
        playAlertSound();
        const assignedEl = document.querySelector('.auto-decline[data-assigned-at]');
        const assignedAtRaw = assignedEl ? assignedEl.getAttribute('data-assigned-at') : null;
        const assignedAt = assignedAtRaw ? Date.parse(assignedAtRaw) : Date.now();
        const elapsedMs = Math.max(0, Date.now() - assignedAt);
        const remainingMs = Math.max(0, 20000 - elapsedMs);
        if (localStorage.getItem(alertsKey) === '1') {
          startAlertLoop(remainingMs);
        }
        showNotification();
        localStorage.setItem('courier_last_delivery_id', String(currentDeliveryId));
      }
    })();
  </script>
@endsection
