<?php
use Illuminate\Support\Facades\Auth;
?>

@php
  $cucine = ($cucine ?? collect())
    ->sortBy(fn ($cucina) => mb_strtolower((string) ($cucina->nome ?? ''), 'UTF-8'))
    ->values();

  $saltacoda = \App\Models\Saltacoda::where('attivita_id', $punto_vendita->attivita_id ?? null)->first();
  $saltacodaAttivo = (bool) ($saltacoda?->is_attivo ?? false);
  $cercaPreOrdineRoute = Auth::guard('operatore')->check()
    ? route('operatore.punto-vendita.cassa.cerca-pre-ordine')
    : route('punto-vendita.cassa.cerca-pre-ordine');
  $importaPreOrdineRoute = Auth::guard('operatore')->check()
    ? route('operatore.punto-vendita.cassa.importa-pre-ordine')
    : route('punto-vendita.cassa.importa-pre-ordine');

  $righeOrdine = $ordine->righe_ordine ?? collect();
  $righeIniziali = $righeOrdine->map(function ($riga) {
    return [
      'id' => (string) ($riga->piatto_id ?? $riga->id),
      'title' => (string) ($riga->piatto->nome ?? ('Riga #' . $riga->id)),
      'price' => (float) ($riga->prezzo ?? 0),
      'qty' => (int) ($riga->quantita ?? 1),
    ];
  })->values();
@endphp

@extends('layouts/blankLayout')

@php
$title = 'Cassa - ' . ($punto_vendita->attivita->nome ?? 'Attività ND');
$infoOrdine = is_array($ordine->info ?? null) ? $ordine->info : [];
$ordineCliente = (string) ($infoOrdine['cliente'] ?? '');
$ordineTavolo = (string) ($infoOrdine['tavolo'] ?? '');
$ordineCoperti = (string) ($infoOrdine['coperti'] ?? '');
@endphp


@section('title', $title)

@section('content')

@include('punto_vendita.cassa.viste.catalogo._partials.style')

