<?php
$pageConfigs = ['navbarType' => 'static', 'contentLayout' => 'wide'];
$configData = Helper::appClasses();
$statusMap = [
  'pending' => ['Pendiente', 'warning', 10],
  'confirmed' => ['Confirmado', 'info', 30],
  'at_restaurant' => ['Confirmado', 'info', 45],
  'en_route' => ['En camino', 'primary', 80],
  'delivered' => ['Entregado', 'success', 100],
  'cancelled' => ['Cancelado', 'danger', 0],
];
$confirmedTotal = ($statusCounts['confirmed'] ?? 0) + ($statusCounts['at_restaurant'] ?? 0);
?>



<?php $__env->startSection('title', 'Operativa'); ?>

<?php $__env->startSection('page-style'); ?>
<?php echo app('Illuminate\Foundation\Vite')('resources/assets/vendor/scss/pages/app-logistics-fleet.scss'); ?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/intl-tel-input@24.5.0/build/css/intlTelInput.css">
<style>
  html,
  body {
    height: 100%;
    margin: 0;
  }

  body.restaurant-fleet-page .layout-page,
  body.restaurant-fleet-page .layout-content,
  body.restaurant-fleet-page .content-wrapper {
    height: 100%;
    padding: 0 !important;
  }

  html.layout-menu-fixed body.restaurant-fleet-page .layout-page,
  html.layout-menu-fixed-offcanvas body.restaurant-fleet-page .layout-page {
    padding-inline-start: var(--bs-menu-width) !important;
  }

  html.layout-menu-fixed.layout-menu-collapsed body.restaurant-fleet-page .layout-page,
  html.layout-menu-fixed-offcanvas.layout-menu-collapsed body.restaurant-fleet-page .layout-page {
    padding-inline-start: var(--bs-menu-collapsed-width) !important;
  }

  body.restaurant-fleet-page .content-footer {
    display: none;
  }

  body.restaurant-fleet-page .layout-page::before {
    display: none !important;
  }

  body.restaurant-fleet-page .content-wrapper > .container-xxl,
  body.restaurant-fleet-page .content-wrapper > .container-fluid,
  body.restaurant-fleet-page .content-wrapper > .container,
  body.restaurant-fleet-page .container-xxl,
  body.restaurant-fleet-page .container-fluid,
  body.restaurant-fleet-page .container {
    padding: 0 !important;
    margin: 0 !important;
    max-width: 100% !important;
  }

  body.restaurant-fleet-page .container-p-y {
    padding-block: 0 !important;
  }

  body.restaurant-fleet-page .card {
    margin: 0;
    border-radius: 0;
  }

  /* Navbar is in normal flow on this page; keep the map filling the remaining viewport height. */
  body.restaurant-fleet-page .app-logistics-fleet-wrapper {
    block-size: calc(100vh - 4.75rem);
  }

  body.restaurant-fleet-page .logistics-fleet-sidebar-body {
    block-size: calc(100vh - 9rem);
  }

  /* Ensure the detached navbar stays centered/nice like other pages. */
  body.restaurant-fleet-page .layout-navbar.navbar-detached {
    margin: 0.75rem 1rem 0;
    border-radius: 12px;
  }

  @media (min-width: 992px) {
    body.restaurant-fleet-page .app-logistics-fleet-sidebar {
      flex: 0 0 33.333%;
      inline-size: 33.333%;
      max-inline-size: 36rem;
      min-inline-size: 20rem;
    }

    body.restaurant-fleet-page .map-container {
      flex: 1 1 66.667%;
      inline-size: 66.667%;
    }
  }

  body.restaurant-fleet-page .gm-fullscreen-control,
  body.restaurant-fleet-page .gm-svpc,
  body.restaurant-fleet-page .gm-control-active,
  body.restaurant-fleet-page .gm-style-mtc,
  body.restaurant-fleet-page .gmnoprint,
  body.restaurant-fleet-page .gm-bundled-control,
  body.restaurant-fleet-page .gm-control-container {
    display: none !important;
  }

  body.restaurant-fleet-page .offcanvas .iti {
    width: 100%;
  }

  body.restaurant-fleet-page .offcanvas .iti__country-list {
    width: 100%;
    max-height: 240px;
  }

  body.restaurant-fleet-page .offcanvas .iti {
    display: block;
  }

  body.restaurant-fleet-page .offcanvas .iti input[type="tel"] {
    width: 100% !important;
    pointer-events: auto;
    position: relative;
    z-index: 1;
  }

  body.restaurant-fleet-page .offcanvas gmp-place-autocomplete,
  body.restaurant-fleet-page .offcanvas .pac-container,
  body.restaurant-fleet-page .offcanvas .pac-item,
  body.restaurant-fleet-page .offcanvas .pac-item-query {
    color: #4b465c !important;
  }

  body.restaurant-fleet-page .offcanvas gmp-place-autocomplete {
    color-scheme: light;
    --gmp-omnibox-text-color: #4b465c;
    --gmp-omnibox-border-color: #d9dbe7;
    --gmp-omnibox-background-color: #fff;
    --gmp-omnibox-placeholder-color: #b2b0c4;
    --gmp-omnibox-focus-border-color: #696cff;
    --gmp-omnibox-shadow: 0 4px 16px rgba(34, 48, 62, 0.12);
    --gmp-omnibox-results-background-color: #fff;
    --gmp-omnibox-results-text-color: #4b465c;
    --gmp-omnibox-results-border-color: #e6e6f0;
  }

  body.restaurant-fleet-page .offcanvas gmp-place-autocomplete::part(input) {
    background: #fff;
    color: #4b465c;
    border-color: #d9dbe7;
  }

  body.restaurant-fleet-page .offcanvas gmp-place-autocomplete::part(listbox),
  body.restaurant-fleet-page .offcanvas gmp-place-autocomplete::part(results) {
    background: #fff;
    color: #4b465c;
  }

  body.restaurant-fleet-page .offcanvas gmp-place-autocomplete::part(option) {
    color: #4b465c;
  }

  body.restaurant-fleet-page .offcanvas gmp-place-autocomplete {
    border: 1px solid #e0e2ee;
    border-radius: 10px;
    padding: 4px 10px;
    background: #fff;
  }

  .restaurant-mobile {
    display: none;
    min-height: 100vh;
    background: #f6f7fb;
    padding: 18px 18px 88px;
    width: 100%;
    text-align: left;
    position: fixed;
    inset: 0;
    overflow-y: auto;
    max-width: 100vw;
    margin: 0;
    transform: none;
  }
  .restaurant-mobile-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    margin-bottom: 18px;
    width: 100%;
  }
  .restaurant-mobile-header > div {
    text-align: left;
  }
  .restaurant-mobile-body {
    display: none;
  }
  .restaurant-mobile-body.active {
    display: block;
  }
  .mobile-hero-card {
    background: #fff;
    border-radius: 20px;
    padding: 18px;
    box-shadow: 0 10px 25px rgba(15, 20, 34, 0.08);
    display: grid;
    place-items: center;
    min-height: 280px;
    width: 100%;
  }
  .mobile-urgent-wrap {
    display: grid;
    place-items: center;
    gap: 14px;
    text-align: center;
  }
  .mobile-urgent-btn {
    width: 190px;
    height: 190px;
    border: none;
    background: transparent;
    position: relative;
    padding: 0;
  }
  @media (max-width: 360px) {
    .mobile-urgent-btn {
      width: 160px;
      height: 160px;
    }
    .mobile-urgent-btn .urgent-core {
      inset: 14px;
      font-size: 30px;
    }
  }
  .mobile-urgent-btn .urgent-ring {
    position: absolute;
    inset: 0;
    border-radius: 50%;
    border: 3px solid rgba(255, 159, 67, 0.6);
    box-shadow: 0 12px 30px rgba(255, 159, 67, 0.2);
  }
  .mobile-urgent-btn .urgent-core {
    position: absolute;
    inset: 18px;
    border-radius: 50%;
    background: #fff7ef;
    display: grid;
    place-items: center;
    color: #ff9f43;
    font-size: 36px;
    box-shadow: inset 0 0 0 1px rgba(255, 159, 67, 0.2);
  }
  .mobile-urgent-btn.is-searching .urgent-ring {
    border-color: rgba(255, 159, 67, 0.9);
    box-shadow: 0 12px 30px rgba(255, 159, 67, 0.35);
    animation: pulseOrange 1.6s infinite;
  }
  .mobile-urgent-btn.is-searching .urgent-core {
    background: #fff4e8;
    color: #ff9f43;
  }
  .mobile-urgent-btn.is-confirmed .urgent-ring {
    border-color: rgba(40, 199, 111, 0.7);
    box-shadow: 0 12px 30px rgba(40, 199, 111, 0.25);
    animation: pulseGreen 1.6s infinite;
  }
  .mobile-urgent-btn.is-confirmed .urgent-core {
    background: #ecfbf3;
    color: #28c76f;
  }
  .urgent-status-line {
    display: flex;
    align-items: center;
    gap: 6px;
  }
  .urgent-dots {
    display: inline-flex;
    gap: 4px;
  }
  .urgent-dots span {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: #ff9f43;
    opacity: 0.35;
    animation: urgentDot 1.2s infinite ease-in-out;
  }
  .urgent-dots span:nth-child(2) { animation-delay: .2s; }
  .urgent-dots span:nth-child(3) { animation-delay: .4s; }
  @keyframes pulseOrange {
    0% { transform: scale(1); opacity: .6; }
    70% { transform: scale(1.08); opacity: 0; }
    100% { opacity: 0; }
  }
  @keyframes pulseGreen {
    0% { transform: scale(1); opacity: .6; }
    70% { transform: scale(1.08); opacity: 0; }
    100% { opacity: 0; }
  }
  @keyframes urgentDot {
    0%, 100% { transform: translateY(0); opacity: 0.35; }
    50% { transform: translateY(-4px); opacity: 1; }
  }
  .mobile-quick-actions {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
    margin-top: 16px;
    width: 100%;
  }
  .mobile-last-order {
    margin-top: 14px;
    background: #fff;
    border-radius: 18px;
    padding: 14px;
    border: 1px solid rgba(15, 20, 34, 0.06);
    box-shadow: 0 10px 24px rgba(15, 20, 34, 0.06);
  }
  .mobile-last-order .last-order-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    margin-bottom: 8px;
  }
  .mobile-last-order .last-order-meta {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
  }
  .mobile-last-order .last-order-link {
    border: none;
    background: transparent;
    padding: 0;
    color: #7367f0;
    font-weight: 600;
    font-size: 13px;
  }
  .quick-item {
    background: #fff;
    border-radius: 16px;
    padding: 14px;
    display: flex;
    gap: 12px;
    align-items: center;
    box-shadow: 0 8px 20px rgba(15, 20, 34, 0.06);
  }
  .quick-icon {
    width: 42px;
    height: 42px;
    border-radius: 12px;
    display: grid;
    place-items: center;
    font-size: 18px;
  }
  .mobile-status-tabs {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 8px;
    margin-bottom: 16px;
  }
  .status-pill {
    border: none;
    background: #fff;
    color: #4b465c;
    border-radius: 999px;
    padding: 8px 6px;
    font-weight: 600;
    box-shadow: 0 6px 16px rgba(15, 20, 34, 0.06);
  }
  .status-pill.active {
    background: #1f2231;
    color: #fff;
  }
  .mobile-orders-list {
    display: grid;
    gap: 12px;
  }
  .mobile-order-card {
    background: #fff;
    border-radius: 16px;
    padding: 14px;
    border: 1px solid rgba(15, 20, 34, 0.06);
    cursor: pointer;
  }
  .mobile-order-card:hover {
    border-color: rgba(115, 103, 240, 0.22);
    box-shadow: 0 10px 24px rgba(15, 20, 34, 0.07);
  }
  .mobile-order-screen {
    position: fixed;
    inset: 0;
    background: #fff;
    z-index: 2000;
    display: none;
    flex-direction: column;
  }
  .mobile-order-screen.active {
    display: flex;
  }
  .mobile-order-screen-header {
    position: sticky;
    top: 0;
    z-index: 1;
    background: #fff;
    padding: 12px 14px;
    border-bottom: 1px solid rgba(15, 20, 34, 0.08);
    display: grid;
    grid-template-columns: 40px 1fr 40px;
    align-items: center;
    gap: 10px;
  }
  .mobile-order-screen-title {
    text-align: center;
    font-weight: 700;
    color: #1f2231;
    font-size: 16px;
  }
  .mobile-order-screen-body {
    padding: 14px;
    overflow: auto;
    -webkit-overflow-scrolling: touch;
    flex: 1;
  }
  .mobile-order-screen-card {
    background: #fff;
    border-radius: 16px;
    padding: 14px;
    border: 1px solid rgba(15, 20, 34, 0.06);
    box-shadow: 0 10px 24px rgba(15, 20, 34, 0.06);
    margin-bottom: 12px;
  }
  body.mobile-order-screen-open {
    overflow: hidden !important;
    touch-action: none;
  }
  .mobile-profile-card {
    background: #fff;
    border-radius: 18px;
    padding: 16px;
    display: flex;
    gap: 12px;
    align-items: center;
    margin-bottom: 16px;
  }
  .mobile-profile-card .profile-avatar {
    width: 54px;
    height: 54px;
    border-radius: 14px;
    background: #ffe6ec;
    color: #eb3d63;
    display: grid;
    place-items: center;
    font-weight: 700;
    font-size: 20px;
  }
  .mobile-profile-meta {
    background: #fff;
    border-radius: 18px;
    padding: 16px;
    display: grid;
    gap: 12px;
    margin-bottom: 16px;
  }
  .mobile-profile-actions {
    display: grid;
    gap: 10px;
  }
  .restaurant-mobile-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(3, 1fr);
    padding: 10px 16px 14px;
    z-index: 100;
  }
  .restaurant-mobile-nav .nav-item {
    border: none;
    background: transparent;
    color: #6f6b7d;
    font-size: 20px;
  }
  .restaurant-mobile-nav .nav-item.active {
    color: #eb3d63;
  }
  @media (max-width: 991px) {
    .restaurant-desktop {
      display: none;
    }
    .restaurant-mobile {
      display: block;
    }
    /* "Version rapida": hide Vuexy chrome (navbar/menu) to avoid overlapping the custom UI. */
    body.restaurant-fleet-page:not(.restaurant-show-desktop) #layout-menu,
    body.restaurant-fleet-page:not(.restaurant-show-desktop) .layout-navbar,
    body.restaurant-fleet-page:not(.restaurant-show-desktop) .layout-menu-toggle,
    body.restaurant-fleet-page:not(.restaurant-show-desktop) .layout-overlay,
    body.restaurant-fleet-page:not(.restaurant-show-desktop) .drag-target,
    body.restaurant-fleet-page:not(.restaurant-show-desktop) .content-footer {
      display: none !important;
    }

    /* We also remove extra padding/margins in both modes. */
    body.restaurant-fleet-page .layout-page,
    body.restaurant-fleet-page .content-wrapper,
    body.restaurant-fleet-page .content-wrapper > .container-xxl,
    body.restaurant-fleet-page .content-wrapper > .container-fluid,
    body.restaurant-fleet-page .content-wrapper > .container {
      padding: 0 !important;
      margin: 0 !important;
      max-width: 100% !important;
    }
    body.restaurant-fleet-page .layout-page {
      padding-inline-start: 0 !important;
    }
    /* "Version completa" (Vuexy responsive + our full panel) */
    body.restaurant-show-desktop .restaurant-desktop {
      display: block;
    }
    body.restaurant-show-desktop .restaurant-mobile {
      display: none;
    }
    body.restaurant-show-desktop .layout-page,
    body.restaurant-show-desktop .content-wrapper,
    body.restaurant-show-desktop .content-wrapper > .container-xxl,
    body.restaurant-show-desktop .content-wrapper > .container-fluid,
    body.restaurant-show-desktop .content-wrapper > .container {
      padding: 0 !important;
      margin: 0 !important;
      max-width: 100% !important;
    }
    body.restaurant-show-desktop .layout-page {
      padding-inline-start: 0 !important;
      padding-left: 0 !important;
      margin-left: 0 !important;
      width: 100% !important;
    }
    html.layout-menu-fixed body.restaurant-show-desktop .layout-page,
    html.layout-menu-fixed-offcanvas body.restaurant-show-desktop .layout-page {
      padding-inline-start: 0 !important;
    }
    body.restaurant-show-desktop .restaurant-desktop,
    body.restaurant-show-desktop .app-logistics-fleet-wrapper {
      width: 100% !important;
      max-width: 100% !important;
    }
    body.restaurant-show-desktop .app-logistics-fleet-wrapper {
      overflow: hidden;
    }
  }
  @media (min-width: 992px) {
    body.restaurant-force-mobile .restaurant-desktop {
      display: none;
    }
    body.restaurant-force-mobile .restaurant-mobile {
      display: block;
    }
    body.restaurant-force-mobile #layout-menu,
    body.restaurant-force-mobile .layout-navbar,
    body.restaurant-force-mobile .layout-menu-toggle,
    body.restaurant-force-mobile .content-footer {
      display: none !important;
    }
    body.restaurant-force-mobile .layout-page,
    body.restaurant-force-mobile .content-wrapper,
    body.restaurant-force-mobile .content-wrapper > .container-xxl,
    body.restaurant-force-mobile .content-wrapper > .container-fluid,
    body.restaurant-force-mobile .content-wrapper > .container {
      padding: 0 !important;
      margin: 0 !important;
      max-width: 100% !important;
    }
    body.restaurant-force-mobile .layout-page {
      padding-inline-start: 0 !important;
    }
  }

