@php
  use Illuminate\Support\Facades\Route;
  use App\Models\Attivita;
  use App\Models\Saltacoda;

  /** @var \App\Models\Attivita|null $attivita */
  $accent = $attivita?->colore ?: '#f58220';
  $festLogoLarge = asset('assets/img/logo_fest_L.png');
  $festLogoFallback = Attivita::defaultLogoUrl();
  $backUrl = $attivita
    ? route('cliente.attivita.show', ['attivita_id' => $attivita->id])
    : (Route::has('welcome') ? route('welcome') : url('/'));
  $istruzioni = Saltacoda::find($saltacoda_id ?? null)?->getIstruzioni() ?? Saltacoda::defaultIstruzioni();
@endphp

@extends('layouts/guest')

@section('title', $attivita ? 'Ordina · ' . $attivita->nome : 'Saltacoda')

@section('page-meta')
  <script>document.documentElement.classList.add('saltacoda-cliente-page');</script>
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,400;0,500;0,600;0,700;0,800;1,400&display=swap" rel="stylesheet" />
  <meta name="theme-color" content="{{ $accent }}">
  <meta name="theme-color" media="(prefers-color-scheme: light)" content="{{ $accent }}">
  <meta name="theme-color" media="(prefers-color-scheme: dark)" content="{{ $accent }}">
  <meta name="color-scheme" content="light">
  <meta name="mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="default">
@endsection

@section('page-style')
  @include('saltacoda._partials.cliente.fest-layout-style')