<div class="cassa-sb-wrapper">
  <div class="cassa-sb-topbar">
    <div class="d-flex align-items-center cassa-sb-topbar-main">
      <h5 class="mb-0">
        {{ $punto_vendita->attivita->nome ?? 'Attività ND' }},
        <span class="text-primary fw-bold">{{ $punto_vendita->nome ?? 'Cassa' }}</span>
        | Ordine #<span class="text-primary fs-6">{{ $ordine->id ?? '-' }}</span>
      </h5>
      <div class="cassa-sb-order-meta" aria-label="Informazioni ordine">
        <div class="cassa-sb-order-field">
          <label for="cliente" class="cassa-sb-order-label text-primary">Cliente</label>
          <input id="cliente" type="text" class="cassa-sb-order-input form-control" placeholder="—" value="{{ $ordineCliente }}">
        </div>
        <div class="cassa-sb-order-field">
          <label for="tavolo" class="cassa-sb-order-label text-primary">Tavolo</label>
          <input id="tavolo" type="text" class="cassa-sb-order-input cassa-sb-order-input--sm form-control" placeholder="—" value="{{ $ordineTavolo }}">
        </div>
        <div class="cassa-sb-order-field">
          <label for="coperti" class="cassa-sb-order-label text-primary">Coperti</label>
          <input id="coperti" type="number" min="0" step="1" class="cassa-sb-order-input cassa-sb-order-input--xs form-control" placeholder="—" value="{{ $ordineCoperti }}">
        </div>
      </div>
      <!-- <small class="text-muted">Sidebar cucine + catalogo compatto</small> -->
    </div>
    <!-- <div>
      @if(Auth::guard('operatore')->check())
        <a href="{{ route('operatore.dashDispositivi') }}" class="btn btn-sm btn-outline-primary">Dashboard</a>
      @elseif(Auth::guard('web')->check())
        <a href="{{ route('dashboard') }}" class="btn btn-sm btn-outline-primary">Dashboard</a>
      @endif
    </div> -->

    
    <div class="col-4 d-flex align-items-center justify-content-end">
      <div class="dropdown">
        <button class="btn btn-sm btn-outline-secondary d-flex align-items-center" type="button" id="transactionID" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          <i class="bx bx-menu fs-5"></i>
        </button>
        <div class="dropdown-menu dropdown-menu-end" aria-labelledby="transactionID">
          @if(Auth::guard('operatore')->check())
            <a class="dropdown-item" href="{{ route('operatore.dashDispositivi') }}">
              <i class="bx bx-category me-2"></i>Dashboard
            </a>
          @elseif(Auth::guard('web')->check())
            <a class="dropdown-item" href="{{ route('dashboard') }}">
              <i class="bx bx-category me-2"></i>Dashboard
            </a>
          @endif
          @if(Auth::guard('web')->check())
            <a class="dropdown-item" href="{{ route('profile.show') }}">
              <i class="bx bx-user-circle me-2"></i>{{ Auth::user()->fullName() }}
            </a>
          @endif
          @if($punto_vendita->binding_token)
            <span class="dropdown-item-text text-success">
              <i class="bx bx-link me-2"></i>Linker attivo
            </span>
          @endif
          <a class="dropdown-item" href="{{ route('punto-vendita.show', ['punto_vendita_id' => $punto_vendita->id , 'vista' => 'catalogo']) }}">
            <i class="bx bx-list-ul me-2"></i>Vista catalogo
          </a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="javascript:void(0);" onclick="showInfoPuntoVendita()">
            <i class="bx bx-info-circle me-2"></i>Informazioni punto vendita
          </a>
          @if(Auth::user()->hasRole('superadmin') || Auth::user()->hasRole('amministratore') || Auth::user()->can('edit-punto_vendita'))
          <a class="dropdown-item" href="{{ route('punto-vendita.edit', ['punto_vendita_id' => $punto_vendita->id]) }}">
            <i class="bx bx-edit-alt me-2"></i>Modifica punto vendita
          </a>
          @endif
          <a class="dropdown-item text-danger" href="javascript:void(0);" onclick="dissociaDispositivo()">
            <i class="bx bx-unlink me-2"></i>Dissocia dispositivo
          </a>
        </div>
      </div>

      <!-- <a href="{{ route('punto-vendita.show', ['punto_vendita_id' => $punto_vendita->id , 'vista' => 'catalogo']) }}" class=" ms-2 px-3 py-1 alert text-bg-primary"> 
        <i class="bx bx-list-ul mx-1"></i>
        vista catalogo
      </a> -->
      <!-- <span class="badge badge-info">{{ $punto_vendita->binding_token }}</span> -->
    </div>

  </div>

  <div class="cassa-sb-layout">
    <section class="cassa-sb-panel cassa-sb-catalog">
      <aside class="cassa-sb-sidebar">
        <!-- <p class="cassa-sb-side-title">Cucine</p> -->
        <div class="cassa-sb-kitchens" id="kitchen-list">
          @if($saltacodaAttivo)
            <button
              type="button"
              class="cassa-sb-kitchen-btn cassa-sb-kitchen-btn--preordine"
              data-kitchen-tab
              data-kitchen-id="pre-ordine"
              data-kitchen-name="pre-ordine"
            >
              <span class="cassa-sb-kitchen-label"><i class="bx bx-receipt me-1"></i>Pre-ordine</span>
              <span class="cassa-sb-kitchen-count">Codice</span>
            </button>
          @endif
          @foreach($cucine as $cucina)

          <?php
            // Calcolo il migliore contrasto (bianco o nero) dato un colore di background in $hexColor
            $bgColore = $cucina->info['colore'] ?? '#808080';

            // Rimuovo il carattere '#' se presente
            $strippedHex = ltrim($bgColore, '#');
            // Espando formato breve (#abc -> #aabbcc)
            if(strlen($strippedHex) == 3) {
              $r = hexdec(str_repeat($strippedHex[0], 2));
              $g = hexdec(str_repeat($strippedHex[1], 2));
              $b = hexdec(str_repeat($strippedHex[2], 2));
            } else {
              $r = hexdec(substr($strippedHex,0,2));
              $g = hexdec(substr($strippedHex,2,2));
              $b = hexdec(substr($strippedHex,4,2));
            }
            // Calcolo luminanza percepita del colore
            $luminance = (0.299 * $r + 0.587 * $g + 0.114 * $b) / 255;
            // Soglia: se luminanza alta, uso testo scuro, altrimenti bianco
            $textColor = $luminance > 0.6 ? '#222' : '#fff';
          ?>

            <button
              type="button"
              class="cassa-sb-kitchen-btn"

              style="background-color: {{ $bgColore }}; color: {{ $textColor }};"
              data-kitchen-tab
              data-kitchen-id="{{ $cucina->id }}"
              data-kitchen-name="{{ mb_strtolower((string) ($cucina->nome ?? ''), 'UTF-8') }}"

            >
              <span class="cassa-sb-kitchen-label">{{ $cucina->nome }}</span>
              <span class="cassa-sb-kitchen-count">{{ ($cucina->piatti ?? collect())->count() }} piatti</span>
            </button>
          @endforeach
        </div>
        <div class="cassa-sb-side-pager">
          <button type="button" id="kitchen-prev">Prec</button>
          <span id="kitchen-status">1 / 1</span>
          <button type="button" id="kitchen-next">Next</button>
        </div>
      </aside>

      <div class="cassa-sb-main">
        <div class="cassa-sb-main-head">
          <input id="product-search" type="text" class="cassa-sb-search" placeholder="Cerca piatto nella cucina selezionata">
          <div class="cassa-sb-selected-kitchen" id="selected-kitchen-label">Tutte</div>
          <div class="cassa-sb-main-pager">
            <button type="button" id="product-prev">Prec</button>
            <span id="product-status">1 / 1</span>
            <button type="button" id="product-next">Next</button>
          </div>
        </div>
        <div class="cassa-sb-main-content">
        @if($saltacodaAttivo)
          <div class="cassa-sb-preordine" id="preordine-panel" hidden>
            <div class="cassa-sb-preordine-inner">
              <p class="cassa-sb-preordine-title">Importa pre-ordine</p>
              <p class="cassa-sb-preordine-hint">Inserisci almeno 3 caratteri del codice per cercare.</p>
              <input
                type="text"
                class="cassa-sb-preordine-input"
                placeholder="Codice pre-ordine"
                name="pre-ordine-input"
                id="pre-ordine-input"
                autocomplete="off"
              >
              <div class="cassa-sb-preordine-result" id="pre-ordine-result"></div>
            </div>
          </div>
        @endif

        <div class="cassa-sb-products-wrap" id="product-panel">
          <div class="cassa-sb-products" id="product-grid">
            @foreach($cucine as $cucina)
              @foreach(($cucina->piatti ?? collect()) as $piatto)
                
                <article
                  class="cassa-sb-product"
                  data-product-item
                  data-kitchen-id="{{ $cucina->id }}"
                  data-name="{{ mb_strtolower((string) ($piatto->nome ?? ''), 'UTF-8') }}"
                  data-piatto-id="{{ $piatto->id }}"
                  data-title="{{ $piatto->nome }}"
                  data-price="{{ (float) ($piatto->prezzo ?? 0) }}"
                  onclik=""
                >
                  @if($piatto->elencoAllergeni?->isNotEmpty() ?? false)
                    <button
                      type="button"
                      class="cassa-sb-allergen-trigger"
                      data-allergen-toggle
                      aria-label="Mostra allergeni"
                    >
                    !
                    <!-- A -->
                      <!-- <i class="bx bx-error-circle"></i> -->
                    </button>
                    <div class="cassa-sb-allergen-tooltip" data-allergen-tooltip>
                      <div class="cassa-sb-allergen-tooltip-title text-primary">Allergeni</div>
                      <div data-allergen-tooltip-text>
                        
                        {{ $piatto->elencoAllergeni->pluck('nome')->implode(', ') }}
                      </div>
                    </div>
                  @endif
                  @php
                    $piattoNome = (string) ($piatto->nome ?? '');
                    $nomeLen = mb_strlen($piattoNome, 'UTF-8');
                    $titleSizeClass = $nomeLen > 24 ? 'is-xlong' : ($nomeLen > 16 ? 'is-long' : '');
                  @endphp
                  <div class="cassa-sb-product-title {{ $titleSizeClass }}">{{ $piattoNome }}</div>
                </article>
              @endforeach
            @endforeach
          </div>
        </div>
        </div>
      </div>
    </section>

    <aside class="cassa-sb-panel cassa-sb-cart">
      <div class="cassa-sb-cart-head">
        <div class="d-flex align-items-center gap-2">
          <i class="bx bx-cart fs-4 text-primary"></i>
          <span class="text-primary fw-bold">#{{ $ordine->id ?? '-' }}</span>
        </div>
        <div>
          <span class="text-primary fw-bold" id="totale_carrello">
            @if(($ordine->totale ?? 0) > 0)
              EUR {{ number_format((float) $ordine->totale, 2, ',', '.') }}
            @else
              EUR {{ number_format((float) ($ordine->righe_ordine->sum('prezzo') ?? 0), 2, ',', '.') }}
            @endif
          </span>
        </div>
      </div>

      <div class="cassa-sb-cart-list" id="cart-list">
        <!-- <div class="text-muted small">Nessun articolo selezionato.</div> -->
         {{ $dataTable_rigaordine->table() }}

      </div>

      <div class="cassa-sb-footer">
        <div class="cassa-sb-pay-grid">
          <button type="button" class="cassa-sb-main-btn" onclick="checkout()">Paga ora</button>
          <button type="button" class="cassa-sb-cash-btn">Contanti</button>
          <button type="button" class="cassa-sb-card-btn">Carta</button>
          <button type="button" class="cassa-sb-clear-btn" id="cart-reset" onclick="azzeraCarrello()">Svuota</button>
        </div>
      </div>
    </aside>
  </div>