</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div id="restaurant-fleet-root" class="card overflow-hidden restaurant-desktop" data-maps-key="<?php echo e(config('services.google.maps_key') ?: env('GOOGLE_MAPS_API_KEY')); ?>">
  <div class="d-flex app-logistics-fleet-wrapper">
    <div class="flex-shrink-0 position-fixed m-6 d-md-none w-auto z-1">
      <button class="btn btn-icon btn-white btn-white-dark-variant z-2" data-bs-toggle="sidebar" data-overlay data-target="#app-logistics-fleet-sidebar" aria-label="Abrir panel de pedidos">
        <i class="icon-base ti tabler-menu icon-md"></i>
      </button>
    </div>

    <div class="app-logistics-fleet-sidebar col h-100" id="app-logistics-fleet-sidebar">
      <div class="card-header border-0 pt-6 pb-1">
        <div class="d-flex justify-content-end gap-2 flex-wrap mt-1" data-header-stats>
          <div class="d-flex align-items-center gap-2 px-3 py-2 rounded bg-label-primary text-primary fw-medium">
            <i class="icon-base ti tabler-wallet"></i>
            €<?php echo e(number_format($restaurant?->wallet_balance ?? 0, 2)); ?>

          </div>
          <div class="d-flex align-items-center gap-2 px-3 py-2 rounded bg-label-secondary text-secondary fw-medium">
            <i class="icon-base ti tabler-currency-euro"></i>
            €<?php echo e(number_format($restaurant?->delivery_fee ?? 0, 2)); ?>

          </div>
          <button class="btn btn-label-secondary btn-sm" type="button" data-view-toggle="mobile" title="Versión rápida">
            <i class="icon-base ti tabler-device-mobile me-1"></i> Versión rápida
          </button>
          <form method="POST" action="<?php echo e(route('logout')); ?>">
            <?php echo csrf_field(); ?>
            <button class="btn btn-label-danger btn-icon" type="submit" title="Cerrar sesión">
              <i class="icon-base ti tabler-logout"></i>
            </button>
          </form>
        </div>
        <div class="d-flex justify-content-between align-items-center gap-3 mt-3" data-header-actions>
          <button class="btn btn-warning btn-sm px-3 flex-grow-1 w-50" type="button" data-bs-toggle="offcanvas" data-bs-target="#urgentCanvas">
            <i class="icon-base ti tabler-bolt"></i> Urgente
          </button>
          <button class="btn btn-danger btn-sm px-3 flex-grow-1 w-50" type="button" data-bs-toggle="offcanvas" data-bs-target="#createTaskCanvas">
            <i class="icon-base ti tabler-plus"></i> Crear
          </button>
        </div>
        <i class="icon-base ti tabler-x icon-xs cursor-pointer close-sidebar d-md-none d-block btn btn-sm btn-icon p-0" data-bs-toggle="sidebar" data-overlay data-target="#app-logistics-fleet-sidebar"></i>
      </div>

      <div class="card-body p-0 logistics-fleet-sidebar-body">
        <div class="d-flex flex-wrap align-items-center gap-2 mb-3 mt-3 px-4" id="status-tabs">
          <button class="btn btn-dark btn-sm rounded-pill flex-grow-1 w-100" type="button" data-status="pending">
            Pendiente <span class="badge bg-warning text-dark ms-1"><?php echo e($statusCounts['pending']); ?></span>
          </button>
          <button class="btn btn-label-secondary btn-sm rounded-pill flex-grow-1 w-100" type="button" data-status="confirmed">
            Confirmado <span class="badge bg-info text-white ms-1"><?php echo e($confirmedTotal); ?></span>
          </button>
          <button class="btn btn-label-secondary btn-sm rounded-pill flex-grow-1 w-100" type="button" data-status="en_route">
            En camino <span class="badge bg-primary text-white ms-1"><?php echo e($statusCounts['en_route']); ?></span>
          </button>
          <button class="btn btn-label-secondary btn-sm rounded-pill flex-grow-1 w-100" type="button" data-status="delivered">
            Entregado <span class="badge bg-success text-white ms-1"><?php echo e($statusCounts['delivered']); ?></span>
          </button>
        </div>

        <div id="delivery-list" class="accordion py-2 px-1">
          <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__empty_1 = true; $__currentLoopData = $deliveries; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $delivery): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
            <?php
              [$statusLabel, $statusColor, $progress] = $statusMap[$delivery->status] ?? ['Pendiente', 'warning', 20];
              $courierName = $delivery->courier?->name ?? 'Sin asignar';
              $courierStatusLabel = match ($delivery->status) {
                'pending' => 'Buscando repartidor',
                'confirmed' => 'Repartidor confirmado',
                'at_restaurant' => 'Repartidor confirmado',
                'en_route' => 'En camino',
                'delivered' => 'Entregado',
                'cancelled' => 'Cancelado',
                default => 'En espera',
              };
              $courierStatusColor = match ($delivery->status) {
                'pending' => 'warning',
                'confirmed' => 'info',
                'at_restaurant' => 'info',
                'en_route' => 'primary',
                'delivered' => 'success',
                'cancelled' => 'danger',
                default => 'secondary',
              };
              $courierStatusNote = match (true) {
                $delivery->courier_id && $delivery->status === 'at_restaurant' => 'Rider en el restaurante',
                $delivery->courier_id && $delivery->status === 'confirmed' => 'Rider en camino al restaurante',
                default => null,
              };
            ?>
            <div class="accordion-item border-0 mb-0 shadow-none delivery-item"
              data-status="<?php echo e($delivery->status); ?>"
              data-delivery-id="<?php echo e($delivery->id); ?>"
              data-pickup-lat="<?php echo e($delivery->restaurant?->lat); ?>"
              data-pickup-lng="<?php echo e($delivery->restaurant?->lng); ?>"
              data-dropoff-lat="<?php echo e($delivery->delivery_lat); ?>"
              data-dropoff-lng="<?php echo e($delivery->delivery_lng); ?>"
              data-pickup-address="<?php echo e($delivery->restaurant?->address); ?>"
              data-dropoff-address="<?php echo e($delivery->delivery_address); ?>">
              <div class="accordion-header" id="fleet-<?php echo e($delivery->id); ?>">
                <div role="button" class="accordion-button shadow-none align-items-center collapsed" data-delivery-toggle>
                  <div class="d-flex align-items-center w-100">
                    <div class="avatar-wrapper">
                      <div class="avatar me-4">
                        <span class="avatar-initial rounded-circle bg-label-<?php echo e($statusColor); ?> w-px-40 h-px-40">
                          <i class="icon-base ti tabler-bike icon-lg"></i>
                        </span>
                      </div>
                    </div>
                    <span class="d-flex flex-column gap-1">
                      <span class="text-heading">#<?php echo e($delivery->id); ?> · <?php echo e($delivery->customer_name); ?></span>
                      <span class="text-body"><?php echo e($delivery->delivery_address); ?></span>
                      <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($courierStatusNote): ?>
                        <span class="text-success small d-flex align-items-center gap-1">
                          <i class="icon-base ti tabler-building-store"></i>
                          <?php echo e($courierStatusNote); ?>

                        </span>
                      <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                    </span>
                    <span class="ms-auto badge bg-label-<?php echo e($courierStatusColor); ?>"><?php echo e($courierStatusLabel); ?></span>
                  </div>
                </div>
              </div>
            </div>
          <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
            <div class="text-center text-muted py-4">
              No hay entregas todavía.
            </div>
          <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
        </div>

        <div id="delivery-detail" class="d-none px-4 py-3">
          <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__currentLoopData = $deliveries; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $delivery): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            <?php
              [$statusLabel, $statusColor, $progress] = $statusMap[$delivery->status] ?? ['Pendiente', 'warning', 20];
              $courierName = $delivery->courier?->name ?? 'Sin asignar';
            ?>
            <div class="delivery-detail-panel d-none" data-delivery-panel="<?php echo e($delivery->id); ?>">
              <div class="d-flex align-items-center gap-2 mb-3">
                <button type="button" class="btn btn-icon btn-label-secondary btn-sm" data-detail-back>
                  <i class="icon-base ti tabler-arrow-left"></i>
                </button>
                <div>
                  <h6 class="mb-0">Entrega #<?php echo e($delivery->id); ?></h6>
                  <small class="text-muted"><?php echo e($statusLabel); ?></small>
                </div>
              </div>
              <div class="card border-0 shadow-sm mb-3">
                <div class="card-body">
                  <div class="d-flex align-items-center justify-content-between mb-2">
                    <span class="text-muted">Cliente</span>
                    <span class="fw-medium"><?php echo e($delivery->customer_name); ?></span>
                  </div>
                  <div class="d-flex align-items-center justify-content-between mb-2">
                    <span class="text-muted">Teléfono</span>
                    <span class="fw-medium"><?php echo e($delivery->customer_phone ?? '-'); ?></span>
                  </div>
                  <div class="d-flex align-items-start justify-content-between mb-2">
                    <span class="text-muted">Dirección</span>
                    <span class="fw-medium text-end"><?php echo e($delivery->delivery_address); ?></span>
                  </div>
                  <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($delivery->delivery_address_extra): ?>
                    <div class="d-flex align-items-start justify-content-between mb-2">
                      <span class="text-muted">Adicional</span>
                      <span class="fw-medium text-end"><?php echo e($delivery->delivery_address_extra); ?></span>
                    </div>
                  <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                  <div class="d-flex align-items-center justify-content-between">
                    <span class="text-muted">Repartidor</span>
                    <span class="fw-medium"><?php echo e($courierName); ?></span>
                  </div>
                </div>
              </div>
              <div class="card border-0 shadow-sm">
                <div class="card-body">
                  <div class="d-flex align-items-center justify-content-between">
                    <h6 class="fw-normal mb-1">Estado</h6>
                    <p class="text-body mb-1"><?php echo e($statusLabel); ?></p>
                  </div>
                  <div class="progress" style="height: 6px;">
                    <div class="progress-bar bg-<?php echo e($statusColor); ?>" role="progressbar" style="width: <?php echo e($progress); ?>%;" aria-valuenow="<?php echo e($progress); ?>" aria-valuemin="0" aria-valuemax="100"></div>
                  </div>
                  <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($delivery->status === 'at_restaurant'): ?>
                    <div class="text-success small d-flex align-items-center gap-1 mt-2">
                      <i class="icon-base ti tabler-building-store"></i>
                      Rider en el restaurante
                    </div>
                  <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                  <ul class="timeline ps-4 mt-4 mb-0">
                    <li class="timeline-item ps-6 pb-3 border-dashed">
                      <span class="timeline-indicator-advanced timeline-indicator-success border-0 shadow-none">
                        <i class="icon-base ti tabler-circle-check"></i>
                      </span>
                      <div class="timeline-event ps-0 pb-0">
                        <div class="timeline-header">
                          <small class="text-success text-uppercase">pedido creado</small>
                        </div>
                        <h6 class="my-50"><?php echo e($delivery->restaurant?->name ?? 'Restaurante'); ?></h6>
                        <small class="text-body"><?php echo e($delivery->created_at->format('d/m/Y H:i')); ?></small>
                      </div>
                    </li>
                    <li class="timeline-item ps-6 pb-3 border-dashed">
                      <span class="timeline-indicator-advanced timeline-indicator-primary border-0 shadow-none">
                        <i class="icon-base ti tabler-bike"></i>
                      </span>
                      <div class="timeline-event ps-0 pb-0">
                        <div class="timeline-header">
                          <small class="text-primary text-uppercase">repartidor</small>
                        </div>
                        <h6 class="my-50"><?php echo e($courierName); ?></h6>
                        <small class="text-body"><?php echo e($delivery->status === 'pending' ? 'En espera' : 'Asignado'); ?></small>
                      </div>
                    </li>
                    <li class="timeline-item ps-6 border-transparent">
                      <span class="timeline-indicator-advanced timeline-indicator-<?php echo e($statusColor); ?> border-0 shadow-none">
                        <i class="icon-base ti tabler-map-pin mt-1"></i>
                      </span>
                      <div class="timeline-event ps-0 pb-0">
                        <div class="timeline-header">
                          <small class="text-<?php echo e($statusColor); ?> text-uppercase fw-medium">entrega</small>
                        </div>
                        <h6 class="my-50"><?php echo e($delivery->delivery_address); ?></h6>
                        <small class="text-body"><?php echo e($delivery->status === 'delivered' ? 'Entregado' : 'En curso'); ?></small>
                      </div>
                    </li>
                  </ul>
                  <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($delivery->status === 'pending'): ?>
                    <form class="mt-3" method="POST" action="<?php echo e(route('restaurant.deliveries.reassign', $delivery)); ?>">
                      <?php echo csrf_field(); ?>
                      <button class="btn btn-outline-primary btn-sm w-100" type="submit">Reasignar pedido</button>
                    </form>
                  <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </div>
              </div>
            </div>
          <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
        </div>
      </div>
    </div>

    <div class="col h-100 map-container">
      <div id="restaurant-map" class="h-100 w-100"></div>
    </div>

    <div class="app-overlay d-none"></div>
  </div>
