@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
  @php
    $saltacoda = \App\Models\Saltacoda::where('attivita_id', $punto_vendita->attivita_id)->first();
    $saltacodaAttivo = (bool) ($saltacoda?->is_attivo ?? false);
    $cucineOrdinate = $cucine
      ->sortBy(fn ($cucina) => mb_strtolower((string) ($cucina->nome ?? ''), 'UTF-8'))
      ->values();
  @endphp

  <div class="card border shadow-sm w-100 cassa-catalogo-card">
    <div class="card-header py-2 px-3 cassa-catalogo-header">
      <div class="d-flex flex-wrap align-items-center gap-2">
        <h6 class="mb-0 fw-bold text-primary me-auto">
          <i class="bx bx-grid-alt me-1"></i>Catalogo completo
        </h6>
        <div class="cassa-catalogo-search-wrap">
          <i class="bx bx-search"></i>
          <input
            type="text"
            class="form-control"
            id="cassa-catalogo-search"
            placeholder="Cerca piatto o cucina"
            autocomplete="off"
          >
        </div>
      </div>

      @if($saltacodaAttivo)
        <div class="mt-2 d-flex flex-wrap align-items-center gap-2">
          <span class="badge bg-label-primary">Pre-ordine</span>
          <input
            type="text"
            class="form-control form-control-sm cassa-preordine-input"
            placeholder="Inserisci codice pre-ordine"
            name="pre-ordine-input"
            id="pre-ordine-input"
            oninput="if(this.value.length >= 3) cercaPreOrdine()"
          >
        </div>
        <div class="mt-2" id="pre-ordine-result"></div>
      @endif
    </div>

    <div class="card-body p-2 cassa-catalogo-body">
      @foreach ($cucineOrdinate as $cucina)
        @php
          $piatti = ($cucina->piatti ?? collect())
            ->sortBy(fn ($piatto) => mb_strtolower((string) ($piatto->nome ?? ''), 'UTF-8'))
            ->values();
        @endphp

        <section class="cassa-cucina-section" data-cucina="{{ mb_strtolower((string) ($cucina->nome ?? ''), 'UTF-8') }}">
          <div class="cassa-cucina-section-title">
            <i class="bx bx-restaurant me-1"></i>{{ $cucina->nome }}
          </div>

          @forelse ($piatti as $piatto)
            @php
              $searchText = mb_strtolower(trim((string) ($piatto->nome ?? '') . ' ' . (string) ($cucina->nome ?? '')), 'UTF-8');
            @endphp
            <div
              class="cassa-piatto-card cassa-piatto-row"
              role="button"
              tabindex="0"
              data-piatto-id="{{ $piatto->id }}"
              data-piatto-nome="{{ $piatto->nome }}"
              data-piatto-prezzo="{{ (float) $piatto->prezzo }}"
              data-cucina-id="{{ $cucina->id }}"
              data-search="{{ $searchText }}"
            >
              <span class="cassa-piatto-row-name">{{ $piatto->nome }}</span>
              <span class="cassa-piatto-row-price">€ {{ number_format((float) $piatto->prezzo, 2, ',', '.') }}</span>
            </div>
          @empty
            <p class="text-muted mb-2">Nessun piatto attivo per questa cucina.</p>
          @endforelse
        </section>
      @endforeach
    </div>
  </div>

  @if($saltacodaAttivo)
    <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) {
            new Notyf({
              duration: 2000,
              position: { x: 'right', y: 'top' }
            }).error(xhr.responseText);
          }
        });
      }
    </script>
  @endif

  <script>
    (function () {
      const searchInput = document.getElementById('cassa-catalogo-search');
      if (!searchInput) {
        return;
      }

      const rows = Array.from(document.querySelectorAll('.cassa-piatto-row[data-search]'));
      const sections = Array.from(document.querySelectorAll('.cassa-cucina-section'));

      const applyFilter = function () {
        const term = searchInput.value.trim().toLowerCase();

        rows.forEach(function (row) {
          const haystack = row.getAttribute('data-search') || '';
          row.classList.toggle('d-none', term !== '' && !haystack.includes(term));
        });

        sections.forEach(function (section) {
          const visibleRows = section.querySelectorAll('.cassa-piatto-row:not(.d-none)');
          section.classList.toggle('d-none', visibleRows.length === 0);
        });
      };

      searchInput.addEventListener('input', applyFilter);
    })();
  </script>
