@php
  use Illuminate\Support\Facades\Storage;
  use Illuminate\Support\Str;
  /** @var \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Collection $cucine */
  $cucine = $cucine ?? collect();
@endphp

@if ($cucine->isEmpty())
  <div class="alert alert-warning mb-0" role="alert">
    <strong>Nessuna cucina disponibile.</strong>
    @if(isset($punto_vendita) && $punto_vendita->attivita_id)
      Non risultano cucine attive per l’attività collegata a questa cassa. Verifica <code>attivita_id</code> su dispositivo e cucine.
    @else
      Aggiungi cucine attive o collega la cassa a un’<strong>attività</strong> per filtrare l’elenco.
    @endif
  </div>
@else
  <div class="card border shadow-sm w-100 cassa-cucine-card">
    <div class="card-header border-bottom-0 pb-0 pt-3 px-3">
      <ul class="nav nav-tabs nav-fill flex-nowrap gap-1 border-0 cassa-cucine-tabs" role="tablist">

      @if(\App\Models\Saltacoda::where('attivita_id', $punto_vendita->attivita_id)->first()->is_attivo)
      <li class="nav-item flex-shrink-0" role="presentation">
            <button
              class="nav-link px-3 bg-primary-subtle"
              id="tab-pre-ordine"
              data-bs-toggle="tab"
              data-bs-target="#pane-pre-ordine"
              type="button"
              role="tab"
              aria-controls="pane-pre-ordine"
              aria-selected="false"
            >
              <i class="bx bx-restaurant me-1"></i>Pre-ordine
            </button>
          </li>
      @endif

        @foreach ($cucine as $index => $cucina)
          <li class="nav-item flex-shrink-0" role="presentation">
            <button
              class="nav-link @if($index === 0) active @endif px-3"
              id="tab-cucina-{{ $cucina->id }}"
              data-bs-toggle="tab"
              data-bs-target="#pane-cucina-{{ $cucina->id }}"
              type="button"
              role="tab"
              aria-controls="pane-cucina-{{ $cucina->id }}"
              aria-selected="{{ $index === 0 ? 'true' : 'false' }}"
            >
              <i class="bx bx-restaurant me-1"></i>{{ $cucina->nome }}
            </button>
          </li>
        @endforeach
      </ul>
    </div>
    <div class="card-body pt-3 cassa-cucine-body">
      <div class="tab-content">

        @if(\App\Models\Saltacoda::where('attivita_id', $punto_vendita->attivita_id)->first()->is_attivo)
        <div class="tab-pane fade" id="pane-pre-ordine" role="tabpanel" aria-labelledby="tab-pre-ordine" tabindex="0">
          <div class="gap-4 row row-cols-2 row-cols-sm-3 row-cols-md-4 row-cols-xl-4 row-cols-xxl-5 g-2 cassa-piatti-grid">
            <div class="w-50 mx-auto d-flex justify-content-center align-items-center">
              <!-- <p class="text-muted mb-0">Nessun pre-ordine attivo per questa cucina.</p> -->
              <input type="text" class="form-control" placeholder="inserisci il codice del pre-ordine" name="pre-ordine-input" id="pre-ordine-input" 
                oninput="if(this.value.length >= 3) cercaPreOrdine()">
              <!-- <button class="btn btn-primary mx-2" onclick="cercaPreOrdine()">Cerca</button> -->
         
            </div>
            <div class="w-50 mx-auto d-flex justify-content-center align-items-center" id="pre-ordine-result">
            
          </div>
          </div>
        </div>


        <script>
          function cercaPreOrdine() {
            $("#pre-ordine-result").load("{{ route('punto-vendita.cassa.cerca-pre-ordine') }}"+"?codice="+$("#pre-ordine-input").val());
          }

          function importaPreOrdine(codice) {
            $.ajax({
              url: "{{ route('punto-vendita.cassa.importa-pre-ordine') }}",
              type: "POST",
              data: {
                codice: codice,
                _token: "{{ csrf_token() }}",
                attivita_id: "{{ $ordine->attivita_id }}",
                dispositivo_id: "{{ $ordine->dispositivo_id }}",
                ordine_id: "{{ $ordine->id }}",
              },
              success: function(response) {
                if(response.success) {
                    new Notyf({
                        duration: 2000,
                        position: { x: 'right', y: 'top' }
                    }).success(response.message);
                    window.location.reload();
                } else {
                    new Notyf({
                        duration: 2000,
                        position: { x: 'right', y: 'top' }
                    }).error(response.message);
                }
              },
              error: function(xhr, status, error) {
                new Notyf({
                    duration: 2000,
                    position: { x: 'right', y: 'top' }
                }).error(xhr.responseText);
              }
            });
          }
        </script>

        @endif
        @foreach ($cucine as $index => $cucina)
          <div
            class="tab-pane fade @if($index === 0) show active @endif"
            id="pane-cucina-{{ $cucina->id }}"
            role="tabpanel"
            aria-labelledby="tab-cucina-{{ $cucina->id }}"
            tabindex="0"
          >
            <div class="gap-4 row row-cols-2 row-cols-sm-3 row-cols-md-4 row-cols-xl-4 row-cols-xxl-5 g-2 cassa-piatti-grid">
              @php
                $piatti = $cucina->piatti ?? collect();
                $preferiti = $piatti
                    ->filter(fn ($piatto) => (bool) ($piatto->in_evidenza ?? false))
                    ->sortBy(fn ($piatto) => mb_strtolower((string) ($piatto->nome ?? '')), SORT_NATURAL);

                $nonPreferiti = $piatti
                    ->reject(fn ($piatto) => (bool) ($piatto->in_evidenza ?? false))
                    ->sortBy(fn ($piatto) => mb_strtolower((string) ($piatto->nome ?? '')), SORT_NATURAL);

                $gruppiAlfabetici = $nonPreferiti->groupBy(function ($piatto) {
                    $nome = trim((string) ($piatto->nome ?? ''));
                    if ($nome === '') {
                        return '#';
                    }

                    $iniziale = mb_strtoupper(mb_substr($nome, 0, 1));
                    return preg_match('/[A-Z]/u', $iniziale) ? $iniziale : '#';
                });
              @endphp

              @if($preferiti->isNotEmpty())
                <div class="col-12 cassa-piatti-divider">
                  <span class="cassa-piatti-divider-pill"><i class="bx bxs-star me-1"></i>Preferiti</span>
                </div>
                @foreach ($preferiti as $piatto)
                  @include('punto_vendita.cassa._partials.piatto', ['piatto' => $piatto, 'cucina' => $cucina])
                @endforeach
              @endif

              @forelse ($gruppiAlfabetici as $lettera => $piattiGruppo)
                <div class="col-12 cassa-piatti-divider">
                  <span class="cassa-piatti-divider-pill">{{ $lettera }}</span>
                </div>
                @foreach ($piattiGruppo as $piatto)
                  @include('punto_vendita.cassa._partials.piatto', ['piatto' => $piatto, 'cucina' => $cucina])
                @endforeach
              @empty
                <div class="col-12">
                  <p class="text-muted mb-0">Nessun piatto attivo per questa cucina.</p>
                </div>
              @endforelse
            </div>
          </div>
        @endforeach
      </div>
    </div>
  </div>