</div>

<div class="restaurant-mobile" data-maps-key="<?php echo e(config('services.google.maps_key') ?: env('GOOGLE_MAPS_API_KEY')); ?>">
  <div class="restaurant-mobile-header">
    <div>
      <div class="text-muted small">Operativa</div>
      <h4 class="mb-0"><?php echo e($restaurant?->name ?? 'Restaurante'); ?></h4>
    </div>
    <button class="btn btn-danger btn-icon" type="button" data-bs-toggle="offcanvas" data-bs-target="#createTaskCanvas" title="Crear tarea">
      <i class="icon-base ti tabler-plus"></i>
    </button>
  </div>

  <div class="restaurant-mobile-body" data-section="home">
    <div class="mobile-hero-card">
      <div class="mobile-urgent-wrap">
        <button
          class="mobile-urgent-btn"
          type="button"
          data-bs-toggle="offcanvas"
          data-bs-target="#urgentCanvas"
          aria-label="Solicitar rider urgente"
          data-last-urgent-status="<?php echo e($latestUrgent?->status ?? ''); ?>"
          data-last-urgent-id="<?php echo e($latestUrgent?->id ?? ''); ?>"
        >
          <div class="urgent-ring"></div>
          <div class="urgent-core">
            <i class="icon-base ti tabler-moped"></i>
          </div>
        </button>
        <div class="mobile-urgent-label">
          <div class="text-muted small">Solicitar repartidor</div>
          <h5 class="mb-1">Rider urgente</h5>
          <p class="text-muted mb-0 urgent-status-line" data-label>
            <span data-urgent-text>Solicitar rider</span>
            <span class="urgent-dots d-none" data-urgent-dots>
              <span></span><span></span><span></span>
            </span>
          </p>
        </div>
      </div>
    </div>

    <div class="mobile-quick-actions">
      <div class="quick-item">
        <div class="quick-icon bg-label-primary text-primary">
          <i class="icon-base ti tabler-wallet"></i>
        </div>
        <div>
          <div class="text-muted small">Saldo</div>
          <div class="fw-semibold">€<?php echo e(number_format($restaurant?->wallet_balance ?? 0, 2)); ?></div>
        </div>
      </div>
      <div class="quick-item">
        <div class="quick-icon bg-label-secondary text-secondary">
          <i class="icon-base ti tabler-currency-euro"></i>
        </div>
        <div>
          <div class="text-muted small">Costo entrega</div>
          <div class="fw-semibold">€<?php echo e(number_format($restaurant?->delivery_fee ?? 0, 2)); ?></div>
        </div>
      </div>
    </div>

    <?php
      $last = $latestDelivery ?? (($allDeliveries ?? collect())->first());
      $lastLabel = $last ? ($statusMap[$last->status][0] ?? 'Pendiente') : null;
      $lastBadge = $last ? ($statusMap[$last->status][1] ?? 'secondary') : 'secondary';
      $lastAgo = $last?->created_at ? $last->created_at->locale('es')->diffForHumans() : null;
      $hasCourier = $last && $last->courier;
      $courierLine = $hasCourier ? ($last->courier->name ?? 'Repartidor asignado') : 'Sin repartidor';
      $courierStatus = $hasCourier
        ? ($last && $last->status === 'at_restaurant' ? 'Rider en el restaurante' : 'Repartidor en camino')
        : ($last && $last->status === 'pending' ? 'Buscando repartidor' : 'Sin asignar');
    ?>
    <div class="mobile-last-order" data-last-order>
      <div class="last-order-top">
        <div class="fw-semibold">Ultimo pedido</div>
        <button class="last-order-link" type="button" data-section-jump="orders">Ver ordenes</button>
      </div>
      <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($last): ?>
        <div class="last-order-meta">
          <span class="badge bg-label-<?php echo e($lastBadge); ?>" data-last-status><?php echo e($lastLabel); ?></span>
          <span class="text-muted small" data-last-id>#<?php echo e($last->id); ?></span>
          <span class="text-muted small" data-last-time><?php echo e(optional($last->created_at)->format('H:i')); ?></span>
          <span class="badge bg-label-warning <?php echo e($last->is_urgent ? '' : 'd-none'); ?>" data-last-urgent>Urgente</span>
        </div>
        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($lastAgo): ?>
          <div class="text-muted small mt-1" data-last-ago>
            Tu ultimo pedido solicitado fue <?php echo e($lastAgo); ?>.
          </div>
        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
        <div class="mt-2">
          <div class="fw-semibold" data-last-customer><?php echo e($last->customer_name ?? 'Por definir'); ?></div>
          <div class="text-muted small" data-last-address><?php echo e($last->delivery_address ?? 'Por definir'); ?></div>
        </div>
        <div class="mt-2">
          <div class="fw-semibold" data-last-courier><?php echo e($courierLine); ?></div>
          <div class="text-muted small" data-last-courier-status><?php echo e($courierStatus); ?></div>
        </div>
      <?php else: ?>
        <div class="text-muted small" data-last-empty>Aun no has solicitado ningun servicio hoy.</div>
      <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
    </div>
  </div>

  <div class="restaurant-mobile-body" data-section="orders">
    <div class="mobile-status-tabs">
      <button class="status-pill active" type="button" data-status="pending">Pendiente (<?php echo e($statusCounts['pending']); ?>)</button>
      <button class="status-pill" type="button" data-status="confirmed">Confirmado (<?php echo e($confirmedTotal); ?>)</button>
      <button class="status-pill" type="button" data-status="en_route">En camino (<?php echo e($statusCounts['en_route']); ?>)</button>
      <button class="status-pill" type="button" data-status="delivered">Entregado (<?php echo e($statusCounts['delivered']); ?>)</button>
    </div>
    <div class="mobile-orders-list">
      <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__empty_1 = true; $__currentLoopData = $allDeliveries ?? collect(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $delivery): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
        <div
          class="mobile-order-card"
          data-status="<?php echo e($delivery->status); ?>"
          data-delivery-id="<?php echo e($delivery->id); ?>"
          data-created-at="<?php echo e(optional($delivery->created_at)->format('d/m/Y H:i')); ?>"
          data-customer-name="<?php echo e($delivery->customer_name ?? 'Por definir'); ?>"
          data-customer-phone="<?php echo e($delivery->customer_phone ?: '-'); ?>"
          data-delivery-address="<?php echo e($delivery->delivery_address ?? 'Por definir'); ?>"
          data-delivery-extra="<?php echo e($delivery->delivery_address_extra ?? ''); ?>"
          data-courier-name="<?php echo e($delivery->courier?->name ?? 'Sin asignar'); ?>"
          data-payment-method="<?php echo e($delivery->payment_method === 'cash' ? 'Efectivo' : 'Wallet'); ?>"
          data-fee="€<?php echo e(number_format($delivery->delivery_fee ?? 0, 2)); ?>"
          data-is-urgent="<?php echo e($delivery->is_urgent ? '1' : '0'); ?>"
          data-notes="<?php echo e($delivery->notes ?? ''); ?>"
        >
          <div class="d-flex justify-content-between align-items-start">
            <div>
              <div class="fw-semibold">#<?php echo e($delivery->id); ?> · <?php echo e($delivery->customer_name ?? 'Por definir'); ?></div>
              <div class="text-muted small"><?php echo e($delivery->delivery_address ?? 'Por definir'); ?></div>
            </div>
            <span class="badge bg-label-<?php echo e($statusMap[$delivery->status][1] ?? 'secondary'); ?>"><?php echo e($statusMap[$delivery->status][0] ?? 'Pendiente'); ?></span>
          </div>
          <div class="d-flex justify-content-between align-items-center mt-2">
            <span class="text-muted small"><?php echo e(optional($delivery->created_at)->format('d/m/Y H:i')); ?></span>
            <span class="text-muted small"><?php echo e($delivery->is_urgent ? 'Urgente' : 'Normal'); ?></span>
          </div>
        </div>
      <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
        <div class="text-center text-muted py-4">No hay pedidos hoy.</div>
      <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
    </div>
  </div>

  <div class="restaurant-mobile-body" data-section="profile">
    <div class="mobile-profile-card">
      <div class="profile-avatar"><?php echo e(strtoupper(substr($restaurant?->name ?? 'R', 0, 1))); ?></div>
      <div>
        <div class="fw-semibold"><?php echo e($restaurant?->name ?? 'Restaurante'); ?></div>
        <div class="text-muted small"><?php echo e($restaurant?->address ?? 'Sin dirección'); ?></div>
      </div>
    </div>
    <div class="mobile-profile-meta">
      <div>
        <div class="text-muted small">Zona</div>
        <div class="fw-semibold"><?php echo e($restaurant?->zone?->name ?? 'No asignada'); ?></div>
      </div>
      <div>
        <div class="text-muted small">Contacto</div>
        <div class="fw-semibold"><?php echo e($restaurant?->contact_name ?? 'Sin contacto'); ?></div>
      </div>
      <div>
        <div class="text-muted small">Teléfono</div>
        <div class="fw-semibold"><?php echo e($restaurant?->phone ?? 'Sin teléfono'); ?></div>
      </div>
      <div>
        <div class="text-muted small">Email</div>
        <div class="fw-semibold"><?php echo e($restaurant?->email ?? 'Sin email'); ?></div>
      </div>
    </div>
    <div class="mobile-profile-actions">
      <button class="btn btn-outline-dark w-100" type="button" data-view-toggle="desktop" data-view-label>Versión completa</button>
      <form method="POST" action="<?php echo e(route('logout')); ?>" class="w-100">
        <?php echo csrf_field(); ?>
        <button class="btn btn-label-danger w-100" type="submit">
          <i class="icon-base ti tabler-logout me-1"></i> Cerrar sesión
        </button>
      </form>
    </div>
  </div>

  <nav class="restaurant-mobile-nav">
    <button class="nav-item active" type="button" data-section-target="home">
      <i class="icon-base ti tabler-bolt"></i>
    </button>
    <button class="nav-item" type="button" data-section-target="orders">
      <i class="icon-base ti tabler-clipboard-text"></i>
    </button>
    <button class="nav-item" type="button" data-section-target="profile">
      <i class="icon-base ti tabler-user"></i>
    </button>
  </nav>