@endif

<style>
  .cassa-catalogo-card {
    width: 100%;
    min-width: 0;
    height: 100% !important;
    max-height: 100%;
    min-height: 0;
    display: flex;
    flex-direction: column;
  }

  .cassa-catalogo-header {
    flex-shrink: 0;
  }

  .cassa-catalogo-search-wrap {
    min-width: min(24rem, 100%);
    width: min(24rem, 100%);
    display: flex;
    align-items: center;
    gap: 0.35rem;
    background: var(--bs-body-bg);
    border: 1px solid rgba(var(--bs-secondary-rgb), 0.25);
    border-radius: 0.6rem;
    padding: 0.18rem 0.45rem;
  }

  .cassa-catalogo-search-wrap > i {
    color: var(--bs-secondary-color);
    font-size: 1rem;
  }

  .cassa-catalogo-search-wrap .form-control {
    border: 0;
    box-shadow: none !important;
    padding: 0.2rem 0.1rem;
    background: transparent;
  }

  .cassa-preordine-input {
    max-width: 18rem;
  }

  .cassa-catalogo-card .cassa-catalogo-body {
    flex: 1 1 0;
    min-height: 0;
    overflow-y: auto;
    overflow-x: hidden;
    scrollbar-width: thin;
    padding-right: 0.25rem;
  }

  .cassa-piatto-row {
    cursor: pointer;
    border: 1px solid rgba(var(--bs-secondary-rgb), 0.25);
    border-radius: 0.6rem;
    padding: 0.6rem 0.7rem;
    margin-bottom: 0.45rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0.5rem;
    background: var(--bs-body-bg);
    transition: box-shadow 0.15s ease, transform 0.12s ease;
  }

  .cassa-cucina-section {
    margin-bottom: 0.65rem;
  }

  .cassa-cucina-section:last-child {
    margin-bottom: 0;
  }

  .cassa-cucina-section-title {
    position: sticky;
    top: -0.45rem;
    z-index: 2;
    font-size: 0.82rem;
    font-weight: 800;
    letter-spacing: 0.03em;
    text-transform: uppercase;
    color: var(--bs-primary);
    background: var(--bs-card-bg);
    padding: 0.35rem 0.2rem 0.35rem;
    margin-bottom: 0.28rem;
    border-bottom: 1px dashed rgba(var(--bs-primary-rgb), 0.25);
  }

  .cassa-piatto-row:hover,
  .cassa-piatto-row:focus-visible {
    box-shadow: 0 0.45rem 0.9rem rgba(67, 89, 113, 0.12) !important;
    transform: translateY(-1px);
    outline: none;
  }

  .cassa-piatto-row:active {
    transform: translateY(0);
    box-shadow: 0 0.25rem 0.6rem rgba(67, 89, 113, 0.14) !important;
  }

  .cassa-piatto-row-name {
    font-size: 0.9rem;
    font-weight: 700;
    line-height: 1.2;
    color: var(--bs-heading-color);
    min-width: 0;
    word-break: break-word;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
  }

  .cassa-piatto-row-price {
    font-size: 0.92rem;
    font-weight: 800;
    color: var(--bs-primary);
    font-variant-numeric: tabular-nums;
    letter-spacing: 0.01em;
    flex-shrink: 0;
  }

  @media (max-width: 1199.98px) {
    .cassa-catalogo-card {
      height: auto;
      min-height: 24rem;
    }

    .cassa-catalogo-search-wrap {
      width: 100%;
      min-width: 0;
    }
  }

  @media (max-width: 767.98px) {
    .cassa-catalogo-card .cassa-catalogo-body {
      padding-right: 0;
    }

    .cassa-piatto-row {
      padding: 0.55rem 0.6rem;
    }

    .cassa-piatto-row-name {
      font-size: 0.86rem;
    }

    .cassa-piatto-row-price {
      font-size: 0.86rem;
    }
  }
</style>
