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

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

  $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');
@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">
      <h5 class="mb-0">
        {{ $punto_vendita->nome ?? 'Cassa' }}
        <span class="text-muted fs-6">| Ordine #{{ $ordine->id ?? '-' }}</span>
      </h5>
      <!-- <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>

  <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">
          @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-products-wrap">
          <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>
                  <div class="cassa-sb-product-price">EUR {{ number_format((float) ($piatto->prezzo ?? 0), 2, ',', '.') }}</div>
                </article>
              @endforeach
            @endforeach
          </div>
        </div>
      </div>
    </section>

    <aside class="cassa-sb-panel cassa-sb-cart">
      <div class="cassa-sb-cart-head">
        <div>
          <strong>Carrello</strong>
          <span class="badge bg-label-primary ms-1" id="cart-badge">0 articoli</span>
        </div>
        <div class="cassa-sb-main-pager">
          <button type="button" id="cart-prev">Prec</button>
          <span id="cart-status">1 / 1</span>
          <button type="button" id="cart-next">Next</button>
        </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-total">
          <span class="fw-semibold">Totale</span>
          <span class="cassa-sb-total-value" id="cart-total">EUR 0,00</span>
        </div>
        <div class="cassa-sb-pay-grid">
          <button type="button" class="cassa-sb-main-btn">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>


<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 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();

    let selectedKitchen = kitchenTabs.length ? kitchenTabs[0].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 renderProducts = function () {
      const term = (productSearch?.value || '').trim().toLowerCase();
      const selectedTab = kitchenTabs.find(function (tab) {
        return tab.dataset.kitchenId === selectedKitchen;
      });
      if (selectedKitchenLabel) {
        const labelEl = selectedTab ? selectedTab.querySelector('.cassa-sb-kitchen-label') : null;
        selectedKitchenLabel.textContent = labelEl ? labelEl.textContent.trim() : 'Tutte';
      }
      visibleProducts = 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);
      current.forEach(function (item) { item.style.display = ''; });

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

      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();
    // renderCart();
  })();
</script>
@endsection


@section('page-script')
  @include('punto_vendita.cassa.viste.catalogo._partials.scripts')

@endsection