</div>

<!-- Pantalla: detalles de pedido (versión rápida) -->
<div class="mobile-order-screen" id="mobileOrderScreen" aria-hidden="true">
  <div class="mobile-order-screen-header">
    <button type="button" class="btn btn-icon btn-label-secondary btn-sm" data-order-screen-back aria-label="Volver">
      <i class="icon-base ti tabler-arrow-left"></i>
    </button>
    <div class="mobile-order-screen-title" id="mobileOrderScreenTitle">Entrega</div>
    <div></div>
  </div>

  <div class="mobile-order-screen-body">
    <div class="mobile-order-screen-card">
      <div class="d-flex align-items-center justify-content-between mb-2">
        <span class="badge bg-label-secondary" id="mobileOrderScreenStatus">Estado</span>
        <span class="text-muted small" id="mobileOrderScreenCreatedAt">--</span>
      </div>

      <div class="mb-3">
        <div class="text-muted small">Cliente</div>
        <div class="fw-semibold" id="mobileOrderScreenCustomer">--</div>
        <div class="text-muted small" id="mobileOrderScreenPhone">--</div>
      </div>

      <div class="mb-3">
        <div class="text-muted small">Entrega</div>
        <div class="fw-semibold" id="mobileOrderScreenAddress">--</div>
        <div class="text-muted small" id="mobileOrderScreenExtra" style="display:none;"></div>
      </div>

      <div class="mb-3">
        <div class="text-muted small">Repartidor</div>
        <div class="fw-semibold" id="mobileOrderScreenCourier">--</div>
      </div>

      <div class="mb-0">
        <div class="text-muted small">Pago</div>
        <div class="fw-semibold" id="mobileOrderScreenPayment">--</div>
        <div class="text-muted small" id="mobileOrderScreenFee">--</div>
      </div>
    </div>

    <div class="mobile-order-screen-card" id="mobileOrderScreenNotesWrap" style="display:none;">
      <div class="text-muted small">Notas</div>
      <div id="mobileOrderScreenNotes"></div>
    </div>
  </div>
