{{--
|--------------------------------------------------------------------------
| Plik Widoku: Zarządzanie Profilem Użytkownika
|--------------------------------------------------------------------------
|
| Lokalizacja: resources/views/users/manage_profile.blade.php
| Wersja: 2.0 (Alpine.js Refactor)
| Ostatnia modyfikacja: 11 lipca 2025
|
|--------------------------------------------------------------------------
| Opis Przeznaczenia
|--------------------------------------------------------------------------
|
| Ten plik Blade renderuje w pełni interaktywny, jednostronicowy interfejs
| (Single Page Application-like experience) do zarządzania profilem zalogowanego
| użytkownika (sprzedawcy/właściciela). Został on zbudowany w nowoczesnym stosie
| technologicznym, kładąc nacisk na doskonałe doświadczenie użytkownika (UX)
| i wydajność poprzez minimalizację przeładowań strony.
|
|--------------------------------------------------------------------------
| Kluczowe Funkcjonalności
|--------------------------------------------------------------------------
|
| - Wyświetlanie i edycja danych osobowych (imię, nazwisko, telefon).
| - Bezpieczna zmiana hasła z ponownym uwierzytelnieniem i walidacją siły hasła w czasie rzeczywistym.
| - Zaawansowany komponent do przesyłania zdjęcia profilowego, wspierający:
|   - Podgląd zdjęcia przed wysłaniem.
|   - Funkcjonalność "przeciągnij i upuść" (Drag & Drop).
|   - Przyciski do zmiany i usuwania zdjęcia.
|   - Pasek postępu podczas wysyłania pliku i opcję anulowania.
| - Dynamiczne pobieranie listy numerów kierunkowych z bazy danych.
| - Pełna obsługa asynchronicznych operacji z wizualnym wskaźnikiem ładowania.
| - System powiadomień "toast" informujących o sukcesie lub błędzie operacji.
| - Walidacja formularzy po stronie klienta z natychmiastową informacją zwrotną.
|
|--------------------------------------------------------------------------
| Stos Technologiczny
|--------------------------------------------------------------------------
|
| - Backend: Laravel (silnik szablonów Blade)
| - Frontend (Interaktywność): Alpine.js
| - Frontend (Style): Tailwind CSS
| - Baza Danych: Google Firebase (Firestore, Storage, Authentication)
| - Biblioteki dodatkowe: Compressor.js (do kompresji obrazów po stronie klienta)
|
|--------------------------------------------------------------------------
| Zależności
|--------------------------------------------------------------------------
|
| - Poprawnie skonfigurowany dostęp do projektu Firebase w środowisku frontendu
|   (globalnie dostępne obiekty `database` i `firebase`).
| - Zdefiniowane tłumaczenia dla kluczy `trans('lang.*')` w plikach językowych Laravela.
| - Dołączone biblioteki JavaScript w głównym szablonie aplikacji (np. layouts/app.blade.php):
|   1. Alpine.js
|   2. Compressor.js
|   3. Font Awesome (dla ikon)
|
|--------------------------------------------------------------------------
| Opis dla Backend Dewelopera
|--------------------------------------------------------------------------
|
| Ten widok jest w dużej mierze samowystarczalny dzięki bezpośredniej
| komunikacji z SDK Firebase po stronie klienta. Główne zadania po stronie
| backendu (Laravel) i konfiguracji (Firebase) to zapewnienie odpowiedniej
| struktury danych i zabezpieczeń.
|
|   1. Konfiguracja Bazy Danych (Firestore):
|      - Kolekcja `users`: Dokumenty muszą zawierać pola: `firstName`, `lastName`,
|        `email`, `phoneNumber`, `phoneNumberPrefix`, `profilePictureURL`,
|        oraz kluczowe dla logiki `vendorID` (ID dokumentu z kolekcji `vendors`).
|      - Kolekcja `vendors`: Dokumenty muszą zawierać pole `author`, które jest
|        kluczem (ID) dokumentu użytkownika z kolekcji `users`. To tworzy
|        powiązanie dwustronne.
|      - Kolekcja `phone_prefixes`: Musi istnieć, a jej dokumenty powinny
|        zawierać pola: `prefix` (string, np. "+48"), `country` (string, np. "Polska")
|        oraz `order` (number, do sortowania na liście).
|      - Reguły Bezpieczeństwa (Security Rules): Należy skonfigurować reguły
|        w Firestore tak, aby zalogowany użytkownik mógł modyfikować wyłącznie
|        swój własny dokument w kolekcji `users`.
|
|   2. Konfiguracja Firebase Storage:
|      - Reguły Bezpieczeństwa (Security Rules): Należy skonfigurować tak,
|        aby umożliwić zalogowanym użytkownikom zapis plików (obrazów)
|        w określonym folderze (np. `images/`). Ścieżka zapisu powinna
|        być zabezpieczona, aby użytkownik nie mógł nadpisać plików
|        innych użytkowników.
|
|   3. Konfiguracja Firebase Authentication:
|      - Metoda Logowania: Uwierzytelnianie za pomocą "Email/Password" musi
|        być włączone w panelu Firebase, ponieważ mechanizm zmiany hasła
|        opiera się na ponownym uwierzytelnieniu z użyciem starego hasła.
|
|   4. Logika po Stronie Laravela:
|      - Przekazanie ID Użytkownika: Kontroler renderujący ten widok musi
|        przekazać do niego ID zalogowanego użytkownika. W kodzie jest ono
|        oczekiwane jako zmienna `$id`, która jest następnie wstawiana do
|        JavaScript: `vendorUserId: "<?php echo $id; ?>"`.
|      - Tłumaczenia: Wszystkie klucze `trans('lang.*')` użyte w widoku muszą
|        posiadać swoje odpowiedniki w plikach `resources/lang/{język}/lang.php`.
|
--}}

