{{--
|--------------------------------------------------------------------------
| Plik Widoku: Edycja Pozycji Menu
|--------------------------------------------------------------------------
|
| Lokalizacja: resources/views/foods/edit.blade.php
| Autor: Tomasz Kaplanski & Coding Partner (Gemini)
| Wersja: 2.1 (Refaktoryzacja z modularnym zapisem)
| Ostatnia modyfikacja: 6 Lipca 2024
|
|--------------------------------------------------------------------------
| Opis Przeznaczenia
|--------------------------------------------------------------------------
|
| Ten plik Blade renderuje w pełni interaktywny, jednostronicowy interfejs
| (Single Page Application-like experience) do edycji istniejącej pozycji menu.
| Cała logika formularza jest zarządzana przez Alpine.js, co minimalizuje
| interakcje z serwerem. Kluczową cechą jest modularność, pozwalająca na
| niezależne zapisywanie poszczególnych sekcji formularza (Szczegóły,
| Ustawienia, Opcje), co znacząco poprawia doświadczenie użytkownika (UX).
|
|--------------------------------------------------------------------------
| Kluczowe Funkcjonalności
|--------------------------------------------------------------------------
|
| - Asynchroniczne ładowanie danych produktu z Firestore na podstawie ID z trasy.
| - Modularny zapis: Niezależne przyciski "Zapisz" dla każdej z trzech głównych
|   sekcji, aktywowane tylko po wykryciu zmian ("dirty state").
| - Sekcja "Szczegóły": Edycja nazwy, ceny, opisu i zdjęcia produktu.
| - Zaawansowany uploader zdjęć: Obsługa "Przeciągnij i Upuść", podgląd na żywo,
|   kompresja po stronie klienta (Compressor.js) i pasek postępu.
| - Sekcja "Ustawienia": Dynamiczne pola wyboru (subkategoria, stawka podatkowa)
|   oraz przełączniki (publikacja, ograniczenie wiekowe).
| - Kreator "Grup Opcji":
|   - Dynamiczne dodawanie/usuwanie grup i opcji wewnątrz nich.
|   - Definiowanie typu wyboru (pojedynczy/wielokrotny) i wymagania grupy.
|   - Ustawianie limitów (min/max) dla wyboru wielokrotnego.
|   - Przypisywanie indywidualnej ceny i stawki podatkowej do każdej opcji.
| - Walidacja formularza w czasie rzeczywistym po stronie klienta dla każdej sekcji.
| - System powiadomień "toast" informujący o sukcesie lub błędach zapisu.
|
|--------------------------------------------------------------------------
| Stos Technologiczny
|--------------------------------------------------------------------------
|
| - Backend: Laravel (silnik szablonów Blade)
| - Frontend (Interaktywność): Alpine.js
| - Frontend (Style): Tailwind CSS
| - Baza Danych: Google Firebase (Firestore)
| - Biblioteki dodatkowe: Compressor.js (do kompresji obrazów)
|
|--------------------------------------------------------------------------
| Zależności
|--------------------------------------------------------------------------
|
| - Poprawnie zdefiniowane nazwane trasy (routes) w Laravelu: 'foods', 'foods.edit'.
| - Skonfigurowany dostęp do bazy danych Firestore (globalnie dostępny obiekt `database`).
| - Dołączone biblioteki JavaScript w głównym szablonie: Alpine.js, Compressor.js.
| - System tłumaczeń Laravela (`trans()`) używany w całym pliku.
|
--}}
@extends('layouts.app')

@section('content')

{{-- Import stylów i skryptów --}}
<script src="https://kit.fontawesome.com/4b4effb0ed.js" crossorigin="anonymous"></script>

