 {{--
|--------------------------------------------------------------------------
| Plik Widoku: Panel Zamówień na Żywo (Kanban Board)
|--------------------------------------------------------------------------
|
| Lokalizacja: resources/views/orders/live.blade.php
| Wersja: 1.2 - Wdrożono filtrowanie i statusy podrzędne (Bar/Kuchnia)
| Ostatnia modyfikacja: 29 czerwca 2025
|
|--------------------------------------------------------------------------
| Opis Przeznaczenia
|--------------------------------------------------------------------------
|
| Ten plik Blade renderuje interaktywny panel zamówień na żywo w stylu
| tablicy Kanban. Jest on zaprojektowany do użytku w dynamicznych
| środowiskach, takich jak kuchnie i bary, gdzie kluczowe jest śledzenie
| postępu zamówień w czasie rzeczywistym. Widok automatycznie odświeża
| się dzięki nasłuchiwaniu zmian w bazie danych Firestore.
|
|--------------------------------------------------------------------------
| Kluczowe Funkcjonalności
|--------------------------------------------------------------------------
|
| - **Tablica Kanban:** Wizualizacja zamówień w trzech kolumnach odpowiadających
|   kluczowym etapom: "Nowe", "W przygotowaniu", "Gotowe do wydania".
| - **Aktualizacje w Czasie Rzeczywistym:** Wykorzystanie `onSnapshot` z Firestore
|   do natychmiastowego odzwierciedlania nowych zamówień i zmian statusu.
| - **Filtrowanie Dynamiczne:** Możliwość filtrowania widocznych zamówień
|   na podstawie miejsca docelowego (np. tylko Bar, tylko Kuchnia, lub oba).
| - **Interaktywne Akcje:** Przyciski pozwalające na zmianę statusu zamówienia
|   (np. "Akceptuj", "Ukończ", "Odebrane") bezpośrednio z poziomu kafelka.
| - **Statusy Podrzędne:** Śledzenie oddzielnych statusów dla części barowej
|   i kuchennej zamówienia (`barStatus`, `kitchenStatus`).
| - **Powiadomienia Dźwiękowe:** Odtwarzanie dźwięku dla nowych zamówień,
|   z modalem proszącym o zgodę użytkownika na włączenie dźwięku.
| - **Prywatność:** Maskowanie adresów e-mail klientów w celu ochrony danych.
|
|--------------------------------------------------------------------------
| Stos Technologiczny i Zależności
|--------------------------------------------------------------------------
|
| - Backend: Laravel (silnik szablonów Blade, system tłumaczeń, routing)
| - Frontend (Interaktywność): Alpine.js
| - Frontend (Style): Tailwind CSS, Font Awesome
| - Baza Danych (Źródło danych): Firebase Firestore (logika po stronie klienta)
| - Wymagane pola w Firestore: `vendorID`, `createdAt`, `status`, `order`,
|   `customerEmail`, `barStatus`, `kitchenStatus`, `printerDestination` w produktach.
|
--}}

@extends('layouts.app')

@section('content')
{{-- Plik audio dla powiadomień --}}
<audio id="notificationAudio" src="{{ asset('assets/notification_sound.mp3') }}" preload="auto"></audio>

