@extends('layouts/guest')

@section('title', 'Saltacoda')

@section('page-meta')
<meta name="theme-color" content="#696cff">
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#696cff">
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#696cff">
<meta name="color-scheme" content="light dark">
<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('content')
<style>
  .content-footer {
    display: none;
  }

  .misc-wrapper {
    display: block !important;
    width: 100% !important;
    min-block-size: 100vh !important;
    text-align: initial !important;
  }

  .saltacoda-mobile {
    --saltacoda-topbar-h: 72px;
    --saltacoda-footbar-h: 86px;
    --saltacoda-accent: #f58220;
    --saltacoda-accent-rgb: 245, 130, 32;
    --saltacoda-accent-line: rgba(var(--saltacoda-accent-rgb), 0.42);
    --saltacoda-accent-text: #c45f10;
    --saltacoda-accent-surface: #fff8f2;
    --saltacoda-accent-border: rgba(var(--saltacoda-accent-rgb), 0.45);
    --saltacoda-accent-shadow: rgba(var(--saltacoda-accent-rgb), 0.18);
    --saltacoda-bg: #f0f2f8;
    position: relative;
    min-height: 100vh;
    min-height: 100dvh;
    width: 100vw;
    background-color: var(--saltacoda-bg);
    background-image:
      radial-gradient(ellipse 100% 60% at 100% 0%, rgba(245, 130, 32, 0.08) 0%, transparent 42%),
      radial-gradient(ellipse 80% 50% at 0% 100%, rgba(96, 45, 145, 0.05) 0%, transparent 40%);
    margin: -1rem -0.75rem 0;
  }

  .saltacoda-topbar {
    position: fixed;
    inset: 0 0 auto 0;
    height: var(--saltacoda-topbar-h);
    z-index: 1020;
    background: #fff;
    border-bottom: 1px solid #e7e7ef;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0.6rem;
    padding: 0 1rem;
    box-shadow: 0 2px 10px rgba(16, 24, 40, 0.06);
  }

  .saltacoda-topbar-title {
    margin: 0;
    font-size: 1rem;
    font-weight: 700;
    color: #566a7f;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .saltacoda-topbar-search {
    display: none;
    flex: 1;
  }

  .saltacoda-topbar.search-open .saltacoda-topbar-title {
    display: none;
  }

  .saltacoda-topbar.search-open .saltacoda-topbar-search {
    display: block;
  }

  .saltacoda-topbar-btn {
    width: 2.15rem;
    height: 2.15rem;
    border: 0;
    border-radius: 999px;
    background: #eef1fb;
    color: #697a8d;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 1.05rem;
    flex-shrink: 0;
  }

  .saltacoda-search {
    width: 100%;
    border: 1px solid #e5e8f2;
    border-radius: 999px;
    background: #fff;
    padding: 0.58rem 0.9rem;
    color: #566a7f;
    font-size: 0.93rem;
    box-shadow: none;
  }

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

  .saltacoda-no-results {
    background: #fff;
    border: 1px dashed #dde1ef;
    border-radius: 0.8rem;
    padding: 0.9rem;
    text-align: center;
    color: #8a93a5;
    display: none;
  }

  .saltacoda-kitchen-title {
    margin: 0 0 0.85rem;
    display: flex;
    align-items: center;
    gap: 0.75rem;
    position: sticky;
    top: 0;
    z-index: 1010;
    padding: 0.55rem 0;
    background: var(--saltacoda-bg);
    border: 0;
    box-shadow: none;
  }

  .saltacoda-kitchen-title::before,
  .saltacoda-kitchen-title::after {
    content: '';
    flex: 1 1 0;
    height: 1px;
    background: linear-gradient(
      90deg,
      transparent 0%,
      var(--saltacoda-accent-line) 18%,
      var(--saltacoda-accent-line) 82%,
      transparent 100%
    );
  }

  .saltacoda-kitchen-badge {
    flex: 0 1 auto;
    max-width: min(72%, 16rem);
    margin: 0;
    padding: 0 0.15rem;
    background: transparent;
    color: var(--saltacoda-accent-text);
    font-size: 0.82rem;
    font-weight: 700;
    font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    text-transform: none;
    letter-spacing: 0.02em;
    line-height: 1.25;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    border-radius: 0;
    box-shadow: none;
  }

  .saltacoda-kitchen {
    margin-bottom: 1.05rem;
    padding: 0;
    background: transparent;
    border: 0;
    box-shadow: none;
  }

  .saltacoda-dish {
    width: 100%;
    border: 0;
    background: #fbfcff;
    border-radius: var(--bs-border-radius)!important;
    /* border-radius: 0.8rem; */
    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 #ebedf6;
    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: rgba(var(--saltacoda-accent-rgb), 0.32);
    background: var(--saltacoda-accent-surface);
  }

  .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: #566a7f;
    margin-right: 0;
    line-height: 1.22;
    word-break: break-word;
  }

  .saltacoda-dish-price {
    font-weight: 700;
    color: #5e63db;
    white-space: nowrap;
    font-size: 0.9rem;
    background: #f0f1ff;
    /* border-radius: 999px; */
    border-radius: var(--bs-border-radius)!important;
    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 rgba(var(--saltacoda-accent-rgb), 0.28);
  }

  .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 rgba(var(--saltacoda-accent-rgb), 0.06);
    }
    45% {
      transform: scale(1.01);
      box-shadow: 0 10px 22px rgba(var(--saltacoda-accent-rgb), 0.22);
    }
    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: #ffffff;
    border-top: 1px solid #dcddeb;
    box-shadow: 0 -8px 26px rgba(16, 24, 40, 0.12);
    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: #566a7f;
  }

  .saltacoda-cart-toggle small {
    display: block;
    color: #a0a8b6;
    font-size: 0.75rem;
  }

  .saltacoda-cart-toggle strong {
    display: block;
    font-size: 0.95rem;
    line-height: 1.2;
  }

  .saltacoda-cart-chevron {
    font-size: 1rem;
    color: #8f97a8;
    margin-left: 0.25rem;
    transition: transform 0.2s ease;
  }

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

  .saltacoda-send-btn {
    border: 0;
    border-radius: 0.7rem;
    padding: 0.7rem 0.95rem;
    font-weight: 700;
    background: linear-gradient(135deg, #22c26a 0%, #13b95c 100%);
    color: #fff;
    min-width: 86px;
  }

  .saltacoda-send-btn:disabled {
    background: #d7dbe5;
    color: #8a93a5;
  }

  .saltacoda-send-btn:not(:disabled) {
    box-shadow: 0 8px 16px rgba(19, 185, 92, 0.28);
  }

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

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

  .saltacoda-info-inline {
    border-top: 1px solid #efeff6;
    padding: 0.65rem 0.75rem 0.45rem;
    background: #fff;
  }

  .saltacoda-info-title {
    font-size: 0.8rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.02em;
    color: #8a93a5;
    margin: 0 0 0.45rem;
  }

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

  .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 #ececf5;
  }

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

  .saltacoda-qty {
    display: inline-flex;
    align-items: center;
    border: 1px solid #e2e4ef;
    border-radius: 999px;
  }

  .saltacoda-qty button {
    border: 0;
    background: transparent;
    width: 28px;
    height: 28px;
    color: #697a8d;
  }

  .saltacoda-qty button:active {
    background: #f3f5fb;
  }

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

  .saltacoda-empty {
    color: #8a93a5;
    text-align: center;
    padding: 0.7rem 0.2rem;
    margin: 0;
  }

  @media (min-width: 768px) {
    .saltacoda-mobile {
      margin: -1rem auto 0;
      max-width: 680px;
      border-left: 1px solid #efeff6;
      border-right: 1px solid #efeff6;
    }
  }

  @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>

