<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" @if (str_replace('_', '-' , app()->getLocale()) === 'ar' ||
@$_COOKIE['is_rtl'] === 'true') dir="rtl" @endif>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    
    <title>{{ trans('lang.Pub&Go_merchant_title') }}</title>

    <link rel="icon" id="favicon" type="image/x-icon"
        href="{{ str_replace('images/', 'images%2F', @$_COOKIE['favicon']) }}">

    
    <link rel='stylesheet' href='https://cdn-uicons.flaticon.com/3.0.0/uicons-solid-rounded/css/uicons-solid-rounded.css'>

    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    
    {{-- Ikony Font Awesome --}}
    <link href="{{ asset('css/icons/font-awesome/css/font-awesome.css') }}" rel="stylesheet">

   
    {{-- DataTables --}}
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.4.1/css/responsive.dataTables.min.css">

    <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
    <script src="https://cdn.jsdelivr.net/npm/moment@2.29.1/moment.min.js"></script>

    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        // Konfiguracja Tailwind CSS dla CDN
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                    },
                    fontFamily: {
                        sans: ['Poppins', 'sans-serif'],
                    }
                }
            }
        }
        
        // Ukryj ostrzeżenie o CDN w produkcji
        if (typeof tailwind !== 'undefined') {
            const originalWarn = console.warn;
            console.warn = function(message) {
                if (typeof message === 'string' && message.includes('cdn.tailwindcss.com should not be used in production')) {
                    return; // Ignoruj to ostrzeżenie
                }
                originalWarn.apply(console, arguments);
            };
        }
    </script>

    @auth
    @php
    $id = Auth::guard('admin')->user()->getvendorId();
    @endphp

    {{-- Globalne przekazanie vendorId do JS --}}
    <script type="text/javascript">
        var cuser_id = '{{ $id }}';
    </script>
    @endauth

    {{-- Font Awesome z kit --}}
    <script src="https://kit.fontawesome.com/4b4effb0ed.js" crossorigin="anonymous"></script>

    <link rel="stylesheet" href="https://cdn-uicons.flaticon.com/uicons-regular-rounded/css/uicons-regular-rounded.css">

    <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Debug jQuery errors
        window.addEventListener('error', function(e) {
            if (e.message && e.message.includes('$.decrypt')) {
                console.warn('jQuery decrypt error (ignorable):', e.message);
                return true;
            }
        });
    });
    </script>

    {{-- Dodajemy CSS i JS dla Flowbite --}}
    <link href="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.3.0/flowbite.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.3.0/flowbite.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.3.0/datepicker.min.js"></script>

    <script defer src="https://cdn.jsdelivr.net/npm/flatpickr"></script>


    {{-- Google Maps API - Wymaga klucza API z włączonym "Places API" --}}
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD3P1NrvMwgDsJfrSY9HOqiuZ3Vq4y6tV4&loading=async" defer></script>

    <style>
        [x-cloak] {
            display: none !important;
        }
    </style>

</head>