<div class="p-10 min-h-screen"
    x-data="liveOrdersAlpine('{{ $id }}')" 
    x-init="initOrders()"
    @visibilitychange.window="document.hidden ? null : onVisibilityChange()">
    
    {{-- NIEBIESKI KAFEL: nagłówek + filtry --}}
    <div class="rounded-lg shadow-[1px_1px_4px_0px_#e2e8f0] p-4 items-center
                bg-gradient-to-r from-slate-900 via-blue-800 to-blue-500 items-center
                flex flex-col sm:flex-row justify-between mb-8">
        <div class="flex flex-col justify-center sm:mb-0">
                <h1 class="text-2xl font-bold text-white">{{ trans('lang.live_orders') }}</h1>
                <p class="text-sm text-slate-200 mt-1 m-0">{{ trans('lang.live_orders_desc') }}</p>
            </div>

        <div class="flex flex-col items-start sm:items-end justify-center gap-4">
            {{-- Etykiety i tekst wyjaśniający --}}
            <div class="flex flex-col items-start sm:items-end">
                <label for="destinationFilter" class="text-sm font-medium text-slate-200 mb-1">
                        {{ trans('lang.kanban_filter_label') }}:
                    </label>

                <p class="text-xs font-light text-white max-w-[220px] pb-3 leading-snug text-right">
                    {{ trans('lang.kanban_filter_explanation') }}
                </p>
            </div>

            {{-- Kontener z obydwoma kontrolkami obok siebie --}}
            <div class="flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
                {{-- Toggle trybu loop dla dźwięku --}}
                <div class="flex items-center gap-3 bg-slate-800 rounded-md px-4 py-2">
                    <svg xmlns="http://www.w3.org/2000/svg" 
                         width="20" 
                         height="20" 
                         viewBox="0 0 24 24" 
                         fill="none" 
                         stroke="currentColor" 
                         stroke-width="2" 
                         stroke-linecap="round" 
                         stroke-linejoin="round" 
                         class="text-white"
                         :class="{'animate-spin': loopSoundEnabled && hasUnreactedOrders}">
                        <path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/>
                        <path d="M21 3v5h-5"/>
                        <path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/>
                        <path d="M8 16H3v5"/>
                    </svg>
                    <span class="text-sm font-medium text-white whitespace-nowrap">
                        {{ trans('lang.loop_mode') }}
                    </span>
                    <label class="relative inline-flex items-center cursor-pointer ml-2">
                        <input type="checkbox" 
                               x-model="loopSoundEnabled" 
                               @change="toggleLoopMode()"
                               class="sr-only peer">
                        <div class="relative w-11 h-6 bg-slate-300 rounded-full peer-checked:bg-green-500 transition-colors after:content-[''] after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border after:border-slate-300 after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:after:translate-x-full peer-checked:after:border-white shadow-sm"></div>
                    </label>
                </div>

                {{-- Filtr destination --}}
                <div class="relative w-full sm:w-auto" @click.outside="isFilterOpen = false">
                    <button type="button" @click="isFilterOpen = !isFilterOpen"
                        class="flex w-full items-center justify-between gap-4 px-4 py-2 rounded-md bg-white text-slate-600 text-sm transition focus:outline-none whitespace-nowrap hover:bg-slate-100 hover:text-slate-900">
                        <span class="font-regular" x-text="currentDestinationLabel"></span>
                        <i class="fa fa-chevron-down text-xs transition-transform"
                            :class="{'rotate-180': isFilterOpen}"></i>
                    </button>
                    <ul class="absolute right-0 mt-2 bg-white border !border-slate-300 rounded-lg shadow-lg z-50 transition-all overflow-hidden max-h-60 overflow-y-auto"
                        x-show="isFilterOpen" x-transition style="display: none;">
                        <template x-for="item in destinationFilters" :key="item.value">
                            <li @click="setDestinationFilter(item.value)"
                                class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-sm text-slate-700 whitespace-nowrap">
                                <div class="w-5 text-center">
                                    <i class="fa-solid fa-check text-blue-600"
                                        x-show="currentDestinationFilter === item.value" style="display: none;"></i>
                                </div>
                                <span x-text="item.label"></span>
                            </li>
                        </template>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    {{-- Loader --}}
    <div x-show="loading" class="
        fixed inset-0
        bg-black bg-opacity-80
        z-50
        flex items-center justify-center
        " x-transition:enter="transition ease-out duration-300" x-transition:enter-start="opacity-0"
            x-transition:enter-end="opacity-100" x-transition:leave="transition ease-in duration-200"
            x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0" style="display: none;">
            <div class="text-white text-lg flex flex-col items-center gap-2">
                <i class="fa-solid fa-spinner fa-spin text-4xl"></i>
                <span class="text-base">
                    {{ trans('lang.loading_orders') }}...
                </span>
            </div>
    </div>

    {{-- KANBAN: 3 kolumny (Nowe, W przygotowaniu, Gotowe) --}}
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mt-6" x-show="!loading">

        {{-- 1) NOWE ZAMÓWIENIA --}}
        <div class="flex flex-col bg-white border !border-slate-300 rounded-lg overflow-hidden">
            <div class="px-4 py-3 bg-slate-900 border !border-slate-900">
                <h2 class="text-lg font-bold text-white">{{ trans('lang.new_orders') }}</h2>
            </div>
            <div class="px-4 pt-2 pb-4 flex-1 space-y-4">
                <template x-for="order in ordersForStatus('Order Placed')" :key="order.id">
                    <div class="flex flex-col rounded-lg border !border-slate-300">
                        {{-- 1) HEADER --}}
                        <div class="p-3 bg-amber-200 rounded-t-lg">
                            <div class="grid grid-cols-12 gap-2">
                                <div class="col-span-11">
                                    <div class="flex justify-between items-center">
                                        <h3 class="font-bold text-base text-gray-900">
                                            {{ trans('lang.order') }} #<span x-text="order.orderNumber"></span>
                                        </h3>
                                        <p class="text-sm text-gray-700" x-text="elapsedTime(order.createdAt)"></p>
                                    </div>
                                    <div class="mt-1">
                                        <p class="text-sm text-gray-700" x-html="serviceLabel(order)"></p>
                                    </div>
                                </div>
                                <div class="col-span-1 flex justify-end">
                                    <div class="text-gray-700 text-xl" x-html="serviceIcon(order)"></div>
                                </div>
                            </div>
                        </div>

                        {{-- 2) BODY --}}
                        <div class="flex-1 p-3 bg-amber-100 border-t border-amber-200">
                            {{-- Informacja o barStatus / kitchenStatus (przykład) --}}
                            <p class="text-xs text-gray-500 mb-2">
                                {{ trans('lang.bar_status') }}: <span class="font-bold text-slate-700" x-text="order.barStatus || 'N/A'"></span> |
                                {{ trans('lang.kitchen_status') }}: <span class="font-bold text-slate-700" x-text="order.kitchenStatus || 'N/A'"></span>
                            </p>

                            <template x-for="(p, index) in order.order" :key="p.productTitle + '-' + p.quantity">
                                <div>
                                    <template x-if="index > 0">
                                        <hr class="border-t !border-amber-300 my-2">
                                    </template>
                                    <div class="text-base leading-tight transition-opacity duration-300" :class="{
                                           'opacity-100': currentDestinationFilter==='All' || currentDestinationFilter===p.destination,
                                           'opacity-40': currentDestinationFilter!=='All' && currentDestinationFilter!==p.destination
                                         }">
                                        <p class="font-bold break-words">
                                            <span x-text="p.quantity + 'x ' + p.productTitle"></span>
                                        </p>
                                        <template x-if="p.productExtras && Array.isArray(p.productExtras) && p.productExtras.length > 0">
                                            <p class="text-sm text-gray-600 mt-1 break-words">
                                                (<span x-text="p.productExtras.map(extra => typeof extra === 'string' ? extra : (extra && extra.name ? extra.name : 'Unknown')).join(', ')"></span>)
                                            </p>
                                        </template>
                                    </div>
                                </div>
                            </template>
                        </div>

                        {{-- 3) FOOTER --}}
                        <div class="p-3 bg-amber-100 rounded-b-lg" x-html="actionButtons(order)"></div>
                    </div>
                </template>
                <template x-if="ordersForStatus('Order Placed').length===0">
                    <p class="text-center text-sm text-gray-400 pt-2">
                        {{ trans('lang.no_new_orders') }}
                    </p>
                </template>
            </div>
        </div>

        {{-- 2) W PRZYGOTOWANIU --}}
        <div class="flex flex-col bg-white border !border-slate-300 rounded-lg overflow-hidden">
            <div class="px-4 py-3 bg-slate-900 border !border-slate-900">
                <h2 class="text-lg font-bold text-white">{{ trans('lang.in_preparation') }}</h2>
            </div>
            <div class="px-4 pt-2 pb-4 flex-1 space-y-4">
                <template x-for="order in ordersForStatus('Order Accepted')" :key="order.id">
                    <div class="flex flex-col rounded-lg border !border-slate-300">
                        {{-- HEADER --}}
                        <div class="p-3 bg-blue-200 rounded-t-lg">
                            <div class="grid grid-cols-12 gap-2">
                                <div class="col-span-11">
                                    <div class="flex justify-between items-center">
                                        <h3 class="font-bold text-base text-gray-900">
                                            {{ trans('lang.order') }} #<span x-text="order.orderNumber"></span>
                                        </h3>
                                        <p class="text-sm text-gray-700" x-text="elapsedTime(order.createdAt)"></p>
                                    </div>
                                    <div class="mt-1">
                                        <p class="text-sm text-gray-700" x-html="serviceLabel(order)"></p>
                                    </div>
                                </div>
                                <div class="col-span-1 flex justify-end">
                                    <div class="text-gray-700 text-xl" x-html="serviceIcon(order)"></div>
                                </div>
                            </div>
                        </div>

                        {{-- BODY --}}
                        <div class="flex-1 p-3 bg-blue-100 border-t border-blue-200">
                            <p class="text-xs text-gray-500 mb-2">
                                {{ trans('lang.bar_status') }}: <span class="font-bold text-slate-700" x-text="order.barStatus || 'N/A'"></span> |
                                {{ trans('lang.kitchen_status') }}: <span class="font-bold text-slate-700" x-text="order.kitchenStatus || 'N/A'"></span>
                            </p>

                            <template x-for="(p, index) in order.order" :key="p.productTitle + '-' + p.quantity">
                                <div>
                                    <template x-if="index > 0">
                                        <hr class="border-t !border-blue-300 my-2">
                                    </template>
                                    <div class="flex items-center gap-2 text-base leading-tight transition-opacity duration-300 cursor-pointer" :class="{
                                           'opacity-100': currentDestinationFilter==='All' || currentDestinationFilter===p.destination,
                                           'opacity-40': currentDestinationFilter!=='All' && currentDestinationFilter!==p.destination
                                         }" @click="toggleItemCompletion(order.id, index)">
                                        <input type="checkbox"
                                               :id="'item-' + order.id + '-' + index"
                                               :checked="isItemCompleted(order.id, index)"
                                               class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 focus:ring-2 pointer-events-none flex-shrink-0">
                                        <div class="flex-1">
                                            <p class="font-bold break-words" :class="{ 'line-through text-gray-500': isItemCompleted(order.id, index) }">
                                                <span x-text="p.quantity + 'x ' + p.productTitle"></span>
                                            </p>
                                            <template x-if="p.productExtras && Array.isArray(p.productExtras) && p.productExtras.length > 0">
                                                <p class="text-sm text-gray-600 mt-1 break-words" :class="{ 'line-through text-gray-400': isItemCompleted(order.id, index) }">
                                                    (<span x-text="p.productExtras.map(extra => typeof extra === 'string' ? extra : (extra && extra.name ? extra.name : 'Unknown')).join(', ')"></span>)
                                                </p>
                                            </template>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </div>

                        {{-- FOOTER --}}
                        <div class="p-3 bg-blue-100 rounded-b-lg" x-html="actionButtons(order)"></div>
                    </div>
                </template>
                <template x-if="ordersForStatus('Order Accepted').length===0">
                    <p class="text-center text-sm text-gray-400 pt-2">
                        {{ trans('lang.no_orders_in_preparation') }}
                    </p>
                </template>
            </div>
        </div>

        {{-- 3) GOTOWE DO WYDANIA --}}
        <div class="flex flex-col bg-white border !border-slate-300 rounded-lg overflow-hidden">
            <div class="px-4 py-3 bg-slate-900 border !border-slate-900">
                <h2 class="text-lg font-bold text-white">{{ trans('lang.ready_to_pickup') }}</h2>
            </div>
            <div class="px-4 pt-2 pb-4 flex-1 space-y-4">
                <template x-for="order in ordersForStatus('Order Completed')" :key="order.id">
                    <div class="flex flex-col rounded-lg border !border-slate-300" :class="order.orderPickedUp
                                  ? 'opacity-70'
                                  : ''">
                        {{-- HEADER --}}
                        <div class="p-3" :class="order.orderPickedUp
                                       ? 'bg-gray-200 rounded-t-lg'
                                       : 'bg-green-200 rounded-t-lg'">
                            <div class="grid grid-cols-12 gap-2">
                                <div class="col-span-11">
                                    <div class="flex justify-between items-center">
                                        <h3 class="font-bold text-base text-gray-900">
                                            {{ trans('lang.order') }} #<span x-text="order.orderNumber"></span>
                                        </h3>
                                        <p class="text-xs text-gray-700" x-text="elapsedTime(order.createdAt)"></p>
                                    </div>
                                    <div class="mt-1">
                                        <p class="text-sm text-gray-700" x-html="serviceLabel(order)"></p>
                                    </div>
                                </div>
                                <div class="col-span-1 flex justify-end">
                                    <div class="text-gray-700 text-xl" x-html="serviceIcon(order)"></div>
                                </div>
                            </div>
                        </div>

                        {{-- BODY --}}
                        <div class="flex-1 p-3 border-t" :class="order.orderPickedUp
                                       ? 'bg-gray-100 border-gray-200'
                                       : 'bg-green-100 border-green-200'">
                            <p class="text-xs text-gray-500 mb-2">
                                {{ trans('lang.bar_status') }}: <span class="font-bold text-slate-700" x-text="order.barStatus || 'N/A'"></span> |
                                {{ trans('lang.kitchen_status') }}: <span class="font-bold text-slate-700" x-text="order.kitchenStatus || 'N/A'"></span>
                            </p>

                            <template x-for="(p, index) in order.order" :key="p.productTitle + '-' + p.quantity">
                                <div>
                                    <template x-if="index > 0">
                                        <hr class="border-t !border-green-300 my-2">
                                    </template>
                                    <div class="flex items-center gap-2 text-base leading-tight transition-opacity duration-300" :class="{
                                           'opacity-100': currentDestinationFilter==='All' || currentDestinationFilter===p.destination,
                                           'opacity-40': currentDestinationFilter!=='All' && currentDestinationFilter!==p.destination
                                         }">
                                        <input type="checkbox"
                                               :id="'item-completed-' + order.id + '-' + index"
                                               :checked="isItemCompleted(order.id, index)"
                                               class="w-4 h-4 text-green-600 bg-gray-100 border-gray-300 rounded focus:ring-green-500 focus:ring-2 pointer-events-none flex-shrink-0"
                                               disabled>
                                        <div class="flex-1">
                                            <p class="font-bold break-words" :class="{ 'line-through text-gray-500': isItemCompleted(order.id, index) }">
                                                <span x-text="p.quantity + 'x ' + p.productTitle"></span>
                                            </p>
                                            <template x-if="p.productExtras && Array.isArray(p.productExtras) && p.productExtras.length > 0">
                                                <p class="text-sm text-gray-600 mt-1 break-words" :class="{ 'line-through text-gray-400': isItemCompleted(order.id, index) }">
                                                    (<span x-text="p.productExtras.map(extra => typeof extra === 'string' ? extra : (extra && extra.name ? extra.name : 'Unknown')).join(', ')"></span>)
                                                </p>
                                            </template>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </div>

                        {{-- FOOTER --}}
                        <div class="p-3 rounded-b-lg" :class="order.orderPickedUp
                                       ? 'bg-gray-100'
                                       : 'bg-green-100'" x-html="actionButtons(order)">
                        </div>
                    </div>
                </template>
                <template x-if="ordersForStatus('Order Completed').length===0">
                    <p class="text-center text-sm text-gray-400 pt-2">
                        {{ trans('lang.no_ready_orders') }}
                    </p>
                </template>
            </div>
        </div>
    </div>

    {{-- Modal odpowiedzialny za włączenie dźwięku (wymagany - brak opcji anulowania) --}}
    <div x-show="showNotificationModal" id="notificationModal"
        class="fixed inset-0 bg-black bg-opacity-90 z-50 flex items-center justify-center p-4" style="display:none;">
        <div class="bg-white rounded-lg text-left overflow-hidden shadow-xl w-full max-w-md flex flex-col">
            <div class="p-6 text-center">
                <div class="mx-auto flex items-center justify-center h-16 w-16 rounded-full bg-blue-100">
                    <i class="fa-solid fa-bell text-3xl text-blue-600"></i>
                </div>
                <h4 class="text-xl font-semibold text-gray-900 mt-4">
                    {{ trans('lang.notification_sound') }}
                </h4>
                <p class="mt-2 text-sm text-gray-600">{{ trans('lang.notification_sound_desc') }} </p>
                <p class="mt-3 text-xs text-amber-600 font-medium">
                    <i class="fa-solid fa-info-circle mr-1"></i>
                    {{ trans('lang.notification_sound_required') }}
                </p>
                
                {{-- Opcja loop mode --}}
                <div class="mt-4 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                    <div class="flex items-center justify-between gap-3">
                        <div class="flex items-center gap-3">
                            <svg xmlns="http://www.w3.org/2000/svg" 
                                 width="20" 
                                 height="20" 
                                 viewBox="0 0 24 24" 
                                 fill="none" 
                                 stroke="currentColor" 
                                 stroke-width="2" 
                                 stroke-linecap="round" 
                                 stroke-linejoin="round" 
                                 class="text-blue-600">
                                <path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/>
                                <path d="M21 3v5h-5"/>
                                <path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/>
                                <path d="M8 16H3v5"/>
                            </svg>
                            <label for="loopSoundCheckbox" class="text-sm font-medium text-gray-800 cursor-pointer">
                                {{ trans('lang.loop_sound_until_reaction') }}
                            </label>
                        </div>
                        <label class="relative inline-flex items-center cursor-pointer">
                            <input type="checkbox" 
                                   id="loopSoundCheckbox"
                                   x-model="loopSoundEnabled"
                                   @change="localStorage.setItem('loopSoundEnabled', loopSoundEnabled)"
                                   class="sr-only peer">
                            <div class="relative w-11 h-6 bg-slate-300 rounded-full peer-checked:bg-green-500 transition-colors after:content-[''] after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border after:border-slate-300 after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:after:translate-x-full peer-checked:after:border-white shadow-sm"></div>
                        </label>
                    </div>
                    <p class="text-xs text-gray-600 mt-2 ml-8">
                        {{ trans('lang.loop_sound_description') }}
                    </p>
                </div>
            </div>

            <div class="bg-gray-50 px-4 py-4 border-t border-gray-200 flex flex-col gap-3">
                <button @click="enableSound()"
                    class="w-full h-12 flex items-center justify-center bg-blue-600 hover:bg-blue-700 text-white text-base font-semibold rounded-md shadow-md uppercase transition-colors">
                    <i class="fa-solid fa-volume-high mr-2"></i>
                    <span x-text="soundEnabled ? '{{ trans('lang.sound_enabled') }}' : '{{ trans('lang.enable_sound') }}'"></span>
                </button>
                <span class="text-xs text-gray-500 block text-center" x-show="soundEnabled">{{ trans('lang.closing') }}</span>
            </div>
        </div>
    </div>
    {{-- Koniec sekcji modal --}}