<div class="saltacoda-mobile">
  <header class="saltacoda-topbar" id="saltacodaTopbar">
    <h1 class="saltacoda-topbar-title">{{ $attivita->nome }}</h1>
    <div class="saltacoda-topbar-search">
      <input
        type="search"
        id="dishSearch"
        class="saltacoda-search"
        placeholder="Cerca un piatto..."
        autocomplete="off">
    </div>
    <button type="button" id="searchToggleBtn" class="saltacoda-topbar-btn" aria-label="Apri ricerca">
      <i id="searchToggleIcon" class="bx bx-search"></i>
    </button>
  </header>

  <main class="saltacoda-content">
    @foreach($cucine as $cucina)
      <section class="saltacoda-kitchen" id="cucina_{{ $cucina->id }}">
        <h2 class="saltacoda-kitchen-title">
          <span class="saltacoda-kitchen-badge">{{ $cucina->nome }}</span>
        </h2>

        @forelse($cucina->piatti as $piatto)
          <button
            type="button"
            class="saltacoda-dish"
            data-piatto-id="{{ $piatto->id }}"
            data-piatto-nome="{{ $piatto->nome }}"
            data-piatto-prezzo="{{ (float) $piatto->prezzo }}">
            <span class="saltacoda-dish-left">
              <span class="saltacoda-dish-name">{{ $piatto->nome }}</span>
            </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="text-muted mb-0">Nessun piatto disponibile.</p>
        @endforelse
      </section>
    @endforeach
    <p id="noResultsMessage" class="saltacoda-no-results mb-0">Nessun piatto trovato con questa ricerca.</p>
  </main>

  <aside class="saltacoda-footbar">
    <div class="saltacoda-cart-summary">
      <button
        class="saltacoda-cart-toggle"
        type="button"
        data-bs-toggle="collapse"
        data-bs-target="#saltacodaCartCollapse"
        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>Invia</button>
    </div>

    <div class="collapse" id="saltacodaCartCollapse">
      <div class="saltacoda-info-inline" id="saltacodaInfoInline">
        <p class="saltacoda-info-title">Informazioni ordine</p>
        <div id="saltacodaInfoFields"></div>
      </div>
      <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>