@extends('layouts.app')

@section('content')

{{-- Reset dla stylów autouzupełniania przeglądarki --}}
<style>
    input:-webkit-autofill,
    input:-webkit-autofill:hover,
    input:-webkit-autofill:focus,
    input:-webkit-autofill:active {
        -webkit-box-shadow: 0 0 0 30px white inset !important;
        box-shadow: 0 0 0 30px white inset !important;
        -webkit-text-fill-color: #0F172A !important;
    }
</style>

{{-- Główny wrapper strony ze stylizowanym tłem --}}
<div id="main-wrapper" class="p-10 min-h-screen">

  <div x-data="profileManager()" x-init="initFirebase()" class="flex flex-col gap-8 relative">

    {{-- Nakładka ładowania --}}
    <div x-show="processing" x-transition.opacity
      class="fixed inset-0 bg-black bg-opacity-80 z-50 flex items-center justify-center" style="display: none;">
      <div class="text-white text-lg flex flex-col items-center gap-2">
        <i class="fa-solid fa-spinner fa-spin text-4xl"></i>
        <span class="text-base">{{ trans('lang.processing') }}</span>
      </div>
    </div>

    {{-- Karta nagłówkowa z przyciskiem powrotu --}}
    <div class="rounded-lg shadow-[1px_1px_4px_0px_#e2e8f0] p-6 bg-gradient-to-r from-slate-900 via-blue-800 to-blue-500 flex items-center justify-between">
        <div>
            <h3 class="text-2xl font-bold text-slate-50">{!! trans('lang.manage_profile') !!}</h3>
            <p class="text-sm text-slate-200 mt-1 m-0">{!! trans('lang.manage_profile_desc') !!}</p>
        </div>
        <a href="{{ route('user.profile') }}" class="px-4 py-2 rounded-md bg-white text-slate-700 text-sm hover:bg-slate-100 hover:text-slate-700 hover:no-underline transition focus:outline-none focus:ring-0 flex items-center gap-2">
            <i class="fa fa-rotate-left"></i>
            {{ trans('lang.back_to_account_settings') }}
        </a>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">

        {{-- Karta: Informacje o profilu --}}
        <div class="rounded-lg border !border-slate-300 shadow-[1px_1px_4px_0px_#e2e8f0] overflow-hidden flex flex-col">
            <div class="bg-slate-900 px-6 py-4">
                <h3 class="text-xl font-bold text-white m-0">{!!trans('lang.profile_informations')!!}</h3>
            </div>
            <div class="p-6 bg-white flex flex-col gap-5 flex-grow">
                <div class="flex flex-col gap-6 flex-grow">
                    {{-- Imię --}}
                    <div>
                        <label class="text-sm text-slate-700 font-medium">{{trans('lang.first_name')}}</label>
                        <input type="text" x-model="user.firstName"
                               @input="user.firstName = user.firstName.replace(/[^\p{L}\s-]/gu, '')" @blur="validateField('firstName')"
                               class="border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50"
                               :class="{ '!border-red-500': errors.firstName }">
                        <span x-show="errors.firstName" x-text="errors.firstName" class="text-red-500 text-sm mt-1" x-transition></span>
                    </div>
                    {{-- Nazwisko --}}
                    <div>
                        <label class="text-sm text-slate-700 font-medium">{{trans('lang.last_name')}}</label>
                        <input type="text" x-model="user.lastName"
                               @input="user.lastName = user.lastName.replace(/[^\p{L}\s-]/gu, '')" @blur="validateField('lastName')"
                               class="border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50"
                               :class="{ '!border-red-500': errors.lastName }">
                        <span x-show="errors.lastName" x-text="errors.lastName" class="text-red-500 text-sm mt-1" x-transition></span>
                    </div>
                    {{-- E-mail --}}
                    <div>
                        <label class="text-sm text-slate-700 font-medium">{{trans('lang.email')}}</label>
                        <input type="email" :value="user.email"
                               class="border !border-slate-300 rounded-lg py-2 px-3 w-full bg-slate-100 cursor-not-allowed" disabled>
                    </div>
                    {{-- Numer telefonu --}}
                    <div>
                        <label class="text-sm text-slate-700 font-medium">{{trans('lang.user_phone')}}</label>
                        <div class="flex items-center">
                            <div class="flex items-center justify-center px-4 h-11 border border-slate-300 rounded-l-lg bg-slate-100 text-slate-700">
                                <span>+49</span>
                            </div>
                            <input type="text" x-model="user.phone"
                                   @input="user.phone = user.phone.replace(/[^0-9\s]/g, '')"
                                   @blur="validateField('phone')"
                                   placeholder="{{ trans('lang.restaurant_phone_placeholder') }}"
                                   class="border !border-slate-300 rounded-r-lg py-2 px-3 flex-1 transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50 -ml-px h-11"
                                   :class="{ '!border-red-500': errors.phone }">
                        </div>
                        <span x-show="errors.phone" x-text="errors.phone" class="text-red-500 text-sm mt-1" x-transition></span>
                    </div>
                    {{-- Zdjęcie profilowe --}}
                    <div>
                        <label class="text-sm text-slate-700 font-medium">{{ trans('lang.profile_pic') }}</label>
                        <div class="mt-2">
                            <input type="file" @change="selectFile($event.target.files[0])" id="profilePicInput" class="hidden" accept="image/png, image/jpeg, image/webp">
                            {{-- Zdjęcie profilowe --}}
                            <template x-if="!isUploading && (user.profilePicUrl || imagePreview)">
                                <div class="flex items-center gap-4">
                                    <img :src="imagePreview || user.profilePicUrl" alt="Podgląd zdjęcia"
                                        class="w-24 h-24 rounded-full object-cover border-2 border-slate-200">
                                    <div class="flex flex-col gap-3">
                                        {{-- Przycisk do zmiany zdjęcia --}}
                                        <button @click="triggerFileInput()" type="button" class="flex items-center gap-2 px-3 py-2 text-sm text-slate-700 rounded-md hover:bg-blue-100 hover:text-blue-500 border !border-slate-300 transition focus:outline-none focus:ring-0">
                                            <i class="fa-solid fa-pencil text-xs"></i>
                                            <span>{{ trans('lang.change_photo') }}</span>
                                        </button>
                                        {{-- Przycisk do usuwania zdjęcia --}}
                                        <button @click="removeImage()" type="button" class="flex items-center gap-2 px-3 py-2 text-sm text-slate-700 rounded-md hover:bg-red-100 hover:text-red-600 border !border-slate-300 transition focus:outline-none focus:ring-0">
                                            <i class="fa-solid fa-trash text-xs"></i>
                                            <span>{{ trans('lang.remove_photo') }}</span>
                                        </button>
                                    </div>
                                </div>
                            </template>
                            {{-- Przycisk do zmiany zdjęcia --}}
                            <template x-if="isUploading">
                                <div class="w-full">
                                    <div class="w-full bg-slate-200 rounded-full h-8 p-1 relative overflow-hidden">
                                        <div class="bg-blue-500 h-full rounded-full flex items-center justify-end px-2 text-white text-xs font-bold transition-all duration-300"
                                            :style="`width: ${uploadProgress}%`">
                                            <span x-text="`${Math.round(uploadProgress)}%`"></span>
                                        </div>
                                    </div>
                                    <button @click="cancelUpload()" title="{{ trans('lang.cancel_upload') }}" class="w-full text-center mt-2 text-sm text-slate-600 hover:text-black focus:outline-none focus:ring-0">
                                        {{ trans('lang.cancel') }}
                                    </button>
                                </div>
                            </template>
                            {{-- Przycisk do zmiany zdjęcia --}}
                            <template x-if="!isUploading && !user.profilePicUrl && !imagePreview">
                                <div @click="triggerFileInput()" @dragover.prevent="isDragging = true"
                                    @dragleave.prevent="isDragging = false"
                                    @drop.prevent="isDragging = false; selectFile($event.dataTransfer.files[0])"
                                    class="w-full p-6 border-2 border-dashed border-slate-300 rounded-lg text-center cursor-pointer transition-colors"
                                    :class="{'bg-blue-50 border-blue-400': isDragging}">
                                    <div class="flex flex-col items-center justify-center gap-2 text-slate-500">
                                        <i class="fa-solid fa-cloud-arrow-up text-3xl"></i>
                                        <p class="font-semibold">{{ trans('lang.drag_and_drop_file_here') }}</p>
                                        <p class="text-sm">{{ trans('lang.or') }}</p>
                                        <p class="font-semibold text-blue-500">{{ trans('lang.click_to_select_from_disk') }}</p>
                                        <p class="text-xs text-slate-400 mt-2">{{ trans('lang.uploader_file_types_info') }}</p>
                                    </div>
                                </div>
                            </template>
                            <p x-show="uploadError" x-text="uploadError" class="text-sm text-red-600 mt-2"></p>
                        </div>
                    </div>
                </div>
                {{-- Przycisk zapisu profilu --}}
                <button type="button" @click="saveProfile" :disabled="isProfileUnchanged || isProfileFormInvalid"
                        class="uppercase w-full mt-auto bg-blue-500 text-white px-4 py-2 rounded hover:opacity-90 transition disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-0">
                    {{trans('lang.submit')}}
                </button>
            </div>
        </div>

        {{-- Karta: Zmiana hasła --}}
        <div class="rounded-lg border !border-slate-300 shadow-[1px_1px_4px_0px_#e2e8f0] overflow-hidden flex flex-col">
            <div class="bg-slate-900 px-6 py-4">
                <h3 class="text-xl font-bold text-white m-0">{{trans('lang.change_password')}}</h3>
            </div>
            <div class="p-6 bg-white flex flex-col gap-5 flex-grow">
                <div class="flex flex-col gap-6 flex-grow">
                    {{-- Stare hasło --}}
                    <div>
                        <label class="text-sm text-slate-700 font-medium">{{trans('lang.old_password')}}</label>
                        <div class="relative">
                            <input :type="passwordVisibility.old ? 'text' : 'password'" x-model="password.old" @blur="validateField('passwordOld')"
                                class="border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50 pr-10"
                                :class="{ '!border-red-500': errors.passwordOld }" autocomplete="current-password">
                            <button type="button" @click="passwordVisibility.old = !passwordVisibility.old" class="absolute inset-y-0 right-0 px-3 flex items-center text-slate-500 hover:text-slate-700 focus:outline-none focus:ring-0">
                                <i class="fa-solid" :class="passwordVisibility.old ? 'fa-eye-slash' : 'fa-eye'"></i>
                            </button>
                        </div>
                        <span x-show="errors.passwordOld" x-text="errors.passwordOld" class="text-red-500 text-sm mt-1" x-transition></span>
                    </div>
                    {{-- Nowe hasło --}}
                    <div>
                        <label class="text-sm text-slate-700 font-medium">{{trans('lang.new_password')}}</label>
                        <div class="relative">
                            <input :type="passwordVisibility.new ? 'text' : 'password'" x-model="password.new" @input="validatePasswordRealtime()"
                                class="border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50 pr-10"
                                :class="{ '!border-red-500': passwordStrength.score > 0 && passwordStrength.score < 4 }" autocomplete="new-password">
                            <button type="button" @click="passwordVisibility.new = !passwordVisibility.new" class="absolute inset-y-0 right-0 px-3 flex items-center text-slate-500 hover:text-slate-700 focus:outline-none focus:ring-0">
                                <i class="fa-solid" :class="passwordVisibility.new ? 'fa-eye-slash' : 'fa-eye'"></i>
                            </button>
                        </div>
                        
                        <div class="mt-3 space-y-3" x-show="password.new.length > 0" x-transition>
                            <div class="flex items-center gap-2">
                                <div class="w-full bg-slate-200 rounded-full h-2">
                                    <div class="h-2 rounded-full transition-all"
                                         :class="{
                                            'bg-red-500 w-1/4': passwordStrength.score <= 1,
                                            'bg-orange-500 w-2/4': passwordStrength.score === 2,
                                            'bg-yellow-500 w-3/4': passwordStrength.score === 3,
                                            'bg-green-500 w-full': passwordStrength.score >= 4,
                                         }"></div>
                                </div>
                                <span class="text-sm font-semibold"
                                      :class="{
                                        'text-red-500': passwordStrength.score <= 1,
                                        'text-orange-500': passwordStrength.score === 2,
                                        'text-yellow-500': passwordStrength.score === 3,
                                        'text-green-500': passwordStrength.score >= 4,
                                      }"
                                      x-text="passwordStrength.text"></span>
                            </div>
                            <div class="grid grid-cols-1 sm:grid-cols-2 text-sm">
                                <div class="flex items-center gap-2" :class="passwordRequirements.length ? 'text-green-600' : 'text-slate-500'">
                                    <i class="fa-solid fa-sm" :class="passwordRequirements.length ? 'fa-check' : 'fa-times'"></i>
                                    <span>{{ trans('lang.password_req_length') }}</span>
                                </div>
                                <div class="flex items-center gap-2" :class="passwordRequirements.uppercase ? 'text-green-600' : 'text-slate-500'">
                                    <i class="fa-solid fa-sm" :class="passwordRequirements.uppercase ? 'fa-check' : 'fa-times'"></i>
                                    <span>{{ trans('lang.password_req_uppercase') }}</span>
                                </div>
                                <div class="flex items-center gap-2" :class="passwordRequirements.lowercase ? 'text-green-600' : 'text-slate-500'">
                                    <i class="fa-solid fa-sm" :class="passwordRequirements.lowercase ? 'fa-check' : 'fa-times'"></i>
                                    <span>{{ trans('lang.password_req_lowercase') }}</span>
                                </div>
                                <div class="flex items-center gap-2" :class="passwordRequirements.number ? 'text-green-600' : 'text-slate-500'">
                                    <i class="fa-solid fa-sm" :class="passwordRequirements.number ? 'fa-check' : 'fa-times'"></i>
                                    <span>{{ trans('lang.password_req_number') }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div>
                         <label class="text-sm text-slate-700 font-medium">{{trans('lang.confirm_password')}}</label>
                         <div class="relative">
                            <input :type="passwordVisibility.confirm ? 'text' : 'password'" x-model="password.confirm" @input="validateConfirmation()"
                                   class="border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50 pr-10"
                                   :class="{ '!border-red-500': passwordConfirmationError }" autocomplete="new-password">
                            <button type="button" @click="passwordVisibility.confirm = !passwordVisibility.confirm" class="absolute inset-y-0 right-0 px-3 flex items-center text-slate-500 hover:text-slate-700 focus:outline-none focus:ring-0">
                                <i class="fa-solid" :class="passwordVisibility.confirm ? 'fa-eye-slash' : 'fa-eye'"></i>
                            </button>
                        </div>
                        <span x-show="passwordConfirmationError" x-text="passwordConfirmationError" class="text-red-500 text-sm mt-1" x-transition></span>
                    </div>
                </div>
                {{-- Przycisk zmiany hasła --}}
                <button type="button" @click="changePassword" :disabled="isPasswordFormInvalid"
                        class="uppercase w-full mt-auto bg-blue-500 text-white px-4 py-2 rounded hover:opacity-90 transition disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-0">
                    {{trans('lang.change_password')}}
                </button>
            </div>
        </div>
    </div>

    {{-- Powiadomienia Toast --}}
    <div x-show="notification.show" x-transition class="fixed top-5 right-5 z-50 max-w-lg w-full rounded-lg shadow-lg pointer-events-auto" :class="{ 'bg-green-100 border-l-4 border-green-500': notification.type === 'success', 'bg-red-100 border-l-4 border-red-500': notification.type === 'error' }" style="display: none;">
        <div class="p-4">
            <div class="grid grid-cols-[auto,1fr,auto] items-center gap-x-3">
                <div class="flex-shrink-0">
                    <i x-show="notification.type === 'success'"
                        class="fa-solid fa-check-circle text-green-500 text-xl"></i>
                    <i x-show="notification.type === 'error'"
                        class="fa-solid fa-times-circle text-red-500 text-xl"></i>
                </div>
                <div>
                    <p class="text-sm font-medium break-words"
                        :class="{ 'text-green-800': notification.type === 'success', 'text-red-800': notification.type === 'error' }"
                        x-text="notification.message"></p>
                </div>
                <div class="flex-shrink-0">
                    <button @click="notification.show = false" class="inline-flex text-slate-500 hover:text-slate-600 focus:outline-none focus:ring-0">
                        <span class="sr-only">{{ trans('lang.close') }}</span>
                        <i class="fa-solid fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>

  </div>
</div>
@endsection

@section('scripts')
<script src="https://cdnjs.cloudflare.com/ajax/libs/compressorjs/1.1.1/compressor.min.js"></script>
<script>
function profileManager() {
    return {
        // --- STAN ---
        processing: true,
        notification: { show: false, type: 'success', message: '' },
        errors: {},
        imagePreview: null,
        isUploading: false,
        uploadProgress: 0,
        uploadError: '',
        isDragging: false,
        uploadTask: null,
        passwordVisibility: { old: false, new: false, confirm: false },
        passwordRequirements: { length: false, uppercase: false, lowercase: false, number: false },
        passwordStrength: { score: 0, text: '' },
        passwordConfirmationError: '',
        vendorUserId: "<?php echo $id; ?>",
        ownerId: null,
        user: { firstName: '', lastName: '', email: '', phone: '', phonePrefix: '+49', profilePicUrl: '' },
        password: { old: '', new: '', confirm: '' },
        originalUser: {},
        
        // --- WŁAŚCIWOŚCI OBLICZENIOWE ---
        get isProfileUnchanged() { return JSON.stringify(this.user) === JSON.stringify(this.originalUser); },
        get isProfileFormInvalid() {
            return !!(this.errors.firstName || this.errors.lastName || this.errors.phone);
        },
        get isPasswordFormInvalid() { 
            const allReqsMet = Object.values(this.passwordRequirements).every(val => val === true);
            return !this.password.old || !allReqsMet || this.password.new !== this.password.confirm;
        },
        
        // --- METODY ---
        triggerFileInput() { document.getElementById('profilePicInput').click(); },
        removeImage() {
            this.user.profilePicUrl = '';
            this.imagePreview = null;
            document.getElementById('profilePicInput').value = '';
            
            // Aktualizuj avatar w headerze po usunięciu zdjęcia
            Alpine.store('user').avatar = '{{ asset('images/icons/account_icon.svg') }}';
        },
        cancelUpload() {
            if (this.uploadTask) { this.uploadTask.cancel(); }
            this.isUploading = false; this.uploadProgress = 0; this.imagePreview = null;
        },
        selectFile(file) {
            if (!file) { this.uploadError = ''; return; }
            const allowedTypes = ['image/png', 'image/jpeg', 'image/webp'];
            if (!allowedTypes.includes(file.type)) {
                this.uploadError = '{{ trans("lang.uploader_file_type_error") }}'; return;
            }
            const maxSizeInMB = 5;
            if (file.size > maxSizeInMB * 1024 * 1024) { this.uploadError = `{{ trans("lang.uploader_file_size_error") }} ${maxSizeInMB}MB.`; return; }
            this.uploadError = '';
            this.imagePreview = URL.createObjectURL(file);
            this.startUpload(file);
        },
        startUpload(file) {
            this.isUploading = true; this.uploadProgress = 0;
            new Compressor(file, {
                quality: 0.8, maxWidth: 1024,
                success: (compressedResult) => {
                    const storageRef = firebase.storage().ref();
                    const fileName = `profile_${this.ownerId || 'new'}_${Date.now()}`;
                    this.uploadTask = storageRef.child(`images/${fileName}`).put(compressedResult);
                    this.uploadTask.on('state_changed', (snapshot) => {
                        this.uploadProgress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                    }, (error) => {
                        if (error.code !== 'storage/canceled') { this.showNotification('{{ trans("lang.upload_error") }}: ' + error.message, 'error'); }
                        this.isUploading = false; this.imagePreview = null;
                    }, () => {
                        this.uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => {
                            this.user.profilePicUrl = downloadURL;
                            this.isUploading = false; this.imagePreview = null;
                            
                            // Aktualizuj avatar w headerze po przesłaniu zdjęcia
                            Alpine.store('user').avatar = downloadURL;
                            
                            this.showNotification('{{ trans("lang.photo_updated_success") }}', 'success');
                        });
                    });
                },
                error: (err) => { this.showNotification('{{ trans("lang.compression_error") }}: ' + err.message, 'error'); this.isUploading = false; },
            });
        },
        validateField(field) {
            switch(field) {
                case 'firstName':
                    if (!this.user.firstName.trim()) {
                        this.errors.firstName = '{{ trans("lang.first_name_error") }}';
                    } else if (/[^\p{L}\s-]/u.test(this.user.firstName)) {
                        this.errors.firstName = '{{ trans("lang.first_name_invalid_error") }}';
                    } else { delete this.errors.firstName; }
                    break;
                case 'lastName':
                    if (!this.user.lastName.trim()) {
                        this.errors.lastName = '{{ trans("lang.last_name_error") }}';
                    } else if (/[^\p{L}\s-]/u.test(this.user.lastName)) {
                        this.errors.lastName = '{{ trans("lang.last_name_invalid_error") }}';
                    } else { delete this.errors.lastName; }
                    break;
                case 'phone':
                    const phoneRegex = /^\d{7,15}$/;
                    const cleanedPhone = this.user.phone.replace(/\s/g, '');
                    if (!cleanedPhone) { this.errors.phone = '{{ trans("lang.phone_number_error") }}'; }
                    else if (!phoneRegex.test(cleanedPhone)) { this.errors.phone = '{{ trans("lang.phone_number_invalid_error") }}'; }
                    else { delete this.errors.phone; }
                    break;
                case 'passwordOld':
                    if (!this.password.old) this.errors.passwordOld = '{{ trans("lang.old_password_error") }}';
                    else delete this.errors.passwordOld;
                    break;
            }
        },
        validatePasswordRealtime() {
            const pass = this.password.new;
            this.passwordRequirements.length = pass.length >= 8;
            this.passwordRequirements.uppercase = /[A-Z]/.test(pass);
            this.passwordRequirements.lowercase = /[a-z]/.test(pass);
            this.passwordRequirements.number = /[0-9]/.test(pass);
            let score = Object.values(this.passwordRequirements).filter(Boolean).length;
            this.passwordStrength.score = score;
            const strengthLevels = {
                0: '{{ trans("lang.password_strength_very_weak") }}', 1: '{{ trans("lang.password_strength_weak") }}',
                2: '{{ trans("lang.password_strength_medium") }}', 3: '{{ trans("lang.password_strength_strong") }}',
                4: '{{ trans("lang.password_strength_very_strong") }}',
            };
            this.passwordStrength.text = strengthLevels[score] || '';
            this.validateConfirmation();
        },
        validateConfirmation() {
            if (this.password.confirm && this.password.new !== this.password.confirm) {
                this.passwordConfirmationError = '{{ trans("lang.confirm_password_error") }}';
            } else { this.passwordConfirmationError = ''; }
        },
        showNotification(message, type = 'success', duration = 4000) {
            this.notification.message = message;
            this.notification.type = type;
            this.notification.show = true;
            setTimeout(() => { this.notification.show = false; }, duration);
        },
        async initFirebase() {
            this.processing = true;
            try {
                const userSnap = await database.collection('users').where('id', '==', this.vendorUserId).get();
                if (userSnap.empty) throw new Error(`Użytkownik o ID ${this.vendorUserId} nie został znaleziony.`);
                const vendorID = userSnap.docs[0].data().vendorID;
                if (!vendorID) throw new Error(`Użytkownik ${this.vendorUserId} nie ma przypisanego vendorID.`);
                const vendorSnap = await database.collection('vendors').where('id', '==', vendorID).get();
                if (vendorSnap.empty) throw new Error(`Vendor o ID ${vendorID} nie został znaleziony.`);
                const ownerId = vendorSnap.docs[0].data().author;
                if (!ownerId) throw new Error(`Vendor ${vendorID} nie ma przypisanego autora.`);
                this.ownerId = ownerId;
                const ownerSnap = await database.collection('users').where('id', '==', ownerId).get();
                if (ownerSnap.empty) throw new Error(`Właściciel o ID ${ownerId} nie został znaleziony.`);
                const ownerData = ownerSnap.docs[0].data();
                this.user = {
                    firstName: ownerData.firstName || '',
                    lastName: ownerData.lastName || '',
                    email: ownerData.email || '',
                    phone: ownerData.phoneNumber || '',
                    phonePrefix: '+49',
                    profilePicUrl: ownerData.profilePictureURL || ''
                };
                this.originalUser = JSON.parse(JSON.stringify(this.user));
            } catch (error) {
                this.showNotification(`{{ trans("lang.data_load_error") }}: ` + error.message, 'error');
                console.error(error);
            } finally {
                this.processing = false;
                if (document.activeElement) { document.activeElement.blur(); }
            }
        },
        async saveProfile() {
            this.validateField('firstName'); this.validateField('lastName'); this.validateField('phone');
            if (Object.keys(this.errors).length > 0) {
                this.showNotification('{{ trans("lang.form_errors_correct_them") }}', 'error'); return;
            }
            if (this.isProfileUnchanged) return;
            this.processing = true;
            try {
                const dataToUpdate = {
                    firstName: this.user.firstName,
                    lastName: this.user.lastName,
                    phoneNumber: this.user.phone,
                    phoneNumberPrefix: '+49',
                    profilePictureURL: this.user.profilePicUrl,
                };
                await database.collection('users').doc(this.ownerId).update(dataToUpdate);
                this.originalUser = JSON.parse(JSON.stringify(this.user));
                
                // Aktualizuj avatar w headerze bez przeładowania strony
                if (this.user.profilePicUrl) {
                    Alpine.store('user').avatar = this.user.profilePicUrl;
                } else {
                    // Jeśli zdjęcie zostało usunięte, ustaw domyślny avatar
                    Alpine.store('user').avatar = '{{ asset('images/icons/account_icon.svg') }}';
                }
                
                this.showNotification('{{ trans("lang.profile_saved_success") }}', 'success');
            } catch (error) {
                this.showNotification(`{{ trans("lang.data_save_error") }}: ` + error.message, 'error');
            } finally {
                this.processing = false;
            }
        },
        changePassword() {
            if (this.isPasswordFormInvalid) {
                this.showNotification('{{ trans("lang.form_errors_correct_them") }}', 'error'); return;
            }
            const user = firebase.auth().currentUser;
            const credential = firebase.auth.EmailAuthProvider.credential(user.email, this.password.old);
            this.processing = true;
            user.reauthenticateWithCredential(credential).then(() => {
                return user.updatePassword(this.password.new);
            }).then(() => {
                this.showNotification('{{ trans("lang.password_changed_success") }}', 'success');
                this.password = { old: '', new: '', confirm: '' };
                this.validatePasswordRealtime();
            }).catch((error) => {
                this.showNotification(`{{ trans("lang.password_change_error") }}: ` + error.message, 'error');
            }).finally(() => {
                this.processing = false;
            });
        }
    }
}
</script>
@endsection