<!-- resources/views/auth/login-tailwind.blade.php -->

<!doctype html>
<html lang="de" class="h-full bg-gradient-to-tr from-slate-950 via-slate-900 to-slate-800">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title id="app_name"><?php echo @$_COOKIE['meta_title']; ?></title>

    <!-- Ikony fontawesome -->
    <script src="https://kit.fontawesome.com/4b4effb0ed.js" crossorigin="anonymous"></script>

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

    <!-- Unicons CSS -->
    <link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.8/css/line.css" />

    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        // Konfiguracja Tailwind CSS dla CDN
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                    },
                    fontFamily: {
                        sans: [
                            'system-ui',
                            '-apple-system',
                            'BlinkMacSystemFont', 
                            'Segoe UI',
                            'Roboto',
                            'Oxygen',
                            'Ubuntu',
                            'Cantarell',
                            '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>

    <!-- Alpine.js -->
    <script defer src="https://unpkg.com/alpinejs@3.13.10/dist/cdn.min.js"></script>

    <style>
        /* Nadpisanie autofill w WebKit (Chrome, Safari) */
        input:-webkit-autofill,
        input:-webkit-autofill:hover,
        input:-webkit-autofill:focus,
        textarea:-webkit-autofill,
        textarea:-webkit-autofill:hover,
        textarea:-webkit-autofill:focus {
            box-shadow: 0 0 0px 1000px #ffffff inset !important;
        }

        [x-cloak] {
            display: none !important;
        }

        /* Niestandardowe style dla inputów */
        .input-focus:focus {
            border-color: #3B82F6 !important;
            border-width: 2px !important;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1) !important;
            background-color: white !important;
        }
        
        /* Style dla selecta w support modal */
        .custom-select {
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
            background-position: right 0.5rem center;
            background-repeat: no-repeat;
            background-size: 1.5em 1.5em;
            padding-right: 2.5rem;
        }
        
        .custom-select:focus {
            background-color: #eff6ff !important;
            border-color: #cbd5e1 !important;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1) !important;
        }
        
        /* Style dla opcji dropdown */
        .custom-select option {
            background-color: white;
            color: #374151;
            padding: 8px 12px;
            font-size: 14px;
            border: none;
        }
        
        .custom-select option:hover {
            background-color: #dbeafe;
            color: #1f2937;
        }
        
        .custom-select option:checked {
            background-color: #3b82f6;
            color: white;
        }
    </style>
</head>

<body>
    <?php
    // Ustaw locale na podstawie cookie jako backup jeśli middleware nie działa
    if (isset($_COOKIE['locale']) && in_array($_COOKIE['locale'], ['de', 'en', 'pl'])) {
        app()->setLocale($_COOKIE['locale']);
    }
    
    // Ładowanie pliku countriesdata.json
    $countries = file_get_contents(public_path('countriesdata.json'));
    $countries = json_decode($countries);
    $countries = (array) $countries;
    $newcountries = array();
    $newcountriesjs = array();
    foreach ($countries as $keycountry => $valuecountry) {
        $newcountries[$valuecountry->phoneCode] = $valuecountry;
        $newcountriesjs[$valuecountry->phoneCode] = $valuecountry->code;
    }
    ?>

    <div x-data="loginComponent()" x-init="init()">
    <section id="wrapper" class="flex items-center justify-center min-h-screen">
        <div class="flex w-full max-w-6xl mx-auto bg-blue-50 shadow-[2px_2px_8px_0px_#00000024] overflow-hidden rounded-2xl h-[600px]">
            {{-- Lewa część: Logo i tło --}}
            <div class="w-1/2 flex flex-col items-center justify-center px-8 py-20 bg-blue-500" style="background-image: url('{{ asset('assets/images/pattern.svg') }}'); background-size: cover; background-position: center; background-repeat: no-repeat;">
                <img src="{{ asset('assets/images/logo-PnG-vertical.svg') }}" alt="Logo" class="max-w-xs w-[40%] h-auto block" />
            </div>

            {{-- Prawa część: Formularz logowania --}}
            <div class="w-1/2 flex flex-col px-8 py-20 h-full">
                {{-- Górna sekcja z logo i tytułem --}}
                <div class="flex-1 flex flex-col items-center justify-center">
                    <div class="w-full max-w-md">
    
                        <h2 class="text-4xl font-extrabold leading-tight text-slate-800 mb-1">
                            {!! trans('lang.merchant_panel') !!}
                        </h2>
                        <p class="text-slate-800 mb-8">
                            {!! trans('lang.log_in_to_continue') !!}
                        </p>

                        @if(count($errors) > 0)
                        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-2 rounded relative mb-4">
                            @foreach($errors->all() as $message)
                            <span class="block sm:inline">{{ $message }}</span>
                            @endforeach
                        </div>
                        @endif

                        <form name="login" id="login-box" @submit.prevent="login()" class="space-y-4" method="POST" novalidate>
                            @csrf

                            {{-- Logika deszyfrowania została przeniesiona do LoginController --}}

                            {{-- Pole Email --}}
                            <div>
                                <div class="relative h-12">
                                    <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" class="lucide lucide-at-sign-icon lucide-at-sign absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
                                        <circle cx="12" cy="12" r="4"/>
                                        <path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"/>
                                    </svg>
                                    <input placeholder="{!! trans('lang.email_address') !!}" id="email" type="email" class="input-focus w-full h-full pl-10 pr-4 bg-white border !border-slate-300 rounded-md text-base placeholder:text-slate-500 focus:outline-none focus:ring-0 transition-all duration-200" name="email" x-model="email" autocomplete="email" autofocus />
                                </div>
                                <div x-show="errors.email" x-cloak class="flex items-center mt-2 text-red-600 text-sm">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 mr-2 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                        <circle cx="12" cy="12" r="10"/>
                                        <path d="m15 9-6 6"/>
                                        <path d="m9 9 6 6"/>
                                    </svg>
                                    <span x-text="errors.email"></span>
                                </div>
                            </div>

                            {{-- Pole Hasło --}}
                            <div>
                                <div class="relative h-12">
                                    <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" class="lucide lucide-lock-keyhole-icon lucide-lock-keyhole absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
                                        <circle cx="12" cy="16" r="1"/>
                                        <rect x="3" y="10" width="18" height="12" rx="2"/>
                                        <path d="M7 10V7a5 5 0 0 1 10 0v3"/>
                                    </svg>
                                    <input id="password" placeholder="{!! trans('lang.password') !!}" :type="isPasswordVisible ? 'text' : 'password'" class="input-focus w-full h-full pl-10 pr-4 bg-white border !border-slate-300 rounded-md text-base placeholder:text-slate-500 focus:outline-none focus:ring-0 transition-all duration-200" name="password" x-model="password" autocomplete="current-password" />
                                </div>
                                <div x-show="errors.password" x-cloak class="flex items-center mt-2 text-red-600 text-sm">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 mr-2 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                        <circle cx="12" cy="12" r="10"/>
                                        <path d="m15 9-6 6"/>
                                        <path d="m9 9 6 6"/>
                                    </svg>
                                    <span x-text="errors.password"></span>
                                </div>
                            </div>

                            {{-- Pokaż hasło + link „Zapomniałeś hasła?” --}}
                            <div class="flex items-center justify-between">
                                <label class="inline-flex items-center cursor-pointer select-none">
                                    <input type="checkbox" x-model="isPasswordVisible" class="peer" style="display: none !important;" />
                                    <div class="w-5 h-5 border !border-slate-300 rounded bg-white peer-checked:!bg-blue-500 peer-checked:!border-blue-500 flex items-center justify-center transition-colors">
                                        <i class="fa-solid fa-check text-white text-xs" x-show="isPasswordVisible" x-cloak></i>
                                    </div>
                                    <span class="ml-2 text-sm text-gray-600">{!! trans('lang.show_password') !!}</span>
                                </label>
                                <div>
                                    <a href="#" @click="handleForgotPassword()" class="text-sm text-slate-600 hover:text-blue-500 transition-colors hover:no-underline">{{ trans('lang.need_help_accessing_account') }}?</a>
                                </div>
                            </div>

                            {{-- Przyciski logowania --}}
                            <div class="mt-8">
                                <button type="submit" :disabled="isLoading" class="mb-2 w-full h-12 flex items-center justify-center bg-blue-500 hover:bg-blue-600 text-white text-base font-semibold rounded-md shadow-md uppercase focus:outline-none focus:ring-0 active:outline-none active:ring-0 transition-opacity" :class="{'opacity-50 cursor-not-allowed': isLoading}" style="box-shadow: 1px 1px 2px rgba(0,0,0,0.3);">
                                    <span x-show="!isLoading" x-cloak>{{ trans('lang.login') }}</span>
                                    <span x-show="isLoading" x-cloak>{{ trans('lang.logging_in') }}</span>
                                </button>
                            </div>

                            {{-- Walidacja błędów --}}
                            <div x-show="errors.general" x-cloak class="mt-4 mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
                                <div class="flex items-start">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 text-red-600 mr-3 mt-0.5 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                        <circle cx="12" cy="12" r="10"/>
                                        <path d="m15 9-6 6"/>
                                        <path d="m9 9 6 6"/>
                                    </svg>
                                    <div class="flex-1">
                                        <h4 class="text-red-800 font-medium text-sm mb-1">{{ trans('lang.login_error') }}</h4>
                                        <p class="text-red-700 text-sm" x-text="errors.general"></p>
                                    </div>
                                </div>
                            </div>
                            
                            <div x-show="isWaitingForApproval" x-cloak class="mt-4 mb-6 p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                                <div class="flex items-start">
                                    <svg class="w-5 h-5 text-yellow-600 mr-3 mt-0.5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                                        <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
                                    </svg>
                                    <div class="flex-1">
                                        <h4 class="text-yellow-800 font-medium text-sm mb-1">{{ trans('lang.account_pending') }}</h4>
                                        <p class="text-yellow-700 text-sm">{{ trans('lang.waiting_for_approval') }}</p>
                                    </div>
                                </div>
                            </div>
                        </form>

                    </div>
                </div>

                {{-- Sekcja dolna z selektorem języka --}}
                <div class="h-8 pt-8 flex items-center justify-center" x-show="activeLanguages.length > 1" x-cloak>
                    <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="mr-2 text-slate-600">
                        <circle cx="12" cy="12" r="10"/>
                        <path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/>
                        <path d="M2 12h20"/>
                    </svg>
                    <div class="inline-flex items-center space-x-2 text-slate-600 text-sm font-normal">
                        <template x-for="(lang, index) in activeLanguages" :key="lang.slug">
                            <div class="inline-flex items-center">
                                <span x-show="index > 0" class="inline-block h-4 w-0.5 bg-slate-600 mr-2 rounded-full"></span>
                                <button type="button" @click="setLang(lang.slug)" :disabled="lang.slug === currentLocale" 
                                        :class="{ 'font-bold cursor-default': lang.slug === currentLocale, 'hover:text-slate-800 transition-colors': lang.slug !== currentLocale }">
                                    <span x-text="lang.title.toUpperCase()"></span>
                                </button>
                            </div>
                        </template>
                    </div>
                </div>
            </div>
        </div>
    </section>

    {{-- QR Login Modal --}}
    {{-- Modal zmiany hasła --}}
    <div x-show="isPasswordModalOpen" x-cloak @keydown.escape.window="closePasswordModal()" class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50" aria-modal="true" role="dialog">
        <div @click.away="closePasswordModal()" class="bg-white w-full max-w-md mx-auto rounded shadow-lg p-6 relative">
            <h5 class="text-xl font-semibold mb-4">{!! trans('lang.change_your_password') !!}</h5>
            <div class="space-y-4 mb-4">
                <div>
                    <label for="newPassword" class="block font-medium">{!! trans('lang.new_password') !!}</label>
                    <input type="password" id="newPassword" x-model="newPassword" class="input-focus mt-1 w-full border border-gray-300 rounded py-2 px-3 bg-white focus:outline-none transition-all duration-200" placeholder="{!! trans('lang.enter_new_password') !!}" />
                </div>
                <div>
                    <label for="confirmPassword" class="block font-medium">{!! trans('lang.confirm_password') !!}</label>
                    <input type="password" id="confirmPassword" x-model="confirmPassword" class="input-focus mt-1 w-full border border-gray-300 rounded py-2 px-3 bg-white focus:outline-none transition-all duration-200" placeholder="{!! trans('lang.confirm_new_password') !!}" />
                </div>
                <div x-show="errors.modal" x-text="errors.modal" class="text-red-500"></div>
            </div>
            <div class="flex justify-end space-x-2">
                <button @click="updatePassword()" type="button" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-400">
                    {{ trans('lang.submit') }}
                </button>
                <button type="button" @click="closePasswordModal()" class="bg-gray-300 text-gray-800 px-4 py-2 rounded hover:bg-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-400">
                    {{ trans('lang.close') }}
                </button>
            </div>
        </div>
    </div>

    <!-- Support Ticket Modal -->
    <div id="supportModal" class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50" style="display: none; z-index: 9999;" onclick="document.getElementById('supportModal').style.display='none'" x-data="{ 
        supportTicketDropdownOpen: false, 
        supportTicket: { email: '', restaurant_name: '', phone: '', contact_time: 'morning', description: '', issue_type: 'password_reset' }, 
        isSubmitting: false,
        getContactTimeLabel(value) {
            const labels = {
                'morning': '{{ trans("lang.morning") }} (9:00-12:00)',
                'afternoon': '{{ trans("lang.afternoon") }} (12:00-17:00)',
                'evening': '{{ trans("lang.evening") }} (17:00-20:00)'
            };
            return labels[value] || labels['morning'];
        },
        async submitSupportTicket() {
            this.isSubmitting = true;
            
            try {
                const response = await fetch('/api/support-ticket', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content
                    },
                    body: JSON.stringify(this.supportTicket)
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert(this.translations.support_request_submitted.replace('{ticket_id}', data.ticket_id));
                    document.getElementById('supportModal').style.display = 'none';
                } else {
                    alert(this.translations.failed_to_submit_request);
                }
            } catch (error) {
                alert(this.translations.network_error_check_connection);
            } finally {
                this.isSubmitting = false;
            }
        }
    }">
        <div onclick="event.stopPropagation()" class="bg-white rounded-lg text-left overflow-hidden shadow-xl w-full max-w-lg flex flex-col">
            <!-- Header -->
            <div class="bg-slate-50 px-6 py-4 flex items-center justify-between border-b border-slate-200">
                <h3 class="text-xl font-bold text-slate-800">{{ trans('lang.account_access_help') }}</h3>
                <button onclick="document.getElementById('supportModal').style.display='none'" class="text-slate-400 hover:text-slate-600 transition-colors">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                </button>
            </div>
            
            <!-- Content -->
            <div class="p-6">
            
            <form id="supportTicketForm" @submit.prevent="submitSupportTicket()" class="space-y-4">
                <div>
                    <label class="block text-sm font-medium mb-1">{{ trans('lang.email') }}</label>
                    <input type="email" x-model="supportTicket.email" required 
                           class="input-focus w-full h-12 border border-gray-300 rounded-md px-3 bg-white text-base placeholder:text-slate-500 focus:outline-none focus:ring-0 transition-all duration-200">
                </div>
                
                <div>
                    <label class="block text-sm font-medium mb-1">{{ trans('lang.restaurant_name') }}</label>
                    <input type="text" x-model="supportTicket.restaurant_name" required 
                           class="input-focus w-full h-12 border border-gray-300 rounded-md px-3 bg-white text-base placeholder:text-slate-500 focus:outline-none focus:ring-0 transition-all duration-200">
                </div>
                
                <div>
                    <label class="block text-sm font-medium mb-1">{{ trans('lang.contact_phone') }}</label>
                    <input type="tel" x-model="supportTicket.phone" required 
                           class="input-focus w-full h-12 border border-gray-300 rounded-md px-3 bg-white text-base placeholder:text-slate-500 focus:outline-none focus:ring-0 transition-all duration-200">
                </div>
                
                <div>
                    <label class="block text-sm font-medium mb-1">{{ trans('lang.preferred_contact_time') }}</label>
                    <div class="relative">
                        <button type="button"
                            @click="supportTicketDropdownOpen = !supportTicketDropdownOpen"
                            class="input-focus relative w-full h-12 text-left cursor-pointer rounded-md border !border-slate-300 py-2 px-3 transition duration-150 focus:outline-none focus:ring-0 text-base text-slate-700 bg-white flex items-center"
                            :class="{'bg-blue-50 !border-blue-500': supportTicketDropdownOpen, 'bg-white': !supportTicketDropdownOpen}">
                            <span class="block truncate flex-1" x-text="getContactTimeLabel(supportTicket.contact_time)"></span>
                            <span class="pointer-events-none flex items-center pl-2">
                                <i class="fa-solid fa-chevron-down text-xs text-gray-400 transition-transform duration-200" :class="{'rotate-180': supportTicketDropdownOpen}"></i>
                            </span>
                        </button>
                        <ul x-show="supportTicketDropdownOpen" @click.away="supportTicketDropdownOpen = false"
                            x-transition:enter="transition ease-out duration-100"
                            x-transition:enter-start="transform opacity-0 scale-95"
                            x-transition:enter-end="transform opacity-100 scale-100"
                            x-transition:leave="transition ease-in duration-75"
                            x-transition:leave-start="transform opacity-100 scale-100"
                            x-transition:leave-end="transform opacity-0 scale-95"
                            class="absolute z-50 mt-1 w-full max-h-40 overflow-y-auto rounded-md bg-white shadow-lg border !border-slate-300"
                            x-cloak>
                            <li @click="supportTicket.contact_time = 'morning'; supportTicketDropdownOpen = false"
                                class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap transition-colors">
                                <i class="fa-solid fa-check text-blue-500 transition-opacity w-4" :class="supportTicket.contact_time === 'morning' ? 'opacity-100' : 'opacity-0'"></i>
                                <span>{{ trans('lang.morning') }} (9:00-12:00)</span>
                            </li>
                            <li @click="supportTicket.contact_time = 'afternoon'; supportTicketDropdownOpen = false"
                                class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap transition-colors">
                                <i class="fa-solid fa-check text-blue-500 transition-opacity w-4" :class="supportTicket.contact_time === 'afternoon' ? 'opacity-100' : 'opacity-0'"></i>
                                <span>{{ trans('lang.afternoon') }} (12:00-17:00)</span>
                            </li>
                            <li @click="supportTicket.contact_time = 'evening'; supportTicketDropdownOpen = false"
                                class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap transition-colors">
                                <i class="fa-solid fa-check text-blue-500 transition-opacity w-4" :class="supportTicket.contact_time === 'evening' ? 'opacity-100' : 'opacity-0'"></i>
                                <span>{{ trans('lang.evening') }} (17:00-20:00)</span>
                            </li>
                        </ul>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium mb-1">{{ trans('lang.additional_info') }}</label>
                    <textarea x-model="supportTicket.description" maxlength="300"
                             class="input-focus w-full border border-gray-300 rounded-md px-3 py-2 h-20 bg-white text-base placeholder:text-slate-500 focus:outline-none focus:ring-0 transition-all duration-200 resize-none" 
                             placeholder="{{ trans('lang.describe_issue_placeholder') }}"></textarea>
                    <div class="text-right text-xs text-gray-500 mt-1">
                        <span x-text="supportTicket.description.length"></span>/300 {{ trans('lang.characters') }}
                    </div>
                </div>
                
            </form>
            </div>
            
            <!-- Footer -->
            <div class="bg-gray-50 px-4 py-4 border-t border-gray-200 flex flex-col gap-3">
                <button type="submit" form="supportTicketForm" :disabled="isSubmitting" 
                        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 disabled:opacity-50"
                        style="box-shadow: 1px 1px 2px rgba(0,0,0,0.2);">
                    <span x-show="!isSubmitting">{{ trans('lang.submit_request') }}</span>
                    <span x-show="isSubmitting">{{ trans('lang.submitting') }}...</span>
                </button>
                <button type="button" onclick="document.getElementById('supportModal').style.display='none'" 
                        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>

    <!-- Employee Auto Reset Modal -->
    <div id="autoResetModal" class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50" style="display: none; z-index: 9999;" onclick="document.getElementById('autoResetModal').style.display='none'">
        <div onclick="event.stopPropagation()" class="bg-white rounded-lg text-left overflow-hidden shadow-xl w-full max-w-md flex flex-col">
            <!-- Header -->
            <div class="bg-slate-50 px-6 py-4 flex items-center justify-between border-b border-slate-200">
                <h3 class="text-xl font-bold text-slate-800">{{ trans('lang.reset_employee_password') }}</h3>
                <button onclick="document.getElementById('autoResetModal').style.display='none'" class="text-slate-400 hover:text-slate-600 transition-colors">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                </button>
            </div>
            
            <!-- Content -->
            <div class="p-6">
                <p class="text-sm text-slate-600 mb-4 leading-relaxed">{{ trans('lang.employee_reset_info') }}</p>
            
            <form id="autoResetForm" onsubmit="handleEmployeeResetSubmit(event)">
                <div class="mb-4">
                    <label class="block text-sm font-medium mb-1">{{ trans('lang.confirm_email') }}</label>
                    <input type="email" id="resetEmailInput" required 
                           class="w-full border border-gray-300 rounded py-2 px-3 focus:outline-none focus:border-blue-500">
                </div>
            </form>
            </div>
            
            <!-- Footer -->
            <div class="bg-gray-50 px-4 py-4 border-t border-gray-200 flex flex-col gap-3">
                <button type="submit" form="autoResetForm" id="submitResetBtn"
                        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 disabled:opacity-50"
                        style="box-shadow: 1px 1px 2px rgba(0,0,0,0.2);">
                    <span id="submitText">{{ trans('lang.send_reset_link') }}</span>
                    <span id="loadingText" style="display: none;">{{ trans('lang.sending') }}...</span>
                </button>
                <button type="button" onclick="document.getElementById('autoResetModal').style.display='none'" 
                        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>


    <!-- Error Info Modal -->
    <div id="errorInfoModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-80" style="display: none;" onclick="document.getElementById('errorInfoModal').style.display='none'" role="dialog" aria-modal="true">
        <div onclick="event.stopPropagation()" class="bg-white rounded-lg text-left overflow-hidden shadow-xl w-full max-w-lg flex flex-col">
            <!-- 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.account_not_found') }}</h3>
                <button onclick="document.getElementById('errorInfoModal').style.display='none'" 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>
            
            <!-- Content -->
            <div class="p-6 text-center">
                <div class="mx-auto flex items-center justify-center h-16 w-16 rounded-full bg-red-100">
                    <i class="fa-solid fa-triangle-exclamation text-3xl text-red-600"></i>
                </div>
                <h4 class="text-xl font-semibold text-gray-900 mt-4">{{ trans('lang.no_account_found_message') }}</h4>
                <p class="mt-2 text-sm text-gray-600">{{ trans('lang.please_check_email_address') }}</p>
            </div>
            
            <!-- Footer -->
            <div class="bg-gray-50 px-4 py-4 border-t border-gray-200">
                <button type="button" onclick="document.getElementById('errorInfoModal').style.display='none'" 
                        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.understood') }}
                </button>
            </div>
        </div>
    </div>

    {{-- Ekran ostrzegawczy dla małych ekranów --}}
    <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 type="text/javascript">
        document.addEventListener('alpine:init', () => {
            Alpine.data('loginComponent', () => ({
                // Security constants
                FIREBASE_TIMEOUT: 15000, // 15 sekund timeout
                MAX_LOGIN_ATTEMPTS: 5,
                ATTEMPT_RESET_TIME: 300000, // 5 minut
                
                // Form state
                email: '{{ old('email', $email ?? '') }}',
                password: '{{ $password ?? '' }}',
                isPasswordVisible: false,
                isLoading: false,
                isWaitingForApproval: false,
                
                // Security state
                loginAttempts: 0,
                lastFailedAttempt: 0,

                // Errors
                errors: {
                    email: '',
                    password: '',
                    general: '',
                    modal: ''
                },

                // Password modal state
                isPasswordModalOpen: false,
                newPassword: '',
                confirmPassword: '',
                currentUser: null,
                oldPassword: '',

                // Support ticket modal state
                isSupportModalOpen: false,
                isAutoResetModalOpen: false,
                isSubmitting: false,
                supportTicket: {
                    email: '',
                    restaurant_name: '',
                    phone: '',
                    contact_time: 'morning',
                    description: '',
                    issue_type: 'password_reset'
                },
                resetEmail: '',
                supportTicketDropdownOpen: false,

                // Language state
                languages: [],
                currentLocale: 'de', // Będzie zaktualizowane w init()

                // Translations for JS
                translations: {
                    email_required: "{{ trans('lang.email_is_required') }}",
                    password_required: "{{ trans('lang.password_is_required') }}",
                    user_not_found: "{{ trans('lang.user_not_found_in_firestore') }}",
                    unexpected_error: "{{ trans('lang.unexpected_error_try_again') }}",
                    login_failed: "{{ trans('lang.login_failed_try_again') }}",
                    server_connection_error: "{{ trans('lang.could_not_connect_to_server') }}",
                    passwords_dont_match: "{{ trans('lang.passwords_dont_match') }}",
                    password_empty: "{{ trans('lang.new_password_cant_be_empty') }}",
                    password_updated: "{{ trans('lang.password_updated_successfully') }}",
                    error_prefix: "{{ trans('lang.error_prefix') }}",
                    request_timeout: "{{ trans('lang.request_timeout') }}",
                    too_many_attempts: "{{ trans('lang.too_many_attempts') }}",
                    support_request_submitted: "{{ trans('lang.support_request_submitted') }}",
                    failed_to_submit_request: "{{ trans('lang.failed_to_submit_request') }}",
                    network_error_check_connection: "{{ trans('lang.network_error_check_connection') }}",
                    please_enter_email_first: "{{ trans('lang.please_enter_email_first') }}",
                    unable_to_verify_account: "{{ trans('lang.unable_to_verify_account') }}",
                    password_reset_link_sent: "{{ trans('lang.password_reset_link_sent') }}",
                    please_enter_email_address: "{{ trans('lang.please_enter_email_address') }}"
                },

                // Initialization
                init() {
                    const sessionLocale = '{{ session()->get('locale') }}';
                    const cookieLocale = this.getCookie('locale');

                    if (sessionLocale && sessionLocale.trim() !== '') {
                        this.currentLocale = sessionLocale;
                    } else if (cookieLocale) {
                        this.currentLocale = cookieLocale;
                    } else {
                        this.currentLocale = 'de';
                    }

                    this.fetchGlobalSettings();
                    this.fetchLanguages();

                    setTimeout(() => { this.checkQrLibraryLoaded(); }, 1000);
                },

                checkQrLibraryLoaded() {
                    if (typeof Html5Qrcode === 'undefined') {
                        console.warn('Html5Qrcode library failed to load from CDN. QR scanner may not work properly.');
                    } else {
                        console.log('Html5Qrcode library loaded successfully');
                    }
                },

                // --- Helper Functions ---
                setCookie(name, value, days) {
                    let expires = "";
                    if (days) {
                        const date = new Date();
                        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                        expires = "; expires=" + date.toUTCString();
                    }
                    document.cookie = name + "=" + (value || "") + expires + "; path=/";
                },

                getCookie(name) {
                    const nameEQ = name + "=";
                    const ca = document.cookie.split(';');
                    for (let i = 0; i < ca.length; i++) {
                        let c = ca[i];
                        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
                    }
                    return null;
                },

                clearPasswords() {
                    // Wyczyść wszystkie hasła z pamięci dla bezpieczeństwa
                    this.password = '';
                    this.oldPassword = '';
                    this.newPassword = '';
                    this.confirmPassword = '';
                },

                getContactTimeLabel(value) {
                    const labels = {
                        'morning': '{{ trans("lang.morning") }} (9:00-12:00)',
                        'afternoon': '{{ trans("lang.afternoon") }} (12:00-17:00)',
                        'evening': '{{ trans("lang.evening") }} (17:00-20:00)'
                    };
                    return labels[value] || labels['morning'];
                },

                clearErrors() {
                    this.errors = { email: '', password: '', general: '', modal: '' };
                    this.isWaitingForApproval = false;
                },

                // Security helpers
                checkRateLimit() {
                    const now = Date.now();
                    
                    // Reset counter po czasie
                    if (now - this.lastFailedAttempt > this.ATTEMPT_RESET_TIME) {
                        this.loginAttempts = 0;
                    }
                    
                    if (this.loginAttempts >= this.MAX_LOGIN_ATTEMPTS) {
                        const remainingTime = Math.ceil((this.ATTEMPT_RESET_TIME - (now - this.lastFailedAttempt)) / 60000);
                        this.errors.general = this.translations.too_many_attempts.replace('{minutes}', remainingTime);
                        return false;
                    }
                    return true;
                },

                recordFailedAttempt() {
                    this.loginAttempts++;
                    this.lastFailedAttempt = Date.now();
                },

                createTimeoutPromise(ms) {
                    return new Promise((_, reject) => 
                        setTimeout(() => reject(new Error('Request timeout')), ms)
                    );
                },

                sanitizeInput(input) {
                    return input ? input.trim().replace(/[<>]/g, '') : '';
                },

                // --- Data Fetching ---
                fetchGlobalSettings() {
                    fetch('/api/settings/global')
                        .then(r => r.json())
                        .then(data => {
                            if (data.meta_title)        document.title                         = data.meta_title;
                            if (data.store_panel_color) this.setCookie('store_panel_color', data.store_panel_color, 365);
                            if (data.favicon)           this.setCookie('favicon',           data.favicon,           365);
                        })
                        .catch(() => {});
                },

                fetchLanguages() {
                    fetch('/api/settings/languages')
                        .then(r => r.json())
                        .then(data => {
                            if (data && data.list) {
                                this.languages = data.list;
                                if (!this.getCookie('locale')) {
                                    this.setCookie('locale', this.currentLocale, 365);
                                }
                            }
                        })
                        .catch(() => {});
                },

                get activeLanguages() {
                    const filtered = this.languages.filter(lang => lang.isActive === true);
                    // Sortuj tak żeby niemiecki był pierwszy
                    return filtered.sort((a, b) => {
                        if (a.slug === 'de') return -1; // Niemiecki na początku
                        if (b.slug === 'de') return 1;
                        return a.title.localeCompare(b.title); // Reszta alfabetycznie
                    });
                },

                setLang(slug) {
                    this.setCookie('locale', slug, 365);
                    const langData = this.languages.find(l => l.slug === slug);
                    if (langData) {
                        this.setCookie('is_rtl', langData.is_rtl ? 'true' : 'false', 365);
                    }
                    window.location.href = "{{ route('changeLang') }}?lang=" + slug;
                },

                // --- Authentication Logic ---
                login() {
                    this.clearErrors();
                    
                    // Rate limiting check
                    if (!this.checkRateLimit()) {
                        return;
                    }
                    
                    // Sanitize inputs
                    this.email = this.sanitizeInput(this.email);
                    this.password = this.sanitizeInput(this.password);
                    
                    if (!this.email || !this.password) {
                        if (!this.email) this.errors.email = this.translations.email_required;
                        if (!this.password) this.errors.password = this.translations.password_required;
                        return;
                    }
                    this.isLoading = true;

                    // Try MySQL login first (for subaccounts/employees)
                    Promise.race([
                        fetch("{{ route('mysql.login') }}", {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                            },
                            body: JSON.stringify({
                                email: this.email,
                                password: this.password
                            })
                        }),
                        this.createTimeoutPromise(this.FIREBASE_TIMEOUT)
                    ])
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // alert("Login successfull");
                            // MySQL login successful
                            this.clearPasswords();
                            // alert(data.redirect_url);
                            window.location.href = data.redirect_url;
                        } else {
                            // MySQL login failed, try Firebase (for main vendor accounts)
                            // this.tryFirebaseLogin();
                            console.log("mysql login failed");
                        }
                    })
                    .catch(error => {
                        // MySQL request failed, try Firebase fallback
                        console.log('MySQL login failed, trying Firebase:', error);
                        // this.tryFirebaseLogin();
                    });
                },

                tryFirebaseLogin() {
                    // Firebase removed — MySQL-only login via login()
                    this.errors.general = this.translations.login_failed;
                    this.isLoading = false;
                },

                handleAuthError(error) {
                    this.tryMysqlLogin();
                },

                tryMysqlLogin() {
                    // MySQL login z timeout
                    Promise.race([
                        fetch("{{ route('mysql.login') }}", {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                            },
                            body: JSON.stringify({
                                email: this.email,
                                password: this.password
                            })
                        }),
                        this.createTimeoutPromise(this.FIREBASE_TIMEOUT)
                    ])
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            this.clearPasswords(); // Wyczyść hasła przed przekierowaniem
                            window.location.href = data.redirect_url;
                        } else {
                            this.errors.general = data.error || this.translations.login_failed;
                            this.password = ''; // Wyczyść hasło po błędzie logowania
                        }
                    })
                    .catch(error => {
                        if (error.message === 'Request timeout') {
                            this.errors.general = this.translations.request_timeout;
                        } else {
                            this.errors.general = this.translations.server_connection_error;
                        }
                        this.password = ''; // Wyczyść hasło po błędzie
                    });
                },

                proceedAfterLogin(user, userData) {
                    if (userData.active !== true) {
                        this.isWaitingForApproval = true;
                        return;
                    }

                    window.location.href = "{{ route('dashboard') }}";
                },

                // --- Forgot Password Logic ---
                async handleForgotPassword() {
                    if (!this.email) {
                        // Pokaż błąd walidacji zamiast alertu
                        this.errors.email = this.translations.please_enter_email_first || 'Please enter your email address first';
                        // Ustaw focus na pole email
                        this.$nextTick(() => {
                            const emailInput = document.querySelector('input[type="email"]');
                            if (emailInput) {
                                emailInput.focus();
                            }
                        });
                        return;
                    }
                    
                    this.resetEmail = this.email;
                    this.openAutoResetModal();
                },

                openSupportModal() {
                    const modal = document.getElementById('supportModal');
                    if (modal) {
                        modal.style.display = 'flex';
                    }
                },

                showErrorModal() {
                    const modal = document.getElementById('errorInfoModal');
                    if (modal) {
                        modal.style.display = 'flex';
                    }
                },

                closeSupportModal() {
                    const modal = document.getElementById('supportModal');
                    if (modal) {
                        modal.style.display = 'none';
                    }
                    this.supportTicket = {
                        email: '',
                        restaurant_name: '',
                        phone: '',
                        contact_time: 'morning',
                        description: '',
                        issue_type: 'password_reset'
                    };
                },

                openAutoResetModal() {
                    const modal = document.getElementById('autoResetModal');
                    if (modal) {
                        modal.style.display = 'flex';
                        
                        // Pre-fill email input
                        const emailInput = document.getElementById('resetEmailInput');
                        if (emailInput) {
                            emailInput.value = this.email;
                        }
                    }
                },

                closeAutoResetModal() {
                    const modal = document.getElementById('autoResetModal');
                    if (modal) {
                        modal.style.display = 'none';
                    }
                    this.resetEmail = '';
                },

                async submitSupportTicket() {
                    this.isSubmitting = true;
                    
                    try {
                        const response = await fetch('/api/support-ticket', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                            },
                            body: JSON.stringify(this.supportTicket)
                        });
                        
                        const data = await response.json();
                        
                        if (data.success) {
                            alert(this.translations.support_request_submitted.replace('{ticket_id}', data.ticket_id));
                            this.closeSupportModal();
                        } else {
                            alert(this.translations.failed_to_submit_request);
                        }
                    } catch (error) {
                        alert(this.translations.network_error_check_connection);
                    } finally {
                        this.isSubmitting = false;
                    }
                },

                async sendEmployeeReset() {
                    this.isSubmitting = true;
                    
                    try {
                        const response = await fetch('/api/employee-password-reset', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                            },
                            body: JSON.stringify({ email: this.resetEmail })
                        });
                        
                        const responseText = await response.text();
                        
                        let data;
                        try {
                            data = JSON.parse(responseText);
                        } catch (parseError) {
                            throw new Error('Server returned HTML instead of JSON');
                        }
                        
                        if (data.success) {
                            alert(this.translations.password_reset_link_sent);
                            this.closeAutoResetModal();
                        } else {
                            alert(data.error || this.translations.failed_to_submit_request);
                        }
                    } catch (error) {
                        alert(this.translations.network_error_check_connection);
                    } finally {
                        this.isSubmitting = false;
                    }
                },

                // --- Password Modal Logic ---
                openPasswordModal() {
                    this.isPasswordModalOpen = true;
                },
                closePasswordModal() {
                    this.isPasswordModalOpen = false;
                    this.newPassword = '';
                    this.confirmPassword = '';
                    this.oldPassword = ''; // Wyczyść stare hasło
                    this.errors.modal = '';
                },
                updatePassword() {
                    if (this.newPassword !== this.confirmPassword) {
                        this.errors.modal = this.translations.passwords_dont_match;
                        return;
                    }
                    if (!this.newPassword) {
                        this.errors.modal = this.translations.password_empty;
                        return;
                    }

                    fetch('/api/profile/change-password', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                        },
                        body: JSON.stringify({ old_password: this.oldPassword, new_password: this.newPassword })
                    })
                    .then(r => r.json())
                    .then(data => {
                        if (data.message) {
                            alert(this.translations.password_updated);
                            this.closePasswordModal();
                            this.clearPasswords();
                            window.location.href = "{{ route('dashboard') }}";
                        } else {
                            this.errors.modal = data.error || this.translations.unexpected_error;
                        }
                    })
                    .catch(() => { this.errors.modal = this.translations.unexpected_error; });
                },

            }));
        });
    </script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            handleScreenResize();
        });

        // Global function for employee reset form
        async function handleEmployeeResetSubmit(event) {
            event.preventDefault();
            
            const emailInput = document.getElementById('resetEmailInput');
            const submitBtn = document.getElementById('submitResetBtn');
            const submitText = document.getElementById('submitText');
            const loadingText = document.getElementById('loadingText');
            
            const email = emailInput.value;
            
            if (!email) {
                alert('{{ trans('lang.please_enter_email_address') }}');
                return;
            }
            
            // Show loading state
            submitBtn.disabled = true;
            submitText.style.display = 'none';
            loadingText.style.display = 'inline';
            
            try {
                const response = await fetch('/api/employee-password-reset', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify({ email: email })
                });
                
                const responseText = await response.text();
                
                let data;
                try {
                    data = JSON.parse(responseText);
                } catch (parseError) {
                    throw new Error('Server returned HTML instead of JSON');
                }
                
                if (data.success) {
                    alert('{{ trans('lang.password_reset_link_sent') }}');
                    document.getElementById('autoResetModal').style.display = 'none';
                } else {
                    alert(data.error || '{{ trans('lang.failed_to_submit_request') }}');
                }
                
            } catch (error) {
                alert('{{ trans('lang.network_error_check_connection') }}');
            } finally {
                // Reset loading state
                submitBtn.disabled = false;
                submitText.style.display = 'inline';
                loadingText.style.display = 'none';
            }
        }

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

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

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

            checkViewportWidth();
            window.addEventListener('resize', debouncedCheck);
        }
    </script>
    </div>
</body>

</html>