</div>

<div class="offcanvas offcanvas-end" tabindex="-1" id="createTaskCanvas">
  <div class="offcanvas-header">
    <h5 class="offcanvas-title">Nueva entrega</h5>
    <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
  </div>
  <div class="offcanvas-body">
    <form method="POST" action="<?php echo e(route('restaurant.deliveries.store')); ?>">
      <?php echo csrf_field(); ?>
      <div class="mb-3">
        <label class="form-label">Nombre del cliente</label>
        <input class="form-control" name="customer_name" placeholder="Ej. Juan Pérez" required />
      </div>
      <div class="mb-3">
        <input class="form-control" id="delivery-phone" name="customer_phone" type="tel" placeholder="600 000 000" />
      </div>
      <div class="mb-3">
        <label class="form-label">Dirección de entrega</label>
        <div id="delivery-address-autocomplete"
          data-zone-lat="<?php echo e($restaurant?->zone?->center_lat); ?>"
          data-zone-lng="<?php echo e($restaurant?->zone?->center_lng); ?>"
          data-zone-radius="<?php echo e($restaurant?->zone?->radius_km); ?>"></div>
        <input type="hidden" id="delivery-address" name="delivery_address" required />
        <input type="hidden" id="delivery-lat" name="delivery_lat" />
        <input type="hidden" id="delivery-lng" name="delivery_lng" />
      </div>
      <div class="mb-3">
        <label class="form-label">Dirección adicional (opcional)</label>
        <input class="form-control" name="delivery_address_extra" placeholder="Piso, puerta, indicaciones" />
      </div>
      <div class="mb-3">
        <label class="form-label">Forma de pago</label>
        <div class="d-flex gap-3">
          <div class="form-check">
            <input class="form-check-input" type="radio" name="payment_method" id="pay-cash" value="cash" checked>
            <label class="form-check-label" for="pay-cash">Efectivo</label>
          </div>
          <div class="form-check">
            <input class="form-check-input" type="radio" name="payment_method" id="pay-wallet" value="wallet">
            <label class="form-check-label" for="pay-wallet">Wallet</label>
          </div>
        </div>
        <div class="form-text">
          Se cobrará €<?php echo e(number_format($restaurant?->delivery_fee ?? 0, 2)); ?> por entrega.
        </div>
      </div>
      <div class="mb-3">
        <label class="form-label">Notas para el repartidor</label>
        <textarea class="form-control" name="notes" rows="3"></textarea>
      </div>
      <button class="btn btn-primary w-100" type="submit">Crear tarea</button>
    </form>
  </div>
</div>