{{-- Główny kontener aplikacji, inicjalizujący komponent Alpine.js --}}
<div id="main-wrapper" class="p-10 min-h-screen"
    x-data="editProductAlpine()" x-init="initForm()">

    {{-- Loader wyświetlany podczas operacji asynchronicznych (ładowanie, zapis) --}}
    <div x-show="isLoading || isSavingDetails || isSavingSettings || isSavingOptions"
        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" x-text="savingMessage"></span>
        </div>
    </div>

    {{-- Kontener na błędy krytyczne, które mogą wystąpić podczas ładowania danych --}}
    <div x-show="errorMessage" class="w-full text-center p-10 bg-white rounded-lg shadow-md" style="display: none;">
        <h3 class="text-xl font-bold text-red-600">{{ trans('lang.error') }}</h3>
        <p class="text-slate-600 mt-2" x-text="errorMessage"></p>
    </div>

    {{-- Główny kontener formularza, widoczny po pomyślnym załadowaniu danych --}}
    <div x-show="!errorMessage && !isLoading" class="flex flex-col gap-8" style="display: none;">

        {{-- Nagłówek strony z tytułem i 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.edit_menu_item') !!}</h3>
                <p class="text-sm text-slate-200 mt-1 m-0">{!! trans('lang.edit_menu_item_desc') !!}</p>
            </div>
            <a href="{!! route('foods') !!}"
                class="px-4 py-2 rounded-md bg-white text-slate-700 text-base hover:bg-slate-100 hover:no-underline hover:text-slate-700 transition focus:outline-none focus:ring-0 flex items-center gap-2">
                <i class="fa fa-rotate-left"></i>
                {{ trans('lang.go_back_to_menu') }}
            </a>
        </div>

        {{-- Główny kontener na karty formularza, ułożone w pionie --}}
        <div class="flex flex-col gap-8">

            {{-- GÓRNY WIERSZ: Siatka zawierająca dwie karty obok siebie na większych ekranach --}}
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">

                {{-- KARTA 1: SZCZEGÓŁY PRODUKTU --}}
                <div
                    class="rounded-lg border !border-slate-300 shadow-[1px_1px_4px_0px_#e2e8f0] overflow-hidden flex flex-col">

                    {{-- Nagłówek karty z tytułem --}}
                    <div class="bg-slate-900 px-6 py-4">
                        <h3 class="text-xl font-bold text-white m-0">{{ trans('lang.item_details') }}</h3>
                    </div>

                    {{-- Główna zawartość karty z formularzem edycji produktu --}}
                    <div class="p-6 bg-white flex flex-col gap-5 flex-grow">

                        {{-- Szczegóły produktu --}}
                        <div class="w-full">
                            <label class="text-sm text-slate-700 font-medium">{{trans('lang.food_name')}}</label>
                            <input type="text" x-model="product.name" @input.debounce.500ms="validate('details')"
                                class="border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:bg-blue-50"
                                :class="{'!border-red-500': errors.name}">
                            <p x-show="errors.name" x-text="errors.name" class="text-sm text-red-600 mt-1"></p>
                        </div>

                        {{-- Cena produktu --}}
                        <div class="w-full">
                            <label class="text-sm text-slate-700 font-medium">{{trans('lang.food_price')}}</label>
                            <div class="flex rounded-lg shadow-sm border !border-slate-300 overflow-hidden"
                                :class="{'!border-red-500': errors.price}">
                                <span
                                    class="inline-flex items-center px-3 rounded-l-lg border-r border-slate-300 bg-slate-50 text-slate-500 sm:text-sm">€</span>
                                <input type="number" step="0.01" x-model.number="product.price"
                                    @input="validate('details')"
                                    class="no-spinners py-2 px-3 w-full transition duration-150 focus:outline-none focus:bg-blue-50 focus:ring-0 border-0">
                                <div class="flex flex-col border-l border-slate-300">
                                    <button @click="adjustNumber(product, 'price', 0.01); validate('details')"
                                        type="button"
                                        class="flex-1 px-2 text-slate-500 hover:bg-slate-100 border-b border-slate-300 focus:outline-none"><i
                                            class="fa-solid fa-chevron-up text-xs"></i></button>
                                    <button @click="adjustNumber(product, 'price', -0.01); validate('details')"
                                        type="button"
                                        class="flex-1 px-2 text-slate-500 hover:bg-slate-100 focus:outline-none"><i
                                            class="fa-solid fa-chevron-down text-xs"></i></button>
                                </div>
                            </div>
                            <p x-show="errors.price" x-text="errors.price" class="text-sm text-red-600 mt-1"></p>
                        </div>

                        {{-- Opis produktu --}}
                        <div class="w-full">
                            <label
                                class="text-sm text-slate-700 font-medium">{{trans('lang.food_description')}}</label>
                            <textarea rows="5" x-model="product.description"
                                @input="if (product.description.length > descriptionCharLimit) product.description = product.description.substring(0, descriptionCharLimit)"
                                class="border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:bg-blue-50"></textarea>
                            <div class="text-right text-xs text-slate-500 mt-1"
                                :class="{'!text-red-600 font-semibold': product.description.length >= descriptionCharLimit}">
                                <span x-text="product.description.length"></span> / <span
                                    x-text="descriptionCharLimit"></span>
                            </div>
                        </div>
                        
                        {{-- Zdjęcie produktu --}}
                        <div class="w-full">
                            <label class="text-sm text-slate-700 font-medium">{{ trans('lang.restaurant_image')
                                }}</label>
                            <div class="mt-2">
                                <input type="file" @change="selectFile($event.target.files[0])" id="product_image_input"
                                    class="hidden" accept="image/png, image/jpeg, image/webp">

                                <template x-if="!isUploading && product.photo">
                                    <div class="flex items-center gap-4">
                                        <img :src="imagePreview" alt="Podgląd produktu"
                                            class="w-32 h-32 rounded-lg object-cover border-2 border-slate-200">
                                        <div class="flex flex-col gap-3">
                                            <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">
                                                <i class="fa-solid fa-pencil text-xs"></i>
                                                <span>{{ trans('lang.change_photo') }}</span>
                                            </button>
                                            <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">
                                                <i class="fa-solid fa-trash text-xs"></i>
                                                <span>{{ trans('lang.remove_photo') }}</span>
                                            </button>
                                        </div>
                                    </div>
                                </template>

                                <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">
                                            {{ trans('lang.cancel') }}
                                        </button>
                                    </div>
                                </template>

                                <template x-if="!isUploading && !product.photo">
                                    <div @click="triggerFileInput()" @dragover.prevent="isDragging = true"
                                        @dragleave.prevent="isDragging = false"
                                        @drop.prevent="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 szczegółów produktu --}}
                    <div class="p-4 bg-slate-50 border-t border-slate-200 text-right">
                        <button @click="saveDetails()" :disabled="!isDetailsDirty || isSavingDetails || isUploading"
                            class="uppercase w-full bg-blue-500 text-white px-4 py-2 rounded hover:opacity-90 transition disabled:opacity-50 disabled:cursor-not-allowed">
                            <span x-show="!isSavingDetails">{{ trans('lang.save_details') }}</span>
                            <span x-show="isSavingDetails"><i class="fa-solid fa-spinner fa-spin"></i>
                                {{ trans('lang.saving') }}</span>
                        </button>
                    </div>
                </div>

                
                {{-- KARTA 2: USTAWIENIA --}}
                <div class="rounded-lg border !border-slate-300 shadow-[1px_1px_4px_0px_#e2e8f0] overflow-hidden flex flex-col">

                    {{-- Nagłówek karty --}}
                    <div class="bg-slate-900 px-6 py-4">
                        <h3 class="text-xl font-bold text-white m-0">{{ trans('lang.settings') }}</h3>
                    </div>

                    {{-- Główna zawartość karty z formularzem ustawień --}}
                    <div class="p-6 bg-white flex flex-col gap-5 flex-grow">

                        {{-- Subkategoria --}}
                        <div class="w-full">
                            <label
                                class="text-sm text-slate-700 font-medium">{{trans('lang.subcategory_title')}}
                            </label>
                            {{-- Dropdown dla subkategorii --}}
                            <div class="relative">
                                <button type="button"
                                    @click="openDropdown = (openDropdown === 'subcategory' ? null : 'subcategory')"
                                    class="relative w-full text-left cursor-pointer rounded-lg border !border-slate-300 py-2 px-3 transition duration-150 focus:outline-none focus:ring-0 text-base"
                                    :class="{'!border-red-500': errors.subcategoryId, 'bg-blue-50': openDropdown === 'subcategory', 'bg-white': openDropdown !== 'subcategory' }">
                                    <span class="block truncate" x-text="selectedSubcategoryName"></span>
                                    <span
                                        class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2"><i
                                            class="fa-solid fa-chevron-down text-xs text-gray-400 transition-transform" :class="{'rotate-180': openDropdown === 'subcategory'}"></i></span>
                                </button>
                                <ul x-show="openDropdown === 'subcategory'" @click.away="openDropdown = null"
                                    x-transition
                                    class="absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-lg bg-white shadow-lg border !border-slate-300 overflow-hidden"
                                    style="display:none;">
                                    <li @click="product.subcategoryId = ''; openDropdown = null; validate('settings')"
                                        class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap">
                                        <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="!product.subcategoryId ? 'opacity-100' : 'opacity-0'"></i>
                                        <span>{{trans('lang.subcategory_select')}}</span>
                                    </li>
                                    <template x-for="cat in subcategories" :key="cat.id">
                                        <li @click="product.subcategoryId = cat.id; openDropdown = null; validate('settings')"
                                            class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap">
                                            <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="product.subcategoryId === cat.id ? 'opacity-100' : 'opacity-0'"></i>
                                            <span x-text="cat.name"></span>
                                        </li>
                                    </template>
                                </ul>
                            </div>
                            <p x-show="errors.subcategoryId" x-text="errors.subcategoryId"
                                class="text-sm text-red-600 mt-1"></p>
                        </div>

                        {{-- Stawka podatkowa --}}
                        <div class="w-full">
                            <label
                                class="text-sm text-slate-700 font-medium">{{trans('lang.tax_rate_title')}}</label>
                            <div class="relative">
                                <button type="button"
                                    @click="openDropdown = (openDropdown === 'tax_rate' ? null : 'tax_rate')"
                                    class="relative w-full text-left cursor-pointer rounded-lg border !border-slate-300 py-2 px-3 transition duration-150 focus:outline-none focus:ring-0 text-base"
                                    :class="{'!border-red-500': errors.taxId, 'bg-blue-50': openDropdown === 'tax_rate', 'bg-white': openDropdown !== 'tax_rate'}">
                                    <span class="block truncate" x-text="selectedTaxRateName"></span>
                                    <span class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                                        <i class="fa-solid fa-chevron-down text-xs text-gray-400 transition-transform" :class="{'rotate-180': openDropdown === 'tax_rate'}"></i></span>
                                </button>
                                <ul x-show="openDropdown === 'tax_rate'" @click.away="openDropdown = null"
                                    x-transition
                                    class="absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-lg bg-white shadow-lg border !border-slate-300 overflow-hidden"
                                    style="display:none;">
                                    <li @click="product.taxId = ''; openDropdown = null; validate('settings')"
                                        class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap">
                                        <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="!product.taxId ? 'opacity-100' : 'opacity-0'"></i>
                                        <span>{{trans('lang.tax_rate_select')}}</span>
                                    </li>
                                    <template x-for="tax in taxRates" :key="tax.id">
                                        <li @click="product.taxId = tax.id; openDropdown = null; validate('settings')"
                                            class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap">
                                            <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="product.taxId === tax.id ? 'opacity-100' : 'opacity-0'"></i>
                                            <span x-text="formatTaxTitle(tax)"></span>
                                        </li>
                                    </template>
                                </ul>
                            </div>
                            <p x-show="errors.taxId" x-text="errors.taxId" class="text-sm text-red-600 mt-1"></p>
                        </div>

                        {{-- Miejsce docelowe drukarki --}}
                        <div class="w-full">
                            <label
                                class="text-sm text-slate-700 font-medium">{{trans('lang.printer_destination')}}</label>
                            <div class="relative">
                                <button type="button"
                                    @click="openDropdown = (openDropdown === 'printer' ? null : 'printer')"
                                    class="relative w-full text-left cursor-pointer rounded-lg border !border-slate-300 py-2 px-3 transition duration-150 focus:outline-none focus:ring-0 text-base"
                                    :class="{'bg-blue-50': openDropdown === 'printer', 'bg-white': openDropdown !== 'printer'}">
                                    <span class="block truncate" x-text="selectedPrinterDestinationLabel"></span>

                                    <span
                                        class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2"><i
                                            class="fa-solid fa-chevron-down text-xs text-gray-400 transition-transform" :class="{'rotate-180': openDropdown === 'printer'}"></i></span>
                                </button>
                                <ul x-show="openDropdown === 'printer'" @click.away="openDropdown = null"
                                    x-transition
                                    class="absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-lg bg-white shadow-lg border !border-slate-300 overflow-hidden"
                                    style="display:none;">

                                    <template x-for="dest in printerDestinations" :key="dest.value">
                                        <li @click="product.printerDestination = dest.value; openDropdown = null"
                                            class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap">
                                            <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="product.printerDestination === dest.value ? 'opacity-100' : 'opacity-0'"></i>
                                            <span x-text="dest.label"></span>
                                        </li>
                                    </template>
                                </ul>
                            </div>
                        </div>
                        
                        {{-- Widoczność produktu --}}
                        <div class="mt-3 p-3 bg-slate-50 rounded-md border border-slate-300 flex flex-col space-y-2">
                            <div class="flex justify-between items-center">
                                <label class="font-semibold text-slate-700">{{ trans('lang.food_publish') }}</label>
                                <label class="inline-flex items-center cursor-pointer">
                                    <input type="checkbox" x-model="product.publish" class="sr-only peer">
                                    <div class="relative w-11 h-6 bg-slate-300 rounded-full peer-checked:bg-blue-500 transition-colors 
                                        after:content-[''] after:absolute after:top-0.5 after:left-[2px] 
                                        after:bg-white after:border after:border-slate-300 after:rounded-full 
                                        after:h-5 after:w-5 after:transition-all peer-checked:after:translate-x-full 
                                        peer-checked:after:border-white">
                                    </div>
                                </label>
                            </div>
                            <p class="text-xs text-slate-600">
                                {{ trans('lang.food_publish_info') }}
                            </p>
                        </div>

                        {{-- Ograniczenie wiekowe --}}
                        <div class="mt-3 p-3 bg-slate-50 rounded-md border !border-slate-300 flex flex-col space-y-2">
                            <div class="flex justify-between items-center">
                                <label class="font-semibold text-slate-700">{{ trans('lang.alcohol_age_restriction')
                                    }}</label>
                                <label class="inline-flex items-center cursor-pointer">
                                    <input type="checkbox" x-model="product.ageRestriction" class="sr-only peer">
                                    <div class="relative w-11 h-6 bg-slate-300 rounded-full peer-checked:bg-red-500 transition-colors
                                        after:content-[''] after:absolute after:top-0.5 after:left-[2px]
                                        after:bg-white after:border after:border-slate-300
                                        after:rounded-full after:h-5 after:w-5 after:transition-all
                                        peer-checked:after:translate-x-full peer-checked:after:border-white">
                                    </div>
                                </label>
                            </div>
                            <p class="text-xs text-slate-600">
                                {{ trans('lang.alcohol_age_restriction_info') }}
                            </p>
                        </div>

                    </div>

                    {{-- Przycisk zapisu ustawień --}}
                    <div class="p-4 bg-slate-50 border-t border-slate-200 text-right">
                        <button @click="saveSettings()" :disabled="!isSettingsDirty || isSavingSettings"
                            class="uppercase w-full bg-blue-500 text-white px-4 py-2 rounded hover:opacity-90 transition disabled:opacity-50 disabled:cursor-not-allowed">
                            <span x-show="!isSavingSettings">{{ trans('lang.save_settings') }}</span>
                            <span x-show="isSavingSettings"><i class="fa-solid fa-spinner fa-spin"></i>
                                {{ trans('lang.saving') }}</span>
                        </button>
                    </div>

                </div>
            </div>

            {{-- KARTA 3: GRUPY OPCJI --}}
            <div
                class="rounded-lg border !border-slate-300 shadow-[1px_1px_4px_0px_#e2e8f0] overflow-hidden flex flex-col lg:col-span-2">

                {{-- Nagłówek karty z tytułem i przyciskiem dodawania grupy --}}
                <div class="bg-slate-900 px-6 py-4 flex justify-between items-center">
                    <div>
                        <h3 class="text-xl font-bold text-white m-0">{!!trans('lang.item_extras_group')!!}</h3>
                    </div>
                    <button @click="addGroup()" type="button"
                        class="flex items-center space-x-2 px-3 py-2 text-base bg-white text-slate-800 rounded-md hover:bg-slate-100 transition whitespace-nowrap">
                        <i class="fa-solid fa-plus text-xs"></i><span>{{trans('lang.options_group_add')}}</span>
                    </button>
                </div>

                {{-- Miejsce na grupy opcji --}}
                <div class="p-6 bg-white flex flex-col gap-6 flex-grow">
                    <template x-for="(group, groupIndex) in product.options" :key="groupIndex">
                        <div class="p-4 border !border-slate-300 rounded-lg bg-slate-50/80"
                            :class="{'!border-red-500': errors.options[groupIndex]?.hasError}">

                            {{-- Nagłówek grupy z tytułem i przyciskiem usuwania --}}
                            <div class="flex flex-col md:flex-row items-end gap-4 pb-4">
                                <div class="flex-grow w-full">

                                    {{-- Tytuł grupy --}}
                                    <label class="text-xs text-slate-500 font-semibold">{{ trans('lang.group_title')
                                        }}
                                    </label>

                                    {{-- Pole tekstowe dla tytułu grupy --}}
                                    <input type="text" x-model="group.title" @input.debounce.500ms="validate('options')"
                                        class="border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:bg-blue-50"
                                        :class="{'!border-red-500': errors.options[groupIndex]?.title}">

                                    {{-- Komunikat o błędzie dla tytułu grupy --}}
                                    <p x-show="errors.options[groupIndex]?.title"
                                        x-text="errors.options[groupIndex]?.title" class="text-sm text-red-600 mt-1">
                                    </p>
                                </div>

                                {{-- Przycisk usuwania grupy --}}
                                <div>
                                    <button @click="removeGroup(groupIndex)" type="button"
                                        class="flex h-10 w-10 items-center justify-center rounded-lg text-slate-400 hover:bg-red-100 hover:text-red-600 transition"
                                       title="{{ trans('lang.remove_group') }}"><i class="fa-solid fa-trash"></i></button>
                                </div>
                            </div>

                            {{-- Opcje grupy --}}
                            <div class="flex flex-col lg:flex-row gap-3 pb-2"> 

                                <div class="pt-3 pb-4 px-3 bg-white rounded-md border border-slate-200 w-full lg:w-auto">
                                   
                                    {{-- Nagłówek opcji grupy --}}
                                    <div class="flex items-center gap-6 h-full">
                                        <fieldset class="flex items-center gap-4">
                                            <legend class="text-xs text-slate-500 font-semibold mb-2">{{
                                                trans('lang.selection_type') }}
                                            </legend>

                                            {{-- Opcje wyboru --}}
                                            <div class="flex gap-4">

                                                {{-- Typ wyboru: pojedynczy lub wielokrotny --}}
                                                <label :for="'single-choice-' + groupIndex"
                                                    class="flex items-center cursor-pointer select-none">
                                                    <input type="radio" :id="'single-choice-' + groupIndex"
                                                        :name="'selection-type-' + groupIndex" value="single"
                                                        x-model="group.selectionType" class="hidden">
                                                    <div class="w-5 h-5 border rounded-full flex items-center justify-center transition-colors"
                                                        :class="{ 'border-blue-500': group.selectionType === 'single', '!border-slate-400': group.selectionType !== 'single' }">
                                                        <div class="w-3 h-3 bg-blue-500 rounded-full transition-transform"
                                                            :class="{ 'scale-100': group.selectionType === 'single', 'scale-0': group.selectionType !== 'single' }">
                                                        </div>
                                                    </div>
                                                    <span class="ml-2 text-slate-800 text-sm">{{
                                                        trans('lang.single_choice') }}</span>
                                                </label>

                                                {{-- Typ wyboru: wielokrotny --}}
                                                <label :for="'multi-choice-' + groupIndex"
                                                    class="flex items-center cursor-pointer select-none">
                                                    <input type="radio" :id="'multi-choice-' + groupIndex"
                                                        :name="'selection-type-' + groupIndex" value="multiple"
                                                        x-model="group.selectionType" class="hidden">
                                                    <div class="w-5 h-5 border rounded-full flex items-center justify-center transition-colors"
                                                        :class="{ 'border-blue-500': group.selectionType === 'multiple', '!border-slate-400': group.selectionType !== 'multiple' }">
                                                        <div class="w-3 h-3 bg-blue-500 rounded-full transition-transform"
                                                            :class="{ 'scale-100': group.selectionType === 'multiple', 'scale-0': group.selectionType !== 'multiple' }">
                                                        </div>
                                                    </div>
                                                    <span class="ml-2 text-slate-800 text-sm">{{
                                                        trans('lang.multiple_choice') }}</span>
                                                </label>
                                            </div>
                                        </fieldset>

                                        <div class="h-10 w-px bg-slate-300"></div>

                                        {{-- Wymagania --}}
                                        <div>
                                            <legend class="text-xs text-slate-500 font-semibold mb-2">{{
                                                trans('lang.requirements') }}</legend>
                                            <label class="flex items-center cursor-pointer select-none">
                                                <input type="checkbox" x-model="group.isRequired" class="sr-only peer">
                                                <div
                                                    class="relative w-11 h-6 bg-slate-300 rounded-full peer-checked:bg-blue-500 transition-colors after:content-[''] after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border after:border-slate-300 after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:after:translate-x-full peer-checked:after:border-white">
                                                </div>
                                                <span class="ml-3 text-slate-800 text-sm">{{ trans('lang.required')
                                                    }}</span>
                                            </label>
                                        </div>
                                    </div>
                                </div>

                                {{-- Ograniczenia wyboru --}}
                                <div x-show="group.selectionType === 'multiple'" x-transition>
                                    <div
                                        class="pt-3 pb-2 px-3 bg-white rounded-md border border-slate-200 w-full h-full">
                                        <legend class="text-xs text-slate-500 font-semibold mb-2">{{
                                            trans('lang.choice_limits_optional') }}</legend>
                                        <div class="flex items-start gap-4">
                                            <div>
                                                <div class="flex rounded-lg shadow-sm border !border-slate-300 w-28 overflow-hidden"
                                                    :class="{'!border-red-500': errors.options[groupIndex]?.minChoices}">
                                                    <input type="number" min="0" x-model.number="group.minChoices"
                                                        @input.debounce.500ms="validate('options')" placeholder="Min."
                                                        class="no-spinners py-2 px-3 w-full transition duration-150 focus:outline-none focus:bg-blue-50 focus:ring-0 border-0">
                                                    <div class="flex flex-col border-l border-slate-300">
                                                        <button
                                                            @click="adjustNumber(group, 'minChoices', 1); validate('options')"
                                                            type="button"
                                                            class="flex-1 px-2 text-slate-500 hover:bg-slate-100 border-b border-slate-300 focus:outline-none">
                                                            <i class="fa-solid fa-chevron-up text-xs"></i>
                                                        </button>
                                                        <button
                                                            @click="adjustNumber(group, 'minChoices', -1); validate('options')"
                                                            type="button"
                                                            class="flex-1 px-2 text-slate-500 hover:bg-slate-100 focus:outline-none">
                                                            <i class="fa-solid fa-chevron-down text-xs"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                                <p x-show="errors.options[groupIndex]?.minChoices"
                                                    x-text="errors.options[groupIndex]?.minChoices"
                                                    class="text-sm text-red-600 mt-1"></p>
                                            </div>
                                            <div>
                                                <div class="flex rounded-lg shadow-sm border !border-slate-300 w-28 overflow-hidden"
                                                    :class="{'!border-red-500': errors.options[groupIndex]?.maxChoices}">
                                                    <input type="number" min="0" x-model.number="group.maxChoices"
                                                        @input.debounce.500ms="validate('options')" placeholder="Maks."
                                                        class="no-spinners py-2 px-3 w-full transition duration-150 focus:outline-none focus:bg-blue-50 focus:ring-0 border-0">
                                                    <div class="flex flex-col border-l border-slate-300">
                                                        <button
                                                            @click="adjustNumber(group, 'maxChoices', 1); validate('options')"
                                                            type="button"
                                                            class="flex-1 px-2 text-slate-500 hover:bg-slate-100 border-b border-slate-300 focus:outline-none">
                                                            <i class="fa-solid fa-chevron-up text-xs"></i>
                                                        </button>
                                                        <button
                                                            @click="adjustNumber(group, 'maxChoices', -1); validate('options')"
                                                            type="button"
                                                            class="flex-1 px-2 text-slate-500 hover:bg-slate-100 focus:outline-none">
                                                            <i class="fa-solid fa-chevron-down text-xs"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                                <p x-show="errors.options[groupIndex]?.maxChoices"
                                                    x-text="errors.options[groupIndex]?.maxChoices"
                                                    class="text-sm text-red-600 mt-1"></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {{-- Lista elementów opcji w grupie --}}
                            <div class="flex flex-col gap-3 pt-4 ">
                                <template x-for="(element, elementIndex) in group.elements" :key="elementIndex">
                                    <div class="flex items-start gap-3">

                                        {{-- Pole wyboru dla elementu opcji --}}
                                        <div class="flex-grow min-h-[92px]">
                                            <label class="text-xs text-slate-500 font-semibold">{{
                                                trans('lang.option_name') }}</label>
                                            <input type="text" x-model="element.name"
                                                @input.debounce.500ms="validate('options')"
                                                class="border !border-slate-300 rounded-lg py-2 px-3 w-full transition focus:outline-none focus:ring-0 focus:bg-blue-50"
                                                :class="{'!border-red-500': errors.options[groupIndex]?.elements[elementIndex]?.name}">
                                            <p x-show="errors.options[groupIndex]?.elements[elementIndex]?.name"
                                                x-text="errors.options[groupIndex]?.elements[elementIndex]?.name"
                                                class="text-sm text-red-600 mt-1"></p>
                                        </div>

                                        {{-- Pole wyboru dla elementu opcji --}}
                                        <div class="w-48 min-h-[92px]">
                                            <label class="text-xs text-slate-500 font-semibold">{{
                                                trans('lang.price_plus') }}</label>
                                            <div class="flex rounded-lg shadow-sm border !border-slate-300 overflow-hidden"
                                                :class="{'!border-red-500': errors.options[groupIndex]?.elements[elementIndex]?.price}">
                                                <span
                                                    class="inline-flex items-center px-3 rounded-l-lg border-r border-slate-300 bg-slate-50 text-slate-500 sm:text-sm">€</span>
                                                <input type="number" step="0.01" x-model.number="element.price"
                                                    @input="validate('options')"
                                                    class="no-spinners py-2 px-3 w-full transition duration-150 focus:outline-none focus:bg-blue-50 focus:ring-0 border-0">
                                                <div class="flex flex-col border-l border-slate-300">
                                                    <button
                                                        @click="adjustNumber(element, 'price', 0.01); validate('options')"
                                                        type="button"
                                                        class="flex-1 px-2 text-slate-500 hover:bg-slate-100 border-b border-slate-300 focus:outline-none focus:ring-0"><i
                                                            class="fa-solid fa-chevron-up text-xs"></i></button>
                                                    <button
                                                        @click="adjustNumber(element, 'price', -0.01); validate('options')"
                                                        type="button"
                                                        class="flex-1 px-2 text-slate-500 hover:bg-slate-100 focus:outline-none focus:ring-0"><i
                                                            class="fa-solid fa-chevron-down text-xs"></i></button>
                                                </div>
                                            </div>
                                            <p x-show="errors.options[groupIndex]?.elements[elementIndex]?.price"
                                                x-text="errors.options[groupIndex]?.elements[elementIndex]?.price"
                                                class="text-sm text-red-600 mt-1"></p>
                                        </div>

                                        {{-- Pole wyboru dla podatku elementu opcji --}}
                                        <div class="w-48 min-h-[92px]">
                                            <label class="text-xs text-slate-500 font-semibold">{{ trans('lang.tax')
                                                }}</label>
                                            <div class="relative">
                                                <button @click="openDropdown = `tax-${groupIndex}-${elementIndex}`"
                                                    type="button"
                                                    class="relative w-full text-left cursor-pointer rounded-lg border !border-slate-300 py-2 px-3 transition duration-150 focus:outline-none focus:ring-0 text-base"
                                                    :class="{'!border-red-500': errors.options[groupIndex]?.elements[elementIndex]?.taxId, 'bg-blue-50': openDropdown === `tax-${groupIndex}-${elementIndex}`, 'bg-white': openDropdown !== `tax-${groupIndex}-${elementIndex}`}">
                                                    <span class="block truncate"
                                                        x-text="getTaxRateName(element.taxId)"></span>
                                                    <span
                                                        class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2"><i
                                                            class="fa-solid fa-chevron-down text-xs text-gray-400 transition-transform" :class="{'rotate-180': openDropdown === `tax-${groupIndex}-${elementIndex}`}"></i></span>
                                                </button>
                                                <ul x-show="openDropdown === `tax-${groupIndex}-${elementIndex}`"
                                                    @click.away="openDropdown = null"
                                                    x-transition
                                                    class="absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-lg bg-white shadow-lg border !border-slate-300 overflow-hidden"
                                                    style="display:none;">
                                                    <li @click="element.taxId = ''; openDropdown = null; validate('options')"
                                                        class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap">
                                                        <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="!element.taxId ? 'opacity-100' : 'opacity-0'"></i>
                                                        <span>{{ trans('lang.placeholders.no_tax') }}</span>
                                                    </li>
                                                    <template x-for="tax in taxRates" :key="tax.id">
                                                        <li @click="element.taxId = tax.id; openDropdown = null; validate('options')"
                                                            class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap">
                                                            <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="element.taxId === tax.id ? 'opacity-100' : 'opacity-0'"></i>
                                                            <span x-text="formatTaxTitle(tax)"></span>
                                                        </li>
                                                    </template>
                                                </ul>
                                            </div>
                                            <p x-show="errors.options[groupIndex]?.elements[elementIndex]?.taxId"
                                                x-text="errors.options[groupIndex]?.elements[elementIndex]?.taxId"
                                                class="text-sm text-red-600 mt-1"></p>
                                        </div>

                                        {{-- Przycisk usuwania elementu opcji --}}
                                        <div class="min-h-[92px] pt-4">
                                            <button @click="removeOption(groupIndex, elementIndex)" type="button"
                                                class="flex h-10 w-10 items-center justify-center rounded-lg text-slate-400 hover:bg-red-100 hover:text-red-600 transition"
                                                 title="{{ trans('lang.remove_option') }}"><i class="fa-solid fa-trash"></i></button>
                                        </div>
                                    </div>
                                </template>
                            </div>

                            {{-- Przycisk dodawania nowej opcji --}}
                            <div class="pt-4 mt-4 border-t border-slate-200">
                                <button @click="addOption(groupIndex)" type="button"
                                    class="flex items-center space-x-2 px-3 py-2 text-sm bg-white text-slate-700 rounded-md hover:bg-slate-100 border !border-slate-300 transition whitespace-nowrap"><i
                                        class="fa-solid fa-plus text-xs"></i><span>{{trans('lang.add_option')}}</span></button>
                            </div>
                        </div>
                    </template>
                </div>

                {{-- Przycisk zapisu grup opcji --}}
                <div class="p-4 bg-slate-50 border-t border-slate-200 text-right">
                    <button @click="saveOptions()" :disabled="!isOptionsDirty || isSavingOptions"
                        class="uppercase w-full bg-blue-500 text-white px-4 py-2 rounded hover:opacity-90 transition disabled:opacity-50 disabled:cursor-not-allowed">
                        <span x-show="!isSavingOptions">{{ trans('lang.save_options_and_extras') }}</span>
                        <span x-show="isSavingOptions"><i class="fa-solid fa-spinner fa-spin"></i> {{
                            trans('lang.saving') }}</span>
                    </button>
                </div>
            </div>

            {{-- Notyfikacje (Toast) --}}
            <div x-show="notification.show" x-transition
                class="fixed top-5 right-5 z-50 max-w-lg 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">
                    {{-- ========================================================= --}}
                    {{-- ZMIANA: Całkowita przebudowa na CSS Grid --}}
                    {{-- ========================================================= --}}
                    <div class="grid grid-cols-[auto,1fr,auto] items-center gap-x-3">

                        {{-- Kolumna 1: Ikona --}}
                        <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>

                        {{-- Kolumna 2: Tekst (elastyczny) --}}
                        <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>

                        {{-- Kolumna 3: Przycisk zamknięcia --}}
                        <div class="flex-shrink-0">
                            <button @click="notification.show = false"
                                class="inline-flex text-slate-500 hover:text-slate-600 focus:outline-none">
                                <span class="sr-only">{{ trans('lang.close') }}</span>
                                <i class="fa-solid fa-times"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        @endsection

        <script>
            var cuser_id = "{{ Auth::id() }}";

    // Obiekt z danymi dla list rozwijanych
    const printerDestinationsData = [
        { value: 'Both',    label: '{{ trans("lang.both") }}' },
        { value: 'Kitchen', label: '{{ trans("lang.kitchen") }}' },
        { value: 'Bar',     label: '{{ trans("lang.bar") }}' }
    ];

    // Obiekt z wszystkimi tłumaczeniami dla skryptu JS
    const translationStrings = {
        // Wiadomości walidacyjne
        validation: {
            product_name_required: '{{ trans("lang.validation.product_name_required") }}',
            price_must_be_number: '{{ trans("lang.validation.price_must_be_number") }}',
            subcategory_required: '{{ trans("lang.validation.subcategory_required") }}',
            tax_required: '{{ trans("lang.validation.tax_required") }}',
            group_title_required: '{{ trans("lang.validation.group_title_required") }}',
            min_non_negative: '{{ trans("lang.validation.min_non_negative") }}',
            max_non_negative: '{{ trans("lang.validation.max_non_negative") }}',
            min_gt_max: '{{ trans("lang.validation.min_gt_max") }}',
            option_name_required: '{{ trans("lang.validation.option_name_required") }}',
            price_must_be_positive_number: '{{ trans("lang.validation.price_must_be_positive_number") }}',
        },
        // Powiadomienia i komunikaty
        notifications: {
            please_correct_errors: '{{ trans("lang.notifications.please_correct_errors") }}',
            details_saved_success: '{{ trans("lang.notifications.details_saved_success") }}',
            settings_saved_success: '{{ trans("lang.notifications.settings_saved_success") }}',
            options_saved_success: '{{ trans("lang.notifications.options_saved_success") }}',
            photo_upload_success: '{{ trans("lang.notifications.photo_upload_success") }}',
            details_save_error: '{{ trans("lang.notifications.details_save_error") }}',
            settings_save_error: '{{ trans("lang.notifications.settings_save_error") }}',
            options_save_error: '{{ trans("lang.notifications.options_save_error") }}',
        },
        // Błędy krytyczne i błędy uploadu
        errors: {
            cuser_id_undefined: '{{ trans("lang.errors.cuser_id_undefined") }}',
            vendor_not_found: '{{ trans("lang.errors.vendor_not_found") }}',
            product_not_found: '{{ trans("lang.errors.product_not_found") }}',
            data_loading_error: '{{ trans("lang.errors.data_loading_error") }}',
            invalid_file_format: '{{ trans("lang.errors.invalid_file_format") }}',
            file_too_large: '{{ trans("lang.errors.file_too_large") }}',
            file_upload_error: '{{ trans("lang.errors.file_upload_error") }}',
            image_url_error: '{{ trans("lang.errors.image_url_error") }}',
            image_compression_error: '{{ trans("lang.errors.image_compression_error") }}',
        },
        // Teksty tymczasowe i zastępcze
        placeholders: {
            processing: '{{ trans("lang.placeholders.processing") }}',
            saving_details: '{{ trans("lang.placeholders.saving_details") }}',
            saving_settings: '{{ trans("lang.placeholders.saving_settings") }}',
            saving_options: '{{ trans("lang.placeholders.saving_options") }}',
            no_tax: '{{ trans("lang.placeholders.no_tax") }}',
        },
        general: {
            vat: '{{ trans("lang.vat_short") }}'
        }
    };
        </script>

        @section('scripts')
        <script src="https://cdnjs.cloudflare.com/ajax/libs/compressorjs/1.2.1/compressor.min.js"
            integrity="sha512-gcAUkasjUYVTYy/eMyjuKzKr/RE5NcL7wG2tG1Mr2A5gN3AmGr0FmfnHMP2v1EwuL_Z4J_S9ImQgnfkU2KzwWg=="
            crossorigin="anonymous" referrerpolicy="no-referrer"></script>

        <style>
            .no-spinners::-webkit-outer-spin-button,
            .no-spinners::-webkit-inner-spin-button {
                -webkit-appearance: none;
                margin: 0;
            }

            .no-spinners {
                -moz-appearance: textfield;
            }
        </style>

        <script>
            function editProductAlpine() {
        return {
            // === STATE ===
            productId: "{{ $id }}",
            descriptionCharLimit: 300,
            isLoading: true,
            isSavingDetails: false,
            isSavingSettings: false,
            isSavingOptions: false,
            savingMessage: translationStrings.placeholders.processing,
            notification: {
                show: false,
                type: 'success',
                message: ''
            },
            placeholderImage: '',
            imagePreview: '',
            isDragging: false,
            isUploading: false,
            uploadProgress: 0,
            uploadError: '',
            uploadTask: null,
            errorMessage: '',
            openDropdown: null,
            product: {
                name: '',
                price: 0,
                taxId: '',
                subcategoryId: '',
                printerDestination: 'Both',
                photo: '',
                description: '',
                publish: true,
                ageRestriction: false,
                options: []
            },
            taxRates: [],
            subcategories: [],
            printerDestinations: printerDestinationsData,
            originalProduct: null,
            errors: {
                name: '',
                price: '',
                subcategoryId: '',
                taxId: '',
                options: []
            },

            // === METHODS ===

            async initForm() {
                this.isLoading = true;
                try {
                    if (typeof cuser_id === 'undefined' || !cuser_id) {
                        throw new Error(translationStrings.errors.cuser_id_undefined);
                    }
                    const vendorSnap = await database.collection('vendors').where('author', '==', cuser_id).limit(1).get();
                    if (vendorSnap.empty) {
                        throw new Error(translationStrings.errors.vendor_not_found);
                    }
                    const vendorId = vendorSnap.docs[0].id;
                    const [taxSnap, subcatSnap, placeholderSnap, productSnap] = await Promise.all([
                        database.collection('tax').where('enable', '==', true).get(),
                        database.collection('vendor_subcategories').where('vendorId', '==', vendorId).get(),
                        database.collection('settings').doc('placeHolderImage').get(),
                        database.collection('vendor_products').doc(this.productId).get()
                    ]);

                    if (placeholderSnap.exists) {
                        this.placeholderImage = placeholderSnap.data().image;
                    }
                    this.taxRates = taxSnap.docs
                        .map(doc => ({ id: doc.id, ...doc.data() }))
                        .filter(tax => ['7', '19'].includes(tax.tax))
                        .sort((a, b) => parseFloat(a.tax) - parseFloat(b.tax));
                    subcatSnap.docs.forEach(doc => this.subcategories.push({
                        id: doc.id,
                        ...doc.data()
                    }));

                    if (productSnap.exists) {
                        const data = productSnap.data();
                        this.product = {
                            name: data.name || '',
                            price: parseFloat(data.price || 0),
                            taxId: data.taxId || '',
                            subcategoryId: data.subcategoryId || '',
                            printerDestination: data.printerDestination || 'Both',
                            photo: data.photo || '',
                            description: data.description || '',
                            publish: data.publish !== undefined ? data.publish : true,
                            ageRestriction: data.ageRestriction || false,
                            options: this.formatOptions(data.options) || []
                        };
                        this.imagePreview = data.photo || this.placeholderImage;
                        this.originalProduct = JSON.parse(JSON.stringify(this.product));
                        this.syncErrorsStructure();
                    } else {
                        throw new Error(translationStrings.errors.product_not_found);
                    }
                } catch (error) {
                    this.errorMessage = translationStrings.errors.data_loading_error + error.message;
                } finally {
                    this.isLoading = false;
                }
            },

            validate(section) {
                const newErrors = { name: '', price: '', subcategoryId: '', taxId: '', options: this.errors.options || [] };
                let isValid = true;
                if (section === 'details') {
                    newErrors.name = !this.product.name.trim() ? translationStrings.validation.product_name_required : '';
                    if (newErrors.name) isValid = false;
                    newErrors.price = (typeof this.product.price !== 'number' || this.product.price < 0) ? translationStrings.validation.price_must_be_number : '';
                    if (newErrors.price) isValid = false;
                }
                if (section === 'settings') {
                    newErrors.subcategoryId = !this.product.subcategoryId ? translationStrings.validation.subcategory_required : '';
                    if (newErrors.subcategoryId) isValid = false;
                    newErrors.taxId = !this.product.taxId ? translationStrings.validation.tax_required : '';
                    if (newErrors.taxId) isValid = false;
                }
                if (section === 'options') {
                    this.product.options.forEach((group, groupIndex) => {
                        let groupHasError = false;
                        if (!group.title.trim()) {
                            newErrors.options[groupIndex].title = translationStrings.validation.group_title_required;
                            isValid = false; groupHasError = true;
                        } else { newErrors.options[groupIndex].title = ''; }
                        const min = group.minChoices ? parseInt(group.minChoices, 10) : 0;
                        const max = group.maxChoices ? parseInt(group.maxChoices, 10) : 0;
                        if (min < 0) {
                            newErrors.options[groupIndex].minChoices = translationStrings.validation.min_non_negative;
                            isValid = false; groupHasError = true;
                        } else { newErrors.options[groupIndex].minChoices = '';}
                        if (max < 0) {
                            newErrors.options[groupIndex].maxChoices = translationStrings.validation.max_non_negative;
                            isValid = false; groupHasError = true;
                        } else { newErrors.options[groupIndex].maxChoices = ''; }
                        if (min > 0 && max > 0 && min > max) {
                            newErrors.options[groupIndex].minChoices = translationStrings.validation.min_gt_max;
                            isValid = false; groupHasError = true;
                        }
                        group.elements.forEach((element, elementIndex) => {
                            if (!element.name.trim()) {
                                newErrors.options[groupIndex].elements[elementIndex].name = translationStrings.validation.option_name_required;
                                isValid = false; groupHasError = true;
                            } else { newErrors.options[groupIndex].elements[elementIndex].name = ''; }
                            if (typeof element.price !== 'number' || element.price < 0) {
                                newErrors.options[groupIndex].elements[elementIndex].price = translationStrings.validation.price_must_be_positive_number;
                                isValid = false; groupHasError = true;
                            } else { newErrors.options[groupIndex].elements[elementIndex].price = ''; }
                        });
                        newErrors.options[groupIndex].hasError = groupHasError;
                    });
                }
                this.errors = newErrors;
                return isValid;
            },

            syncErrorsStructure() {
                this.errors.options = this.product.options.map(group => ({ title: '', minChoices: '', maxChoices: '', hasError: false, elements: group.elements.map(() => ({ name: '', price: '', taxId: '' })) }));
            },

            async saveDetails() {
                if (!this.validate('details')) { this.showNotification(translationStrings.notifications.please_correct_errors, 'error'); return; }
                this.isSavingDetails = true;
                this.savingMessage = translationStrings.placeholders.saving_details;
                try {
                    const dataToUpdate = { name: this.product.name, price: this.product.price, description: this.product.description, photo: this.product.photo };
                    await database.collection('vendor_products').doc(this.productId).update(dataToUpdate);
                    this.originalProduct.name = this.product.name;
                    this.originalProduct.price = this.product.price;
                    this.originalProduct.description = this.product.description;
                    this.originalProduct.photo = this.product.photo;
                    this.showNotification(translationStrings.notifications.details_saved_success, 'success');
                } catch (error) {
                    this.showNotification(translationStrings.notifications.details_save_error + error.message, 'error');
                } finally {
                    this.isSavingDetails = false;
                }
            },
            async saveSettings() {
                if (!this.validate('settings')) { this.showNotification(translationStrings.notifications.please_correct_errors, 'error'); return; }
                this.isSavingSettings = true;
                this.savingMessage = translationStrings.placeholders.saving_settings;
                try {
                    const dataToUpdate = { subcategoryId: this.product.subcategoryId, taxId: this.product.taxId, printerDestination: this.product.printerDestination, publish: this.product.publish, ageRestriction: this.product.ageRestriction };
                    await database.collection('vendor_products').doc(this.productId).update(dataToUpdate);
                    this.originalProduct.subcategoryId = this.product.subcategoryId;
                    this.originalProduct.taxId = this.product.taxId;
                    this.originalProduct.printerDestination = this.product.printerDestination;
                    this.originalProduct.publish = this.product.publish;
                    this.originalProduct.ageRestriction = this.product.ageRestriction;
                    this.showNotification(translationStrings.notifications.settings_saved_success, 'success');
                } catch (error) {
                    this.showNotification(translationStrings.notifications.settings_save_error + error.message, 'error');
                } finally {
                    this.isSavingSettings = false;
                }
            },
            async saveOptions() {
                if (!this.validate('options')) { this.showNotification(translationStrings.notifications.please_correct_errors, 'error'); return; }
                this.isSavingOptions = true;
                this.savingMessage = translationStrings.placeholders.saving_options;
                try {
                    const dataToUpdate = { options: this.formatOptionsForSave(this.product.options) };
                    await database.collection('vendor_products').doc(this.productId).update(dataToUpdate);
                    this.originalProduct.options = JSON.parse(JSON.stringify(this.product.options));
                    this.showNotification(translationStrings.notifications.options_saved_success, 'success');
                } catch (error) {
                    this.showNotification(translationStrings.notifications.options_save_error + error.message, 'error');
                } finally {
                    this.isSavingOptions = false;
                }
            },

            triggerFileInput() { this.uploadError = ''; document.getElementById('product_image_input').click(); },
            selectFile(file) {
                if (!file) return;
                this.uploadError = '';
                const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
                if (!allowedTypes.includes(file.type)) { this.uploadError = translationStrings.errors.invalid_file_format; return; }
                const maxSize = 5 * 1024 * 1024;
                if (file.size > maxSize) { this.uploadError = translationStrings.errors.file_too_large; return; }
                this.imagePreview = URL.createObjectURL(file);
                this.uploadAndTrackProgress(file);
            },
            uploadAndTrackProgress(file) {
                this.isUploading = true;
                this.uploadProgress = 0;
                new Compressor(file, {
                    quality: 0.8, maxWidth: 1920,
                    success: (compressedResult) => {
                        const storageRef = firebase.storage().ref();
                        const imageName = `images/products/${Date.now()}-${compressedResult.name}`;
                        const imageRef = storageRef.child(imageName);
                        this.uploadTask = imageRef.put(compressedResult);
                        this.uploadTask.on('state_changed',
                            (snapshot) => { this.uploadProgress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; },
                            (error) => { console.error("Upload error:", error); this.uploadError = translationStrings.errors.file_upload_error; this.isUploading = false; this.uploadTask = null; },
                            async () => {
                                try {
                                    const downloadURL = await this.uploadTask.snapshot.ref.getDownloadURL();
                                    this.product.photo = downloadURL;
                                    this.imagePreview = downloadURL;
                                    this.showNotification(translationStrings.notifications.photo_upload_success, 'success');
                                } catch (error) { this.uploadError = translationStrings.errors.image_url_error; } finally { this.isUploading = false; this.uploadTask = null; }
                            }
                        );
                    },
                    error: (err) => { this.uploadError = translationStrings.errors.image_compression_error + err.message; this.isUploading = false; },
                });
            },
            removeImage() { this.product.photo = ''; this.imagePreview = this.placeholderImage; this.uploadError = ''; },
            cancelUpload() { if (this.uploadTask) { this.uploadTask.cancel(); this.isUploading = false; this.uploadProgress = 0; this.uploadTask = null; this.imagePreview = this.originalProduct.photo || this.placeholderImage; } },

            adjustNumber(object, property, amount) {
                let currentValue = parseFloat(object[property]) || 0;
                let newValue = currentValue + amount;
                if (newValue < 0) { newValue = 0; }
                object[property] = parseFloat(newValue.toFixed(2));
            },

            formatOptions(optionsObject) {
                if (!optionsObject || typeof optionsObject !== 'object') return [];
                return Object.values(optionsObject).map(group => ({ ...group, selectionType: group.isMultiChoice ? 'multiple' : 'single', isRequired: group.isRequired || false, minChoices: group.minChoices || null, maxChoices: group.maxChoices || null, elements: group.elements ? Object.values(group.elements) : [] }));
            },

            formatOptionsForSave(optionsArray) {
                const obj = {};
                optionsArray.forEach((group, groupIndex) => {
                    const elementsObj = {};
                    group.elements.forEach((el, elIndex) => { elementsObj[elIndex] = el; });
                    const groupToSave = { ...group };
                    obj[groupIndex] = { ...groupToSave, isMultiChoice: group.selectionType === 'multiple', elements: elementsObj };
                });
                return obj;
            },

            addGroup() { this.product.options.push({ title: '', selectionType: 'single', isRequired: false, minChoices: null, maxChoices: null, elements: [] }); this.syncErrorsStructure(); },
            removeGroup(index) { this.product.options.splice(index, 1); this.syncErrorsStructure(); },
            addOption(groupIndex) { this.product.options[groupIndex].elements.push({ name: '', price: 0, taxId: '' }); this.syncErrorsStructure(); },
            removeOption(groupIndex, elementIndex) { this.product.options[groupIndex].elements.splice(elementIndex, 1); this.syncErrorsStructure(); },
            showNotification(message, type = 'success', duration = 4000) { this.notification.message = message; this.notification.type = type; this.notification.show = true; setTimeout(() => { this.notification.show = false; }, duration); },
            formatTaxTitle(tax) {
                if (!tax) return '';
                const vatLabel = translationStrings.general.vat || 'VAT';
                return `${tax.tax}% ${vatLabel}`;
            },

            // === COMPUTED PROPERTIES ===

            get isDetailsDirty() { if (!this.originalProduct) return false; return this.product.name !== this.originalProduct.name || this.product.price !== this.originalProduct.price || this.product.description !== this.originalProduct.description || this.product.photo !== this.originalProduct.photo; },
            get isSettingsDirty() { if (!this.originalProduct) return false; return this.product.subcategoryId !== this.originalProduct.subcategoryId || this.product.taxId !== this.originalProduct.taxId || this.product.printerDestination !== this.originalProduct.printerDestination || this.product.publish !== this.originalProduct.publish || this.product.ageRestriction !== this.originalProduct.ageRestriction; },
            get isOptionsDirty() { if (!this.originalProduct) return false; return JSON.stringify(this.product.options) !== JSON.stringify(this.originalProduct.options); },

            get selectedSubcategoryName() { const subcategory = this.subcategories.find(s => s.id === this.product.subcategoryId); return subcategory ? subcategory.name : '{{ trans("lang.subcategory_select") }}'; },
            get selectedTaxRateName() { 
                const tax = this.taxRates.find(t => t.id === this.product.taxId); 
                return tax ? this.formatTaxTitle(tax) : '{{ trans("lang.tax_rate_select") }}'; 
            },
            getTaxRateName(taxId) { 
                if (!taxId) return translationStrings.placeholders.no_tax; 
                const tax = this.taxRates.find(t => t.id === taxId); 
                return tax ? this.formatTaxTitle(tax) : translationStrings.placeholders.no_tax; 
            },
            get selectedPrinterDestinationLabel() { const destination = this.printerDestinations.find(d => d.value === this.product.printerDestination); return destination ? destination.label : '...'; }
        }
    }
        </script>
        @endsection