{{--
|--------------------------------------------------------------------------
| 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">
            <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 class="relative mt-1 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-3 py-2 text-sm rounded-md hover:bg-blue-50 focus:outline-none transition"
                    :class="{'bg-blue-50': isFilterOpen, 'bg-white': !isFilterOpen}">
                    <span class="text-sm text-slate-700 font-regular" x-text="currentDestinationLabel"></span>
                    <i class="fa fa-chevron-down text-xs text-slate-700 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>

    {{-- Sekcja ładowania --}}
    <template x-if="loading">
        <p class="text-center py-10 text-gray-500">
            {{ trans('lang.loading_orders') }}...
        </p>
    </template>

    {{-- KANBAN: 3 kolumny (Nowe, W przygotowaniu, Gotowe) --}}
    <div class="grid grid-cols-1 md:grid-cols-3 gap-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">
                            <p class="text-sm text-gray-700" x-text="elapsedTime(order.createdAt)"></p>
                            <div class="flex justify-between items-start mt-1">
                                <h3 class="font-bold text-base text-gray-900">
                                    {{ trans('lang.order') }} #<span x-text="order.orderNumber"></span>
                                </h3>
                                <div class="text-gray-700 text-xl" x-html="serviceIcon(order)"></div>
                            </div>
                            <div class="text-base text-gray-700 mt-1">
                                <p x-html="serviceLabel(order)"></p>
                                <p class="text-sm text-gray-600">
                                    Email: <span x-text="obfuscatedEmail(order.customerEmail)"></span>
                                </p>
                            </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="truncate font-bold">
                                            <span x-text="p.quantity + 'x ' + p.productTitle"></span>
                                        </p>
                                        <template x-if="p.productExtras && p.productExtras.length > 0">
                                            <ul class="list-disc list-inside text-base text-gray-600 mt-1">
                                                <template x-for="extra in p.productExtras" :key="extra.name || extra">
                                                    <li x-text="typeof extra === 'string' ? extra : extra.name"></li>
                                                </template>
                                            </ul>
                                        </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">
                            <p class="text-sm text-gray-700" x-text="elapsedTime(order.createdAt)"></p>
                            <div class="flex justify-between items-start mt-1">
                                <h3 class="font-bold text-base text-gray-900">
                                    {{ trans('lang.order') }} #<span x-text="order.orderNumber"></span>
                                </h3>
                                <div class="text-gray-700 text-xl" x-html="serviceIcon(order)"></div>
                            </div>
                            <div class="text-sm text-gray-700 mt-1">
                                <p x-html="serviceLabel(order)"></p>
                                <p class="text-xs text-gray-600">
                                    Email: <span x-text="obfuscatedEmail(order.customerEmail)"></span>
                                </p>
                            </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="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="truncate font-bold">
                                            <span x-text="p.quantity + 'x ' + p.productTitle"></span>
                                        </p>
                                        <template x-if="p.productExtras && p.productExtras.length > 0">
                                            <ul class="list-disc list-inside text-base text-gray-600 mt-1">
                                                <template x-for="extra in p.productExtras" :key="extra.name || extra">
                                                    <li x-text="typeof extra === 'string' ? extra : extra.name"></li>
                                                </template>
                                            </ul>
                                        </template>
                                    </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'">
                            <p class="text-xs text-gray-700" x-text="elapsedTime(order.createdAt)"></p>
                            <div class="flex justify-between items-start mt-1">
                                <h3 class="font-bold text-base text-gray-900">
                                    {{ trans('lang.order') }} #<span x-text="order.orderNumber"></span>
                                </h3>
                                <div class="text-gray-700 text-xl" x-html="serviceIcon(order)"></div>
                            </div>
                            <div class="text-sm text-gray-700 mt-1">
                                <p x-html="serviceLabel(order)"></p>
                                <p class="text-xs text-gray-600">
                                    Email: <span x-text="obfuscatedEmail(order.customerEmail)"></span>
                                </p>
                            </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="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="truncate font-bold" x-text="p.quantity + 'x ' + p.productTitle"></p>
                                        <template x-if="p.productExtras && p.productExtras.length > 0">
                                            <ul class="list-disc list-inside text-base text-gray-600 mt-1">
                                                <template x-for="extra in p.productExtras" :key="extra.name || extra">
                                                    <li x-text="typeof extra === 'string' ? extra : extra.name"></li>
                                                </template>
                                            </ul>
                                        </template>
                                    </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 --}}
    <div x-show="showNotificationModal" id="notificationModal"
        class="fixed inset-0 bg-black bg-opacity-80 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>
            </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"
                    x-text="soundEnabled ? '{{ trans('lang.sound_enabled') }}' : '{{ trans('lang.enable_sound') }}'"></button>
                <button @click="cancelSound()"
                    class="w-full h-12 flex items-center justify-center bg-white text-gray-700 border border-gray-300 text-base font-semibold rounded-md shadow-sm uppercase transition-colors hover:bg-gray-50">
                    {{ trans('lang.cancel') }}
                </button>
                <span class="text-xs text-gray-500 mt-2 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: true,
                soundEnabled: false,
                audioUnlocked: false,
                isFilterOpen: false,

                vendorId: '',
                currentDestinationFilter: 'All',
                destinationFilters: [],

                allOrdersData: [],
                vendorProductsCache: {},

                // Inicjalizacja zamówień
                async initOrders() {
                    this.destinationFilters = [
                        { value: 'All', label: `{{ trans('lang.both') }} ({{ trans('lang.bar') }} + {{ trans('lang.kitchen') }})` },
                        { value: 'Bar', label: `{{ trans('lang.bar') }} ({{ trans('lang.only_bar_orders') }})` },
                        { value: 'Kitchen', label: `{{ trans('lang.kitchen') }} ({{ trans('lang.only_kitchen_orders') }})` }
                    ];

                    try {
                        const db = firebase.firestore();
                        const userSnapshot = await db.collection('users')
                            .where('id', '==', userId)
                            .get();
                        if (userSnapshot.empty) throw new Error('User not found');

                        this.vendorId = userSnapshot.docs[0].data().vendorID || '';
                        if (!this.vendorId) throw new Error('No vendorID assigned');

                        this.initializeFirestoreListener(db);
                    } catch (err) {
                        console.error(err);
                        this.loading = false;
                    }
                },

                // Nasłuchiwanie zmian w Firestore
                initializeFirestoreListener(db) {
                    const yesterday = new Date();
                    yesterday.setDate(yesterday.getDate() - 1);
                    // Pobieramy zamówienia z ostatnich 24 godzin
                    db.collection('restaurant_orders')
                        .where('vendorID', '==', this.vendorId)
                        .where('createdAt', '>', yesterday)
                        .orderBy('createdAt', 'desc')
                        .onSnapshot(async snapshot => {
                            let newOrders = false;
                            // Przetwarzanie zmian w zamówieniach
                            for (const change of snapshot.docChanges()) {
                                let doc = change.doc.data();
                                doc.id = change.doc.id;
                                doc = await this.processOrderData(doc);

                                if (change.type === 'added') {
                                    // Nowe zamówienie
                                    if (!this.allOrdersData.find(o => o.id === doc.id)) {
                                        this.allOrdersData.push(doc);
                                        newOrders = true;
                                    }
                                } else if (change.type === 'modified') {
                                    // Zmiana zamówienia
                                    const i = this.allOrdersData.findIndex(o => o.id === doc.id);
                                    if (i !== -1) this.allOrdersData[i] = doc;
                                } else if (change.type === 'removed') {
                                    // Usunięcie zamówienia
                                    this.allOrdersData = this.allOrdersData.filter(o => o.id !== doc.id);
                                }
                            }

                            // Sortuj od najnowszych do najstarszych
                            this.allOrdersData.sort((a, b) =>
                                b.createdAt.toMillis() - a.createdAt.toMillis()
                            );

                            // Remove orders where both statuses are Finished
                            this.allOrdersData = this.allOrdersData.filter(order =>
                                !(order.barStatus === 'Finished' && order.kitchenStatus === 'Finished')
                            );


                            // Nowe zamówienia + zakładka aktywna -> odtwórz dźwięk
                            if (newOrders && !document.hidden) {
                                this.playNotificationSound();
                            }
                            this.loading = false;
                        }, err => {
                            console.error(err);
                            this.loading = false;
                        });
                },

                // Metoda do ustalenia docelowego printerDestination w pętlach
                async processOrderData(order) {
                    const destinations = new Set();
                    if (Array.isArray(order.order)) {
                        for (const product of order.order) {
                            const pId = product.id || product.productId || product.item_id;
                            if (pId) {
                                const dest = await this.getProductPrinterDestination(pId);
                                if (dest) {
                                    destinations.add(dest);
                                    product.destination = dest;
                                }
                            }
                        }
                    }
                    order.destinations = Array.from(destinations);
                    return order;
                },

                async getProductPrinterDestination(productId) {
                    if (!productId) return null;
                    if (this.vendorProductsCache[productId]) {
                        return this.vendorProductsCache[productId];
                    }
                    try {
                        const snap = await firebase.firestore()
                            .collection('vendor_products')
                            .doc(productId)
                            .get();
                        const dest = (snap.exists && snap.data().printerDestination)
                            ? snap.data().printerDestination
                            : 'Kitchen';
                        this.vendorProductsCache[productId] = dest;
                        return dest;
                    } catch {
                        return 'Kitchen';
                    }
                },

                // Filtrowanie zamówień wg statusu
                ordersForStatus(status) {
                    const excluded = [
                        'Payment Refund',
                        'Payment Pending',
                        'Payment Failed',
                        'Order Rejected',
                        'Order Cancelled'
                    ];
                    return this.allOrdersData.filter(o =>
                        !excluded.includes(o.status) &&
                        o.status === status &&
                        (this.currentDestinationFilter === 'All' ||
                            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 m = Math.floor((Date.now() - createdAt.toMillis()) / 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);
                },

                // 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>`;
                            }
                        }
                    }
                    // 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') {
                        // Assuming order.serviceType is available.
                        // You might need to adjust the click handlers (e.g., hideOrder, markAsPickedUp)
                        // to methods you have defined in your Vue component.
                        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>`;
                        }
                    }


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

                    // Tworzymy kopię, aby uniknąć bezpośrednich mutacji przed zapisem
                    let order = { ...this.allOrdersData[orderIndex] };

                    // Przygotowujemy dane do aktualizacji
                    let payload = {};
                    if (type === 'Bar') {
                        payload.barStatus = newSubStatus;
                    } else if (type === 'Kitchen') {
                        payload.kitchenStatus = newSubStatus;
                    }

                    // Aplikujemy zmiany do naszej lokalnej kopii, żeby obliczyć główny status
                    Object.assign(order, payload);

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

                    // Logika progresji statusu (przeniesiona z Twojego oryginalnego kodu)
                    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'; // Zmieniono na 'Order Completed' zgodnie z logiką progresji
                    }

                    // Jeśli zamówienie nie ma pozycji z kuchni, status kuchni odzwierciedla status baru
                    if (!hasKitchenItems && payload.barStatus) {
                        payload.kitchenStatus = payload.barStatus;
                    }
                    // I na odwrót
                    if (!hasBarItems && payload.kitchenStatus) {
                        payload.barStatus = payload.kitchenStatus;
                    }
                    
                    console.log("Aktualizowanie Firebase z payloadem:", payload);

                    try {
                        const db = firebase.firestore();
                        const orderRef = db.collection('restaurant_orders').doc(orderId);
                        
                        // *** GŁÓWNA ZMIANA: Bezpośredni zapis do Firebase zamiast fetch() ***
                        await orderRef.update(payload);

                        // Aktualizacja jest teraz obsługiwana przez listener onSnapshot,
                        // więc ręczna modyfikacja lokalnych danych nie jest już konieczna,
                        // ale może być pozostawiona dla natychmiastowej reakcji UI.
                        // Listener i tak za chwilę nadpisze te dane świeżymi z bazy.
                        console.log('Status zamówienia pomyślnie zaktualizowany w Firebase.');

                    } catch (error) {
                        console.error("Błąd podczas aktualizacji statusu w Firebase:", error);
                        alert(`Wystąpił błąd: ${error.message}`);
                        // Tutaj można dodać logikę przywracania stanu w razie błędu,
                        // ale listener onSnapshot powinien sobie z tym poradzić,
                        // po prostu nie otrzymując nowej wersji danych.
                    }
                },
                async hideOrder(orderId) {
                    const order = this.allOrdersData.find(o => o.id === orderId);
                    if (!order) {
                        console.error('Order not found for hiding:', orderId);
                        return;
                    }

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

                        // Update Bar status to "Finished" if applicable
                        if (hasBarItems && order.barStatus !== 'Finished') {
                            await this.updateSubStatus(orderId, 'Bar', 'Finished');
                            order.barStatus = 'Finished'; // Optimistic update for UI responsiveness
                            this.allOrdersData = this.allOrdersData.filter(o => o.id !== orderId); // Remove from view
                        }

                        // Update Kitchen status to "Finished" if applicable
                        if (hasKitchenItems && order.kitchenStatus !== 'Finished') {
                            await this.updateSubStatus(orderId, 'Kitchen', 'Finished');
                            order.kitchenStatus = 'Finished'; // Optimistic update
                        }

                        // Remove the order from the list displayed on screen
                        // This assumes 'this.orders' is the reactive array powering your list
                        this.allOrdersData = this.allOrdersData.filter(o => o.id !== orderId);

                    } catch (error) {
                        console.error(`Error in hideOrder for order ${orderId}:`, error);
                        // Potentially revert optimistic updates or show a user notification here
                    }
                },

                async markAsPickedUp(orderId) {
                    const order = this.allOrdersData.find(o => o.id === orderId);
                    if (!order) {
                        console.error('Order not found for marking as picked up:', orderId);
                        return;
                    }

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

                        // Update Bar status to "Finished" if applicable
                        if (hasBarItems && order.barStatus !== 'Finished') {
                            await this.updateSubStatus(orderId, 'Bar', 'Finished');
                            order.barStatus = 'Finished'; // Optimistic update
                            this.allOrdersData = this.allOrdersData.filter(o => o.id !== orderId); // Remove from view
                        }

                        // Update Kitchen status to "Finished" if applicable
                        if (hasKitchenItems && order.kitchenStatus !== 'Finished') {
                            await this.updateSubStatus(orderId, 'Kitchen', 'Finished');
                            order.kitchenStatus = 'Finished'; // Optimistic update
                        }
                
                        // Remove the order from allOrdersData
                        this.allOrdersData = this.allOrdersData.filter(o => o.id !== orderId);

                    } catch (error) {
                        console.error(`Error in markAsPickedUp for order ${orderId}:`, error);
                        // Potentially revert optimistic updates or show a user notification here
                    }
                },


                // Dodatkowe przyciski do aktualizacji barStatus / kitchenStatus
                barKitchenButtons(o) {
                    let html = ``;

                    // Jeżeli barStatus !== "Ready" – pokazujemy przycisk "Bar gotowy"
                    if (o.barStatus !== 'Ready') {
                        html += `
                    <button class="m-2 flex-1 py-3 text-xs font-bold text-white bg-green-500 hover:bg-green-400 rounded-lg"
                            @click="markBarReady('${o.id}')">
                        Bar gotowy
                    </button>
                `;
                    }

                    // Jeżeli kitchenStatus !== "Ready" – pokazujemy przycisk "Kuchnia gotowa"
                    if (o.kitchenStatus !== 'Ready') {
                        html += `
                    <button class="m-2 flex-1 py-3 text-xs font-bold text-white bg-orange-500 hover:bg-orange-400 rounded-lg"
                            @click="markKitchenReady('${o.id}')">
                        Kuchnia gotowa
                    </button>
                `;
                    }

                    return html;
                },

                // Metody do zmiany globalnego statusu
                updateOrderStatus(id, status) {
                    firebase.firestore().collection('restaurant_orders')
                        .doc(id)
                        .update({status});
                },

                // Oznaczenie, że zamówienie zostało odebrane
                updatePickupStatus(id) {
                    firebase.firestore().collection('restaurant_orders')
                        .doc(id)
                        .update({orderPickedUp: true});
                },

                // Ukrycie kafelka
                hideTile(id) {
                    this.allOrdersData = this.allOrdersData.filter(o => o.id !== id);
                },

                // --- NOWE METODY bar/kitchen ---
                async markBarReady(orderId) {
                    // Wywołujemy endpoint w OrderController (updateStatus) - via AJAX
                    try {
                        const resp = await fetch('/orders/update-status', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({
                                orderId: orderId,
                                barStatus: 'Ready'
                            })
                        });
                        const data = await resp.json();
                        console.log('markBarReady ->', data);
                    } catch (err) {
                        console.error(err);
                    }
                },

                async markKitchenReady(orderId) {
                    try {
                        const resp = await fetch('/orders/update-status', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({
                                orderId: orderId,
                                kitchenStatus: 'Ready'
                            })
                        });
                        const data = await resp.json();
                        console.log('markKitchenReady ->', data);
                    } catch (err) {
                        console.error(err);
                    }
                },

                // 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;
                            setTimeout(() => {
                                this.showNotificationModal = false;
                            }, 1200);
                        })
                        .catch(() => {
                            this.showNotificationModal = false;
                        });
                },
                cancelSound() {
                    this.soundEnabled = false;
                    this.showNotificationModal = false;
                },
                playNotificationSound() {
                    if (this.soundEnabled) {
                        document.getElementById('notificationAudio').play();
                    }
                },

                onVisibilityChange() {
                    // np. odświeżanie w razie potrzeby
                }
            };
        }
</script>
@endsection