<style>
  .saltacoda-mobile {
    --saltacoda-topbar-h: 56px;
    --saltacoda-topbar-offset: calc(var(--saltacoda-topbar-h) + env(safe-area-inset-top, 0px));
    --saltacoda-kitchen-chips-h: 56px;
    --saltacoda-kitchen-search-h: 44px;
    --saltacoda-kitchen-nav-h: calc(var(--saltacoda-kitchen-chips-h) + var(--saltacoda-kitchen-search-h));
    --saltacoda-footbar-h: 86px;
    --saltacoda-accent: var(--card-accent);
    --saltacoda-accent-line: color-mix(in srgb, var(--card-accent) 42%, transparent);
    --saltacoda-accent-text: color-mix(in srgb, var(--card-accent) 72%, #15265c);
    --saltacoda-accent-surface: color-mix(in srgb, var(--card-accent) 8%, #fff);
    --saltacoda-accent-border: color-mix(in srgb, var(--card-accent) 45%, transparent);
    --saltacoda-accent-shadow: color-mix(in srgb, var(--card-accent) 18%, transparent);
    position: relative;
    z-index: 1;
    min-height: 100vh;
    min-height: 100dvh;
    width: 100vw;
    background: transparent;
    margin: 0;
  }

  .saltacoda-topbar {
    min-height: var(--saltacoda-topbar-offset);
    height: auto;
    box-sizing: border-box;
    overflow: visible;
  }

  .saltacoda-topbar.saltacoda-fest-topbar.saltacoda-topbar--text-only {
    justify-content: center;
    gap: 0;
    padding: calc(0.45rem + env(safe-area-inset-top, 0px)) 0.75rem 0.45rem;
  }

  .saltacoda-topbar-title {
    margin: 0;
    font-size: 0.88rem;
    font-weight: 800;
    color: var(--text-main);
    line-height: 1.1;
    letter-spacing: -0.01em;
  }

  .saltacoda-topbar-heading {
    width: 100%;
    min-width: 0;
    text-align: center;
    padding: 0;
  }

  .saltacoda-topbar-subtitle {
    margin: 0.1rem 0 0;
    font-size: 0.68rem;
    font-weight: 600;
    color: var(--text-muted);
    line-height: 1.15;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .saltacoda-menu-search-wrap {
    flex: 0 0 var(--saltacoda-kitchen-search-h);
    display: flex;
    align-items: center;
    height: var(--saltacoda-kitchen-search-h);
    padding: 0 0.75rem;
    box-sizing: border-box;
    border-top: 1px solid color-mix(in srgb, var(--fest-border) 65%, transparent);
  }

  .saltacoda-menu-search {
    width: 100%;
    border: 1px solid var(--fest-border);
    border-radius: 999px;
    background: #fff;
    padding: 0.48rem 0.85rem;
    color: var(--text-main);
    font-size: 0.86rem;
    font-family: inherit;
    box-shadow: none;
  }

  .saltacoda-menu-search:focus {
    outline: none;
    border-color: color-mix(in srgb, var(--card-accent) 45%, transparent);
    box-shadow: 0 0 0 0.12rem color-mix(in srgb, var(--card-accent) 14%, transparent);
  }

  .saltacoda-kitchen-nav {
    position: fixed;
    top: var(--saltacoda-topbar-offset);
    left: 0;
    right: 0;
    z-index: 1015;
    height: var(--saltacoda-kitchen-nav-h);
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    background: rgba(255, 255, 255, 0.94);
    backdrop-filter: blur(8px);
    border-bottom: 1px solid var(--fest-border);
    box-shadow: 0 4px 14px rgba(21, 38, 92, 0.05);
  }

  .saltacoda-kitchen-chips {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    flex: 0 0 var(--saltacoda-kitchen-chips-h);
    height: var(--saltacoda-kitchen-chips-h);
    padding: 0.5rem 0.75rem 0.35rem;
    overflow-x: auto;
    overflow-y: visible;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none;
  }

  .saltacoda-kitchen-chips::-webkit-scrollbar {
    display: none;
  }

  .saltacoda-kitchen-chip {
    flex: 0 0 auto;
    display: inline-flex;
    align-items: center;
    gap: 0.4rem;
    border: 1px solid var(--fest-border);
    border-radius: 999px;
    background: #fff;
    color: var(--text-main);
    padding: 0.42rem 0.8rem;
    font-family: inherit;
    font-size: 0.82rem;
    font-weight: 700;
    line-height: 1.1;
    white-space: nowrap;
    transition: background 0.15s ease, border-color 0.15s ease, color 0.15s ease, box-shadow 0.15s ease;
  }

  .saltacoda-kitchen-chip__count {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 1.25rem;
    height: 1.25rem;
    padding: 0 0.3rem;
    border-radius: 999px;
    font-size: 0.68rem;
    font-weight: 800;
    color: var(--text-muted);
    background: color-mix(in srgb, var(--text-main) 6%, #fff);
  }

  .saltacoda-kitchen-chip.is-active {
    border-color: color-mix(in srgb, var(--card-accent) 45%, transparent);
    color: #fff;
    background: linear-gradient(
      135deg,
      color-mix(in srgb, var(--card-accent) 92%, #fff) 0%,
      color-mix(in srgb, var(--card-accent) 78%, #15265c) 100%
    );
    box-shadow: 0 6px 16px color-mix(in srgb, var(--card-accent) 28%, transparent);
  }

  .saltacoda-kitchen-chip.is-active .saltacoda-kitchen-chip__count {
    color: #fff;
    background: rgba(255, 255, 255, 0.22);
  }

  .saltacoda-content {
    margin-top: calc(var(--saltacoda-topbar-offset) + var(--saltacoda-kitchen-nav-h));
    padding: 0.75rem 0.75rem calc(var(--saltacoda-footbar-h) + 1rem + env(safe-area-inset-bottom));
    height: calc(100dvh - var(--saltacoda-topbar-offset) - var(--saltacoda-kitchen-nav-h));
    overflow-y: auto;
  }

  .saltacoda-kitchen-empty {
    background: var(--fest-surface);
    border: 1px dashed var(--fest-border);
    border-radius: 0.85rem;
    padding: 1.25rem 1rem;
    text-align: center;
    color: var(--text-muted);
    font-size: 0.9rem;
  }

  .saltacoda-kitchen:not(.is-active) {
    display: none !important;
  }

  .saltacoda-no-results {
    background: var(--fest-surface);
    border: 1px dashed var(--fest-border);
    border-radius: 0.8rem;
    padding: 0.9rem;
    text-align: center;
    color: var(--text-muted);
    display: none;
  }

  .saltacoda-dish {
    width: 100%;
    background: var(--fest-surface);
    border-radius: 0.85rem;
    padding: 0.82rem 0.85rem;
    margin-bottom: 0.55rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 0.75rem;
    text-align: left;
    border: 1px solid var(--fest-border);
    transition: transform 0.15s ease, box-shadow 0.15s ease, border-color 0.15s ease;
  }

  .saltacoda-dish:active {
    transform: scale(0.99);
  }

  .saltacoda-dish.added {
    border-color: var(--saltacoda-accent-border);
    box-shadow: 0 6px 14px var(--saltacoda-accent-shadow);
    animation: saltacodaDishAdded 0.42s ease;
  }

  .saltacoda-dish.has-items {
    border-color: color-mix(in srgb, var(--card-accent) 32%, transparent);
    background: var(--saltacoda-accent-surface);
  }

  .saltacoda-dish--has-varianti .saltacoda-dish-variant-hint {
    display: inline-flex;
    align-items: center;
    font-size: 0.66rem;
    font-weight: 700;
    letter-spacing: 0.02em;
    text-transform: uppercase;
    color: var(--saltacoda-accent-text);
    background: color-mix(in srgb, var(--card-accent) 12%, #fff);
    border: 1px solid color-mix(in srgb, var(--card-accent) 28%, transparent);
    border-radius: 999px;
    padding: 0.14rem 0.45rem;
  }

  .saltacoda-dish-variant-hint {
    display: none;
  }

  .sc-variant-picker {
    z-index: 10060;
  }

  .sc-variant-sheet {
    display: flex;
    flex-direction: column;
    gap: 0.65rem;
  }

  .sc-variant-close {
    position: absolute;
    top: 0.65rem;
    right: 0.65rem;
    width: 2rem;
    height: 2rem;
    border: 0;
    border-radius: 999px;
    background: color-mix(in srgb, var(--text-main) 6%, #fff);
    color: var(--text-muted);
    font-size: 1.25rem;
    line-height: 1;
    cursor: pointer;
  }

  .sc-variant-dish-head {
    padding-right: 2.25rem;
  }

  .sc-variant-dish-head h2 {
    margin: 0;
    font-size: 1.05rem;
    font-weight: 800;
    color: var(--text-main);
    line-height: 1.2;
  }

  .sc-variant-dish-head p {
    margin: 0.2rem 0 0;
    font-size: 0.82rem;
    color: var(--text-muted);
  }

  .sc-variant-group + .sc-variant-group {
    margin-top: 0.15rem;
  }

  .sc-variant-group__title {
    margin: 0 0 0.45rem;
    font-size: 0.72rem;
    font-weight: 800;
    letter-spacing: 0.04em;
    text-transform: uppercase;
    color: var(--text-muted);
  }

  .sc-variant-options {
    display: flex;
    flex-direction: column;
    gap: 0.45rem;
  }

  .sc-variant-option {
    display: flex;
    align-items: center;
    gap: 0.65rem;
    border: 1px solid var(--fest-border);
    border-radius: 0.75rem;
    background: #fff;
    padding: 0.62rem 0.7rem;
    cursor: pointer;
    transition: border-color 0.15s ease, background 0.15s ease, box-shadow 0.15s ease;
  }

  .sc-variant-option.is-checked {
    border-color: color-mix(in srgb, var(--card-accent) 45%, transparent);
    background: var(--saltacoda-accent-surface);
    box-shadow: 0 4px 12px color-mix(in srgb, var(--card-accent) 12%, transparent);
  }

  .sc-variant-option input {
    width: 1rem;
    height: 1rem;
    flex-shrink: 0;
    accent-color: var(--card-accent);
  }

  .sc-variant-option__label {
    flex: 1;
    min-width: 0;
    font-size: 0.9rem;
    font-weight: 600;
    color: var(--text-main);
    line-height: 1.25;
  }

  .sc-variant-option__price {
    font-size: 0.8rem;
    font-weight: 700;
    color: var(--card-accent);
    white-space: nowrap;
  }

  .sc-variant-group__hint {
    margin: -0.2rem 0 0.45rem;
    font-size: 0.78rem;
    color: var(--text-muted);
    line-height: 1.35;
  }

  .sc-variant-total {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0.75rem;
    margin-top: 0.15rem;
    padding: 0.7rem 0.8rem;
    border-radius: 0.75rem;
    background: color-mix(in srgb, var(--card-accent) 8%, #fff);
    border: 1px solid color-mix(in srgb, var(--card-accent) 22%, transparent);
  }

  .sc-variant-total span {
    font-size: 0.82rem;
    font-weight: 600;
    color: var(--text-muted);
  }

  .sc-variant-total strong {
    font-size: 1rem;
    font-weight: 800;
    color: var(--text-main);
  }

  .saltacoda-cart-item__varianti {
    margin-top: 0.2rem;
    font-size: 0.74rem;
    color: var(--text-muted);
    line-height: 1.35;
  }

  .saltacoda-dish:last-child {
    margin-bottom: 0;
  }

  .saltacoda-dish-left {
    min-width: 0;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 0.45rem;
    flex: 1;
  }

  .saltacoda-dish-name {
    font-weight: 600;
    color: var(--text-main);
    margin-right: 0;
    line-height: 1.22;
    word-break: break-word;
  }

  .saltacoda-dish-price {
    font-weight: 700;
    color: var(--card-accent);
    white-space: nowrap;
    font-size: 0.9rem;
    background: color-mix(in srgb, var(--card-accent) 12%, #fff);
    border-radius: 999px;
    padding: 0.2rem 0.55rem;
  }

  .saltacoda-dish-meta {
    display: inline-flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 0.35rem;
    flex-shrink: 0;
  }

  .saltacoda-dish-counter {
    min-width: 22px;
    height: 22px;
    border-radius: 999px;
    font-size: 0.75rem;
    font-weight: 700;
    display: none;
    align-items: center;
    justify-content: center;
    background: var(--saltacoda-accent);
    color: #fff;
    box-shadow: 0 2px 8px color-mix(in srgb, var(--card-accent) 28%, transparent);
  }

  .saltacoda-dish-counter.visible {
    display: inline-flex;
  }

  .saltacoda-dish-counter.pulse {
    animation: saltacodaCounterPulse 0.35s ease;
  }

  @keyframes saltacodaDishAdded {
    0% {
      transform: scale(1);
      box-shadow: 0 0 0 color-mix(in srgb, var(--card-accent) 6%, transparent);
    }
    45% {
      transform: scale(1.01);
      box-shadow: 0 10px 22px color-mix(in srgb, var(--card-accent) 22%, transparent);
    }
    100% {
      transform: scale(1);
      box-shadow: 0 6px 14px var(--saltacoda-accent-shadow);
    }
  }

  @keyframes saltacodaCounterPulse {
    0% {
      transform: scale(1);
    }
    50% {
      transform: scale(1.22);
    }
    100% {
      transform: scale(1);
    }
  }

  .saltacoda-footbar {
    position: fixed !important;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(8px);
    border-top: 1px solid rgba(21, 38, 92, 0.08);
    box-shadow: 0 -6px 24px var(--fest-shadow);
    display: block !important;
    visibility: visible !important;
  }

  .saltacoda-cart-summary {
    min-height: var(--saltacoda-footbar-h);
    padding: 0.65rem 0.75rem calc(0.65rem + env(safe-area-inset-bottom));
    display: flex;
    gap: 0.6rem;
    align-items: center;
  }

  .saltacoda-cart-toggle {
    border: 0;
    flex: 1;
    padding: 0.5rem;
    background: transparent;
    text-align: left;
    color: var(--text-muted);
  }

  .saltacoda-cart-toggle small {
    display: block;
    color: var(--text-muted);
    font-size: 0.75rem;
  }

  .saltacoda-cart-toggle strong {
    display: block;
    font-size: 0.95rem;
    line-height: 1.2;
    color: var(--text-main);
  }

  .saltacoda-cart-chevron {
    font-size: 1rem;
    color: var(--text-muted);
    margin-left: 0.25rem;
    transition: transform 0.2s ease;
  }

  .saltacoda-cart-toggle[aria-expanded="true"] .saltacoda-cart-chevron {
    transform: rotate(180deg);
  }

  .saltacoda-send-btn {
    min-width: 86px;
    padding: 0.7rem 0.95rem;
  }

  .saltacoda-cart-body {
    border-top: 1px solid var(--fest-border);
    max-height: 36vh;
    overflow-y: auto;
    padding: 0.5rem 0.75rem 0.85rem;
  }

  #saltacodaCartCollapse {
    display: none;
    max-height: calc(100dvh - var(--saltacoda-topbar-offset) - var(--saltacoda-kitchen-nav-h) - var(--saltacoda-footbar-h) - env(safe-area-inset-bottom) - 0.5rem);
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }

  #saltacodaCartCollapse.is-open {
    display: block;
  }

  .saltacoda-cart-actions {
    border-top: 1px solid var(--fest-border);
    padding: 0.6rem 0.75rem calc(0.7rem + env(safe-area-inset-bottom));
    background: var(--fest-surface);
  }

  .saltacoda-clear-btn {
    width: 100%;
    border: 1px solid #f1c2c2;
    border-radius: 0.65rem;
    background: #fff7f7;
    color: #d14343;
    font-size: 0.86rem;
    font-weight: 700;
    padding: 0.62rem 0.85rem;
  }

  .saltacoda-clear-btn:disabled {
    background: #f7f7f9;
    border-color: #ebedf4;
    color: #9aa3b2;
  }

  .saltacoda-info-required {
    color: #d14343;
    margin-left: 0.15rem;
  }

  .saltacoda-cart-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 0.5rem;
    padding: 0.55rem 0;
    border-bottom: 1px dashed var(--fest-border);
  }

  .saltacoda-cart-item:last-child {
    border-bottom: 0;
  }

  .saltacoda-qty {
    display: inline-flex;
    align-items: center;
    border: 1px solid var(--fest-border);
    border-radius: 999px;
  }

  .saltacoda-qty button {
    border: 0;
    background: transparent;
    width: 28px;
    height: 28px;
    color: var(--text-muted);
  }

  .saltacoda-qty button:active {
    background: color-mix(in srgb, var(--card-accent) 8%, #fff);
  }

  .saltacoda-qty span {
    min-width: 22px;
    text-align: center;
    font-size: 0.8rem;
    font-weight: 700;
  }

  .saltacoda-empty {
    color: var(--text-muted);
    text-align: center;
    padding: 0.7rem 0.2rem;
    margin: 0;
  }

  .saltacoda-mobile--no-kitchens {
    --saltacoda-kitchen-nav-h: 0px;
  }

  .saltacoda-mobile--no-kitchens .saltacoda-content {
    margin-top: var(--saltacoda-topbar-offset);
    height: calc(100dvh - var(--saltacoda-topbar-offset));
  }

  @media (min-width: 768px) {
    .saltacoda-kitchen-nav {
      left: 50%;
      right: auto;
      width: min(680px, 100%);
      transform: translateX(-50%);
    }

    .saltacoda-mobile {
      margin: 0 auto;
      max-width: 680px;
      border-left: 1px solid color-mix(in srgb, var(--text-main) 8%, transparent);
      border-right: 1px solid color-mix(in srgb, var(--text-main) 8%, transparent);
    }
  }

  @media (max-width: 767.98px) {
    .saltacoda-topbar,
    .saltacoda-footbar {
      width: 100dvw;
      max-width: 100dvw;
    }

    .saltacoda-footbar {
      bottom: 0;
      padding-bottom: env(safe-area-inset-bottom);
    }
  }
</style>
@endsection

@section('content')
<div class="saltacoda-cliente">
  <div class="saltacoda-cliente__bg" aria-hidden="true"></div>

<div class="saltacoda-mobile {{ $cucine->isEmpty() ? 'saltacoda-mobile--no-kitchens' : '' }}">
  <header class="saltacoda-topbar saltacoda-fest-topbar saltacoda-topbar--text-only" id="saltacodaTopbar">
    <div class="saltacoda-topbar-heading">
      <h1 class="saltacoda-topbar-title">Il tuo pre-ordine</h1>
      <p class="saltacoda-topbar-subtitle">presso {{ $attivita->nome }}</p>
    </div>
  </header>

  @if($cucine->isNotEmpty())
    <nav class="saltacoda-kitchen-nav" id="saltacodaKitchenNav" aria-label="Cucine disponibili">
      <div class="saltacoda-kitchen-chips" id="saltacodaKitchenChips" role="tablist">
        @foreach($cucine as $cucina)
          @php
            $piattiCount = $cucina->piatti?->count() ?? 0;
          @endphp
          <button
            type="button"
            class="saltacoda-kitchen-chip"
            role="tab"
            aria-selected="false"
            data-cucina-id="{{ $cucina->id }}"
            data-cucina-nome="{{ $cucina->nome }}"
            id="cucina-tab-{{ $cucina->id }}"
            aria-controls="cucina-panel-{{ $cucina->id }}">
            <span class="saltacoda-kitchen-chip__label">{{ $cucina->nome }}</span>
            <span class="saltacoda-kitchen-chip__count">{{ $piattiCount }}</span>
          </button>
        @endforeach
      </div>
      <div class="saltacoda-menu-search-wrap">
        <input
          type="search"
          id="dishSearch"
          class="saltacoda-menu-search"
          placeholder="Cerca nella cucina..."
          autocomplete="off">
      </div>
    </nav>
  @endif

  <main class="saltacoda-content" id="saltacodaMenuContent">
    @forelse($cucine as $cucina)
      <section
        class="saltacoda-kitchen"
        id="cucina-panel-{{ $cucina->id }}"
        data-cucina-id="{{ $cucina->id }}"
        role="tabpanel"
        aria-labelledby="cucina-tab-{{ $cucina->id }}"
        hidden>
        @forelse($cucina->piatti as $piatto)
          @php
            $variantiPiatto = $varianti_per_piatto[$piatto->id] ?? [];
            $variantiCucina = $varianti_per_cucina[$cucina->id] ?? [];
            $haVariantiPiatto = !empty($variantiPiatto);
            $haVariantiCucina = !empty($variantiCucina);
            $haVarianti = $haVariantiPiatto || $haVariantiCucina;
            if ($haVariantiPiatto && $haVariantiCucina) {
              $variantiHint = 'Varianti piatto e cucina';
            } elseif ($haVariantiCucina) {
              $variantiHint = 'Varianti cucina';
            } else {
              $variantiHint = 'Varianti piatto';
            }
          @endphp
          <button
            type="button"
            class="saltacoda-dish{{ $haVarianti ? ' saltacoda-dish--has-varianti' : '' }}"
            data-cucina-id="{{ $cucina->id }}"
            data-piatto-id="{{ $piatto->id }}"
            data-piatto-nome="{{ $piatto->nome }}"
            data-piatto-prezzo="{{ (float) $piatto->prezzo }}"
            data-ha-varianti-cucina="{{ $haVariantiCucina ? '1' : '0' }}"
            data-ha-varianti-piatto="{{ $haVariantiPiatto ? '1' : '0' }}">
            <span class="saltacoda-dish-left">
              <span class="saltacoda-dish-name">{{ $piatto->nome }}</span>
              @if($haVarianti)
                <span class="saltacoda-dish-variant-hint">{{ $variantiHint }}</span>
              @endif
            </span>
            <span class="saltacoda-dish-meta">
              <span class="saltacoda-dish-price">€ {{ number_format((float) $piatto->prezzo, 2, ',', '.') }}</span>
              <span class="saltacoda-dish-counter" data-counter-for="{{ $piatto->id }}">0</span>
            </span>
          </button>
        @empty
          <p class="saltacoda-kitchen-empty mb-0">Nessun piatto disponibile in questa cucina.</p>
        @endforelse
      </section>
    @empty
      <p class="saltacoda-kitchen-empty mb-0">Nessuna cucina disponibile al momento.</p>
    @endforelse
    <p id="noResultsMessage" class="saltacoda-no-results mb-0">Nessun piatto trovato in questa cucina.</p>
  </main>

  <aside class="saltacoda-footbar">
    <div class="saltacoda-cart-summary">
      <button
        class="saltacoda-cart-toggle"
        type="button"
        id="cartToggleBtn"
        aria-expanded="false"
        aria-controls="saltacodaCartCollapse">
        <small>Il mio ordine</small>
        <strong>
          <span id="cartCount">0</span> piatti · € <span id="cartTotal">0,00</span>
          <i class="bx bx-chevron-up saltacoda-cart-chevron"></i>
        </strong>
      </button>

      <button type="button" id="sendOrderBtn" class="saltacoda-send-btn" disabled>Procedi</button>
    </div>

    <div class="collapse" id="saltacodaCartCollapse" hidden>
      <div class="saltacoda-cart-body" id="cartItemsContainer">
        <p class="saltacoda-empty mb-0">Il carrello è vuoto.</p>
      </div>
      <div class="saltacoda-cart-actions">
        <button type="button" id="clearCartBtn" class="saltacoda-clear-btn" disabled>
          Elimina tutti i piatti
        </button>
      </div>
    </div>
  </aside>
</div>

  <div id="scStepApertura" class="sc-step-overlay" hidden>
    <div class="sc-step-sheet sc-step-sheet--center">
      <div class="sc-istruzione-panel">
        <h2 class="sc-istruzione-panel__title" id="scAperturaTitle"></h2>
        <div class="sc-istruzione-panel__text" id="scAperturaText"></div>
      </div>
      <div class="sc-step-actions">
        <button type="button" id="scAperturaNext" class="saltacoda-fest-btn">Avanti</button>
      </div>
    </div>
  </div>

  <div id="scCheckoutWizard" class="sc-step-overlay sc-checkout-wizard" hidden>
    <div class="sc-step-sheet sc-checkout-wizard__sheet">
      <div id="scStepInfo" class="sc-wizard-pane sc-wizard-pane--info" hidden>
        <div class="sc-wizard-pane__head">
          <span class="sc-wizard-step-badge" id="scWizardStepBadge" hidden></span>
          <h2 class="sc-wizard-pane__heading">I tuoi dati</h2>
          <p class="sc-wizard-pane__hint">Compila i campi per completare l'ordine.</p>
        </div>
        <div class="sc-wizard-pane__body">
          <div class="sc-info-fields-wrap" id="saltacodaInfoFields"></div>
        </div>
        <div class="sc-wizard-pane__foot sc-step-actions">
          <button type="button" id="scInfoBack" class="sc-step-btn-secondary">Indietro</button>
          <button type="button" id="scInfoNext" class="saltacoda-fest-btn">Continua</button>
        </div>
      </div>

      <div id="scStepPreInvio" class="sc-wizard-pane sc-wizard-pane--confirm" hidden>
        <div class="sc-wizard-pane__head">
          <span class="sc-wizard-step-badge" id="scWizardConfirmBadge" hidden></span>
          <h2 class="sc-wizard-pane__heading">Conferma ordine</h2>
        </div>
        <div class="sc-wizard-pane__body">
          <div class="sc-istruzione-panel">
            <h3 class="sc-istruzione-panel__title" id="scPreInvioTitle"></h3>
            <div class="sc-istruzione-panel__text" id="scPreInvioText"></div>
          </div>
        </div>
        <div class="sc-wizard-pane__foot sc-step-actions">
          <button type="button" id="scPreInvioBack" class="sc-step-btn-secondary">Indietro</button>
          <button type="button" id="scPreInvioSend" class="saltacoda-fest-btn">Conferma e invia</button>
        </div>
      </div>
    </div>
  </div>

  <div id="scVariantPicker" class="sc-step-overlay sc-variant-picker" hidden>
    <div class="sc-step-sheet sc-variant-sheet" role="dialog" aria-labelledby="scVariantDishName">
      <button type="button" class="sc-variant-close" id="scVariantClose" aria-label="Chiudi">×</button>
      <div class="sc-variant-dish-head">
        <h2 id="scVariantDishName"></h2>
        <p id="scVariantDishBasePrice"></p>
      </div>
      <div id="scVariantGroups"></div>
      <div class="sc-variant-total">
        <span>Totale unità</span>
        <strong id="scVariantTotalPrice">€ 0,00</strong>
      </div>
      <div class="sc-step-actions">
        <button type="button" id="scVariantCancel" class="sc-step-btn-secondary">Annulla</button>
        <button type="button" id="scVariantConfirm" class="saltacoda-fest-btn">Aggiungi al carrello</button>
      </div>
    </div>
  </div>
</div>

<script>
  (function () {
    const infoFieldsConfig = @json($campi_info ?? []);
    const istruzioni = @json($istruzioni);
    const savePreOrderUrl = @json(route('saltacoda.pre-ordine.salva'));
    const saltacodaId = @json($saltacoda_id ?? null);
    const attivitaId = @json($attivita->id ?? null);
    const variantiPerPiatto = @json($varianti_per_piatto ?? []);
    const variantiPerCucina = @json($varianti_per_cucina ?? []);
    const cart = {};
    const infoValues = {};
    const countEl = document.getElementById('cartCount');
    const totalEl = document.getElementById('cartTotal');
    const cartToggleBtnEl = document.getElementById('cartToggleBtn');
    const cartCollapseEl = document.getElementById('saltacodaCartCollapse');
    const containerEl = document.getElementById('cartItemsContainer');
    const sendBtnEl = document.getElementById('sendOrderBtn');
    const clearBtnEl = document.getElementById('clearCartBtn');
    const dishSearchEl = document.getElementById('dishSearch');
    const noResultsEl = document.getElementById('noResultsMessage');
    const infoFieldsEl = document.getElementById('saltacodaInfoFields');
    const aperturaOverlayEl = document.getElementById('scStepApertura');
    const aperturaTitleEl = document.getElementById('scAperturaTitle');
    const aperturaTextEl = document.getElementById('scAperturaText');
    const aperturaNextEl = document.getElementById('scAperturaNext');
    const checkoutWizardEl = document.getElementById('scCheckoutWizard');
    const stepInfoEl = document.getElementById('scStepInfo');
    const stepPreInvioEl = document.getElementById('scStepPreInvio');
    const preInvioTitleEl = document.getElementById('scPreInvioTitle');
    const preInvioTextEl = document.getElementById('scPreInvioText');
    const infoBackEl = document.getElementById('scInfoBack');
    const infoNextEl = document.getElementById('scInfoNext');
    const preInvioBackEl = document.getElementById('scPreInvioBack');
    const preInvioSendEl = document.getElementById('scPreInvioSend');
    const wizardStepBadgeEl = document.getElementById('scWizardStepBadge');
    const wizardConfirmBadgeEl = document.getElementById('scWizardConfirmBadge');
    const kitchenChipsEl = document.getElementById('saltacodaKitchenChips');
    const menuContentEl = document.getElementById('saltacodaMenuContent');
    const variantPickerEl = document.getElementById('scVariantPicker');
    const variantDishNameEl = document.getElementById('scVariantDishName');
    const variantDishBasePriceEl = document.getElementById('scVariantDishBasePrice');
    const variantGroupsEl = document.getElementById('scVariantGroups');
    const variantTotalPriceEl = document.getElementById('scVariantTotalPrice');
    const variantCloseEl = document.getElementById('scVariantClose');
    const variantCancelEl = document.getElementById('scVariantCancel');
    const variantConfirmEl = document.getElementById('scVariantConfirm');
    let isSending = false;
    let activeKitchenId = null;
    let pendingDish = null;
    let selectedVariantIds = new Set();

    function slotIsActive(key) {
      const slot = istruzioni[key];
      return !!(slot && slot.attivo && ((slot.titolo || '').trim() || (slot.testo || '').trim()));
    }

    function fillIstruzioneSlot(titleEl, textEl, key) {
      const slot = istruzioni[key] || {};
      const titolo = (slot.titolo || '').trim();
      const testo = (slot.testo || '').trim();
      titleEl.textContent = titolo;
      textEl.textContent = testo;
      titleEl.hidden = titolo === '';
      textEl.hidden = testo === '';
    }

    function setWizardOpen(isOpen) {
      document.body.classList.toggle('sc-wizard-open', isOpen);
    }

    function showApertura() {
      fillIstruzioneSlot(aperturaTitleEl, aperturaTextEl, 'apertura');
      aperturaOverlayEl.hidden = false;
      setWizardOpen(true);
    }

    function hideApertura() {
      aperturaOverlayEl.hidden = true;
      if (checkoutWizardEl.hidden) {
        setWizardOpen(false);
      }
    }

    function getCheckoutStepCount() {
      let count = 0;
      if (infoFieldsConfig.length > 0) {
        count += 1;
      }
      if (slotIsActive('pre_invio')) {
        count += 1;
      }
      return count;
    }

    function updateStepBadges(currentStep) {
      const totalSteps = getCheckoutStepCount();
      const showBadges = totalSteps > 1;
      let currentIndex = 1;

      if (currentStep === 'pre_invio') {
        currentIndex = infoFieldsConfig.length > 0 ? 2 : 1;
      }

      const label = showBadges ? `Passo ${currentIndex} di ${totalSteps}` : '';

      if (wizardStepBadgeEl) {
        wizardStepBadgeEl.textContent = label;
        wizardStepBadgeEl.hidden = !showBadges || currentStep !== 'info';
      }

      if (wizardConfirmBadgeEl) {
        wizardConfirmBadgeEl.textContent = label;
        wizardConfirmBadgeEl.hidden = !showBadges || currentStep !== 'pre_invio';
      }
    }

    function showCheckoutStep(step) {
      checkoutWizardEl.hidden = false;
      checkoutWizardEl.classList.toggle('sc-checkout-wizard--info', step === 'info');
      checkoutWizardEl.classList.toggle('sc-checkout-wizard--confirm', step === 'pre_invio');
      stepInfoEl.hidden = step !== 'info';
      stepPreInvioEl.hidden = step !== 'pre_invio';
      if (step === 'pre_invio') {
        fillIstruzioneSlot(preInvioTitleEl, preInvioTextEl, 'pre_invio');
      }
      updateStepBadges(step);
      setWizardOpen(true);

      const activeBody = step === 'info'
        ? stepInfoEl.querySelector('.sc-wizard-pane__body')
        : stepPreInvioEl.querySelector('.sc-wizard-pane__body');
      if (activeBody) {
        activeBody.scrollTop = 0;
      }
    }

    function hideCheckoutWizard() {
      checkoutWizardEl.hidden = true;
      checkoutWizardEl.classList.remove('sc-checkout-wizard--info', 'sc-checkout-wizard--confirm');
      stepInfoEl.hidden = true;
      stepPreInvioEl.hidden = true;
      if (aperturaOverlayEl.hidden) {
        setWizardOpen(false);
      }
    }

    function startCheckoutFlow() {
      if (infoFieldsConfig.length > 0) {
        showCheckoutStep('info');
        return;
      }
      if (slotIsActive('pre_invio')) {
        showCheckoutStep('pre_invio');
        return;
      }
      completeOrderSend();
    }

    function goBackFromPreInvio() {
      if (infoFieldsConfig.length > 0) {
        showCheckoutStep('info');
        return;
      }
      hideCheckoutWizard();
    }

    function formatEuro(value) {
      return value.toLocaleString('it-IT', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }

    function createLineId() {
      if (window.crypto && window.crypto.randomUUID) {
        return window.crypto.randomUUID();
      }
      return `line_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
    }

    function getVariantiForDish(piattoId, cucinaId) {
      return {
        piatto: variantiPerPiatto[String(piattoId)] || variantiPerPiatto[piattoId] || [],
        cucina: variantiPerCucina[String(cucinaId)] || variantiPerCucina[cucinaId] || [],
      };
    }

    function dishHasVarianti(piattoId, cucinaId) {
      const varianti = getVariantiForDish(piattoId, cucinaId);
      return varianti.piatto.length > 0 || varianti.cucina.length > 0;
    }

    function variantKey(varianti) {
      return (varianti || [])
        .map((variante) => String(variante.id))
        .sort()
        .join('-');
    }

    function calcLinePrice(basePrice, varianti) {
      const extra = (varianti || []).reduce((acc, variante) => acc + (parseFloat(variante.prezzo) || 0), 0);
      return (parseFloat(basePrice) || 0) + extra;
    }

    function formatVariantePrice(prezzo) {
      const value = parseFloat(prezzo) || 0;
      if (value <= 0) {
        return 'Inclusa';
      }
      return `+€ ${formatEuro(value)}`;
    }

    function getQtyForPiatto(piattoId) {
      return Object.values(cart)
        .filter((item) => String(item.piattoId) === String(piattoId))
        .reduce((acc, item) => acc + item.qty, 0);
    }

    function findMatchingLine(piattoId, varianti) {
      const key = variantKey(varianti);
      return Object.values(cart).find((item) => (
        String(item.piattoId) === String(piattoId) && variantKey(item.varianti) === key
      )) || null;
    }

    function getTotals() {
      const items = Object.values(cart);
      const count = items.reduce((acc, item) => acc + item.qty, 0);
      const total = items.reduce((acc, item) => acc + item.qty * item.price, 0);
      return { count, total };
    }

    function renderVariantiHtml(varianti) {
      if (!varianti || varianti.length === 0) {
        return '';
      }

      const labels = varianti.map((variante) => {
        const extra = parseFloat(variante.prezzo) || 0;
        const suffix = extra > 0 ? ` (+€ ${formatEuro(extra)})` : '';
        const scope = variante.scope === 'cucina' ? 'Cucina: ' : '';
        return `${scope}${variante.label}${suffix}`;
      });

      return `<div class="saltacoda-cart-item__varianti">${labels.join('<br>')}</div>`;
    }

    function renderCart() {
      const items = Object.values(cart);
      const { count, total } = getTotals();

      countEl.textContent = count;
      totalEl.textContent = formatEuro(total);
      sendBtnEl.disabled = count === 0;
      clearBtnEl.disabled = count === 0;

      document.querySelectorAll('.saltacoda-dish-counter').forEach((counterEl) => {
        const piattoId = counterEl.dataset.counterFor;
        const qty = getQtyForPiatto(piattoId);
        counterEl.textContent = qty;
        counterEl.classList.toggle('visible', qty > 0);
      });

      document.querySelectorAll('.saltacoda-dish').forEach((dishEl) => {
        const piattoId = dishEl.dataset.piattoId;
        const qty = getQtyForPiatto(piattoId);
        dishEl.classList.toggle('has-items', qty > 0);
      });

      if (items.length === 0) {
        containerEl.innerHTML = '<p class="saltacoda-empty mb-0">Il carrello è vuoto.</p>';
        return;
      }

      containerEl.innerHTML = items.map((item) => {
        return `
          <div class="saltacoda-cart-item">
            <div>
              <strong>${item.name}</strong>
              ${renderVariantiHtml(item.varianti)}
              <div class="text-muted small">€ ${formatEuro(item.price)} cad.</div>
              <input
                type="text"
                class="form-control form-control-sm mt-2"
                placeholder="Nota riga (opzionale)"
                data-note-id="${item.lineId}"
                value="${(item.note || '').replace(/"/g, '&quot;')}">
            </div>
            <div class="d-flex align-items-center gap-2">
              <div class="saltacoda-qty">
                <button type="button" data-action="dec" data-id="${item.lineId}">−</button>
                <span>${item.qty}</span>
                <button type="button" data-action="inc" data-id="${item.lineId}">+</button>
              </div>
              <strong>€ ${formatEuro(item.qty * item.price)}</strong>
            </div>
          </div>
        `;
      }).join('');
    }

    function normalizeSelectedVarianti(selectedVarianti, cucinaId, piattoId) {
      const cucinaIds = new Set((getVariantiForDish(piattoId, cucinaId).cucina || []).map((v) => String(v.id)));

      return (selectedVarianti || []).map((variante) => ({
        id: variante.id,
        label: variante.label,
        prezzo: parseFloat(variante.prezzo) || 0,
        scope: cucinaIds.has(String(variante.id)) ? 'cucina' : 'piatto',
      }));
    }

    function addToCart(piattoId, cucinaId, name, basePrice, varianti) {
      const normalizedVarianti = normalizeSelectedVarianti(varianti, cucinaId, piattoId);
      const existingLine = findMatchingLine(piattoId, normalizedVarianti);

      if (existingLine) {
        existingLine.qty += 1;
      } else {
        const lineId = createLineId();
        cart[lineId] = {
          lineId,
          piattoId: String(piattoId),
          cucinaId: String(cucinaId),
          name,
          basePrice: parseFloat(basePrice) || 0,
          price: calcLinePrice(basePrice, normalizedVarianti),
          qty: 1,
          note: '',
          varianti: normalizedVarianti,
        };
      }

      renderCart();
    }

    function changeLineQty(lineId, delta) {
      const item = cart[lineId];
      if (!item) {
        return;
      }

      item.qty += delta;
      if (item.qty <= 0) {
        delete cart[lineId];
      }

      renderCart();
    }

    function getSelectedVarianti() {
      if (!pendingDish) {
        return [];
      }

      const allVarianti = [
        ...getVariantiForDish(pendingDish.piattoId, pendingDish.cucinaId).cucina,
        ...getVariantiForDish(pendingDish.piattoId, pendingDish.cucinaId).piatto,
      ];

      return allVarianti.filter((variante) => selectedVariantIds.has(String(variante.id)));
    }

    function updateVariantPickerTotal() {
      if (!pendingDish || !variantTotalPriceEl) {
        return;
      }

      const total = calcLinePrice(pendingDish.basePrice, getSelectedVarianti());
      variantTotalPriceEl.textContent = `€ ${formatEuro(total)}`;
    }

    function renderVariantGroup(title, varianti, hint) {
      if (!varianti.length) {
        return '';
      }

      const options = varianti.map((variante) => {
        const checked = selectedVariantIds.has(String(variante.id));
        return `
          <label class="sc-variant-option${checked ? ' is-checked' : ''}">
            <input
              type="checkbox"
              class="sc-variant-checkbox"
              value="${variante.id}"
              ${checked ? 'checked' : ''}>
            <span class="sc-variant-option__label">${variante.label}</span>
            <span class="sc-variant-option__price">${formatVariantePrice(variante.prezzo)}</span>
          </label>
        `;
      }).join('');

      const hintHtml = hint ? `<p class="sc-variant-group__hint">${hint}</p>` : '';

      return `
        <section class="sc-variant-group">
          <h3 class="sc-variant-group__title">${title}</h3>
          ${hintHtml}
          <div class="sc-variant-options">${options}</div>
        </section>
      `;
    }

    function renderVariantPicker() {
      if (!pendingDish || !variantGroupsEl) {
        return;
      }

      const varianti = getVariantiForDish(pendingDish.piattoId, pendingDish.cucinaId);
      variantDishNameEl.textContent = pendingDish.name;
      variantDishBasePriceEl.textContent = `Prezzo base € ${formatEuro(pendingDish.basePrice)}`;
      variantGroupsEl.innerHTML = [
        renderVariantGroup(
          'Varianti cucina',
          varianti.cucina,
          'Valide per tutti i piatti di questa cucina.'
        ),
        renderVariantGroup('Varianti piatto', varianti.piatto, ''),
      ].join('');
      updateVariantPickerTotal();
    }

    function setVariantPickerOpen(isOpen) {
      if (!variantPickerEl) {
        return;
      }

      variantPickerEl.hidden = !isOpen;
      document.body.classList.toggle('sc-variant-open', isOpen);

      if (!isOpen) {
        pendingDish = null;
        selectedVariantIds = new Set();
      }
    }

    function openVariantPicker(dish) {
      pendingDish = {
        piattoId: dish.piattoId,
        cucinaId: dish.cucinaId,
        name: dish.name,
        basePrice: dish.basePrice,
      };
      selectedVariantIds = new Set();
      renderVariantPicker();
      setVariantPickerOpen(true);
    }

    function closeVariantPicker() {
      setVariantPickerOpen(false);
    }

    function confirmVariantPicker() {
      if (!pendingDish) {
        return;
      }

      const dishRef = { ...pendingDish };
      const selectedVarianti = getSelectedVarianti();
      addToCart(
        dishRef.piattoId,
        dishRef.cucinaId,
        dishRef.name,
        dishRef.basePrice,
        selectedVarianti
      );
      animateAddedFeedback(dishRef.piattoId);

      const dishEl = document.querySelector(`.saltacoda-dish[data-piatto-id="${dishRef.piattoId}"]`);
      if (dishEl) {
        dishEl.classList.add('added');
        setTimeout(() => dishEl.classList.remove('added'), 220);
      }

      closeVariantPicker();
      ensureCartOpen();
    }

    function handleDishTap(dishEl) {
      const piattoId = dishEl.dataset.piattoId;
      const cucinaId = dishEl.dataset.cucinaId;
      const name = dishEl.dataset.piattoNome;
      const basePrice = parseFloat(dishEl.dataset.piattoPrezzo || '0');

      if (dishHasVarianti(piattoId, cucinaId)) {
        openVariantPicker({ piattoId, cucinaId, name, basePrice });
        return;
      }

      addToCart(piattoId, cucinaId, name, basePrice, []);
      animateAddedFeedback(piattoId);
      dishEl.classList.add('added');
      setTimeout(() => dishEl.classList.remove('added'), 220);
    }

    function animateAddedFeedback(dishId) {
      const counterEl = document.querySelector(`.saltacoda-dish-counter[data-counter-for="${dishId}"]`);
      if (!counterEl) {
        return;
      }

      counterEl.classList.remove('pulse');
      // Force reflow to restart animation when tapping quickly.
      void counterEl.offsetWidth;
      counterEl.classList.add('pulse');
      setTimeout(() => counterEl.classList.remove('pulse'), 380);
    }

    document.querySelectorAll('.saltacoda-dish').forEach((dishBtn) => {
      dishBtn.addEventListener('click', function () {
        handleDishTap(this);
      });
    });

    if (variantPickerEl) {
      variantPickerEl.addEventListener('click', function (event) {
        if (event.target === variantPickerEl) {
          closeVariantPicker();
        }
      });

      variantPickerEl.querySelector('.sc-variant-sheet')?.addEventListener('click', function (event) {
        event.stopPropagation();
      });
    }

    if (variantGroupsEl) {
      variantGroupsEl.addEventListener('change', function (event) {
        const checkboxEl = event.target.closest('.sc-variant-checkbox');
        if (!checkboxEl) {
          return;
        }

        const varianteId = String(checkboxEl.value);
        if (checkboxEl.checked) {
          selectedVariantIds.add(varianteId);
        } else {
          selectedVariantIds.delete(varianteId);
        }

        const optionEl = checkboxEl.closest('.sc-variant-option');
        if (optionEl) {
          optionEl.classList.toggle('is-checked', checkboxEl.checked);
        }

        updateVariantPickerTotal();
      });
    }

    variantCloseEl?.addEventListener('click', closeVariantPicker);
    variantCancelEl?.addEventListener('click', closeVariantPicker);
    variantConfirmEl?.addEventListener('click', confirmVariantPicker);

    function normalizeText(value) {
      return (value || '').toLowerCase().trim();
    }

    function renderInfoFields() {
      if (!infoFieldsConfig.length) {
        infoFieldsEl.innerHTML = '';
        return;
      }

      infoFieldsEl.innerHTML = infoFieldsConfig.map((field, index) => {
        const requiredAttr = field.required ? 'required' : '';
        const errorEl = '<p class="sc-info-field-card__error">Compila questo campo per continuare.</p>';
        const currentValue = infoValues[field.key] || '';
        const totalFields = infoFieldsConfig.length;
        const indexLabel = totalFields > 1
          ? `<span class="sc-info-field-card__index">${index + 1} di ${totalFields}</span>`
          : '';
        const statusPill = field.required
          ? '<span class="sc-info-field-card__pill sc-info-field-card__pill--required">Obbligatorio</span>'
          : '<span class="sc-info-field-card__pill">Facoltativo</span>';
        const metaParts = [indexLabel, statusPill].filter(Boolean).join('<span class="sc-info-field-card__sep" aria-hidden="true">·</span>');
        const metaRow = `<p class="sc-info-field-card__meta">${metaParts}</p>`;
        const controlWrapStart = '<div class="sc-info-field-card__control-wrap">';
        const controlWrapEnd = '</div>';

        if (field.type === 'boolean') {
          return `
            <div class="sc-info-field-card" data-info-card="${field.key}">
              <div class="sc-info-field-card__header">
                <label class="sc-info-field-card__label" for="info-${field.key}">${field.label}</label>
                ${metaRow}
              </div>
              ${controlWrapStart}
              <select
                id="info-${field.key}"
                class="sc-info-field-card__control"
                data-info-key="${field.key}"
                data-info-type="boolean"
                ${requiredAttr}>
                <option value="">Scegli una risposta</option>
                <option value="si" ${currentValue === 'si' ? 'selected' : ''}>Sì</option>
                <option value="no" ${currentValue === 'no' ? 'selected' : ''}>No</option>
              </select>
              ${controlWrapEnd}
              ${errorEl}
            </div>
          `;
        }

        if (field.type === 'time') {
          return `
            <div class="sc-info-field-card" data-info-card="${field.key}">
              <div class="sc-info-field-card__header">
                <label class="sc-info-field-card__label" for="info-${field.key}">${field.label}</label>
                ${metaRow}
              </div>
              ${controlWrapStart}
              <input
                type="time"
                id="info-${field.key}"
                class="sc-info-field-card__control"
                data-info-key="${field.key}"
                data-info-type="time"
                value="${currentValue}"
                ${requiredAttr}>
              ${controlWrapEnd}
              ${errorEl}
            </div>
          `;
        }

        return `
          <div class="sc-info-field-card" data-info-card="${field.key}">
            <div class="sc-info-field-card__header">
              <label class="sc-info-field-card__label" for="info-${field.key}">${field.label}</label>
              ${metaRow}
            </div>
            ${controlWrapStart}
            <input
              type="text"
              id="info-${field.key}"
              class="sc-info-field-card__control"
              data-info-key="${field.key}"
              data-info-type="text"
              value="${currentValue}"
              autocomplete="off"
              ${requiredAttr}>
            ${controlWrapEnd}
            ${errorEl}
          </div>
        `;
      }).join('');
    }

    function validateInfoFields() {
      if (!infoFieldsConfig.length) {
        return true;
      }

      let isValid = true;
      infoFieldsEl.querySelectorAll('[data-info-key]').forEach((inputEl) => {
        const fieldKey = inputEl.dataset.infoKey;
        const fieldValue = (inputEl.value || '').trim();
        const config = infoFieldsConfig.find((field) => field.key === fieldKey);
        const required = !!(config && config.required);

        infoValues[fieldKey] = fieldValue;
        const hasError = required && fieldValue === '';
        inputEl.classList.toggle('is-invalid', hasError);
        const cardEl = inputEl.closest('[data-info-card]');
        if (cardEl) {
          cardEl.classList.toggle('sc-info-field-card--error', hasError);
        }
        if (hasError) {
          isValid = false;
        }
      });

      return isValid;
    }

    function completeOrderSend() {
      if (isSending) {
        return;
      }

      if (infoFieldsConfig.length > 0 && !validateInfoFields()) {
        showCheckoutStep('info');
        const firstInvalid = infoFieldsEl.querySelector('.is-invalid');
        if (firstInvalid) {
          const cardEl = firstInvalid.closest('[data-info-card]') || firstInvalid;
          cardEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
          firstInvalid.focus({ preventScroll: true });
        }
        return;
      }

      const rigaOrdine = Object.values(cart)
        .filter((item) => item.qty > 0)
        .map((item) => ({
          piatto_id: Number(item.piattoId),
          qta: Number(item.qty),
          note: (item.note || '').trim(),
          varianti: (item.varianti || []).map((variante) => Number(variante.id)),
        }));

      if (rigaOrdine.length === 0) {
        alert('Aggiungi almeno un piatto prima di inviare.');
        return;
      }

      const infoCliente = {};
      infoFieldsConfig.forEach((field) => {
        const value = (infoValues[field.key] || '').trim();
        if (value !== '') {
          infoCliente[field.key] = value;
        }
      });

      const payload = {
        saltacoda_id: saltacodaId,
        attivita_id: attivitaId,
        riga_ordine: rigaOrdine,
        info_cliente: infoCliente,
        idempotency_key: (window.crypto && window.crypto.randomUUID)
          ? window.crypto.randomUUID()
          : `${Date.now()}_${Math.random().toString(36).slice(2)}`
      };

      if (!payload.saltacoda_id || !payload.attivita_id) {
        alert('Configurazione saltacoda non valida. Ricarica la pagina.');
        return;
      }

      sendBtnEl.disabled = true;
      isSending = true;
      preInvioSendEl.disabled = true;
      fetch(savePreOrderUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: JSON.stringify(payload)
      })
        .then(async (response) => {
          const data = await response.json().catch(() => ({}));
          if (!response.ok) {
            throw data;
          }
          return data;
        })
        .then((data) => {
          if (data.success === true) {
            alert('Pre-ordine inviato correttamente.');
            window.location.href = "{{ route('saltacoda.pre-ordine.show') }}"+'?codice='+data.data.codice;
          } else {
            alert(data.message);
          }
        })
        .catch((error) => {
          const message = error && error.message ? error.message : 'Errore durante l\'invio del pre-ordine.';
          alert(message);
        })
        .finally(() => {
          isSending = false;
          sendBtnEl.disabled = getTotals().count === 0;
          preInvioSendEl.disabled = false;
        });
    }

    function setCartOpen(isOpen) {
      if (!cartCollapseEl || !cartToggleBtnEl) {
        return;
      }
      cartCollapseEl.classList.toggle('is-open', isOpen);
      cartCollapseEl.hidden = !isOpen;
      cartToggleBtnEl.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
    }

    function ensureCartOpen() {
      setCartOpen(true);
    }

    function getActiveKitchenSection() {
      if (!activeKitchenId) {
        return null;
      }
      return document.querySelector(`.saltacoda-kitchen[data-cucina-id="${activeKitchenId}"]`);
    }

    function getActiveKitchenChip() {
      if (!activeKitchenId || !kitchenChipsEl) {
        return null;
      }
      return kitchenChipsEl.querySelector(`.saltacoda-kitchen-chip[data-cucina-id="${activeKitchenId}"]`);
    }

    function updateSearchPlaceholder() {
      const chipEl = getActiveKitchenChip();
      const kitchenName = chipEl ? (chipEl.dataset.cucinaNome || 'cucina') : 'cucina';
      if (dishSearchEl) {
        dishSearchEl.placeholder = `Cerca in ${kitchenName}...`;
      }
    }

    function setActiveKitchen(cucinaId) {
      activeKitchenId = String(cucinaId);

      if (kitchenChipsEl) {
        kitchenChipsEl.querySelectorAll('.saltacoda-kitchen-chip').forEach((chipEl) => {
          const isActive = chipEl.dataset.cucinaId === activeKitchenId;
          chipEl.classList.toggle('is-active', isActive);
          chipEl.setAttribute('aria-selected', isActive ? 'true' : 'false');
          if (isActive) {
            chipEl.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' });
          }
        });
      }

      document.querySelectorAll('.saltacoda-kitchen').forEach((kitchenEl) => {
        const isActive = kitchenEl.dataset.cucinaId === activeKitchenId;
        kitchenEl.classList.toggle('is-active', isActive);
        kitchenEl.hidden = !isActive;
      });

      updateSearchPlaceholder();
      applyDishFilter();
    }

    function initKitchenTabs() {
      if (!kitchenChipsEl) {
        return;
      }

      const chips = Array.from(kitchenChipsEl.querySelectorAll('.saltacoda-kitchen-chip'));
      if (chips.length === 0) {
        return;
      }

      const preferredChip = chips.find((chipEl) => Number(chipEl.querySelector('.saltacoda-kitchen-chip__count')?.textContent || 0) > 0) || chips[0];
      setActiveKitchen(preferredChip.dataset.cucinaId);

      kitchenChipsEl.addEventListener('click', function (event) {
        const chipEl = event.target.closest('.saltacoda-kitchen-chip');
        if (!chipEl) {
          return;
        }
        setActiveKitchen(chipEl.dataset.cucinaId);
      });
    }

    function applyDishFilter() {
      const query = normalizeText(dishSearchEl ? dishSearchEl.value : '');
      const activeKitchenEl = getActiveKitchenSection();
      let visibleDishCount = 0;

      if (!activeKitchenEl) {
        noResultsEl.style.display = 'none';
        return;
      }

      activeKitchenEl.querySelectorAll('.saltacoda-dish').forEach((dishEl) => {
        const dishName = normalizeText(dishEl.dataset.piattoNome);
        const isVisible = query === '' || dishName.includes(query);
        dishEl.style.display = isVisible ? 'flex' : 'none';
        if (isVisible) {
          visibleDishCount += 1;
        }
      });

      const hasDishes = activeKitchenEl.querySelectorAll('.saltacoda-dish').length > 0;
      noResultsEl.style.display = hasDishes && visibleDishCount === 0 ? 'block' : 'none';
    }

    if (dishSearchEl) {
      dishSearchEl.addEventListener('input', applyDishFilter);
    }
    initKitchenTabs();
    renderInfoFields();
    setCartOpen(false);

    if (cartToggleBtnEl) {
      cartToggleBtnEl.addEventListener('click', function () {
        const willOpen = cartCollapseEl.hidden;
        setCartOpen(willOpen);
      });
    }

    if (slotIsActive('apertura')) {
      showApertura();
    }

    aperturaNextEl.addEventListener('click', hideApertura);
    infoBackEl.addEventListener('click', hideCheckoutWizard);
    infoNextEl.addEventListener('click', function () {
      if (!validateInfoFields()) {
        const firstInvalid = infoFieldsEl.querySelector('.is-invalid');
        if (firstInvalid) {
          const cardEl = firstInvalid.closest('[data-info-card]') || firstInvalid;
          cardEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
          firstInvalid.focus({ preventScroll: true });
        }
        return;
      }
      if (slotIsActive('pre_invio')) {
        showCheckoutStep('pre_invio');
        return;
      }
      hideCheckoutWizard();
      completeOrderSend();
    });
    preInvioBackEl.addEventListener('click', goBackFromPreInvio);
    preInvioSendEl.addEventListener('click', completeOrderSend);

    containerEl.addEventListener('click', function (event) {
      const action = event.target.dataset.action;
      const id = event.target.dataset.id;
      if (!action || !id) {
        return;
      }

      const item = cart[id];
      if (!item) {
        return;
      }

      changeLineQty(id, action === 'inc' ? 1 : -1);
    });

    containerEl.addEventListener('input', function (event) {
      const noteInput = event.target.closest('[data-note-id]');
      if (!noteInput) {
        return;
      }
      const itemId = noteInput.dataset.noteId;
      if (!cart[itemId]) {
        return;
      }
      cart[itemId].note = noteInput.value || '';
    });

    function handleInfoFieldChange(event) {
      const inputEl = event.target.closest('[data-info-key]');
      if (!inputEl) {
        return;
      }

      inputEl.classList.remove('is-invalid');
      const cardEl = inputEl.closest('[data-info-card]');
      if (cardEl) {
        cardEl.classList.remove('sc-info-field-card--error');
      }
      infoValues[inputEl.dataset.infoKey] = (inputEl.value || '').trim();
    }

    infoFieldsEl.addEventListener('input', handleInfoFieldChange);
    infoFieldsEl.addEventListener('change', handleInfoFieldChange);

    sendBtnEl.addEventListener('click', function () {
      const { count } = getTotals();
      if (count === 0) {
        return;
      }
      startCheckoutFlow();
    });

    clearBtnEl.addEventListener('click', function () {
      if (Object.keys(cart).length === 0) {
        return;
      }

      const firstConfirm = confirm('Vuoi eliminare tutti i piatti dal carrello?');
      if (!firstConfirm) {
        return;
      }

      const secondConfirm = confirm('Confermi definitivamente? Questa azione non può essere annullata.');
      if (!secondConfirm) {
        return;
      }

      Object.keys(cart).forEach((key) => {
        delete cart[key];
      });
      renderCart();
    });
  })();
</script>
@endsection