<body class="min-h-screen bg-gradient-to-br from-blue-50 to-white" x-data>
    <div id="app" class="overflow-x-hidden">
        @auth
        <header class="fixed top-0 left-0 right-0 z-30">
            @include('layouts.header')
        </header>

        <aside
            class="fixed top-[85px] left-0 w-[120px] h-[calc(100vh-85px)] z-20 bg-gradient-to-b from-slate-800 via-slate-900 to-slate-950 overflow-y-auto pt-[40px]">
            @include('layouts.menu')
        </aside>
        @endauth

        <div class="main-wrapper">
            <!-- ============================================================== -->
            <!-- Preloader - style you can find in spinners.css -->
            <!-- ============================================================== -->
            <div class="preloader"></div>
            <!-- ============================================================== -->
            <!-- Preloader - style you can find in spinners.css -->
            <!-- ============================================================== -->

            <main @auth class="ml-[120px] mt-[85px] pb-16 [&>*:last-child]:mb-0" @endauth>
                @yield('content')
            </main>

        </div>
        
        {{-- Modal: nowe zamówienie --}}
        <div id="notification_add_order" tabindex="-1" aria-hidden="true"
            class="hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-[1010] justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full">
            <div class="relative p-4 w-full max-w-md max-h-full">
                <!-- Modal content -->
                <div class="relative bg-white rounded-lg shadow flex flex-col overflow-hidden">
                    <!-- Modal header -->
                    <div class="bg-gray-50 px-6 py-4 flex items-center justify-between border-b border-gray-200">
                        <h3 class="text-lg font-bold text-slate-700 order_placed_subject"></h3>
                        <button type="button" data-modal-hide="notification_add_order"
                            class="text-slate-400 hover:text-slate-600 transition-colors focus:outline-none">
                            <span class="sr-only">{{ trans('lang.close') }}</span>
                            <i class="fa-solid fa-times text-xl"></i>
                        </button>
                    </div>
                    <!-- Modal body -->
                    <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>
                        <p class="mt-4 text-base text-gray-600 order_placed_msg"></p>
                    </div>
                    <!-- Modal footer -->
                    <div class="bg-gray-50 px-4 py-4 border-t border-gray-200">
                        <a href="{{ url('live-orders') }}" id="notification_add_order_a"
                            class="w-full h-12 flex items-center justify-center bg-blue-500 text-white text-base font-semibold rounded-md shadow-md uppercase transition-colors hover:bg-blue-600 focus:outline-none focus:ring-0 active:outline-none active:ring-0 no-underline hover:no-underline"
                            style="box-shadow: 1px 1px 2px rgba(0,0,0,0.2);">
                            {{ trans('lang.check_order') }}
                        </a>
                    </div>
                </div>
            </div>
        </div>

        
        
        {{-- Modal: QR Code dla restauracji --}}
        <div id="qr-code-modal" 
            x-data="{ open: false }" 
            x-show="open"
            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"
            @qr-modal-open.window="open = true"
            @qr-modal-close.window="open = false"
            @keydown.escape.window="open = false"
            class="fixed inset-0 z-[1010] flex items-center justify-center p-4 bg-black bg-opacity-80"
            role="dialog"
            aria-modal="true"
            style="display: none;"
            x-cloak>
            <div @click.away="open = false"
                x-transition:enter="transition ease-out duration-300"
                x-transition:enter-start="opacity-0 scale-95"
                x-transition:enter-end="opacity-100 scale-100"
                x-transition:leave="transition ease-in duration-200"
                x-transition:leave-start="opacity-100 scale-100"
                x-transition:leave-end="opacity-0 scale-95"
                class="bg-white rounded-lg text-left overflow-hidden shadow-xl w-full max-w-md flex flex-col">
                <!-- Modal header -->
                <div class="bg-gray-50 px-6 py-4 flex items-center justify-between border-b border-gray-200">
                    <h3 class="text-lg font-bold text-slate-700">{{ trans('lang.your_restaurant') }}</h3>
                    <button @click="open = false" type="button"
                        class="text-slate-400 hover:text-slate-600 transition-colors focus:outline-none">
                        <span class="sr-only">{{ trans('lang.close') }}</span>
                        <i class="fa-solid fa-times text-xl"></i>
                    </button>
                </div>
                <!-- Modal body -->
                <div class="p-6 text-center">
                    <div class="w-56 h-56 mx-auto my-4" id="qrcode-container"></div>
                    <p class="mt-2 text-sm text-gray-600">{{ trans('lang.scan_qr_to_see_restaurant') }}</p>
                </div>
                <!-- Modal footer -->
                <div class="bg-gray-50 px-4 py-4 border-t border-gray-200">
                    <button @click="open = false" type="button"
                        class="w-full h-12 flex items-center justify-center bg-blue-500 text-white text-base font-semibold rounded-md shadow-md uppercase transition-colors hover:bg-blue-600 focus:outline-none focus:ring-0 active:outline-none active:ring-0"
                        style="box-shadow: 1px 1px 2px rgba(0,0,0,0.2);">
                        {{ trans('lang.close') }}
                    </button>
                </div>
            </div>
        </div>
    </div>

    {{-- ============================================ --}}
    {{-- STRIPE DASHBOARD MODAL                       --}}
    {{-- (Moved outside aside to fix z-index issue)  --}}
    {{-- ============================================ --}}
    <div id="stripeModal" 
         x-data="{ open: false }"
         x-show="open"
         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"
         @stripe-modal-open.window="open = true"
         @stripe-modal-close.window="open = false"
         @keydown.escape.window="open = false"
         class="fixed inset-0 z-[1010] flex items-center justify-center p-4 bg-black bg-opacity-80" 
         role="dialog"
         aria-modal="true"
         style="display: none;"
         x-cloak>
        <div @click.away="open = false"
             x-transition:enter="transition ease-out duration-300"
             x-transition:enter-start="opacity-0 scale-95"
             x-transition:enter-end="opacity-100 scale-100"
             x-transition:leave="transition ease-in duration-200"
             x-transition:leave-start="opacity-100 scale-100"
             x-transition:leave-end="opacity-0 scale-95"
             class="bg-white rounded-lg text-left overflow-hidden shadow-xl w-full max-w-md flex flex-col">
            
            {{-- Nagłówek modala --}}
            <div class="bg-gray-50 px-6 py-4 flex items-center justify-between border-b border-gray-200">
                <h3 class="text-lg font-bold text-slate-700">
                    Stripe Dashboard
                </h3>
                <button @click="open = false" type="button"
                    class="text-slate-400 hover:text-slate-600 transition-colors focus:outline-none">
                    <span class="sr-only">{{ trans('lang.close') }}</span>
                    <i class="fa-solid fa-times text-xl"></i>
                </button>
            </div>

            {{-- Treść modala --}}
            <div class="p-6">
                <p class="text-slate-600 mb-4 text-sm">
                    {{ trans('lang.stripe_modal_description') }}
                </p>
                
                {{-- Funkcje w kafelkach (styl connection details) --}}
                <div class="grid grid-cols-1 gap-3 mb-4">
                    <div class="bg-blue-50/50 border !border-slate-300 p-3 rounded-lg 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-500 flex-shrink-0"><rect width="20" height="14" x="2" y="5" rx="2"/><line x1="2" x2="22" y1="10" y2="10"/></svg>
                        <span class="text-slate-700 text-sm">{{ trans('lang.stripe_feature_transactions') }}</span>
                    </div>
                    <div class="bg-blue-50/50 border !border-slate-300 p-3 rounded-lg 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-500 flex-shrink-0"><path d="M12 18H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5"/><path d="m16 19 3 3 3-3"/><path d="M18 12h.01"/><path d="M19 16v6"/><path d="M6 12h.01"/><circle cx="12" cy="12" r="2"/></svg>
                        <span class="text-slate-700 text-sm">{{ trans('lang.stripe_feature_payouts') }}</span>
                    </div>
                    <div class="bg-blue-50/50 border !border-slate-300 p-3 rounded-lg 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-500 flex-shrink-0"><path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"/><path d="M14 2v5a1 1 0 0 0 1 1h5"/><path d="m9 15 2 2 4-4"/></svg>
                        <span class="text-slate-700 text-sm">{{ trans('lang.stripe_feature_reports') }}</span>
                    </div>
                </div>
                
                {{-- Info notice --}}
                <div class="text-xs text-slate-400 text-center">
                    {{ trans('lang.stripe_modal_new_window_info') }}
                </div>
                
                {{-- Error message --}}
                <p id="stripeErrorMsg" class="text-sm mt-3 hidden"></p>
            </div>

            {{-- Stopka modala --}}
            <div class="bg-gray-50 px-4 py-4 border-t border-gray-200">
                <button id="stripeOpenBtn" onclick="openStripeDashboard()" type="button"
                    class="w-full h-12 flex items-center justify-center gap-2 bg-blue-500 text-white text-base font-semibold rounded-md shadow-md uppercase transition-colors hover:bg-blue-600 focus:outline-none focus:ring-0 disabled:opacity-50 disabled:cursor-not-allowed">
                    <span id="stripeBtnText">{{ trans('lang.stripe_open_dashboard') }}</span>
                    <svg id="stripeBtnSpinner" class="hidden animate-spin h-4 w-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6"/><path d="m21 3-9 9"/><path d="M15 3h6v6"/></svg>
                </button>
            </div>
        </div>
    </div>

    {{-- ============================================ --}}
    {{-- BUSINESS TYPE SELECTION MODAL               --}}
    {{-- (For Stripe Connect onboarding)             --}}
    {{-- ============================================ --}}
    <div id="businessTypeModal" 
         x-data="{ open: false, selectedType: null }"
         x-show="open"
         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"
         @business-type-modal-open.window="open = true"
         @business-type-modal-close.window="open = false; selectedType = null"
         @keydown.escape.window="open = false; selectedType = null"
         class="fixed inset-0 z-[1020] flex items-center justify-center p-4 bg-black bg-opacity-80" 
         role="dialog"
         aria-modal="true"
         style="display: none;"
         x-cloak>
        <div @click.away="open = false; selectedType = null"
             x-transition:enter="transition ease-out duration-300"
             x-transition:enter-start="opacity-0 scale-95"
             x-transition:enter-end="opacity-100 scale-100"
             x-transition:leave="transition ease-in duration-200"
             x-transition:leave-start="opacity-100 scale-100"
             x-transition:leave-end="opacity-0 scale-95"
             class="bg-white rounded-lg text-left overflow-hidden shadow-xl w-full max-w-md flex flex-col">
            
            {{-- Nagłówek modala --}}
            <div class="bg-gray-50 px-6 py-4 flex items-center justify-between border-b border-gray-200">
                <h3 class="text-lg font-bold text-slate-700">
                    {{ trans('lang.business_type_modal_title') }}
                </h3>
                <button @click="open = false; selectedType = null" type="button"
                    class="text-slate-400 hover:text-slate-600 transition-colors focus:outline-none">
                    <span class="sr-only">{{ trans('lang.close') }}</span>
                    <i class="fa-solid fa-times text-xl"></i>
                </button>
            </div>

            {{-- Treść modala --}}
            <div class="p-6">
                <p class="text-slate-600 mb-4 text-sm">
                    {{ trans('lang.business_type_modal_description') }}
                </p>
                
                {{-- Opcje wyboru typu działalności (styl kafelków) --}}
                <div class="grid grid-cols-1 gap-3 mb-4">
                    {{-- Opcja 1: Osoba fizyczna / Individual --}}
                    <label for="business-type-individual"
                           class="cursor-pointer transition-all select-none rounded-lg"
                           :class="selectedType === 'individual' ? 'bg-blue-50 border !border-blue-500' : 'bg-blue-50/50 border !border-slate-300 hover:border-slate-400'">
                        <div class="p-3 flex items-start gap-3">
                            {{-- Custom radio button --}}
                            <input type="radio" 
                                   id="business-type-individual"
                                   name="business_type" 
                                   value="individual"
                                   x-model="selectedType"
                                   class="hidden">
                            <div class="w-5 h-5 border rounded-full flex items-center justify-center transition-colors flex-shrink-0 mt-0.5"
                                 :class="{ 'border-blue-500': selectedType === 'individual', '!border-slate-400': selectedType !== 'individual' }">
                                <div class="w-3 h-3 bg-blue-500 rounded-full transition-transform"
                                     :class="{ 'scale-100': selectedType === 'individual', 'scale-0': selectedType !== 'individual' }">
                                </div>
                            </div>
                            {{-- Tekst opcji --}}
                            <div class="flex-1">
                                <div class="font-semibold text-slate-700 text-sm mb-0.5">
                                    {{ trans('lang.business_type_individual') }}
                                </div>
                                <div class="text-xs text-slate-600">
                                    {{ trans('lang.business_type_individual_desc') }}
                                </div>
                            </div>
                        </div>
                    </label>
                    
                    {{-- Opcja 2: Firma / Company --}}
                    <label for="business-type-company"
                           class="cursor-pointer transition-all select-none rounded-lg"
                           :class="selectedType === 'company' ? 'bg-blue-50 border !border-blue-500' : 'bg-blue-50/50 border !border-slate-300 hover:border-slate-400'">
                        <div class="p-3 flex items-start gap-3">
                            {{-- Custom radio button --}}
                            <input type="radio" 
                                   id="business-type-company"
                                   name="business_type" 
                                   value="company"
                                   x-model="selectedType"
                                   class="hidden">
                            <div class="w-5 h-5 border rounded-full flex items-center justify-center transition-colors flex-shrink-0 mt-0.5"
                                 :class="{ 'border-blue-500': selectedType === 'company', '!border-slate-400': selectedType !== 'company' }">
                                <div class="w-3 h-3 bg-blue-500 rounded-full transition-transform"
                                     :class="{ 'scale-100': selectedType === 'company', 'scale-0': selectedType !== 'company' }">
                                </div>
                            </div>
                            {{-- Tekst opcji --}}
                            <div class="flex-1">
                                <div class="font-semibold text-slate-700 text-sm mb-0.5">
                                    {{ trans('lang.business_type_company') }}
                                </div>
                                <div class="text-xs text-slate-600">
                                    {{ trans('lang.business_type_company_desc') }}
                                </div>
                            </div>
                        </div>
                    </label>
                </div>
                
                {{-- Info notice --}}
                <div class="text-xs text-slate-400 text-center">
                    {{ trans('lang.stripe_modal_new_window_info') }}
                </div>
            </div>

            {{-- Stopka modala - przyciski jeden pod drugim --}}
            <div class="bg-gray-50 px-4 py-4 border-t border-gray-200 flex flex-col gap-3">
                {{-- Główny przycisk Continue --}}
                <button @click="proceedToStripeOnboarding()"
                        :disabled="!selectedType"
                        type="button"
                        class="w-full h-12 flex items-center justify-center gap-2 bg-blue-600 text-white text-base font-semibold rounded-md shadow-md uppercase transition-colors hover:bg-blue-700 focus:outline-none focus:ring-0 disabled:opacity-50 disabled:cursor-not-allowed"
                        :class="{'opacity-50 cursor-not-allowed': !selectedType}"
                        style="box-shadow: 1px 1px 2px rgba(0,0,0,0.2);">
                    <span id="businessTypeBtnText">{{ trans('lang.continue') }}</span>
                    <svg id="businessTypeBtnSpinner" class="hidden animate-spin h-4 w-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <i class="fas fa-arrow-right" id="businessTypeBtnArrow"></i>
                </button>
                
                {{-- Przycisk Cancel --}}
                <button @click="open = false; selectedType = null" type="button"
                        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 focus:outline-none focus:ring-0">
                    {{ trans('lang.cancel') }}
                </button>
            </div>
        </div>
    </div>

    {{-- Overlay dla ekranu ostrzegawczego --}}
    <div id="overlay" class="fixed inset-0 z-[9999] flex-col items-center justify-center bg-blue-500 p-8 text-center text-white" style="display: none;">
        <div class="mb-6">
            <img src="{{ asset('assets/images/logo-PnG-vertical.svg') }}" alt="Logo" class="mx-auto h-40 w-auto">
        </div>
        <h2 class="mb-3 text-3xl font-bold">{!! trans('lang.warning_screen_title') !!}</h2>
        <p class="max-w-2xl text-lg text-slate-300">{!! trans('lang.warning_screen_desc') !!}</p>
    </div>

    <script src="{{ asset('assets/plugins/jquery/jquery.min.js') }}"></script>
    
    
    <script src="{{ asset('js/waves.js') }}"></script>
    <script src="{{ asset('assets/plugins/sticky-kit-master/dist/sticky-kit.min.js') }}"></script>
    <script src="{{ asset('assets/plugins/sparkline/jquery.sparkline.min.js') }}"></script>
    <script src="{{ asset('js/jquery.resizeImg.js') }}"></script>

    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.4.1/js/dataTables.responsive.min.js"></script>

    
    

    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.30.1/moment.min.js"></script>
    <script src="https://cdn.datatables.net/plug-ins/2.0.8/sorting/datetime-moment.js"></script>
    <script src="https://cdn.datatables.net/plug-ins/1.10.11/sorting/date-eu.js"></script>
    <script src="https://cdn.datatables.net/plug-ins/2.0.8/sorting/date-euro.js"></script>

    <script src="{{ asset('js/crypto-js.js') }}"></script>
    <script src="{{ asset('js/jquery.cookie.js') }}"></script>
    <script src="{{ asset('js/jquery.validate.js') }}"></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/compressorjs/1.2.1/compressor.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/davidshimjs-qrcodejs@0/qrcode.min.js"></script>

    @yield('scripts')
    <script type="text/javascript">
        var route1 = '{{ route("orders.edit", ":id") }}';
        var booktable = '{{ route("booktable.edit", ":id") }}';
        var pageloadded = 0;
        var vendorId = cuser_id; // set from PHP (VendorUsers.uuid)
        var scheduleOrderPlacedMsg = '';

        let newOrderCount = 0;
        let isInitialLoad = true;
        let attachNotification = false;
        let latestOrderTimestamp = getLatestOrderTimestamp();
        // console.log('🔄 Initial latestOrderTimestamp:', latestOrderTimestamp);
        
        const isLivePage = window.location.pathname.includes('live-orders');
        const isStatusScreen = window.location.pathname.includes('status-screen');

        let newOrderModalInstance = null;
        let qrCodeGenerator = null;

        document.addEventListener('DOMContentLoaded', function () {

            const newOrderModalEl = document.getElementById('notification_add_order');
            if (newOrderModalEl) {
                const modalOptions = {
                    placement: 'center',
                    backdrop: 'dynamic',
                    backdropClasses: 'bg-black/80 fixed inset-0 z-[1000]',
                    closable: true,
                    onHide: () => {
                        console.log('Modal hidden');
                    },
                    onShow: () => {
                        console.log('Modal shown');
                    }
                };
                newOrderModalInstance = new Modal(newOrderModalEl, modalOptions);
                console.log('New order modal initialized:', newOrderModalInstance);
                
                // Test czy modal element jest dostępny
                console.log('Modal element:', newOrderModalEl);
                console.log('Modal element classes:', newOrderModalEl.className);
            } else {
                console.error('New order modal element not found');
            }

            // QR modal is now handled by Alpine.js, no Flowbite initialization needed

            const qrContainer = document.getElementById('qrcode-container');
            if (qrContainer) {
                // Inicjalizacja generatora QR kodu
                qrCodeGenerator = new QRCode(qrContainer, { text: "", width: 224, height: 224, colorDark: "#000000", colorLight: "#ffffff", correctLevel: QRCode.CorrectLevel.H });
            }
        });

        $(document).ready(function () {
            handleScreenResize();
            changeHeaderTitle();
            findVendorAndSetupListener();
            loadDynamicNotifications();
            
            // Obsługa zmiany URL dla dynamicznego tytułu
            let currentPath = window.location.pathname;
            const observer = new MutationObserver(() => {
                if (currentPath !== window.location.pathname) {
                    currentPath = window.location.pathname;
                    setTimeout(changeHeaderTitle, 100); // Małe opóźnienie dla pewności
                }
            });
            observer.observe(document.body, { childList: true, subtree: true });
            
            // Obsługa przycisków wstecz/dalej w przeglądarce
            window.addEventListener('popstate', () => {
                setTimeout(changeHeaderTitle, 100);
            });
        });

        // Funkcja testowa do sprawdzenia czy modal działa
        function testModal() {
            console.log('Testing modal...');
            if (newOrderModalInstance) {
                console.log('Modal instance exists, showing...');
                newOrderModalInstance.show();
            } else {
                console.error('Modal instance not found, trying manual show');
                showModalManually();
            }
        }

        // Alternatywna metoda wyświetlania modala bez Flowbite
        function showModalManually() {
            const modalEl = document.getElementById('notification_add_order');
            if (modalEl) {
                console.log('Showing modal manually');
                modalEl.classList.remove('hidden');
                modalEl.style.display = 'flex';
                modalEl.setAttribute('aria-hidden', 'false');
                
                // Dodaj backdrop
                const backdrop = document.createElement('div');
                backdrop.className = 'fixed inset-0 bg-black bg-opacity-80 z-[1000]';
                backdrop.id = 'modal-backdrop';
                document.body.appendChild(backdrop);
                
                // Zamknij modal po kliknięciu backdrop
                backdrop.addEventListener('click', hideModalManually);
            }
        }

        function hideModalManually() {
            const modalEl = document.getElementById('notification_add_order');
            const backdrop = document.getElementById('modal-backdrop');
            
            if (modalEl) {
                modalEl.classList.add('hidden');
                modalEl.style.display = 'none';
                modalEl.setAttribute('aria-hidden', 'true');
            }
            
            if (backdrop) {
                backdrop.remove();
            }
        }

        // Funkcja do symulacji nowego zamówienia
        function simulateNewOrder() {
            console.log('Simulating new order...');
            const fakeOrder = {
                id: 'test_' + Date.now(),
                status: 'Order Placed',
                createdAt: new Date()
            };
            updateModal(fakeOrder);
        }

        // Dodaj funkcje testowe do window
        window.testModal = testModal;
        window.showModalManually = showModalManually;
        window.hideModalManually = hideModalManually;
        window.simulateNewOrder = simulateNewOrder;

        function handleScreenResize() {
            const MIN_WIDTH = 999;
            const overlay = document.getElementById('overlay');
            const appContainer = document.getElementById('app');
            let resizeTimeout;

            function checkViewportWidth() {
                const isTooSmall = window.innerWidth < MIN_WIDTH;
                overlay.style.display = isTooSmall ? 'flex' : 'none';
                appContainer.style.display = isTooSmall ? 'none' : '';
            }

            const debouncedCheck = () => {
                clearTimeout(resizeTimeout);
                resizeTimeout = setTimeout(checkViewportWidth, 150);
            };

            checkViewportWidth();
            window.addEventListener('resize', debouncedCheck);
        }

        function findVendorAndSetupListener() {
            // vendorId is already set from PHP (cuser_id = VendorUsers.uuid).
            // No Firebase user lookup needed — name/avatar come from Laravel's Alpine store.
            setupVendorListener();
        }
        
        function setupVendorListener() {
            // Load initial restaurant online/offline status from the API
            fetch('{{ route("api.vendor.status") }}', { headers: { 'Accept': 'application/json' } })
                .then(r => r.json())
                .then(data => setOnlineSwitch(data.active))
                .catch(err => console.warn('Could not load vendor status:', err));

            setupOrderListener();
        }
        
        function setOnlineSwitch(reststatus) {
            Alpine.store('restaurant').isOnline = reststatus;
            Alpine.store('restaurant').statusText = reststatus ? 'Online' : 'Offline';

            // Save to localStorage for persistence across page switches
            localStorage.setItem('restaurantStatus', JSON.stringify(reststatus));
        }

        function setupOrderListener() {
            // console.log('Setting up order listener for vendorID:', vendorID);
            // console.log('Current page - isLivePage:', isLivePage, 'isStatusScreen:', isStatusScreen);
            // console.log('🕒 Current stored timestamp at listener setup:', latestOrderTimestamp);
            
            // Track the last order ID set seen to detect new additions
            let knownOrderIds = new Set();

            const pollOrders = () => {
                if (isStatusScreen) return;

                fetch('{{ route("orders.api") }}', { headers: { 'Accept': 'application/json' } })
                    .then(r => r.json())
                    .then(function(orders) {
                        if (!Array.isArray(orders)) return;
                        let newLatestOrderTimestamp = latestOrderTimestamp;

                        orders.forEach(function(val) {
                            const orderTimestamp = val.createdAt ? new Date(val.createdAt) : null;
                            // Use order id as string key
                            const orderId = String(val.id);
                        
                        // console.log('Processing order change:', {
                        //     changeType: change.type,
                        //     orderId: val.id,
                        //     status: val.status,
                        //     isInitialLoad: isInitialLoad,
                        //     orderTimestamp: orderTimestamp,
                        //     latestOrderTimestamp: latestOrderTimestamp
                        // });
                        
                        if (isInitialLoad) {
                            // console.log('Initial load - skipping modal, just updating timestamp');
                            if (orderTimestamp && (!newLatestOrderTimestamp || orderTimestamp > newLatestOrderTimestamp)) {
                                newLatestOrderTimestamp = orderTimestamp;
                            }
                        } else {
                            // console.log('Not initial load - checking conditions for modal');
                            
                            // FIXED: Sprawdź czy to jest rzeczywiście NOWE zamówienie
                            const isNewOrder = change.type === 'added' || change.type === 'modified';
                            // DEBUG: Sprawdź wszystkie statusy zamówień - USUNIĘTE
                            // console.log('🔍 Order status debug:', val.status, 'Order ID:', val.id);
                            
                            // Modal tylko po udanej płatności - nie dla pending_payment
                            const isOrderPlaced = val.status === "Order Placed" || 
                                                 val.status === "Order Completed" ||
                                                 val.status === "paid" || 
                                                 val.status === "confirmed" ||
                                                 val.status === "completed";
                            
                            // KLUCZOWE: Sprawdź czy zamówienie jest nowsze niż ostatni visit
                            // ZMIANA: Bardziej liberalna logika - pokazuj modal dla nowych zamówień z ostatnich 24h
                            const now = new Date();
                            const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
                            // FIX: Używaj oryginalnego latestOrderTimestamp, nie zaktualizowanego newLatestOrderTimestamp
                            const isRecentOrder = orderTimestamp && orderTimestamp > oneDayAgo && 
                                                (!latestOrderTimestamp || orderTimestamp > latestOrderTimestamp);
                            
                            // console.log('Change type:', change.type, 'Status:', val.status);
                            // console.log('Order timestamp:', orderTimestamp);
                            // console.log('Latest stored timestamp:', latestOrderTimestamp);
                            // console.log('Is recent order:', isRecentOrder);
                            // console.log('Is new order:', isNewOrder, 'Is order placed:', isOrderPlaced);
                            
                            // DEBUG: Tymczasowe logi dla diagnozy problemu z modalem - USUNIĘTE
                            // console.log('🔍 Modal Debug - isNewOrder:', isNewOrder, 'isOrderPlaced:', isOrderPlaced, 'isRecentOrder:', isRecentOrder);
                            // console.log('🔍 Modal Debug - orderTimestamp:', orderTimestamp, 'latestOrderTimestamp:', latestOrderTimestamp);
                            // console.log('🔍 Modal Debug - orderTimestamp type:', typeof orderTimestamp, 'valid:', orderTimestamp instanceof Date);
                            // console.log('🔍 Modal Debug - now:', now, 'oneDayAgo:', oneDayAgo);
                            // if (orderTimestamp) {
                            //     console.log('🔍 Modal Debug - order is newer than 24h:', orderTimestamp > oneDayAgo);
                            //     console.log('🔍 Modal Debug - order is newer than stored:', !latestOrderTimestamp || orderTimestamp > latestOrderTimestamp);
                            // }
                            
                            // DEBUG: Warunki modala - USUNIĘTE
                            // console.log('🔍 Modal conditions:', {
                            //     isNewOrder: isNewOrder,
                            //     isOrderPlaced: isOrderPlaced,
                            //     isRecentOrder: isRecentOrder,
                            //     status: val.status,
                            //     changeType: change.type
                            // });
                            
                            // Modal pokazuj TYLKO dla zamówień z udaną płatnością
                            if (isNewOrder && isOrderPlaced && isRecentOrder) {
                                // console.log('✅ TRULY NEW "Order Placed" detected:', val.id, 'isLivePage:', isLivePage);
                                if (!isLivePage) {
                                    // console.log('Showing modal for truly new order');
                                    updateModal(val);
                                } else {
                                    // console.log('On live page - letting live.blade.php handle the order');
                                }
                            } else {
                                // console.log('❌ Not showing modal - isNewOrder:', isNewOrder, 'isOrderPlaced:', isOrderPlaced, 'isRecentOrder:', isRecentOrder);
                            }
                            
                            // Aktualizuj timestamp TYLKO dla zamówień z udaną płatnością
                            // Nie dla pending_payment - żeby modal mógł się pokazać przy Order Placed
                            if (isOrderPlaced && orderTimestamp && orderTimestamp > newLatestOrderTimestamp) {
                                newLatestOrderTimestamp = orderTimestamp;
                                // console.log('📅 Updated latest timestamp to:', orderTimestamp, '(status:', val.status + ')');
                            }
                        }
                    });
                    if (isInitialLoad) {
                        isInitialLoad = false;
                        
                        // FIXED: Przy pierwszym załadowaniu ustaw timestamp na aktualny czas
                        // aby nie pokazywać modali dla starych zamówień
                        if (!latestOrderTimestamp) {
                            latestOrderTimestamp = new Date();
                            console.log('🕒 Setting initial timestamp to current time:', latestOrderTimestamp);
                            saveLatestOrderTimestamp(latestOrderTimestamp);
                        }
                    }
                    
                    // Aktualizuj timestamp tylko jeśli mamy nowsze zamówienia
                    if (newLatestOrderTimestamp > latestOrderTimestamp) {
                        latestOrderTimestamp = newLatestOrderTimestamp;
                        saveLatestOrderTimestamp(latestOrderTimestamp);
                        console.log('📅 Updated latest timestamp to:', latestOrderTimestamp);
                    }
                },
                    function (error) {
                        console.error('Error listening to restaurant orders:', error);
                    }
                );
        }
        
        function updateModal(val) {
            newOrderCount++;
            console.log('updateModal called - newOrderCount:', newOrderCount);
            
            document.querySelector('#notification_add_order .order_placed_subject').textContent = '{{ trans('lang.new_order_placed') }}';
            document.querySelector('#notification_add_order .order_placed_msg').textContent = '{{ trans('lang.you_have') }} ' + newOrderCount + ' {{ trans('lang.new_orders') }}.';

            const link = document.getElementById('notification_add_order_a');
            link.setAttribute("href", "{{ url('live-orders') }}");
            
            console.log('Attempting to show modal, newOrderModalInstance:', newOrderModalInstance);
            if (newOrderModalInstance) {
                try {
                    newOrderModalInstance.show();
                    console.log('Flowbite modal show() called successfully');
                } catch (error) {
                    console.error('Error showing Flowbite modal:', error);
                    console.log('Falling back to manual modal display');
                    showModalManually();
                }
            } else {
                console.error('newOrderModalInstance is null - using manual modal display');
                showModalManually();
            }
        }

        function getLatestOrderTimestamp() {
            const timestampStr = localStorage.getItem('latestOrderTimestamp');
            // RESET: Jeśli timestamp jest z przyszłości lub null, użyj bezpiecznej daty z przeszłości
            const timestamp = timestampStr ? new Date(timestampStr) : new Date('2024-01-01');
            const now = new Date();
            
            // Jeśli timestamp jest z przyszłości, zresetuj do wczoraj
            if (timestamp > now) {
                console.log('🔄 RESET: Timestamp z przyszłości detected, resetting to yesterday');
                const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
                localStorage.setItem('latestOrderTimestamp', yesterday.toISOString());
                return yesterday;
            }
            
            return timestamp;
        }
        function saveLatestOrderTimestamp(timestamp) {
            if (timestamp) {
                // Sprawdź czy timestamp jest obiektem Date, jeśli nie - konwertuj
                const dateObj = timestamp instanceof Date ? timestamp : new Date(timestamp);
                if (!isNaN(dateObj.getTime())) {
                    localStorage.setItem('latestOrderTimestamp', dateObj.toISOString());
                }
            }
        }

        function loadDynamicNotifications() { /* notifications migrated to lang files */ }

        function setCookie(name, value, days) {
            var expires = "";
            if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toUTCString(); }
            document.cookie = name + "=" + (value || "") + expires + "; path=/";
        }
        function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i].trim(); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; }
        
        document.addEventListener('alpine:init', () => {
            @php
                $displayName = Auth::guard('admin')->user()->name ?? '...';
                $avatarUrl = asset('images/icons/account_icon.svg'); // domyślny avatar
                $merchantEmployee = \App\Models\MerchantEmployee::where('user_id', Auth::id())->first();
                if ($merchantEmployee) {
                    $displayName = trim($merchantEmployee->name . ' ' . $merchantEmployee->surname);
                    // Jeśli pracownik ma zdjęcie profilowe, użyj go
                    if ($merchantEmployee->profile_picture) {
                        $avatarUrl = $merchantEmployee->profile_picture;
                    }
                }
            @endphp
            Alpine.store('user', {
                name: '{{ $displayName }}',
                avatar: '{{ $avatarUrl }}'
            });
            
            console.log('Initial Alpine user name set to:', '{{ $displayName }}');

            // Load restaurant status from localStorage, default to offline if not set
            const savedRestaurantStatus = localStorage.getItem('restaurantStatus');
            const initialIsOnline = savedRestaurantStatus ? JSON.parse(savedRestaurantStatus) : false;

            Alpine.store('restaurant', {
                isOnline: initialIsOnline,
                statusText: initialIsOnline ? 'Online' : 'Offline'
            });

            Alpine.store('header', {
                title: ''
            });

            Alpine.store('app', {
                showStatusModal: false,
                statusModalTitle: '',
                statusModalText: '',
                checkboxElement: null,

                openStatusModal(el) {
                    this.checkboxElement = el;
                    const isCurrentlyChecked = el.checked;

                    if (!isCurrentlyChecked) {
                        this.statusModalTitle = "{!! trans('lang.modal_status_offline_title') !!}";
                        this.statusModalText = "{!! trans('lang.modal_status_offline_desc') !!}";
                    } else {
                        this.statusModalTitle = "{!! trans('lang.modal_status_online_title') !!}";
                        this.statusModalText = "{!! trans('lang.modal_status_online_desc') !!}";
                    }
                    this.showStatusModal = true;
                },

                confirmStatusChange() {
                    if (this.checkboxElement) {
                        // 1. Zmień stan w magazynie Alpine
                        const newStatus = !Alpine.store('restaurant').isOnline;
                        Alpine.store('restaurant').isOnline = newStatus;

                        // Save to localStorage for persistence across page switches
                        localStorage.setItem('restaurantStatus', JSON.stringify(newStatus));

                        // 2. Wywołaj funkcję aktualizującą Firebase
                        switchRestStatus();
                    }
                    this.hideModal();
                },

                hideModal() {
                    this.showStatusModal = false;
                    this.checkboxElement = null;
                }
            });
        });

        function switchRestStatus() {
            const isOnline = Alpine.store('restaurant').isOnline;
            fetch('{{ route("api.vendor.setStatus") }}', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                },
                body: JSON.stringify({ active: isOnline }),
            })
            .then(r => r.json())
            .then(data => {
                Alpine.store('restaurant').statusText = data.active ? 'Online' : 'Offline';
                localStorage.setItem('restaurantStatus', JSON.stringify(data.active));
            })
            .catch(err => console.error('Failed to update restaurant status:', err));
        }

        // =========================================================================
        // ZMIANA: Zaktualizowana funkcja do dynamicznej zmiany tytułu w nagłówku
        // =========================================================================
        function changeHeaderTitle() {
            const currentUrl = window.location.href;
            const currentPath = window.location.pathname;
            
            // Mapowanie ścieżek do tytułów (używamy pathname zamiast pełnego URL)
            const pathMappings = {
                '/users/restaurant': "{!! trans('lang.restaurant_settings') !!}", 
                '/orders/create': "{!! trans('lang.create_order') !!}",
                '/orders': "{!! trans('lang.orders') !!}",
                '/dashboard': "{!! trans('lang.home') !!}",
                '/foods/create': "{!! trans('lang.create_menu_item') !!}",
                '/foods': "{!! trans('lang.menu_management_title') !!}", 
                '/category/create': "{!! trans('lang.create_category') !!}",
                '/category': "{!! trans('lang.categories_management_title') !!}",
                '/users/profile': "{!! trans('lang.account') !!}",
                '/users/manage_profile': "{!! trans('lang.manage_profile') !!}",
                '/users/manage_users': "{!! trans('lang.user_management') !!}",
                '/users/payment_details': "{!! trans('lang.export_center_title') !!}",
                '/live-orders': "{!! trans('lang.live_orders') !!}",
            };
            
            // Sprawdzamy dokładne dopasowania najpierw
            if (pathMappings[currentPath]) {
                Alpine.store('header').title = pathMappings[currentPath];
                console.log('Header title set to:', pathMappings[currentPath]);
                return;
            }
            
            // Sprawdzamy częściowe dopasowania dla stron z ID (np. /orders/edit/123)
            if (currentPath.startsWith('/orders/edit/')) {
                Alpine.store('header').title = "{!! trans('lang.order_edit') !!}";
                console.log('Header title set to: Order Edit');
                return;
            }
            
            if (currentPath.startsWith('/foods/edit/')) {
                Alpine.store('header').title = "{!! trans('lang.edit_menu_item') !!}";
                console.log('Header title set to: Edit Menu Item');
                return;
            }
            
            if (currentPath.startsWith('/category/edit/')) {
                Alpine.store('header').title = "{!! trans('lang.edit_category_title') !!}";
                console.log('Header title set to: Edit Category');
                return;
            }
            
            // Jeśli nie znaleziono dopasowania, wyczyść tytuł
            Alpine.store('header').title = '';
            console.log('No header title mapping found for path:', currentPath);
        }

        // Redirect to restaurant — get coordinates from the Laravel API
        function handleRedirectToRestaurant() {
            fetch('/api/vendor', { headers: { 'Accept': 'application/json' } })
                .then(r => r.json())
                .then(function(data) {
                    const vendor = data.vendor;
                    if (vendor && vendor.latitude && vendor.longitude) {
                        redirectToRestaurant(vendor.latitude, vendor.longitude);
                    } else {
                        console.error('handleRedirectToRestaurant: lat/lng not found in vendor data.');
                    }
                })
                .catch(err => console.error('handleRedirectToRestaurant error:', err));
        }

        // ZMIANA: Funkcja do pokazywania modala z kodem QR
        function showRestaurantQrCode() {
            if (!vendorId) {
                console.error("showRestaurantQrCode: Błąd - ID restauracji (vendorId) jest niedostępne.");
                return;
            }
            const url = `https://www.pubandgo.de/restaurant?id=${vendorId}`;

            if (qrCodeGenerator) {
                qrCodeGenerator.clear();
                qrCodeGenerator.makeCode(url + '&counterPickup=true');
            } else {
                console.error("showRestaurantQrCode: Generator QR kodu nie został zainicjowany.");
                return;
            }
            // Use Alpine.js event instead of Flowbite modal
            window.dispatchEvent(new CustomEvent('qr-modal-open'));
        }

        // ZMIANA: Poprawiona funkcja pobierania miasta na podstawie koordynatów
        function getCityFromLatLng(lat, lng, callback) {
            const url = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&zoom=10&addressdetails=1`;
            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    const response = JSON.parse(xhr.responseText);
                    const city = response.address ? (response.address.city || response.address.town || response.address.village) : null;
                    callback(city);
                } else if (xhr.readyState === 4) {
                    console.error(`Błąd zapytania do Nominatim API, status: ${xhr.status}`);
                    callback(null);
                }
            };
            xhr.open("GET", url, true);
            xhr.send();
        }

        // ZMIANA: Poprawiona funkcja otwierająca stronę restauracji
        function redirectToRestaurant(lat, lng) {
            getCityFromLatLng(lat, lng, function (city) {
                if (city) {
                    setCookie('address_name', city, 7); setCookie('address_lat', lat, 7); setCookie('address_lng', lng, 7); setCookie('address_city', city, 7);
                } else {
                    console.error("Nie udało się ustalić miasta. Przekierowanie nastąpi bez ustawienia ciasteczek lokalizacji.");
                }
                // Otwieramy stronę w nowej karcie
                window.open(`https://www.pubandgo.de/restaurant?id=${vendorId}`, '_blank');
            });
        }

        function handleRedirectToStatusPage() {
            window.location.href = "{{ route('statusScreen') }}";
        }

        // version / globalSettings fetches removed (migrated away from Firebase)
    </script>