</div>
@endsection


@section('scripts')
<script>
    function liveOrdersAlpine(userId) {
            return {
                loading: true,
                showNotificationModal: !sessionStorage.getItem('notificationModalShown'),
                soundEnabled: false,
                audioUnlocked: false,
                isFilterOpen: false,

                loopSoundEnabled: localStorage.getItem('loopSoundEnabled') === 'true',
                loopIntervalId: null,
                hasUnreactedOrders: false,
                pollIntervalId: null,

                currentDestinationFilter: 'All',
                destinationFilters: [],

                allOrdersData: [],
                completedItems: {},

                async initOrders() {
                    this.loadCompletedItems();

                    this.destinationFilters = [
                        { value: 'All', label: `{{ trans('lang.both') }}` },
                        { value: 'Bar', label: `{{ trans('lang.bar') }} ({{ trans('lang.only_bar_orders') }})` },
                        { value: 'Kitchen', label: `{{ trans('lang.kitchen') }} ({{ trans('lang.only_kitchen_orders') }})` }
                    ];

                    await this.fetchOrders();

                    // Poll for new orders every 5 seconds
                    this.pollIntervalId = setInterval(() => this.fetchOrders(), 5000);
                },

                async fetchOrders() {
                    try {
                        const response = await fetch('{{ route('orders.api.live') }}', {
                            headers: {
                                'Accept': 'application/json',
                                'X-Requested-With': 'XMLHttpRequest',
                            }
                        });
                        if (!response.ok) throw new Error('HTTP ' + response.status);

                        const freshOrders = await response.json();
                        let newVisibleOrders = false;

                        for (const freshOrder of freshOrders) {
                            const existingIndex = this.allOrdersData.findIndex(o => o.id === freshOrder.id);
                            if (existingIndex === -1) {
                                if (this.isOrderVisible(freshOrder)) newVisibleOrders = true;
                                this.allOrdersData.push(freshOrder);
                            } else {
                                const existing = this.allOrdersData[existingIndex];
                                if (!this.isOrderVisible(existing) && this.isOrderVisible(freshOrder)) {
                                    newVisibleOrders = true;
                                }
                                this.allOrdersData[existingIndex] = freshOrder;
                            }
                        }

                        // Remove orders no longer returned (finished/cancelled)
                        const freshIds = freshOrders.map(o => o.id);
                        this.allOrdersData = this.allOrdersData.filter(o => freshIds.includes(o.id));

                        // Sort newest first
                        this.allOrdersData.sort((a, b) => {
                            const aTime = a.createdAt ? new Date(a.createdAt).getTime() : 0;
                            const bTime = b.createdAt ? new Date(b.createdAt).getTime() : 0;
                            return bTime - aTime;
                        });

                        this.cleanOldCompletedItems();

                        if (newVisibleOrders && !document.hidden) {
                            this.hasUnreactedOrders = true;
                            if (this.loopSoundEnabled) {
                                this.startLoopSound();
                            } else {
                                this.playNotificationSound();
                            }
                        }

                        this.checkForUnreactedOrders();
                    } catch (err) {
                        console.error('Error fetching live orders:', err);
                    } finally {
                        this.loading = false;
                    }
                },

                isOrderVisible(order) {
                    const excluded = [
                        'Payment Refund',
                        'Payment Pending',
                        'Payment Failed',
                        'Order Rejected',
                        'Order Cancelled'
                    ];
                    const visibleStatuses = ['Order Placed', 'Order Accepted', 'Order Completed'];
                    if (excluded.includes(order.status) || !visibleStatuses.includes(order.status)) return false;
                    if (order.barStatus === 'Finished' && order.kitchenStatus === 'Finished') {
                        return false;
                    }
                    
                    return true;
                },

                // Filtrowanie zamówień wg statusu
                ordersForStatus(status) {
                    const excluded = [
                        'Payment Refund',
                        'Payment Pending',
                        'Payment Failed',
                        'Order Rejected',
                        'Order Cancelled'
                    ];
                    
                    return this.allOrdersData.filter(o => {
                        if (excluded.includes(o.status) || o.status !== status) {
                            return false;
                        }
                        if (status === 'Order Completed') {
                            return true;
                        }
                        if (this.currentDestinationFilter === 'All') {
                            return true;
                        } else if (this.currentDestinationFilter === 'Both') {
                            return o.destinations.includes('Bar') && o.destinations.includes('Kitchen');
                        } else {
                            return o.destinations.includes(this.currentDestinationFilter);
                        }
                    });
                },

                // --- NOWE METODY I GETTERY DLA DROPDOWNA ---
                get currentDestinationLabel() {
                    const found = this.destinationFilters.find(f => f.value === this.currentDestinationFilter);
                    return found ? found.label : '...';
                },

                setDestinationFilter(value) {
                    this.currentDestinationFilter = value;
                    this.isFilterOpen = false;
                },

                // Wyliczanie "ile czasu minęło"
                elapsedTime(createdAt) {
                    if (!createdAt) return '';
                    const ms = Date.now() - new Date(createdAt).getTime();
                    const m = Math.floor(ms / 60000);
                    if (m < 1) return "@lang('lang.moments_ago')";
                    if (m < 60) {
                        return "@lang('lang.minutes_ago')".replace(':count', m);
                    }
                    const h = Math.floor(m / 60), mm = m % 60;
                    return "@lang('lang.hours_minutes_ago')"
                        .replace(':hours', h)
                        .replace(':minutes', mm);
                },

                // Check if an item is completed
                isItemCompleted(orderId, itemIndex) {
                    return this.completedItems[orderId] && this.completedItems[orderId].includes(itemIndex);
                },

                // Toggle item completion status
                toggleItemCompletion(orderId, itemIndex) {
                    if (!this.completedItems[orderId]) {
                        this.completedItems[orderId] = [];
                    }

                    const index = this.completedItems[orderId].indexOf(itemIndex);
                    if (index > -1) {
                        // Item is completed, remove it from completed list
                        this.completedItems[orderId].splice(index, 1);
                    } else {
                        // Item is not completed, add it to completed list
                        this.completedItems[orderId].push(itemIndex);
                    }
                    
                    // Zapisz do localStorage
                    this.saveCompletedItems();
                },
                
                // Zapisz stan checkboxów do localStorage
                saveCompletedItems() {
                    try {
                        localStorage.setItem('liveOrdersCompletedItems', JSON.stringify(this.completedItems));
                        console.log('Zapisano checkboxy do localStorage:', this.completedItems);
                    } catch (e) {
                        console.error('Nie można zapisać stanu checkboxów:', e);
                    }
                },
                
                // Wczytaj stan checkboxów z localStorage
                loadCompletedItems() {
                    try {
                        const saved = localStorage.getItem('liveOrdersCompletedItems');
                        if (saved) {
                            this.completedItems = JSON.parse(saved);
                            console.log('Wczytano checkboxy z localStorage:', this.completedItems);
                            // NIE czyścimy tutaj - zrobimy to po załadowaniu zamówień
                        } else {
                            console.log('Brak zapisanych checkboxów w localStorage');
                        }
                    } catch (e) {
                        console.error('Nie można wczytać stanu checkboxów:', e);
                        this.completedItems = {};
                    }
                },
                
                // Usuń stare wpisy checkboxów (opcjonalne - dla czyszczenia pamięci)
                cleanOldCompletedItems() {
                    // Zachowaj tylko checkboxy dla aktualnie istniejących zamówień
                    const currentOrderIds = this.allOrdersData.map(order => order.id);
                    const cleanedItems = {};
                    
                    for (const orderId in this.completedItems) {
                        if (currentOrderIds.includes(orderId)) {
                            cleanedItems[orderId] = this.completedItems[orderId];
                        }
                    }
                    
                    this.completedItems = cleanedItems;
                    this.saveCompletedItems();
                },

                // Ikona w zależności od rodzaju obsługi
                serviceIcon(o) {
                    return o.tableNumber
                        ? '<i class="fas fa-utensils"></i>'
                        : '<i class="fas fa-person-walking"></i>';
                },

                // Etykieta: Stolik/ Odbiór
                serviceLabel(o) {
                    if (o.tableNumber) {
                        return `{{ trans('lang.table_service') }}: ${o.tableNumber}`;
                    } else {
                        return `{{ trans('lang.counter_pickup') }}`;
                    }
                },

                // Maskowanie emaila
                obfuscatedEmail(e) {
                    if (!e) return 'N/A';
                    const i = e.indexOf('@');
                    if (i === -1) return e;
                    const name = e.slice(0, i);
                    const dom = e.slice(i);
                    return name.length > 3
                        ? name.slice(0, 3) + '...' + dom
                        : e;
                },

                // --- PRZYCISKI AKCJI ---
                actionButtons(order) {
                    let buttonsHtml = '';
                    const hasBarItems = order.order.some(item => item.destination === 'Bar');
                    const hasKitchenItems = order.order.some(item => item.destination === 'Kitchen');

                    // Define a consistent button style, adapt to your project's TailwindCSS or other styles
                    const btnClass = "flex-1 py-3 text-sm font-semibold text-white rounded-md shadow-md uppercase transition-colors flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-opacity-75";
                    const pInfoClass = "text-xs text-gray-600 mt-1 clear-both"; // For "Waiting for..." messages

                    // Stage 1: Order Placed (New Orders) -> Transition to 'Order Accepted'
                    if (order.status === 'Order Placed') {
                        // Show "Accept Bar" button
                        if (this.currentDestinationFilter === 'All' || this.currentDestinationFilter === 'Bar') {
                            if (hasBarItems && order.barStatus !== 'Ready') {
                                buttonsHtml += `<button @click="updateSubStatus('${order.id}', 'Bar', 'Ready')" class="${btnClass} bg-blue-500 hover:bg-blue-600 focus:ring-blue-400">Accept Bar</button>`;
                            }
                        }
                        // Show "Accept Kitchen" button
                        if (this.currentDestinationFilter === 'All' || this.currentDestinationFilter === 'Kitchen') {
                            if (hasKitchenItems && order.kitchenStatus !== 'Ready') {
                                buttonsHtml += `<button @click="updateSubStatus('${order.id}', 'Kitchen', 'Ready')" class="${btnClass} bg-green-500 hover:bg-green-600 focus:ring-green-400">Accept Kitchen</button>`;
                            }
                        }

                        // "Waiting for..." messages for 'Order Placed' state
                        if (hasBarItems && order.barStatus === 'Ready' && hasKitchenItems && order.kitchenStatus !== 'Ready') {
                            if (this.currentDestinationFilter === 'All' || this.currentDestinationFilter === 'Bar') {
                                buttonsHtml += `<p class="${pInfoClass}">Bar Accepted. Waiting for Kitchen.</p>`;
                            }
                        } else if (hasKitchenItems && order.kitchenStatus === 'Ready' && hasBarItems && order.barStatus !== 'Ready') {
                            if (this.currentDestinationFilter === 'All' || this.currentDestinationFilter === 'Kitchen') {
                                buttonsHtml += `<p class="${pInfoClass}">Kitchen Accepted. Waiting for Bar.</p>`;
                            }
                        }
                        
                        // === PRINT BUTTON (Terminal POS) ===
                        buttonsHtml += `<button @click="printOrder('${order.id}')" 
                            id="print-btn-${order.id}"
                            class="${btnClass} bg-purple-500 hover:bg-purple-600 focus:ring-purple-400">
                            <i class="fas fa-print mr-2"></i><span>{{ trans('lang.print_receipt') }}</span>
                        </button>`;
                    }
                    // Stage 2: Order Accepted (In Preparation) -> Transition to 'Order Ready'
                    else if (order.status === 'Order Accepted') {
                        // Show "Complete Bar" button
                        if (this.currentDestinationFilter === 'All' || this.currentDestinationFilter === 'Bar') {
                            // Only show complete if it's 'Ready' and belongs to Bar
                            if (hasBarItems && order.barStatus === 'Ready' && order.barStatus !== 'Complete') {
                                buttonsHtml += `<button @click="updateSubStatus('${order.id}', 'Bar', 'Complete')" class="${btnClass} bg-blue-600 hover:bg-blue-700 focus:ring-blue-500">Complete Bar</button>`;
                            }
                        }
                        // Show "Complete Kitchen" button
                        if (this.currentDestinationFilter === 'All' || this.currentDestinationFilter === 'Kitchen') {
                            // Only show complete if it's 'Ready' and belongs to Kitchen
                            if (hasKitchenItems && order.kitchenStatus === 'Ready' && order.kitchenStatus !== 'Complete') {
                                buttonsHtml += `<button @click="updateSubStatus('${order.id}', 'Kitchen', 'Complete')" class="${btnClass} bg-green-600 hover:bg-green-700 focus:ring-green-500">Complete Kitchen</button>`;
                            }
                        }

                        // "Waiting for..." messages for 'Order Accepted' state
                        if (hasBarItems && order.barStatus === 'Complete' && hasKitchenItems && order.kitchenStatus === 'Ready' && order.kitchenStatus !== 'Complete') {
                            if (this.currentDestinationFilter === 'All' || this.currentDestinationFilter === 'Bar') {
                                buttonsHtml += `<p class="${pInfoClass}">Bar Complete. Waiting for Kitchen to Complete.</p>`;
                            }
                        } else if (hasKitchenItems && order.kitchenStatus === 'Complete' && hasBarItems && order.barStatus === 'Ready' && order.barStatus !== 'Complete') {
                            if (this.currentDestinationFilter === 'All' || this.currentDestinationFilter === 'Kitchen') {
                                buttonsHtml += `<p class="${pInfoClass}">Kitchen Complete. Waiting for Bar to Complete.</p>`;
                            }
                        }
                    }
                    // Stage: Order Completed
                    else if (order.status === 'Order Completed') {
                        // For completed orders, show one action button regardless of destination filter
                        // This ensures products with "Both" destination get proper action buttons
                        
                        if (order.serviceType === 'tableService') {
                            buttonsHtml += `<button @click="hideOrder('${order.id}')" class="${btnClass} bg-gray-500 hover:bg-gray-600 focus:ring-gray-400">Hide</button>`;
                        } else if (order.serviceType === 'counterPickup') {
                            buttonsHtml += `<button @click="markAsPickedUp('${order.id}')" class="${btnClass} bg-purple-500 hover:bg-purple-600 focus:ring-purple-400">Picked up</button>`;
                        } else {
                            // Default action for orders without specific service type
                            buttonsHtml += `<button @click="hideOrder('${order.id}')" class="${btnClass} bg-gray-500 hover:bg-gray-600 focus:ring-gray-400">Complete Order</button>`;
                        }
                    }


                    if (buttonsHtml.trim() === '') {
                        buttonsHtml = '<p class="text-xs text-gray-500 mt-1">No actions available for this filter/status.</p>';
                    }

                    return `<div class="flex items-center gap-2 w-full">${buttonsHtml}</div>`;
                },
                async updateSubStatus(orderId, type, newSubStatus) {
                    const orderIndex = this.allOrdersData.findIndex(o => o.id === orderId);
                    if (orderIndex === -1) {
                        console.error("Order not found:", orderId);
                        return;
                    }

                    let order = { ...this.allOrdersData[orderIndex] };
                    let payload = {};
                    if (type === 'Bar') {
                        payload.barStatus = newSubStatus;
                    } else if (type === 'Kitchen') {
                        payload.kitchenStatus = newSubStatus;
                    }

                    Object.assign(order, payload);

                    const hasBarItems = order.order.some(item => item.destination === 'Bar');
                    const hasKitchenItems = order.order.some(item => item.destination === 'Kitchen');

                    const currentBarReady = !hasBarItems || order.barStatus === 'Ready';
                    const currentKitchenReady = !hasKitchenItems || order.kitchenStatus === 'Ready';
                    const currentBarComplete = !hasBarItems || order.barStatus === 'Complete';
                    const currentKitchenComplete = !hasKitchenItems || order.kitchenStatus === 'Complete';

                    if (order.status === 'Order Placed' && currentBarReady && currentKitchenReady) {
                        payload.status = 'Order Accepted';
                    } else if (order.status === 'Order Accepted' && currentBarComplete && currentKitchenComplete) {
                        payload.status = 'Order Completed';
                    }

                    if (!hasKitchenItems && payload.barStatus) {
                        payload.kitchenStatus = payload.barStatus;
                    }
                    if (!hasBarItems && payload.kitchenStatus) {
                        payload.barStatus = payload.kitchenStatus;
                    }

                    try {
                        const resp = await fetch(`/api/live-orders/${orderId}/sub-status`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify(payload)
                        });
                        if (!resp.ok) throw new Error('HTTP ' + resp.status);

                        // Optimistic local update
                        this.allOrdersData[orderIndex] = { ...this.allOrdersData[orderIndex], ...payload };

                        if (payload.status === 'Order Completed') {
                            try {
                                await fetch('/orders/send-finished-email', {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json',
                                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                                    },
                                    body: JSON.stringify({ orderId })
                                });
                            } catch (err) {
                                console.error(err);
                            }
                        }

                        setTimeout(() => {
                            if (!this.checkForUnreactedOrders()) {
                                this.stopLoopSound();
                            }
                        }, 500);

                    } catch (error) {
                        console.error("Error updating sub-status:", error);
                        alert(`Error: ${error.message}`);
                    }
                },
                async hideOrder(orderId) {
                    try {
                        const resp = await fetch(`/api/live-orders/${orderId}/finish`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({})
                        });
                        if (!resp.ok) throw new Error('HTTP ' + resp.status);
                        this.allOrdersData = this.allOrdersData.filter(o => o.id !== orderId);
                    } catch (error) {
                        console.error(`Error hiding order ${orderId}:`, error);
                    }
                },

                async markAsPickedUp(orderId) {
                    try {
                        const resp = await fetch(`/api/live-orders/${orderId}/finish`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({})
                        });
                        if (!resp.ok) throw new Error('HTTP ' + resp.status);
                        this.allOrdersData = this.allOrdersData.filter(o => o.id !== orderId);
                    } catch (error) {
                        console.error(`Error marking order ${orderId} as picked up:`, error);
                    }
                },

                // === PRINTER FUNCTIONS ===
                
                /**
                 * Drukuj zamówienie na drukarce termicznej
                 */
                async printOrder(orderId) {
                    console.log('🖨️ Print order:', orderId);
                    
                    const order = this.allOrdersData.find(o => o.id === orderId);
                    if (!order) {
                        console.error('Order not found:', orderId);
                        return;
                    }
                    
                    // Znajdź button i pokaż loading
                    const btn = document.getElementById('print-btn-' + orderId);
                    if (btn) {
                        btn.disabled = true;
                        btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i><span>{{ trans('lang.printing') }}</span>';
                    }
                    
                    try {
                        // Sprawdź czy drukarka jest dostępna (terminal POS)
                        if (typeof window.AndroidPrinter !== 'undefined') {
                            // Terminal POS - drukuj na drukarce termicznej
                            this.printToThermalPrinter(order);
                            
                            // Success feedback
                            if (btn) {
                                btn.classList.remove('bg-purple-500', 'hover:bg-purple-600');
                                btn.classList.add('bg-green-500');
                                btn.innerHTML = '<i class="fas fa-check mr-2"></i><span>{{ trans('lang.printed') }}</span>';
                                
                                // Przywróć po 3 sekundach
                                setTimeout(() => {
                                    btn.disabled = false;
                                    btn.classList.remove('bg-green-500');
                                    btn.classList.add('bg-purple-500', 'hover:bg-purple-600');
                                    btn.innerHTML = '<i class="fas fa-print mr-2"></i><span>{{ trans('lang.print_receipt') }}</span>';
                                }, 3000);
                            }
                            
                        } else {
                            // Przeglądarka - fallback
                            console.warn('Terminal printer not available, using browser print');
                            this.printToBrowser(order);
                            
                            // Przywróć button
                            if (btn) {
                                btn.disabled = false;
                                btn.innerHTML = '<i class="fas fa-print mr-2"></i><span>{{ trans('lang.print_receipt') }}</span>';
                            }
                        }
                        
                        // ⭐ Sprawdź czy są jeszcze nowe zamówienia po wydrukowaniu
                        setTimeout(() => {
                            if (!this.checkForUnreactedOrders()) {
                                this.stopLoopSound();
                                console.log('✅ Wszystkie zamówienia opracowane - zatrzymano loop');
                            } else {
                                console.log('⏳ Nadal są nowe zamówienia - loop kontynuowany');
                            }
                        }, 500);
                        
                    } catch (error) {
                        console.error('Print error:', error);
                        
                        // Error feedback
                        if (btn) {
                            btn.classList.remove('bg-purple-500');
                            btn.classList.add('bg-red-500');
                            btn.innerHTML = '<i class="fas fa-times mr-2"></i><span>{{ trans('lang.print_error') }}</span>';
                            
                            setTimeout(() => {
                                btn.disabled = false;
                                btn.classList.remove('bg-red-500');
                                btn.classList.add('bg-purple-500', 'hover:bg-purple-600');
                                btn.innerHTML = '<i class="fas fa-print mr-2"></i><span>{{ trans('lang.print_receipt') }}</span>';
                            }, 3000);
                        }
                    }
                },
                
                /**
                 * Drukuj na drukarce termicznej (terminal POS)
                 */
                printToThermalPrinter(order) {
                    const receiptData = this.formatReceiptForThermal(order);
                    
                    // Wywołaj API drukarki z aplikacji Android
                    window.AndroidPrinter.printReceipt(
                        receiptData.header,
                        receiptData.body,
                        receiptData.footer
                    );
                    
                    console.log('✅ Receipt sent to thermal printer');
                },
                
                /**
                 * Formatuj dane zamówienia dla drukarki termicznej
                 */
                formatReceiptForThermal(order) {
                    // === HEADER (wycentrowany, pogrubiony) ===
                    let header = 'PUB & GO\n';
                    header += 'Bestellung #' + order.orderNumber + '\n';
                    
                    // === BODY (wyrównany do lewej) ===
                    let body = '================================\n';
                    
                    // Data i czas
                    const date = order.createdAt ? new Date(order.createdAt) : new Date();
                    body += 'Datum: ' + date.toLocaleDateString('de-DE') + '\n';
                    body += 'Uhrzeit: ' + date.toLocaleTimeString('de-DE') + '\n';
                    
                    // Typ usługi - wyróżniony (taka sama logika jak serviceLabel)
                    body += '\n';
                    if (order.tableNumber) {
                        body += '>>> TISCH: ' + order.tableNumber + ' <<<\n';
                    } else {
                        body += '>>> THEKE / ZUM MITNEHMEN <<<\n';
                    }
                    body += '\n';
                    
                    body += '================================\n\n';
                    
                    // === ITEMS ===
                    body += 'ARTIKEL:\n';
                    body += '--------------------------------\n';
                    
                    order.order.forEach((item, index) => {
                        // Nazwa i ilość
                        body += item.quantity + 'x ' + item.productTitle + '\n';
                        
                        // Extras/Modifiers
                        if (item.productExtras && Array.isArray(item.productExtras) && item.productExtras.length > 0) {
                            item.productExtras.forEach(extra => {
                                const extraName = typeof extra === 'string' ? extra : (extra.name || 'Extra');
                                body += '   + ' + extraName + '\n';
                            });
                        }
                        
                        // Notes
                        if (item.productNotes) {
                            body += '   Notiz: ' + item.productNotes + '\n';
                        }
                        
                        // Destination (Kitchen/Bar)
                        if (item.destination) {
                            body += '   -> ' + item.destination + '\n';
                        }
                        
                        // Przerywana linia między produktami (nie po ostatnim)
                        if (index < order.order.length - 1) {
                            body += '- - - - - - - - - - - - - - - -\n';
                        }
                        
                        body += '\n';
                    });
                    
                    body += '--------------------------------\n';
                    body += '================================\n';
                    
                    // Customer info (zamaskowany email)
                    if (order.customerEmail) {
                        const email = order.customerEmail;
                        const atIndex = email.indexOf('@');
                        const masked = email.substring(0, 3) + '...' + email.substring(atIndex);
                        body += 'Kunde: ' + masked + '\n';
                    }
                    
                    // Payment status
                    if (order.paymentStatus) {
                        body += 'Zahlung: ' + order.paymentStatus + '\n';
                    }
                    
                    // === FOOTER (wycentrowany) ===
                    let footer = '\n\n';
                    footer += 'Vielen Dank!\n';
                    footer += 'www.pubandgo.de\n';
                    
                    return { header, body, footer };
                },
                
                /**
                 * Fallback - drukuj w przeglądarce
                 */
                printToBrowser(order) {
                    // Otwórz w nowym oknie
                    const printWindow = window.open('', '_blank', 'width=400,height=600');
                    
                    const html = this.formatReceiptHTML(order);
                    
                    printWindow.document.write(`
                        <!DOCTYPE html>
                        <html>
                        <head>
                            <meta charset="UTF-8">
                            <title>Bestellung #${order.orderNumber}</title>
                            <style>
                                body {
                                    font-family: 'Courier New', monospace;
                                    width: 300px;
                                    margin: 20px;
                                    font-size: 12px;
                                }
                                .center { text-align: center; }
                                .bold { font-weight: bold; }
                                .line { border-top: 1px dashed #000; margin: 10px 0; }
                            </style>
                        </head>
                        <body>
                            ${html}
                        </body>
                        </html>
                    `);
                    
                    printWindow.document.close();
                    
                    // Drukuj po załadowaniu
                    setTimeout(() => {
                        printWindow.print();
                    }, 500);
                },
                
                /**
                 * Format HTML dla przeglądarki
                 */
                formatReceiptHTML(order) {
                    let html = '<div class="center bold">';
                    html += '<h2>PUB & GO</h2>';
                    html += '<p>Bestellung #' + order.orderNumber + '</p>';
                    html += '</div>';
                    
                    html += '<div class="line"></div>';
                    
                    const receiptDate = order.createdAt ? new Date(order.createdAt) : new Date();
                    html += '<p>Datum: ' + receiptDate.toLocaleString('de-DE') + '</p>';
                    
                    // Typ odbioru - wyróżniony ramką (taka sama logika jak serviceLabel)
                    if (order.tableNumber) {
                        html += '<div style="border: 3px solid #000; padding: 10px; margin: 10px 0; text-align: center; font-weight: bold; font-size: 18px;">';
                        html += 'TISCH: ' + order.tableNumber;
                        html += '</div>';
                    } else {
                        html += '<div style="border: 3px solid #000; padding: 10px; margin: 10px 0; text-align: center; font-weight: bold; font-size: 18px;">';
                        html += 'THEKE / ZUM MITNEHMEN';
                        html += '</div>';
                    }
                    
                    html += '<div class="line"></div>';
                    
                    html += '<h3>Artikel:</h3>';
                    order.order.forEach((item, index) => {
                        html += '<p>' + item.quantity + 'x ' + item.productTitle + '</p>';
                        if (item.productExtras && item.productExtras.length > 0) {
                            item.productExtras.forEach(extra => {
                                const name = typeof extra === 'string' ? extra : extra.name;
                                html += '<p style="margin-left: 20px;">+ ' + name + '</p>';
                            });
                        }
                        // Notes
                        if (item.productNotes) {
                            html += '<p style="margin-left: 20px; font-style: italic;">Notiz: ' + item.productNotes + '</p>';
                        }
                        // Destination (Kitchen/Bar)
                        if (item.destination) {
                            html += '<p style="margin-left: 20px; font-style: italic;">→ ' + item.destination + '</p>';
                        }
                        // Przerywana linia między produktami (nie po ostatnim)
                        if (index < order.order.length - 1) {
                            html += '<p style="border-bottom: 1px dashed #999; margin: 10px 0;"></p>';
                        }
                    });
                    
                    html += '<div class="line"></div>';
                    
                    // Customer info (zamaskowany email)
                    if (order.customerEmail) {
                        const email = order.customerEmail;
                        const atIndex = email.indexOf('@');
                        const masked = email.substring(0, 3) + '...' + email.substring(atIndex);
                        html += '<p>Kunde: ' + masked + '</p>';
                    }
                    
                    // Payment status
                    if (order.paymentStatus) {
                        html += '<p>Zahlung: ' + order.paymentStatus + '</p>';
                    }
                    
                    html += '<div class="line"></div>';
                    html += '<div class="center"><p>Vielen Dank!</p></div>';
                    
                    return html;
                },

                // Obsługa dźwięku powiadomień
                enableSound() {
                    const a = document.getElementById('notificationAudio');
                    a.play()
                        .then(() => {
                            a.pause();
                            a.currentTime = 0;
                            this.audioUnlocked = true;
                            this.soundEnabled = true;
                            sessionStorage.setItem('notificationModalShown', 'true');
                            setTimeout(() => {
                                this.showNotificationModal = false;
                                // Jeśli są nowe zamówienia i loop jest włączony, rozpocznij od razu
                                if (this.loopSoundEnabled && this.checkForUnreactedOrders()) {
                                    this.startLoopSound();
                                }
                            }, 1200);
                        })
                        .catch(() => {
                            sessionStorage.setItem('notificationModalShown', 'true');
                            this.showNotificationModal = false;
                        });
                },
                playNotificationSound() {
                    if (this.soundEnabled) {
                        const audio = document.getElementById('notificationAudio');
                        audio.currentTime = 0; // Reset do początku
                        audio.play().catch(e => console.warn('Nie można odtworzyć dźwięku:', e));
                    }
                },

                // === FUNKCJE TRYBU LOOP ===
                
                // Toggle trybu loop
                toggleLoopMode() {
                    // Wartość loopSoundEnabled jest już zmieniona przez x-model checkboxa
                    localStorage.setItem('loopSoundEnabled', this.loopSoundEnabled);
                    
                    console.log('🔁 Loop mode:', this.loopSoundEnabled ? 'WŁĄCZONY' : 'WYŁĄCZONY');
                    
                    // Jeśli wyłączamy loop, zatrzymaj aktualną pętlę
                    if (!this.loopSoundEnabled) {
                        this.stopLoopSound();
                    }
                    // Jeśli włączamy i są nowe zamówienia, rozpocznij loop
                    else if (this.checkForUnreactedOrders()) {
                        this.startLoopSound();
                    }
                },

                // Rozpocznij odtwarzanie w pętli
                startLoopSound() {
                    if (!this.soundEnabled || !this.loopSoundEnabled) {
                        console.log('⚠️ Loop sound nie może wystartować - brak uprawnień lub tryb wyłączony');
                        return;
                    }
                    
                    // Zatrzymaj poprzednią pętlę jeśli istnieje
                    this.stopLoopSound();
                    
                    // Odtwórz dźwięk natychmiast
                    this.playNotificationSound();
                    
                    // Ustaw interval (co 5 sekund)
                    this.loopIntervalId = setInterval(() => {
                        if (this.checkForUnreactedOrders()) {
                            this.playNotificationSound();
                        } else {
                            this.stopLoopSound();
                        }
                    }, 5000); // 5 sekund między odtworzeniami
                    
                    console.log('🔁 Loop sound started (interval: 5s)');
                },

                // Zatrzymaj pętlę
                stopLoopSound() {
                    if (this.loopIntervalId) {
                        clearInterval(this.loopIntervalId);
                        this.loopIntervalId = null;
                        console.log('⏹️ Loop sound stopped');
                    }
                },

                // Sprawdź czy są zamówienia wymagające reakcji
                checkForUnreactedOrders() {
                    const newOrders = this.ordersForStatus('Order Placed');
                    this.hasUnreactedOrders = newOrders.length > 0;
                    return this.hasUnreactedOrders;
                },

                onVisibilityChange() {
                    if (!document.hidden) {
                        // Gdy użytkownik wraca do zakładki
                        console.log('👁️ Zakładka aktywna');
                        if (this.loopSoundEnabled && this.checkForUnreactedOrders()) {
                            this.startLoopSound();
                        }
                    } else {
                        // Gdy użytkownik opuszcza zakładkę - zatrzymaj loop
                        console.log('👁️ Zakładka nieaktywna - zatrzymuję loop');
                        this.stopLoopSound();
                    }
                }
            };
        }
</script>
@endsection