</div>


  <div class="modal fade" id="modalPagamento" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Pagamento</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          //Checkout
        </div>
      </div>
    </div>
  </div>

  <!-- Modal basic -->
<div class="modal fade" id="basicModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog" role="document">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="exampleModalLabel1"></h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                  
                </div>
                <div class="modal-footer">

              </div>
              </div>
            </div>
          </div>
          
<script>
  (function () {
    const KITCHEN_PAGE_SIZE = 10;
    const PRODUCT_PAGE_SIZE = 40;
    // const CART_PAGE_SIZE = 6;
    // const money = new Intl.NumberFormat('it-IT', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

    const kitchenTabs = Array.from(document.querySelectorAll('[data-kitchen-tab]'));
    const kitchenList = document.getElementById('kitchen-list');
    const kitchenPrev = document.getElementById('kitchen-prev');
    const kitchenNext = document.getElementById('kitchen-next');
    const kitchenStatus = document.getElementById('kitchen-status');

    const productPanel = document.getElementById('product-panel');
    const preOrdinePanel = document.getElementById('preordine-panel');
    const productMainHead = document.querySelector('.cassa-sb-main-head');
    const productGrid = document.getElementById('product-grid');
    const productItems = Array.from(document.querySelectorAll('[data-product-item]'));
    const productSearch = document.getElementById('product-search');
    const productPrev = document.getElementById('product-prev');
    const productNext = document.getElementById('product-next');
    const productStatus = document.getElementById('product-status');
    const selectedKitchenLabel = document.getElementById('selected-kitchen-label');

    // const cartList = document.getElementById('cart-list');
    // const cartPrev = document.getElementById('cart-prev');
    // const cartNext = document.getElementById('cart-next');
    // const cartStatus = document.getElementById('cart-status');
    // const cartBadge = document.getElementById('cart-badge');
    // const cartTotal = document.getElementById('cart-total');
    // const cartReset = document.getElementById('cart-reset');

    // const initialCart = @json($righeIniziali);
    // const cart = new Map();

    const defaultKitchenTab = kitchenTabs.find(function (tab) {
      return tab.dataset.kitchenId !== 'pre-ordine';
    }) || kitchenTabs[0];
    let selectedKitchen = defaultKitchenTab ? defaultKitchenTab.dataset.kitchenId : 'all';
    let kitchenPage = 1;
    let productPage = 1;
    // let cartPage = 1;
    let visibleKitchens = [];
    let visibleProducts = [];
    // let visibleCartRows = [];

    // initialCart.forEach(function (row) {
    //   if (!row.id) return;
    //   const key = String(row.id);
    //   const existing = cart.get(key);
    //   if (existing) {
    //     existing.qty += Number(row.qty || 0);
    //     cart.set(key, existing);
    //   } else {
    //     cart.set(key, {
    //       id: key,
    //       title: row.title || 'Prodotto',
    //       price: Number(row.price || 0),
    //       qty: Number(row.qty || 1)
    //     });
    //   }
    // });

    const renderKitchenTabs = function () {
      visibleKitchens = kitchenTabs;
      const maxPage = Math.max(1, Math.ceil(visibleKitchens.length / KITCHEN_PAGE_SIZE));
      if (kitchenPage > maxPage) kitchenPage = maxPage;
      const start = (kitchenPage - 1) * KITCHEN_PAGE_SIZE;
      const end = start + KITCHEN_PAGE_SIZE;

      kitchenTabs.forEach(function (tab) { tab.style.display = 'none'; });
      const current = visibleKitchens.slice(start, end);
      current.forEach(function (tab) {
        tab.style.display = '';
        tab.classList.toggle('is-active', tab.dataset.kitchenId === selectedKitchen);
      });

      kitchenList.querySelectorAll('.js-kitchen-placeholder').forEach(function (node) { node.remove(); });
      const placeholders = Math.max(0, KITCHEN_PAGE_SIZE - current.length);
      for (let i = 0; i < placeholders; i += 1) {
        const placeholder = document.createElement('div');
        placeholder.className = 'cassa-sb-placeholder js-kitchen-placeholder';
        kitchenList.appendChild(placeholder);
      }

      kitchenStatus.textContent = kitchenPage + ' / ' + maxPage;
      kitchenPrev.disabled = kitchenPage <= 1;
      kitchenNext.disabled = kitchenPage >= maxPage;
    };

    const getProductColumnCount = function () {
      const w = window.innerWidth;
      if (w <= 768) return 2;
      if (w <= 1200) return 3;
      if (w <= 1400) return 4;
      return 5;
    };

    const applyProductGridLayout = function (itemCount) {
      const cols = getProductColumnCount();
      const rows = Math.max(1, Math.ceil(itemCount / cols));
      productGrid.style.setProperty('--product-cols', String(cols));
      productGrid.style.setProperty('--product-rows', String(rows));
    };

    const sortProductsAlphabetically = function (items) {
      return items.slice().sort(function (a, b) {
        const nameA = (a.dataset.title || a.dataset.name || '').trim();
        const nameB = (b.dataset.title || b.dataset.name || '').trim();
        return nameA.localeCompare(nameB, 'it', { sensitivity: 'base' });
      });
    };

    const getProductInitialLetter = function (name) {
      const trimmed = (name || '').trim();
      if (trimmed === '') return '#';
      const initial = [...trimmed][0]?.toLocaleUpperCase('it') || '#';
      return /^[A-Z]$/.test(initial.normalize('NFD').replace(/\p{M}/gu, '')) ? initial : '#';
    };

    const createLetterDivider = function (letter) {
      const divider = document.createElement('div');
      divider.className = 'cassa-sb-letter-divider js-letter-divider';
      divider.setAttribute('data-letter', letter);
      const label = document.createElement('span');
      label.className = 'cassa-sb-letter-divider-label';
      label.textContent = letter;
      divider.appendChild(label);
      return divider;
    };

    const clearLetterDividers = function () {
      productGrid.querySelectorAll('.js-letter-divider').forEach(function (node) {
        node.remove();
      });
    };

    const LETTER_DIVIDER_MIN_ITEMS = 10;

    const buildProductGridSequence = function (items, totalVisibleCount) {
      const sequence = [];
      const showLetterDividers = totalVisibleCount > LETTER_DIVIDER_MIN_ITEMS;
      let lastLetter = null;

      items.forEach(function (item) {
        const letter = getProductInitialLetter(item.dataset.title || item.dataset.name || '');
        if (showLetterDividers && letter !== lastLetter) {
          sequence.push(createLetterDivider(letter));
          lastLetter = letter;
        }
        if (!showLetterDividers) {
          lastLetter = letter;
        }
        sequence.push(item);
      });

      return sequence;
    };

    const renderProducts = function () {
      const isPreOrdine = selectedKitchen === 'pre-ordine';
      const selectedTab = kitchenTabs.find(function (tab) {
        return tab.dataset.kitchenId === selectedKitchen;
      });

      if (preOrdinePanel) preOrdinePanel.hidden = !isPreOrdine;
      if (productPanel) productPanel.hidden = isPreOrdine;
      if (productMainHead) productMainHead.hidden = isPreOrdine;

      if (selectedKitchenLabel) {
        if (isPreOrdine) {
          selectedKitchenLabel.textContent = 'Pre-ordine';
        } else {
          const labelEl = selectedTab ? selectedTab.querySelector('.cassa-sb-kitchen-label') : null;
          selectedKitchenLabel.textContent = labelEl ? labelEl.textContent.trim() : 'Tutte';
        }
      }

      if (isPreOrdine) {
        productStatus.textContent = '-';
        productPrev.disabled = true;
        productNext.disabled = true;
        return;
      }

      const term = (productSearch?.value || '').trim().toLowerCase();
      visibleProducts = sortProductsAlphabetically(productItems.filter(function (item) {
        const okKitchen = selectedKitchen === 'all' || item.dataset.kitchenId === selectedKitchen;
        const okSearch = term === '' || (item.dataset.name || '').includes(term);
        return okKitchen && okSearch;
      }));

      const maxPage = Math.max(1, Math.ceil(visibleProducts.length / PRODUCT_PAGE_SIZE));
      if (productPage > maxPage) productPage = maxPage;
      const start = (productPage - 1) * PRODUCT_PAGE_SIZE;
      const end = start + PRODUCT_PAGE_SIZE;

      productItems.forEach(function (item) { item.style.display = 'none'; });
      const current = visibleProducts.slice(start, end);
      clearLetterDividers();

      const gridSequence = buildProductGridSequence(current, visibleProducts.length);
      gridSequence.forEach(function (node) {
        if (node.classList.contains('cassa-sb-product')) {
          node.style.display = '';
        }
        productGrid.appendChild(node);
      });

      visibleProducts.forEach(function (item) {
        if (current.indexOf(item) === -1) {
          productGrid.appendChild(item);
        }
      });

      productItems.forEach(function (item) {
        if (visibleProducts.indexOf(item) === -1) {
          productGrid.appendChild(item);
        }
      });

      productGrid.querySelectorAll('.js-product-placeholder').forEach(function (node) { node.remove(); });
      applyProductGridLayout(gridSequence.length);

      productStatus.textContent = productPage + ' / ' + maxPage;
      productPrev.disabled = productPage <= 1;
      productNext.disabled = productPage >= maxPage;
    };

    // --- Carrello demo client-side (disabilitato: usa DataTable reale) ---
    // const renderCart = function () {
    //   const rows = Array.from(cart.values()).sort(function (a, b) {
    //     return a.title.localeCompare(b.title, 'it');
    //   });
    //
    //   const itemCount = rows.reduce((acc, row) => acc + row.qty, 0);
    //   const total = rows.reduce((acc, row) => acc + (row.qty * row.price), 0);
    //   cartBadge.textContent = itemCount + ' articoli';
    //   cartTotal.textContent = 'EUR ' + money.format(total);
    //
    //   if (!rows.length) {
    //     cartList.innerHTML = '<div class="text-muted small">Nessun articolo selezionato.</div>';
    //     cartStatus.textContent = '1 / 1';
    //     cartPrev.disabled = true;
    //     cartNext.disabled = true;
    //     visibleCartRows = [];
    //     return;
    //   }
    //
    //   visibleCartRows = rows;
    //   const maxPage = Math.max(1, Math.ceil(rows.length / CART_PAGE_SIZE));
    //   if (cartPage > maxPage) cartPage = maxPage;
    //   const start = (cartPage - 1) * CART_PAGE_SIZE;
    //   const end = start + CART_PAGE_SIZE;
    //   const current = rows.slice(start, end);
    //   const placeholders = Math.max(0, CART_PAGE_SIZE - current.length);
    //
    //   cartList.innerHTML = current.map(function (row) {
    //     const rowTotal = row.qty * row.price;
    //     return '<div class="cassa-sb-cart-row">' +
    //       '<div class="cassa-sb-cart-name">' + row.title + '</div>' +
    //       '<div class="cassa-sb-qty">' +
    //         '<button type="button" data-cart-action="dec" data-id="' + row.id + '">-</button>' +
    //         '<span>' + row.qty + '</span>' +
    //         '<button type="button" data-cart-action="inc" data-id="' + row.id + '">+</button>' +
    //       '</div>' +
    //       '<div class="cassa-sb-note-row"><button type="button" class="cassa-sb-note-btn">Nota</button></div>' +
    //       '<div class="cassa-sb-cart-total">EUR ' + money.format(rowTotal) + '</div>' +
    //       '</div>';
    //   }).join('') + Array.from({ length: placeholders }).map(function () {
    //     return '<div class="cassa-sb-cart-row" style="opacity:.35">' +
    //       '<div class="text-muted small">-</div>' +
    //       '<div></div>' +
    //       '<div class="cassa-sb-note-row"></div>' +
    //       '<div></div>' +
    //     '</div>';
    //   }).join('');
    //
    //   cartStatus.textContent = cartPage + ' / ' + maxPage;
    //   cartPrev.disabled = cartPage <= 1;
    //   cartNext.disabled = cartPage >= maxPage;
    // };

    kitchenTabs.forEach(function (tab) {
      tab.addEventListener('click', function () {
        selectedKitchen = tab.dataset.kitchenId || 'all';
        productPage = 1;
        renderKitchenTabs();
        renderProducts();
      });
    });

    kitchenPrev?.addEventListener('click', function () {
      if (kitchenPage <= 1) return;
      kitchenPage -= 1;
      renderKitchenTabs();
    });
    kitchenNext?.addEventListener('click', function () {
      const maxPage = Math.max(1, Math.ceil(visibleKitchens.length / KITCHEN_PAGE_SIZE));
      if (kitchenPage >= maxPage) return;
      kitchenPage += 1;
      renderKitchenTabs();
    });

    productSearch?.addEventListener('input', function () {
      productPage = 1;
      renderProducts();
    });
    productPrev?.addEventListener('click', function () {
      if (productPage <= 1) return;
      productPage -= 1;
      renderProducts();
    });
    productNext?.addEventListener('click', function () {
      const maxPage = Math.max(1, Math.ceil(visibleProducts.length / PRODUCT_PAGE_SIZE));
      if (productPage >= maxPage) return;
      productPage += 1;
      renderProducts();
    });

    // Click piatto → carrello demo (disabilitato: usare aumentaQuantita() lato server)
    // productItems.forEach(function (item) {
    //   item.addEventListener('click', function () {
    //     if (item.dataset.allergenOpen === '1') return;
    //     const id = String(item.dataset.id || '');
    //     if (!id) return;
    //     const row = cart.get(id) || {
    //       id: id,
    //       title: item.dataset.title || 'Prodotto',
    //       price: parseFloat(item.dataset.price || '0'),
    //       qty: 0
    //     };
    //     row.qty += 1;
    //     cart.set(id, row);
    //     cartPage = Math.max(1, Math.ceil(cart.size / CART_PAGE_SIZE));
    //     renderCart();
    //   });
    // });

    document.addEventListener('click', function (evt) {
      const target = evt.target;
      if (!(target instanceof HTMLElement)) return;

      const closeAllTooltips = function () {
        document.querySelectorAll('[data-allergen-tooltip].is-open').forEach(function (tip) {
          tip.classList.remove('is-open');
        });
        document.querySelectorAll('[data-product-item][data-allergen-open="1"]').forEach(function (card) {
          card.dataset.allergenOpen = '0';
        });
      };

      const trigger = target.closest('[data-allergen-toggle]');
      if (!trigger) {
        if (!target.closest('[data-allergen-tooltip]')) {
          closeAllTooltips();
        }
        return;
      }

      evt.preventDefault();
      evt.stopPropagation();

      const card = trigger.closest('[data-product-item]');
      if (!card) return;
      const tooltip = card.querySelector('[data-allergen-tooltip]');
      const textNode = card.querySelector('[data-allergen-tooltip-text]');
      if (!tooltip || !textNode) return;

      const wasOpen = tooltip.classList.contains('is-open');
      closeAllTooltips();
      if (wasOpen) return;

      // textNode.textContent = card.dataset.allergens || 'Nessun allergene';
      tooltip.classList.add('is-open');
      card.dataset.allergenOpen = '1';
    });

    // cartList?.addEventListener('click', function (evt) {
    //   const target = evt.target;
    //   if (!(target instanceof HTMLElement)) return;
    //   const action = target.dataset.cartAction;
    //   const id = target.dataset.id;
    //   if (!action || !id || !cart.has(id)) return;
    //   const row = cart.get(id);
    //   if (!row) return;
    //   if (action === 'inc') row.qty += 1;
    //   if (action === 'dec') row.qty -= 1;
    //   if (row.qty <= 0) cart.delete(id);
    //   else cart.set(id, row);
    //   renderCart();
    // });

    // cartPrev?.addEventListener('click', function () {
    //   if (cartPage <= 1) return;
    //   cartPage -= 1;
    //   renderCart();
    // });
    // cartNext?.addEventListener('click', function () {
    //   const maxPage = Math.max(1, Math.ceil(visibleCartRows.length / CART_PAGE_SIZE));
    //   if (cartPage >= maxPage) return;
    //   cartPage += 1;
    //   renderCart();
    // });
    // cartReset?.addEventListener('click', function () {
    //   cart.clear();
    //   cartPage = 1;
    //   renderCart();
    // });

    renderKitchenTabs();
    renderProducts();

    window.addEventListener('resize', function () {
      renderProducts();
    });
    // renderCart();
  })();
</script>
@endsection


@section('page-script')
  @include('punto_vendita.cassa.viste.catalogo._partials.scripts')
  @if($saltacodaAttivo)
    @include('punto_vendita.cassa.viste.catalogo._partials.pre_ordine')
  @endif

  <script>
  function dissociaDispositivo() {
    $.ajax({
      url: "{{ route('punto-vendita.dissocia-dispositivo', ['punto_vendita_id' => $punto_vendita->id]) }}",
      type: "POST",
      data: {
        punto_vendita_id: "{{ $punto_vendita->id }}",
        _token: "{{ csrf_token() }}",
      },
      success: function(response) {
       new Notyf({
        type: 'success',
        layout: 'topRight',
        text: response.message || 'Disassociazione completata',
        timeout: 3000
      }).success(response.message);
        window.location.href = "{{ route('punto-vendita.index') }}";
      },
      error: function(xhr, status, error) {
        new Notyf({
          type: 'error',
          layout: 'topRight',
          text: xhr.responseJSON.message || 'Si è verificato un errore',
          timeout: 3000
        }).error(xhr.responseJSON.message);
      }
    });
  }
  </script>
@endsection