{{-- Modal potwierdzenia zmiany statusu --}}
<div x-show="$store.app.showStatusModal" 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"
    class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-80" style="display: none;"
    x-cloak>
    <div @click.away="$store.app.hideModal()" x-transition:enter="transition ease-out duration-300"
        x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100"
        x-transition:leave="transition ease-in duration-200" x-transition:leave-start="opacity-100 scale-100"
        x-transition:leave-end="opacity-0 scale-95"
        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-store text-3xl text-blue-600"></i>
            </div>
            <h4 class="text-xl font-semibold text-gray-900 mt-4" x-html="$store.app.statusModalTitle"></h4>
            <p class="mt-2 text-sm text-gray-600" x-html="$store.app.statusModalText"></p>
        </div>

        <div class="bg-gray-50 px-4 py-4 border-t border-gray-200 flex flex-col gap-3">
            <button @click="$store.app.confirmStatusChange()" type="button"
                class="w-full h-12 flex items-center justify-center bg-blue-600 text-white text-base font-semibold rounded-md shadow-md uppercase transition-colors hover:bg-blue-700 focus:outline-none focus:ring-0 active:outline-none active:ring-0"
                style="box-shadow: 1px 1px 2px rgba(0,0,0,0.2);">{!! trans('lang.confirm') !!}</button>
            <button @click="$store.app.hideModal()" type="button"
                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 focus:outline-none focus:ring-0 active:outline-none active:ring-0">{!! trans('lang.cancel') !!}</button>
        </div>
    </div>
</div>

    <x-ai_assistant />

</body>

</html>