@endif

<style>
  .cassa-cucine-card {
    width: 100%;
    min-width: 0;
    height: 100% !important;
    max-height: 100%;
    min-height: 0;
    display: flex;
    flex-direction: column;
  }
  .cassa-cucine-card .card-header {
    flex-shrink: 0;
  }
  .cassa-cucine-card .cassa-cucine-body {
    display: flex;
    flex-direction: column;
    flex: 1 1 auto;
    min-height: 0;
    overflow: hidden;
  }
  .cassa-cucine-card .tab-content,
  .cassa-cucine-card .tab-pane {
    min-width: 0;
  }
  .cassa-cucine-card .tab-content {
    flex: 1 1 0;
    height: 0;
    min-height: 0;
  }
  .cassa-cucine-card .tab-pane {
    height: 100%;
    min-height: 0;
    overflow: hidden;
  }
  .cassa-cucine-card .tab-pane.active.show {
    display: flex;
    flex-direction: column;
  }
  .cassa-cucine-tabs .nav-link {
    white-space: nowrap;
    border-radius: 0.375rem 0.375rem 0 0;
  }
  .cassa-cucine-tabs {
    overflow-x: auto;
    flex-wrap: nowrap;
    scrollbar-width: thin;
  }
  .cassa-piatto-card {
    cursor: pointer;
    border-radius: 0.8rem;
    border-color: rgba(var(--bs-secondary-rgb), 0.2) !important;
    transition: box-shadow 0.15s ease, transform 0.12s ease;
    background: var(--bs-body-bg);
  }
  .cassa-piatto-card:hover,
  .cassa-piatto-card:focus-visible {
    box-shadow: 0 0.45rem 0.9rem rgba(67, 89, 113, 0.12) !important;
    transform: translateY(-1px);
    outline: none;
  }
  .cassa-piatto-card:active {
    transform: translateY(0);
    box-shadow: 0 0.25rem 0.6rem rgba(67, 89, 113, 0.14) !important;
  }
  .cassa-piatto-card--compact .cassa-piatto-body {
    padding: 0.75rem 0.8rem;
  }
  .cassa-piatto-title {
    font-size: 0.9rem;
    font-weight: 700;
    line-height: 1.25;
    color: var(--bs-heading-color);
    margin-bottom: 0;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  .cassa-piatto-price {
    font-size: 1rem;
    font-weight: 800;
    color: var(--bs-primary);
    font-variant-numeric: tabular-nums;
    letter-spacing: 0.01em;
    display: block;
  }
  .cassa-piatto-allergeni-badge {
    display: inline-flex;
    align-items: center;
    font-size: 0.68rem;
    font-weight: 700;
    color: #8a5a00;
    background: rgba(var(--bs-warning-rgb), 0.16);
    border: 1px solid rgba(var(--bs-warning-rgb), 0.35);
    border-radius: 999px;
    padding: 0.14rem 0.42rem;
    line-height: 1.2;
    width: fit-content;
  }
  [data-bs-theme='dark'] .cassa-piatto-allergeni-badge {
    color: rgba(255, 225, 160, 0.95);
    background: rgba(var(--bs-warning-rgb), 0.22);
    border-color: rgba(var(--bs-warning-rgb), 0.45);
  }
  .cassa-piatti-grid > .col {
    min-width: 0;
  }
  .cassa-cucine-card .cassa-piatti-grid {
    flex: 1 1 0;
    height: 0;
    min-height: 0;
    max-height: none;
    overflow-y: auto;
    overflow-x: hidden;
    -webkit-overflow-scrolling: touch;
    overscroll-behavior: contain;
    align-content: flex-start;
    margin: 0;
    padding-right: 0.35rem;
    padding-bottom: 0.35rem;
    scrollbar-width: thin;
  }
  @media (max-width: 1199.98px) {
    .cassa-cucine-card {
      height: 100% !important;
      min-height: 0;
    }
  }
  .cassa-piatto-add-icon {
    flex-shrink: 0;
    width: 1.35rem;
    height: 1.35rem;
    border-radius: 999px;
    border: 1px solid rgba(var(--bs-primary-rgb), 0.22);
    color: var(--bs-primary);
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 0.95rem;
    line-height: 1;
  }
  .cassa-piatti-divider {
    position: static;
    flex: 0 0 100% !important;
    width: 100% !important;
    max-width: 100% !important;
    z-index: 1;
    padding-top: 0.35rem;
    padding-bottom: 0.15rem;
    background: transparent;
  }
  .cassa-piatti-divider-pill {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    width: 100%;
    font-size: 0.9rem;
    font-weight: 800;
    letter-spacing: 0.04em;
    text-transform: uppercase;
    color: var(--bs-primary);
    gap: 0.6rem;
    line-height: 1;
  }
  .cassa-piatti-divider-pill::before,
  .cassa-piatti-divider-pill::after {
    content: "";
    flex: 0 0 0;
    border-top: 1px solid rgba(var(--bs-secondary-rgb), 0.25);
  }
  .cassa-piatti-divider-pill::after {
    flex: 1 1 auto;
  }
</style>