<script>
  (function () {
    const infoFieldsConfig = @json($campi_info ?? []);
    const savePreOrderUrl = @json(route('saltacoda.pre-ordine.salva'));
    const saltacodaId = @json($saltacoda_id ?? null);
    const attivitaId = @json($attivita->id ?? null);
    const cart = {};
    const infoValues = {};
    const countEl = document.getElementById('cartCount');
    const totalEl = document.getElementById('cartTotal');
    const cartToggleBtnEl = document.querySelector('.saltacoda-cart-toggle');
    const cartCollapseEl = document.getElementById('saltacodaCartCollapse');
    const containerEl = document.getElementById('cartItemsContainer');
    const sendBtnEl = document.getElementById('sendOrderBtn');
    const clearBtnEl = document.getElementById('clearCartBtn');
    const topbarEl = document.getElementById('saltacodaTopbar');
    const searchToggleBtnEl = document.getElementById('searchToggleBtn');
    const searchToggleIconEl = document.getElementById('searchToggleIcon');
    const dishSearchEl = document.getElementById('dishSearch');
    const noResultsEl = document.getElementById('noResultsMessage');
    const infoInlineEl = document.getElementById('saltacodaInfoInline');
    const infoFieldsEl = document.getElementById('saltacodaInfoFields');
    let isSearchOpen = false;

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

    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 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 id = counterEl.dataset.counterFor;
        const qty = cart[id] ? cart[id].qty : 0;
        counterEl.textContent = qty;
        counterEl.classList.toggle('visible', qty > 0);
      });
      document.querySelectorAll('.saltacoda-dish').forEach((dishEl) => {
        const id = dishEl.dataset.piattoId;
        const qty = cart[id] ? cart[id].qty : 0;
        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>
              <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.id}"
                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.id}">−</button>
                <span>${item.qty}</span>
                <button type="button" data-action="inc" data-id="${item.id}">+</button>
              </div>
              <strong>€ ${formatEuro(item.qty * item.price)}</strong>
            </div>
          </div>
        `;
      }).join('');
    }

    function upsertItem(id, name, price, delta) {
      if (!cart[id]) {
        cart[id] = { id, name, price, qty: 0, note: '' };
      }

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

      renderCart();
    }

    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 () {
        const id = this.dataset.piattoId;
        const name = this.dataset.piattoNome;
        const price = parseFloat(this.dataset.piattoPrezzo || '0');
        upsertItem(id, name, price, 1);
        animateAddedFeedback(id);
        this.classList.add('added');
        setTimeout(() => this.classList.remove('added'), 220);
      });
    });

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

    function renderInfoFields() {
      if (!infoFieldsConfig.length) {
        infoInlineEl.classList.add('d-none');
        infoFieldsEl.innerHTML = '';
        return;
      }

      infoInlineEl.classList.remove('d-none');
      infoFieldsEl.innerHTML = infoFieldsConfig.map((field) => {
        const requiredMark = field.required ? '<span class="saltacoda-info-required">*</span>' : '';
        const requiredAttr = field.required ? 'required' : '';
        const errorEl = '<div class="invalid-feedback">Campo obbligatorio.</div>';
        const currentValue = infoValues[field.key] || '';

        if (field.type === 'boolean') {
          return `
            <div class="mb-3">
              <label class="form-label">${field.label}${requiredMark}</label>
              <select class="form-select" data-info-key="${field.key}" data-info-type="boolean" ${requiredAttr}>
                <option value="">Seleziona...</option>
                <option value="si" ${currentValue === 'si' ? 'selected' : ''}>Si</option>
                <option value="no" ${currentValue === 'no' ? 'selected' : ''}>No</option>
              </select>
              ${errorEl}
            </div>
          `;
        }

        if (field.type === 'time') {
          return `
            <div class="mb-3">
              <label class="form-label">${field.label}${requiredMark}</label>
              <input type="time" class="form-control" data-info-key="${field.key}" data-info-type="time" value="${currentValue}" ${requiredAttr}>
              ${errorEl}
            </div>
          `;
        }

        return `
          <div class="mb-3">
            <label class="form-label">${field.label}${requiredMark}</label>
            <input type="text" class="form-control" data-info-key="${field.key}" data-info-type="text" value="${currentValue}" ${requiredAttr}>
            ${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);
        if (hasError) {
          isValid = false;
        }
      });

      return isValid;
    }

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

      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;
      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(() => {
          sendBtnEl.disabled = false;
        });
    }

    function ensureCartOpen() {
      if (cartCollapseEl.classList.contains('show')) {
        return;
      }
      cartToggleBtnEl.click();
    }

    function applyDishFilter() {
      const query = normalizeText(dishSearchEl.value);
      let visibleKitchenCount = 0;

      document.querySelectorAll('.saltacoda-kitchen').forEach((kitchenEl) => {
        let visibleDishCount = 0;
        kitchenEl.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;
          }
        });

        kitchenEl.style.display = visibleDishCount > 0 ? '' : 'none';
        if (visibleDishCount > 0) {
          visibleKitchenCount += 1;
        }
      });

      noResultsEl.style.display = visibleKitchenCount === 0 ? 'block' : 'none';
    }

    function setSearchOpen(nextValue) {
      isSearchOpen = nextValue;
      topbarEl.classList.toggle('search-open', isSearchOpen);
      searchToggleIconEl.className = isSearchOpen ? 'bx bx-x' : 'bx bx-search';
      searchToggleBtnEl.setAttribute('aria-label', isSearchOpen ? 'Chiudi ricerca' : 'Apri ricerca');

      if (isSearchOpen) {
        dishSearchEl.focus();
        return;
      }

      if (dishSearchEl.value !== '') {
        dishSearchEl.value = '';
        applyDishFilter();
      }
      dishSearchEl.blur();
    }

    searchToggleBtnEl.addEventListener('click', function () {
      setSearchOpen(!isSearchOpen);
    });

    dishSearchEl.addEventListener('keydown', function (event) {
      if (event.key === 'Escape') {
        setSearchOpen(false);
      }
    });

    dishSearchEl.addEventListener('input', applyDishFilter);
    applyDishFilter();
    renderInfoFields();

    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;
      }

      upsertItem(id, item.name, item.price, 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');
      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;
      }

      if (!validateInfoFields()) {
        ensureCartOpen();
        const firstInvalid = infoFieldsEl.querySelector('.is-invalid');
        if (firstInvalid) {
          firstInvalid.scrollIntoView({ behavior: 'smooth', block: 'center' });
          firstInvalid.focus();
        }
        return;
      }

      completeOrderSend();
    });

    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