<div class="offcanvas offcanvas-end" tabindex="-1" id="urgentCanvas">
  <div class="offcanvas-header">
    <h5 class="offcanvas-title">Pedir repartidor urgente</h5>
    <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
  </div>
  <div class="offcanvas-body">
    <div class="alert alert-warning">
      Un repartidor llegará al restaurante con urgencia. El repartidor completará los datos del cliente al llegar.
    </div>
    <form method="POST" action="<?php echo e(route('restaurant.deliveries.urgent')); ?>">
      <?php echo csrf_field(); ?>
      <div class="mb-3">
        <label class="form-label">Forma de pago</label>
        <div class="d-flex gap-3">
          <div class="form-check">
            <input class="form-check-input" type="radio" name="payment_method" id="urgent-pay-cash" value="cash" checked>
            <label class="form-check-label" for="urgent-pay-cash">Efectivo</label>
          </div>
          <div class="form-check">
            <input class="form-check-input" type="radio" name="payment_method" id="urgent-pay-wallet" value="wallet">
            <label class="form-check-label" for="urgent-pay-wallet">Wallet</label>
          </div>
        </div>
        <div class="form-text">
          Se cobrará €<?php echo e(number_format($restaurant?->delivery_fee ?? 0, 2)); ?> por entrega.
        </div>
      </div>
      <div class="mb-3">
        <label class="form-label">Notas (opcional)</label>
        <textarea class="form-control" name="notes" rows="3" placeholder="Instrucciones para el repartidor"></textarea>
      </div>
      <button class="btn btn-warning w-100" type="submit">
        Solicitar repartidor urgente
      </button>
    </form>
  </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('page-script'); ?>
  <script src="https://cdn.jsdelivr.net/npm/intl-tel-input@24.5.0/build/js/intlTelInput.min.js"></script>
  <script>
    document.body.classList.add('restaurant-fleet-page');

    (function initRestaurantTabs() {
      const tabs = document.getElementById('status-tabs');
      if (!tabs) return;
      const statusStorageKey = 'restaurant_status_tab';
      const buttons = tabs.querySelectorAll('[data-status]');
      const items = document.querySelectorAll('.delivery-item[data-status]');
      const detail = document.getElementById('delivery-detail');
      const list = document.getElementById('delivery-list');
      const headerStats = document.querySelector('[data-header-stats]');
      const headerActions = document.querySelector('[data-header-actions]');

      const setActive = (status) => {
        buttons.forEach((btn) => {
          btn.classList.toggle('btn-dark', btn.dataset.status === status);
          btn.classList.toggle('btn-label-secondary', btn.dataset.status !== status);
        });
        items.forEach((item) => {
          const matches = status === 'confirmed'
            ? (item.dataset.status === 'confirmed' || item.dataset.status === 'at_restaurant')
            : item.dataset.status === status;
          item.style.display = matches ? '' : 'none';
        });
        if (detail && list) {
          detail.classList.add('d-none');
          list.classList.remove('d-none');
        }
        if (headerStats) headerStats.classList.remove('d-none');
        if (headerActions) headerActions.classList.remove('d-none');
        if (tabs) tabs.classList.remove('d-none');
        if (window.__restaurantSetMapStatus) {
          window.__restaurantSetMapStatus(status);
        }

        Array.from(items).find((item) => item.dataset.status === status);
      };

      buttons.forEach((btn) => {
        btn.addEventListener('click', () => {
          const nextStatus = btn.dataset.status;
          setActive(nextStatus);
          localStorage.setItem(statusStorageKey, nextStatus);
        });
      });

      const savedStatus = localStorage.getItem(statusStorageKey) || 'pending';
      const hasSaved = Array.from(buttons).some((btn) => btn.dataset.status === savedStatus);
      setActive(hasSaved ? savedStatus : 'pending');
    })();

    (function initDeliveryToggles() {
      const toggles = document.querySelectorAll('[data-delivery-toggle]');
      const detail = document.getElementById('delivery-detail');
      const list = document.getElementById('delivery-list');
      const headerStats = document.querySelector('[data-header-stats]');
      const headerActions = document.querySelector('[data-header-actions]');
      const tabs = document.getElementById('status-tabs');
      if (!toggles.length) return;
      toggles.forEach((toggle) => {
        toggle.addEventListener('click', () => {
          const item = toggle.closest('.delivery-item');
          if (!item) return;
          const deliveryId = item.dataset.deliveryId;
          if (!deliveryId || !detail || !list) return;
          list.classList.add('d-none');
          detail.classList.remove('d-none');
          if (headerStats) headerStats.classList.add('d-none');
          if (headerActions) headerActions.classList.add('d-none');
          if (tabs) tabs.classList.add('d-none');
          detail.querySelectorAll('[data-delivery-panel]').forEach((panel) => {
            panel.classList.toggle('d-none', panel.dataset.deliveryPanel !== deliveryId);
          });

          if (window.__restaurantShowDelivery) {
            window.__restaurantShowDelivery({
              pickupLat: item.dataset.pickupLat,
              pickupLng: item.dataset.pickupLng,
              dropoffLat: item.dataset.dropoffLat,
              dropoffLng: item.dataset.dropoffLng,
              pickupAddress: item.dataset.pickupAddress,
              dropoffAddress: item.dataset.dropoffAddress,
            });
          }
        });
      });

      document.querySelectorAll('[data-detail-back]').forEach((btn) => {
        btn.addEventListener('click', () => {
          if (!detail || !list) return;
          detail.classList.add('d-none');
          list.classList.remove('d-none');
          if (headerStats) headerStats.classList.remove('d-none');
          if (headerActions) headerActions.classList.remove('d-none');
          if (tabs) tabs.classList.remove('d-none');
        });
      });
    })();

    window.initRestaurantDashboardMap = async function initRestaurantDashboardMap() {
      const mapEl = document.getElementById('restaurant-map');
      const addressContainer = document.getElementById('delivery-address-autocomplete');
      const addressInput = document.getElementById('delivery-address');
      const latInput = document.getElementById('delivery-lat');
      const lngInput = document.getElementById('delivery-lng');
      const phoneInput = document.getElementById('delivery-phone');
      const phoneValueInput = document.getElementById('delivery-phone-value');

      if (!mapEl) {
        return;
      }

      const restaurantLat = <?php echo e($restaurant?->lat ?? 'null'); ?>;
      const restaurantLng = <?php echo e($restaurant?->lng ?? 'null'); ?>;
      const fallbackCenter = {
        lat: restaurantLat || 42.2673,
        lng: restaurantLng || 2.9617
      };

      const map = new google.maps.Map(mapEl, {
        center: fallbackCenter,
        zoom: 12,
        disableDefaultUI: true,
        zoomControl: false,
        mapTypeControl: false,
        streetViewControl: false,
        fullscreenControl: false,
      });
      window.__restaurantMap = map;

      if (restaurantLat && restaurantLng) {
        window.__restaurantPickupMarker = new google.maps.Marker({
          map,
          position: { lat: restaurantLat, lng: restaurantLng },
          label: 'R',
        });
      }

      const deliveries = <?php echo json_encode($deliveriesForMap, 15, 512) ?>;
      const statusMarkers = { pending: [], confirmed: [], at_restaurant: [], en_route: [], delivered: [], cancelled: [] };

      deliveries.forEach((delivery) => {
        if (!delivery.lat || !delivery.lng) {
          return;
        }
        const marker = new google.maps.Marker({
          map,
          position: { lat: parseFloat(delivery.lat), lng: parseFloat(delivery.lng) },
        });
        const status = delivery.status || 'pending';
        if (!statusMarkers[status]) {
          statusMarkers[status] = [];
        }
        statusMarkers[status].push(marker);
      });

      const setMapStatus = (status) => {
        Object.entries(statusMarkers).forEach(([key, markers]) => {
          const shouldShow = status === 'confirmed'
            ? (key === 'confirmed' || key === 'at_restaurant')
            : key === status;
          markers.forEach((marker) => {
            marker.setMap(shouldShow ? map : null);
          });
        });
      };

      setMapStatus('pending');
      window.__restaurantSetMapStatus = setMapStatus;
      window.__restaurantShowDelivery = (delivery) => {
        if (!delivery || !window.__restaurantMap) return;
        const pickupLat = parseFloat(delivery.pickupLat);
        const pickupLng = parseFloat(delivery.pickupLng);
        const dropoffLat = parseFloat(delivery.dropoffLat);
        const dropoffLng = parseFloat(delivery.dropoffLng);

        if (!Number.isNaN(pickupLat) && !Number.isNaN(pickupLng)) {
          if (!window.__restaurantPickupMarker) {
            window.__restaurantPickupMarker = new google.maps.Marker({
              map,
              position: { lat: pickupLat, lng: pickupLng },
              label: 'R',
            });
          } else {
            window.__restaurantPickupMarker.setMap(map);
            window.__restaurantPickupMarker.setPosition({ lat: pickupLat, lng: pickupLng });
          }
        } else if (window.__restaurantPickupMarker) {
          window.__restaurantPickupMarker.setMap(null);
        }

        if (!Number.isNaN(dropoffLat) && !Number.isNaN(dropoffLng)) {
          if (!window.__restaurantDropoffMarker) {
            window.__restaurantDropoffMarker = new google.maps.Marker({
              map,
              position: { lat: dropoffLat, lng: dropoffLng },
              label: 'D',
            });
          } else {
            window.__restaurantDropoffMarker.setMap(map);
            window.__restaurantDropoffMarker.setPosition({ lat: dropoffLat, lng: dropoffLng });
          }
        } else if (window.__restaurantDropoffMarker) {
          window.__restaurantDropoffMarker.setMap(null);
        }

        if (!Number.isNaN(pickupLat) && !Number.isNaN(pickupLng) && !Number.isNaN(dropoffLat) && !Number.isNaN(dropoffLng)) {
          const bounds = new google.maps.LatLngBounds();
          bounds.extend({ lat: pickupLat, lng: pickupLng });
          bounds.extend({ lat: dropoffLat, lng: dropoffLng });
          map.fitBounds(bounds, 80);
        } else if (!Number.isNaN(dropoffLat) && !Number.isNaN(dropoffLng)) {
          map.setCenter({ lat: dropoffLat, lng: dropoffLng });
          map.setZoom(14);
        }
      };

      if (addressContainer && addressInput) {
        const zoneLat = parseFloat(addressContainer.dataset.zoneLat);
        const zoneLng = parseFloat(addressContainer.dataset.zoneLng);
        const zoneRadiusKm = parseFloat(addressContainer.dataset.zoneRadius) || 8;

        let bounds = null;
        if (!Number.isNaN(zoneLat) && !Number.isNaN(zoneLng)) {
          const zoneCircle = new google.maps.Circle({
            center: { lat: zoneLat, lng: zoneLng },
            radius: zoneRadiusKm * 1000,
          });
          bounds = zoneCircle.getBounds();
        }

        const { PlaceAutocompleteElement } = await google.maps.importLibrary('places');
        const placeAutocomplete = new PlaceAutocompleteElement({});
        placeAutocomplete.setAttribute('placeholder', 'Calle, número, ciudad');
        placeAutocomplete.includedRegionCodes = ['es'];
        if (bounds) {
          placeAutocomplete.locationRestriction = bounds;
        }
        addressContainer.appendChild(placeAutocomplete);

        placeAutocomplete.addEventListener('gmp-select', async (event) => {
          const placePrediction = event.placePrediction;
          const place = placePrediction.toPlace();
          await place.fetchFields({ fields: ['formattedAddress', 'location'] });

          if (!place.location) {
            return;
          }

          latInput.value = place.location.lat();
          lngInput.value = place.location.lng();
          addressInput.value = place.formattedAddress || '';
          map.setCenter(place.location);
          map.setZoom(14);
          new google.maps.Marker({
            map,
            position: place.location,
          });
        });
      }

      if (window.__deliveryPhoneInit) {
        window.__deliveryPhoneInit();
      }
    };

    (function loadRestaurantDashboardMaps() {
      if (window.google && window.google.maps) {
        return;
      }
      const mapsKeyFromData = document.getElementById('restaurant-fleet-root')?.dataset.mapsKey
        || document.querySelector('.restaurant-mobile')?.dataset.mapsKey;
      const mapsKey = mapsKeyFromData || <?php echo json_encode(config('services.google.maps_key') ?: env('GOOGLE_MAPS_API_KEY'), 15, 512) ?>;
      if (!mapsKey) {
        console.warn('Google Maps API key missing. Set GOOGLE_MAPS_API_KEY and clear config cache.');
        return;
      }
      const script = document.createElement('script');
      script.src = `https://maps.googleapis.com/maps/api/js?key=${mapsKey}&libraries=places&loading=async&callback=initRestaurantDashboardMap`;
      script.async = true;
      script.defer = true;
      document.head.appendChild(script);
    })();

    (function initDeliveryPhone() {
      const phoneInput = document.getElementById('delivery-phone');
      if (!phoneInput) return;
      if (phoneInput.dataset.phoneInit === 'true') return;

      const tryInit = () => {
        if (!window.intlTelInput) {
          setTimeout(tryInit, 200);
          return;
        }

        phoneInput.dataset.phoneInit = 'true';
        const iti = window.intlTelInput(phoneInput, {
          initialCountry: 'es',
          preferredCountries: ['es', 'fr', 'pt', 'ad'],
          separateDialCode: true,
        });

        const syncPhone = () => {
          const formatted = iti.getNumber();
          if (formatted) {
            phoneInput.value = formatted;
          } else {
            phoneInput.value = phoneInput.value.trim();
          }
        };

        phoneInput.addEventListener('blur', syncPhone);
        phoneInput.addEventListener('change', syncPhone);
        phoneInput.addEventListener('countrychange', syncPhone);
        phoneInput.form?.addEventListener('submit', syncPhone);

        window.__deliveryPhoneInit = syncPhone;
      };

      tryInit();
    })();

    (function initRestaurantMobileUi() {
      const viewKey = 'restaurant_view_mode';
      const mobileSections = document.querySelectorAll('.restaurant-mobile-body');
      const navButtons = document.querySelectorAll('.restaurant-mobile-nav [data-section-target]');
      const viewButtons = document.querySelectorAll('[data-view-toggle]');
      const viewLabel = document.querySelector('[data-view-label]');

      const applyViewMode = () => {
        const mode = localStorage.getItem(viewKey);
        const isMobileViewport = window.matchMedia('(max-width: 991px)').matches;
        document.body.classList.remove('restaurant-show-desktop', 'restaurant-force-mobile');

        if (isMobileViewport) {
          if (mode === 'desktop') {
            document.body.classList.add('restaurant-show-desktop');
          } else {
            document.body.classList.add('restaurant-force-mobile');
          }
          if (viewLabel) {
            viewLabel.textContent = mode === 'desktop' ? 'Versión rápida' : 'Versión completa';
          }
          return;
        }

        if (mode === 'desktop') {
          document.body.classList.add('restaurant-show-desktop');
        } else if (mode === 'mobile') {
          document.body.classList.add('restaurant-force-mobile');
        }
        if (viewLabel) {
          viewLabel.textContent = mode === 'desktop' ? 'Versión rápida' : 'Versión completa';
        }
      };


      const setViewMode = (mode) => {
        if (!mode) {
          localStorage.removeItem(viewKey);
        } else {
          localStorage.setItem(viewKey, mode);
        }
        applyViewMode();
      };

      const syncViewFromUrl = () => {
        const params = new URLSearchParams(window.location.search);
        const viewParam = params.get('view');
        if (viewParam === 'desktop') {
          setViewMode('desktop');
        } else if (viewParam === 'mobile') {
          setViewMode('mobile');
        }
        if (viewParam) {
          params.delete('view');
          const newUrl = `${window.location.pathname}${params.toString() ? `?${params}` : ''}`;
          window.history.replaceState({}, '', newUrl);
        }
      };

      document.addEventListener('click', (event) => {
        const btn = event.target.closest('[data-view-toggle]');
        if (!btn) return;
        const target = btn.getAttribute('data-view-toggle');
        if (target === 'desktop') {
          const current = localStorage.getItem(viewKey);
          setViewMode(current === 'desktop' ? null : 'desktop');
        } else if (target === 'mobile') {
          setViewMode('mobile');
        }
      });

      // In "version completa", keep Vuexy's native mobile menu toggle (navbar)
      // and Vuexy's logistics-fleet sidebar toggle (data-bs-toggle="sidebar").

      const setActiveSection = (section) => {
        mobileSections.forEach((el) => {
          el.classList.toggle('active', el.dataset.section === section);
        });
        navButtons.forEach((btn) => {
          btn.classList.toggle('active', btn.dataset.sectionTarget === section);
        });
        localStorage.setItem('restaurant_mobile_tab', section);
      };

      navButtons.forEach((btn) => {
        btn.addEventListener('click', () => setActiveSection(btn.dataset.sectionTarget));
      });

      syncViewFromUrl();
      const savedTab = localStorage.getItem('restaurant_mobile_tab') || 'home';
      setActiveSection(savedTab);
      applyViewMode();
      window.addEventListener('resize', applyViewMode);

      // Vuexy handles layout overlay clicks internally.


      document.querySelectorAll('.mobile-status-tabs .status-pill').forEach((pill) => {
        pill.addEventListener('click', () => {
          document.querySelectorAll('.mobile-status-tabs .status-pill').forEach((btn) => {
            btn.classList.toggle('active', btn === pill);
          });
          const status = pill.dataset.status;
          localStorage.setItem('restaurant_mobile_status_tab', status);
          document.querySelectorAll('.mobile-order-card').forEach((card) => {
            const matches = status === 'confirmed'
              ? (card.dataset.status === 'confirmed' || card.dataset.status === 'at_restaurant')
              : card.dataset.status === status;
            card.style.display = matches ? '' : 'none';
          });
        });
      });
      const savedMobileStatus = localStorage.getItem('restaurant_mobile_status_tab');
      const initialStatus = savedMobileStatus
        || document.querySelector('.mobile-status-tabs .status-pill.active')?.dataset.status
        || 'pending';
      document.querySelectorAll('.mobile-status-tabs .status-pill').forEach((btn) => {
        btn.classList.toggle('active', btn.dataset.status === initialStatus);
      });
      document.querySelectorAll('.mobile-order-card').forEach((card) => {
        const matches = initialStatus === 'confirmed'
          ? (card.dataset.status === 'confirmed' || card.dataset.status === 'at_restaurant')
          : card.dataset.status === initialStatus;
        card.style.display = matches ? '' : 'none';
      });

        const urgentBtn = document.querySelector('.mobile-urgent-btn');
        if (urgentBtn) {
          const urgentUntilKey = 'restaurant_urgent_until';
          const urgentAcceptedKey = 'restaurant_urgent_accepted_until';
          const label = document.querySelector('[data-label]');
          const labelText = document.querySelector('[data-urgent-text]');
          const dots = document.querySelector('[data-urgent-dots]');
          const urgentForm = document.querySelector('#urgentCanvas form');
        let lastUrgentStatus = urgentBtn.dataset.lastUrgentStatus || '';

        const setUrgentState = (state) => {
          urgentBtn.classList.remove('is-searching', 'is-confirmed');
          urgentBtn.disabled = false;
          urgentBtn.removeAttribute('aria-disabled');
          if (dots) dots.classList.add('d-none');

          if (state === 'searching') {
            urgentBtn.classList.add('is-searching');
            urgentBtn.disabled = true;
            urgentBtn.setAttribute('aria-disabled', 'true');
          if (labelText) labelText.textContent = 'Buscando repartidor en tu zona';
          if (dots) dots.classList.remove('d-none');
          return;
        }

        if (state === 'confirmed') {
          urgentBtn.classList.add('is-confirmed');
          if (labelText) labelText.textContent = 'Repartidor en camino';
          return;
        }

          if (labelText) labelText.textContent = 'Solicitar rider';
          localStorage.removeItem(urgentUntilKey);
          localStorage.removeItem(urgentAcceptedKey);
        };

        const applyUrgentUi = (untilTs) => {
          const nowTs = Date.now();
          if (!untilTs || Number.isNaN(untilTs) || untilTs <= nowTs) {
            const acceptedUntil = Number(localStorage.getItem(urgentAcceptedKey));
            if (acceptedUntil && acceptedUntil > nowTs) {
              setUrgentState('confirmed');
              return;
            }
            setUrgentState('idle');
            return;
          }

          setUrgentState('searching');

          window.clearTimeout(window.__restaurantUrgentResetTimeout);
          window.__restaurantUrgentResetTimeout = window.setTimeout(() => {
            setUrgentState('idle');
          }, untilTs - nowTs);
        };

        const flashAccepted = () => {
          const untilTs = Date.now() + 5000;
          localStorage.setItem(urgentAcceptedKey, String(untilTs));
          setUrgentState('confirmed');
          window.clearTimeout(window.__restaurantUrgentAcceptedTimeout);
          window.__restaurantUrgentAcceptedTimeout = window.setTimeout(() => {
            setUrgentState('idle');
          }, 5000);
        };

        // El pedido urgente realmente se "solicita" al enviar el formulario.
        // Al enviarlo, mostramos el estado durante 5s y luego permitimos pedir otro.
        if (urgentForm) {
          urgentForm.addEventListener('submit', () => {
            const untilTs = Date.now() + 5000;
            localStorage.setItem(urgentUntilKey, String(untilTs));
            applyUrgentUi(untilTs);
          });
        }

        const savedUntil = Number(localStorage.getItem(urgentUntilKey));
        if (lastUrgentStatus === 'pending') {
          setUrgentState('searching');
        } else if (lastUrgentStatus === 'confirmed' || lastUrgentStatus === 'accepted') {
          flashAccepted();
        } else {
          applyUrgentUi(savedUntil);
        }

        const syncUrgentStatus = async () => {
          try {
            const resp = await fetch('<?php echo e(route('restaurant.urgent.status')); ?>', {
              headers: { 'X-Requested-With': 'XMLHttpRequest' }
            });
            if (!resp.ok) return;
            const data = await resp.json();
            const nextStatus = data.status || 'none';
            lastUrgentStatus = nextStatus;

            if (nextStatus === 'pending') {
              setUrgentState('searching');
            } else if (nextStatus === 'confirmed' || nextStatus === 'accepted') {
              flashAccepted();
            } else {
              setUrgentState('idle');
            }
          } catch (err) {
            // Silent fail for polling
          }
        };

        syncUrgentStatus();
        window.setInterval(syncUrgentStatus, 10000);
      }

      const lastOrderEl = document.querySelector('[data-last-order]');
      if (lastOrderEl) {
        const statusMap = {
          pending: { label: 'Pendiente', badge: 'warning' },
          confirmed: { label: 'Confirmado', badge: 'info' },
          at_restaurant: { label: 'Confirmado', badge: 'info' },
          en_route: { label: 'En camino', badge: 'primary' },
          delivered: { label: 'Entregado', badge: 'success' },
          cancelled: { label: 'Cancelado', badge: 'danger' }
        };

        const statusBadge = lastOrderEl.querySelector('[data-last-status]');
        const statusId = lastOrderEl.querySelector('[data-last-id]');
        const statusTime = lastOrderEl.querySelector('[data-last-time]');
        const statusUrgent = lastOrderEl.querySelector('[data-last-urgent]');
        const statusAgo = lastOrderEl.querySelector('[data-last-ago]');
        const customer = lastOrderEl.querySelector('[data-last-customer]');
        const address = lastOrderEl.querySelector('[data-last-address]');
        const courier = lastOrderEl.querySelector('[data-last-courier]');
        const courierStatus = lastOrderEl.querySelector('[data-last-courier-status]');
        const empty = lastOrderEl.querySelector('[data-last-empty]');

        const applyStatusBadge = (badge, label) => {
          if (!statusBadge) return;
          statusBadge.textContent = label;
          ['warning', 'info', 'success', 'danger', 'secondary'].forEach((item) => {
            statusBadge.classList.remove(`bg-label-${item}`);
          });
          statusBadge.classList.add(`bg-label-${badge}`);
        };

        const updateLastOrder = (data) => {
          if (!data || data.status === 'none') {
            if (empty) empty.classList.remove('d-none');
            return;
          }

          if (empty) empty.classList.add('d-none');
          const mapped = statusMap[data.status] || statusMap.pending;
          applyStatusBadge(mapped.badge, mapped.label);

          if (statusId) statusId.textContent = `#${data.id}`;
          if (statusTime) statusTime.textContent = data.created_time || '--:--';

          if (statusUrgent) {
            statusUrgent.classList.toggle('d-none', !data.is_urgent);
          }

          if (statusAgo) {
            if (data.ago) {
              statusAgo.textContent = `Tu ultimo pedido solicitado fue ${data.ago}.`;
              statusAgo.classList.remove('d-none');
            } else {
              statusAgo.classList.add('d-none');
            }
          }

          if (customer) customer.textContent = data.customer_name || 'Por definir';
          if (address) address.textContent = data.delivery_address || 'Por definir';
          if (courier) courier.textContent = data.courier_line || 'Sin repartidor';
          if (courierStatus) courierStatus.textContent = data.courier_status || 'Sin asignar';
        };

        const syncLastOrder = async () => {
          try {
            const resp = await fetch('<?php echo e(route('restaurant.last-order.status')); ?>', {
              headers: { 'X-Requested-With': 'XMLHttpRequest' }
            });
            if (!resp.ok) return;
            const data = await resp.json();
            updateLastOrder(data);
          } catch (err) {
            // Silent fail for polling
          }
        };

        syncLastOrder();
        window.setInterval(syncLastOrder, 15000);
      }

      document.addEventListener('click', (event) => {
        const jump = event.target.closest('[data-section-jump]');
        if (!jump) return;
        const target = jump.getAttribute('data-section-jump');
        if (target) setActiveSection(target);
      });

      // Modal de detalles (version rapida) al tocar una orden
      const orderScreenEl = document.getElementById('mobileOrderScreen');

      const closeOrderScreen = () => {
        if (!orderScreenEl) return;
        orderScreenEl.classList.remove('active');
        orderScreenEl.setAttribute('aria-hidden', 'true');
        document.body.classList.remove('mobile-order-screen-open');
      };

      const openOrderScreen = (card) => {
        if (!orderScreenEl || !card) return;
        const status = card.querySelector('.badge')?.textContent?.trim() || 'Pendiente';
        const isUrgent = card.dataset.isUrgent === '1';

        const title = `Entrega #${card.dataset.deliveryId || ''}`.trim();
        orderScreenEl.querySelector('#mobileOrderScreenTitle').textContent = title || 'Entrega';

        const statusEl = orderScreenEl.querySelector('#mobileOrderScreenStatus');
        statusEl.textContent = status + (isUrgent ? ' · Urgente' : '');

        orderScreenEl.querySelector('#mobileOrderScreenCreatedAt').textContent = card.dataset.createdAt || '--';
        orderScreenEl.querySelector('#mobileOrderScreenCustomer').textContent = card.dataset.customerName || 'Por definir';
        orderScreenEl.querySelector('#mobileOrderScreenPhone').textContent = card.dataset.customerPhone || '-';
        orderScreenEl.querySelector('#mobileOrderScreenAddress').textContent = card.dataset.deliveryAddress || 'Por definir';

        const extra = (card.dataset.deliveryExtra || '').trim();
        const extraEl = orderScreenEl.querySelector('#mobileOrderScreenExtra');
        if (extra) {
          extraEl.style.display = '';
          extraEl.textContent = extra;
        } else {
          extraEl.style.display = 'none';
          extraEl.textContent = '';
        }

        orderScreenEl.querySelector('#mobileOrderScreenCourier').textContent = card.dataset.courierName || 'Sin asignar';
        orderScreenEl.querySelector('#mobileOrderScreenPayment').textContent = card.dataset.paymentMethod || '—';
        orderScreenEl.querySelector('#mobileOrderScreenFee').textContent = card.dataset.fee || '';

        const notes = (card.dataset.notes || '').trim();
        const notesWrap = orderScreenEl.querySelector('#mobileOrderScreenNotesWrap');
        const notesEl = orderScreenEl.querySelector('#mobileOrderScreenNotes');
        if (notes) {
          notesWrap.style.display = '';
          notesEl.textContent = notes;
        } else {
          notesWrap.style.display = 'none';
          notesEl.textContent = '';
        }

        orderScreenEl.classList.add('active');
        orderScreenEl.setAttribute('aria-hidden', 'false');
        document.body.classList.add('mobile-order-screen-open');
      };

      document.addEventListener('click', (event) => {
        const back = event.target.closest('[data-order-screen-back]');
        if (!back) return;
        closeOrderScreen();
      });

      document.addEventListener('click', (event) => {
        const card = event.target.closest('.mobile-order-card');
        if (!card) return;
        // Only open modal from the Orders tab to avoid accidental taps in other views
        if (!document.querySelector('.restaurant-mobile-body[data-section="orders"]')?.classList.contains('active')) return;
        openOrderScreen(card);
      });
    })();
  </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts/layoutMaster', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /Users/w/Documents/TAKS/resources/views/restaurant/dashboard.blade.php ENDPATH**/ ?>