




<?php $__env->startSection('content'); ?>
<style type="text/css">
/*<![CDATA[*/


/* PLACEHOLDER - podgląd produktu podczas przeciągania */
.sortable-chosen {
    opacity: 0.35 !important;
    background: #f1f5f9 !important;
    border: 2px dashed #94a3b8 !important;
    border-radius: 8px !important;
    transition: all 0.2s ease !important;
    transform: scale(0.98) !important;
    /* Zachowujemy przestrzeń i POKAZUJEMY zawartość jako podgląd */
}

/* GHOST - element podążający za kursorem */
.sortable-ghost {
    opacity: 0.9 !important;
    background: #ffffff !important;
    border: 2px solid #3b82f6 !important;
    border-radius: 8px !important;
    box-shadow: 0 12px 30px rgba(59, 130, 246, 0.4) !important;
    cursor: grabbing !important;
}

/* Przyciemnij interaktywne elementy w placeholder */
.sortable-chosen .product-actions,
.sortable-chosen .drag-handle,
.sortable-chosen input[type="checkbox"] {
    opacity: 0.2 !important;
    pointer-events: none !important;
}

/* Ukryj problematyczne elementy w ghost */
.sortable-ghost .product-actions {
    display: none !important;
}

.sortable-ghost input,
.sortable-ghost button,
.sortable-ghost a,
.sortable-ghost .tooltip-container,
.sortable-ghost [x-show],
.sortable-ghost .tooltip,
.sortable-ghost [data-tooltip] {
    visibility: hidden !important;
    display: none !important;
}





/* Proste animacje dla produktów */
.product-row {
    transition: all 0.2s ease;
}

.product-row:hover {
    background: #f8fafc;
}

.product-row.dragging {
    opacity: 0.8;
}

/* Piękne wskazówki dla kategorii docelowej */
.category-container.drag-over {
    background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 50%, #bbf7d0 100%) !important;
    border: 3px dashed #22c55e !important;
    border-radius: 16px !important;
    /* transform: scale(1.05) !important; - USUNIĘTE */
    box-shadow: 0 20px 40px rgba(34, 197, 94, 0.4) !important;
    /* animation: category-pulse 1.2s ease-in-out infinite !important; - USUNIĘTE */
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
}

/* 🎭 Animacja pulsowania dla kategorii */
@keyframes category-pulse {
    0%, 100% { 
        background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 50%, #bbf7d0 100%) !important;
        box-shadow: 0 20px 40px rgba(34, 197, 94, 0.4) !important;
        transform: scale(1.05) !important;
    }
    50% { 
        background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 50%, #a7f3d0 100%) !important;
        box-shadow: 0 30px 60px rgba(34, 197, 94, 0.6) !important;
        transform: scale(1.08) !important;
    }
}

/* 🎯 Potencjalne cele do upuszczenia - USUNIĘTE
.potential-drop-target {
    background: linear-gradient(135deg, #fefce8 0%, #fef3c7 100%) !important;
    border: 2px dashed #f59e0b !important;
    border-radius: 12px !important;
    /* transform: scale(1.02) !important; - USUNIĘTE */
    box-shadow: 0 12px 25px rgba(245, 158, 11, 0.3) !important;
    transition: all 0.3s ease !important;
}
*/

/* 🎯 Piękny drag handle z efektami */
.drag-handle {
    cursor: grab;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    padding: 8px;
    border-radius: 10px;
    position: relative;
}

.drag-handle:hover {
    background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
    color: #1e40af;
    /* transform: scale(1.2); - USUNIĘTE */
    box-shadow: 0 8px 20px rgba(30, 64, 175, 0.2);
}

.drag-handle:active {
    cursor: grabbing;
    /* transform: scale(1.1); - USUNIĘTE */
    background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
}

/* 💡 Tooltip dla drag handle - USUNIĘTE
.drag-handle::after {
    content: '🎯 Przeciągnij';
    position: absolute;
    top: -35px;
    left: 50%;
    transform: translateX(-50%);
    background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
    color: white;
    padding: 6px 12px;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 600;
    white-space: nowrap;
    opacity: 0;
    pointer-events: none;
    transition: all 0.3s ease;
    z-index: 1000;
    box-shadow: 0 8px 20px rgba(30, 64, 175, 0.3);
}

.drag-handle:hover::after {
    opacity: 1;
    transform: translateX(-50%) translateY(-3px);
}
*/

/* 🎭 Animacja bounce dla drop hints - USUNIĘTE
@keyframes drop-hint-bounce {
    0%, 100% { 
        transform: translateY(0px) scale(1);
        opacity: 1;
    }
    50% { 
        transform: translateY(-6px) scale(1.05);
        opacity: 0.9;
    }
}
*/

/* 🎨 Efekty podczas przeciągania */
body.is-dragging {
    cursor: grabbing;
    user-select: none;
}

body.is-dragging .category-container {
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* Responsive drag handle */
@media (max-width: 768px) {
    .drag-handle {
        padding: 10px;
        font-size: 1.3em;
    }
    
    .drop-hint {
        font-size: 11px !important;
        padding: 6px 10px !important;
    }
    
    .sortable-ghost {
        transform: scale(1.1) rotate(2deg) !important;
    }
}

/* Tooltips - zapewnienie, że są zawsze widoczne */
.tooltip-container {
    position: relative;
    z-index: 1;
}

.tooltip-content {
    position: absolute;
    z-index: 9999 !important;
    pointer-events: none;
}

/* Zapewnienie, że tooltipsy nie są przycinane */
.product-row {
    position: relative;
    overflow: visible;
}

.product-actions {
    position: relative;
    z-index: 10;
}

/* Wizualne wskazówki dla drag & drop między kategoriami */
.category-container.drag-over {
    background-color: #dbeafe !important;
    border: 2px dashed #3b82f6 !important;
    border-radius: 8px;
}

.category-container.drag-over .category-header {
    background-color: #3b82f6 !important;
}

.product-row.dragging {
    opacity: 0.5;
    transform: rotate(2deg);
}

/* Animacje dla smooth transitions */
.product-row {
    transition: all 0.2s ease;
}

.category-container {
    transition: all 0.3s ease;
}
/*]]>*/
</style>
<div id="main-wrapper" class="p-10"
    x-data="menuAlpine()" x-init="initMenu()">
    
    <div class="flex flex-col gap-6">
         
        <div class="p-6 bg-gradient-to-r from-slate-900 via-blue-800 to-blue-500 rounded-lg shadow-[1px_1px_4px_0px_#e2e8f0]">
            
              
            <div class="flex flex-col md:flex-row justify-between md:items-start gap-4">

                
                <div>
                    <h3 class="text-2xl font-bold text-slate-50"><?php echo trans('lang.menu_management_title'); ?></h3>
                    <p class="text-sm text-slate-200 mt-1 m-0"><?php echo trans('lang.menu_management_description'); ?></p>
                </div>

                
                <div class="flex items-center gap-4 flex-shrink-0 mt-2 md:mt-0">
                   
                    
                    <a href="<?php echo route('category'); ?>" class="flex items-center px-4 py-2 text-sm bg-white text-slate-600 rounded-md hover:bg-slate-100 hover:text-slate-900 hover:no-underline transition focus:outline-none whitespace-nowrap">
                        <?php echo trans('lang.menu_categories'); ?>

                    </a>
                    
                    <button @click="handleAddProduct()" type="button" class="flex items-center gap-2 px-4 py-2 text-sm bg-white text-slate-600 rounded-md hover:bg-slate-100 hover:text-slate-900 transition focus:outline-none whitespace-nowrap">
                        <i class="fa-solid fa-plus text-xs"></i>
                        <span><?php echo trans('lang.create_menu_item'); ?></span>
                    </button>
                </div>
            </div>

            
            <div class="flex flex-col md:flex-row items-start md:items-center gap-4 md:gap-6 mt-6">

                    
                <div class="flex-1 relative w-full md:w-auto">
                    <input x-model.debounce.300ms="searchTerm" type="text"
                        placeholder="<?php echo e(trans('lang.menu_search_placeholder')); ?>"
                        class="w-full rounded-md pl-10 pr-4 py-2 text-sm focus:outline-none focus:ring-0 border-0 transition" />
                    <i class="fa fa-search text-lg absolute left-3 top-1/2 -translate-y-1/2 text-slate-700"></i>
                </div>

                
                <div class="relative" @click.outside="openCategoryFilter = false">

                    
                    <button type="button" x-ref="categoryFilterButton" @click="toggleCategoryFilter()"
                        class="flex items-center gap-2 px-4 py-2 text-sm bg-white text-slate-600 rounded-md hover:bg-slate-100 hover:text-slate-900 focus:outline-none transition whitespace-nowrap">
                        <i class="fa-solid fa-filter"></i>
                        <span class="font-regular" x-text="currentCategoryLabel"></span>
                        <i class="fa fa-chevron-down text-xs transition-transform"
                            :class="{'rotate-180': openCategoryFilter}"></i>
                    </button>

                    
                    <ul x-show="openCategoryFilter" x-transition
                        :class="dropUpCategory ? 'bottom-full mb-2 right-0' : 'top-full mt-2 right-0'"
                        class="
                        absolute w-56
                        bg-white
                        border !border-slate-300
                        rounded-lg
                        shadow-lg
                        z-50
                        transition-all
                        overflow-hidden
                        max-h-60 overflow-y-auto
                    " style="display: none;">
                        <li @click="setCategory('')" class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-sm text-slate-700 whitespace-nowrap">
                            <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="selectedCategory === '' ? 'opacity-100' : 'opacity-0'"></i>
                            <span><?php echo e(trans('lang.menu_filter_all_categories')); ?></span>
                        </li>
                        <template x-for="category in categories" :key="category">
                            <li @click="setCategory(category)" class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-sm text-slate-700 whitespace-nowrap">
                                <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="selectedCategory === category ? 'opacity-100' : 'opacity-0'"></i>
                                <span x-text="category"></span>
                            </li>
                        </template>
                    </ul>
                </div>
            </div>
        </div>

        
        <div x-show="loading" class="
            fixed inset-0
            bg-black bg-opacity-80
            z-50
            flex items-center justify-center
            " x-transition:enter="transition ease-out duration-300" x-transition:enter-start="opacity-0"
                x-transition:enter-end="opacity-100" x-transition:leave="transition ease-in duration-200"
                x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0" 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">
                        <?php echo e(trans('lang.loading')); ?>...
                    </span>
                </div>
        </div>

        
        <div class="space-y-6" x-show="!loading">
            <template x-for="group in groupedItems" :key="group.categoryName">
                <div class="category-container bg-white rounded-lg shadow-sm border border-slate-300 overflow-visible relative">
                    
                    <div class="category-header bg-slate-900 text-white px-6 py-4 rounded-t-lg">
                        <h3 class="text-lg font-semibold" x-text="group.categoryName"></h3>
                        <p class="text-slate-300 text-sm" x-text="getProductCountText(group.items.length)"></p>
                    </div>
                    
                    
                    <div :id="`products-${group.subcategoryId}`" class="divide-y divide-slate-200">
                        <template x-for="item in group.items" :key="item.id">
                            <div 
                                class="product-row flex items-center p-4 hover:bg-slate-50 transition-colors duration-200"
                                x-data="{ productId: item.id, productName: item.name, productPhoto: item.photo }"
                                x-init="
                                    $el.dataset.productId = productId;
                                    $el.dataset.productName = productName || '';
                                    $el.dataset.productPhoto = productPhoto || '';
                                "
                            >
                                
                                <div class="drag-handle cursor-move mr-4 text-slate-400 hover:text-slate-600">
                                    <i class="fa-solid fa-grip-vertical"></i>
                                </div>
                                
                            
                                <div class="flex-shrink-0 mr-4">
                                    <img :src="productPhoto || placeholderImage" alt="Zdjęcie produktu" class="rounded w-16 h-16 object-cover">
                                </div>
                                
                                
                                <div class="flex-grow min-w-0">
                                    <h4 class="text-lg font-semibold text-slate-800 truncate" x-text="productName"></h4>
                                    <div class="flex items-center gap-2">
                                        <p class="text-blue-600 font-semibold" x-html="formatPrice(item)"></p>
                                        
                                        <template x-if="item.isBundle">
                                            <div class="inline-flex items-center px-2 py-0.5 rounded-full bg-purple-100 text-purple-700" title="Product Bundle">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" 
                                                     stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                    <path d="M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z"/>
                                                    <path d="M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12"/>
                                                    <path d="M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17"/>
                                                </svg>
                                                <span class="ml-1 text-xs font-medium">Bundle</span>
                                            </div>
                                        </template>
                                    </div>
                                </div>
                                
                            
                                <div class="flex-shrink-0 mr-4 tooltip-container" x-data="{ tooltipVisible: false }">
                                    <label class="inline-flex items-center cursor-pointer relative" @mouseenter="tooltipVisible = true" @mouseleave="tooltipVisible = false">
                                        <input type="checkbox" class="sr-only peer" @change="togglePublish(item)" :checked="item.publish">
                                        <div class="relative h-6 w-11 rounded-full bg-slate-300 peer-checked:bg-blue-500 transition-colors">
                                            <div class="absolute left-0.5 top-0.5 h-5 w-5 rounded-full bg-white transition-transform" :class="{ 'translate-x-5': item.publish }"></div>
                                        </div>
                                    </label>
                                    <div x-show="tooltipVisible"
                                        x-transition:enter="transition ease-out duration-300"
                                        x-transition:enter-start="opacity-0 translate-y-2"
                                        x-transition:enter-end="opacity-100 translate-y-0"
                                        x-transition:leave="transition ease-in duration-200"
                                        x-transition:leave-start="opacity-100 translate-y-0"
                                        x-transition:leave-end="opacity-0 translate-y-2"
                                        class="tooltip-content top-full left-1/2 transform -translate-x-1/2 mt-2 w-max max-w-xs bg-slate-800 text-white text-center text-xs rounded py-2 px-3 pointer-events-none"
                                        style="display: none;">
                                        <span x-text="item.publish ? '<?php echo e(trans('lang.published')); ?>' : '<?php echo e(trans('lang.unpublished')); ?>'"></span>
                                        <div class="absolute left-1/2 bottom-full w-0 h-0 border-x-8 border-x-transparent border-b-8 border-b-slate-800 transform -translate-x-1/2"></div>
                                    </div>
                                </div>
                                
                            
                                <div class="product-actions flex-shrink-0 flex gap-2">
                                    
                                    <div x-data="{ tooltipVisible: false }" class="tooltip-container">
                                        <a :href="editUrl(productId)" @mouseenter="tooltipVisible = true"
                                            @mouseleave="tooltipVisible = false"
                                            class="flex h-10 w-10 items-center justify-center rounded-lg text-slate-400 hover:bg-blue-100 hover:text-blue-500 transition focus:outline-none focus:ring-0 hover:no-underline">
                                            <i class="fa fa-pen"></i>
                                        </a>
                                        <div x-show="tooltipVisible"
                                            x-transition:enter="transition ease-out duration-300"
                                            x-transition:enter-start="opacity-0 translate-y-2"
                                            x-transition:enter-end="opacity-100 translate-y-0"
                                            x-transition:leave="transition ease-in duration-200"
                                            x-transition:leave-start="opacity-100 translate-y-0"
                                            x-transition:leave-end="opacity-0 translate-y-2"
                                            class="tooltip-content top-full left-1/2 transform -translate-x-1/2 mt-2 w-max max-w-xs bg-slate-800 text-white text-center text-xs rounded py-2 px-3 pointer-events-none"
                                            style="display: none;">
                                            <?php echo e(trans('lang.edit')); ?>

                                            <div class="absolute left-1/2 bottom-full w-0 h-0 border-x-8 border-x-transparent border-b-8 border-b-slate-800 transform -translate-x-1/2"></div>
                                        </div>
                                    </div>

                                    
                                    <div x-data="{ tooltipVisible: false }" class="tooltip-container">
                                        <a :href="duplicateUrl(productId)" @mouseenter="tooltipVisible = true"
                                            @mouseleave="tooltipVisible = false"
                                            class="flex h-10 w-10 items-center justify-center rounded-lg text-slate-400 hover:bg-green-100 hover:text-green-600 transition focus:outline-none focus:ring-0 hover:no-underline">
                                            <i class="fa fa-copy"></i>
                                        </a>
                                        <div x-show="tooltipVisible"
                                            x-transition:enter="transition ease-out duration-300"
                                            x-transition:enter-start="opacity-0 translate-y-2"
                                            x-transition:enter-end="opacity-100 translate-y-0"
                                            x-transition:leave="transition ease-in duration-200"
                                            x-transition:leave-start="opacity-100 translate-y-0"
                                            x-transition:leave-end="opacity-0 translate-y-2"
                                            class="tooltip-content top-full left-1/2 transform -translate-x-1/2 mt-2 w-max max-w-xs bg-slate-800 text-white text-center text-xs rounded py-2 px-3 pointer-events-none"
                                            style="display: none;">
                                            <?php echo e(trans('lang.use_as_template')); ?>

                                            <div class="absolute left-1/2 bottom-full w-0 h-0 border-x-8 border-x-transparent border-b-8 border-b-slate-800 transform -translate-x-1/2"></div>
                                        </div>
                                    </div>

                                    
                                    <div x-data="{ tooltipVisible: false }" class="tooltip-container">
                                        <button @click="confirmDelete(item.id)" @mouseenter="tooltipVisible = true"
                                            @mouseleave="tooltipVisible = false"
                                            class="flex h-10 w-10 items-center justify-center rounded-lg text-slate-400 hover:bg-red-100 hover:text-red-600 transition focus:outline-none focus:ring-0">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                        <div x-show="tooltipVisible"
                                            x-transition:enter="transition ease-out duration-300"
                                            x-transition:enter-start="opacity-0 translate-y-2"
                                            x-transition:enter-end="opacity-100 translate-y-0"
                                            x-transition:leave="transition ease-in duration-200"
                                            x-transition:leave-start="opacity-100 translate-y-0"
                                            x-transition:leave-end="opacity-0 translate-y-2"
                                            class="tooltip-content top-full left-1/2 transform -translate-x-1/2 mt-2 w-max max-w-xs bg-slate-800 text-white text-center text-xs rounded py-2 px-3 pointer-events-none"
                                            style="display: none;">
                                            <?php echo e(trans('lang.delete')); ?>

                                            <div class="absolute left-1/2 bottom-full w-0 h-0 border-x-8 border-x-transparent border-b-8 border-b-slate-800 transform -translate-x-1/2"></div>
                                        </div>
                                    </div>
                                </div>
        </div>
                        </template>
                </div>
            </div>
            </template>
            
            
            <template x-if="!groupedItems.length">
                <div class="bg-white rounded-lg shadow-sm border border-slate-300 p-10 text-center">
                    <p class="text-slate-500" x-text="searchTerm || selectedCategory ? '<?php echo e(trans('lang.no_results_found')); ?>' : '<?php echo e(trans('lang.no_items_to_display')); ?>'"></p>
        </div>
            </template>
        </div>






    </div>

    
    <div x-show="showMissingCategoriesModal" x-transition:enter="transition ease-out duration-300" x-transition:enter-start="opacity-0"
        x-transition:enter-end="opacity-100" x-transition:leave="transition ease-in duration-200"
        x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0"
        class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-80" style="display: none;"
        x-cloak>
        <div @click.away="showMissingCategoriesModal = false" x-transition:enter="transition ease-out duration-300"
            x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100"
            x-transition:leave="transition ease-in duration-200" x-transition:leave-start="opacity-100 scale-100"
            x-transition:leave-end="opacity-0 scale-95"
            class="bg-white rounded-lg text-left overflow-hidden shadow-xl w-full max-w-md flex flex-col">

            <div class="p-6 text-center">
                <div class="mx-auto flex items-center justify-center h-16 w-16 rounded-full bg-amber-100">
                    <i class="fa-solid fa-exclamation-triangle text-3xl text-amber-600"></i>
                </div>
                <h4 class="text-xl font-semibold text-gray-900 mt-4"><?php echo trans('lang.no_categories_found'); ?></h4>
                <p class="mt-2 text-sm text-gray-600"><?php echo trans('lang.no_categories_description'); ?></p>
            </div>

            <div class="bg-gray-50 px-4 py-4 border-t border-gray-200 flex flex-col gap-3">
                <a href="<?php echo route('category'); ?>" class="w-full h-12 flex items-center justify-center bg-blue-500 text-white text-base font-semibold rounded-md shadow-md uppercase transition-colors hover:bg-blue-600 focus:outline-none focus:ring-0 active:outline-none active:ring-0 hover:no-underline"
                    style="box-shadow: 1px 1px 2px rgba(0,0,0,0.2);">
                    <?php echo trans('lang.go_to_categories'); ?>

                </a>
                <button @click="showMissingCategoriesModal = false" type="button" class="w-full h-12 flex items-center justify-center bg-white text-gray-700 border border-gray-300 text-base font-semibold rounded-md shadow-sm uppercase transition-colors hover:bg-gray-50 focus:outline-none focus:ring-0 active:outline-none active:ring-0">
                    <?php echo trans('lang.cancel'); ?>

                </button>
            </div>
        </div>
    </div>

    
    <div x-show="showModal" x-transition:enter="transition ease-out duration-300" x-transition:enter-start="opacity-0"
        x-transition:enter-end="opacity-100" x-transition:leave="transition ease-in duration-200"
        x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0"
        class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-80" style="display: none;"
        x-cloak>
        <div @click.away="showModal = false" x-transition:enter="transition ease-out duration-300"
            x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100"
            x-transition:leave="transition ease-in duration-200" x-transition:leave-start="opacity-100 scale-100"
            x-transition:leave-end="opacity-0 scale-95"
            class="bg-white rounded-lg text-left overflow-hidden shadow-xl w-full max-w-md flex flex-col">

            <div class="p-6 text-center">
                <div class="mx-auto flex items-center justify-center h-16 w-16 rounded-full bg-red-100">
                    <i class="fa-solid fa-triangle-exclamation text-3xl text-red-600"></i>
                </div>
                <h4 class="text-xl font-semibold text-gray-900 mt-4"><?php echo trans('lang.confirmation'); ?></h4>
                <p class="mt-2 text-sm text-gray-600"><?php echo trans('lang.delete_confirmation_desc'); ?></p>
            </div>

            <div class="bg-gray-50 px-4 py-4 border-t border-gray-200 flex flex-col gap-3">
                <button @click="deleteItem()" type="button" class="w-full h-12 flex items-center justify-center bg-red-600 text-white text-base font-semibold rounded-md shadow-md uppercase transition-colors hover:bg-red-700 focus:outline-none focus:ring-0 active:outline-none active:ring-0" style="box-shadow: 1px 1px 2px rgba(0,0,0,0.2);"><?php echo trans('lang.delete'); ?></button>
                <button @click="showModal=false" type="button" class="w-full h-12 flex items-center justify-center bg-white text-gray-700 border border-gray-300 text-base font-semibold rounded-md shadow-sm uppercase transition-colors hover:bg-gray-50 focus:outline-none focus:ring-0 active:outline-none active:ring-0"><?php echo trans('lang.cancel'); ?></button>
            </div>
        </div>
    </div>

    
    <div x-show="notification.show" 
        x-transition:enter="transition ease-out duration-300"
        x-transition:enter-start="opacity-0 transform translate-y-2 sm:translate-y-0 sm:translate-x-2"
        x-transition:enter-end="opacity-100 transform translate-y-0 sm:translate-x-0"
        x-transition:leave="transition ease-in duration-300"
        x-transition:leave-start="opacity-100"
        x-transition:leave-end="opacity-0"
        class="fixed top-5 right-5 z-50 w-full 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">
            <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">
                        <span class="sr-only"><?php echo e(trans('lang.close')); ?></span>
                        <i class="fa-solid fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
    
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script>
    const translations = {
        item_deleted_successfully: "<?php echo e(trans('lang.item_deleted_successfully')); ?>",
        item_delete_error: "<?php echo e(trans('lang.item_delete_error')); ?>",
        status_updated_successfully: "<?php echo e(trans('lang.status_updated_successfully')); ?>",
        status_update_error: "<?php echo e(trans('lang.status_update_error')); ?>",
        data_load_error: "<?php echo e(trans('lang.data_load_error')); ?>",
        product_singular: "<?php echo e(trans('lang.product_singular')); ?>",
        products_plural: "<?php echo e(trans('lang.products_plural')); ?>",
    };

    // Data pre-loaded from PostgreSQL by FoodController
    const serverData = {
        items:            <?php echo json_encode($products->values(), 15, 512) ?>,
        categories:       <?php echo json_encode($categories->values(), 15, 512) ?>,
        categoryOrderMap: <?php echo json_encode($categoryOrderMap, 15, 512) ?>,
        subcategoryMap:   <?php echo json_encode($subcategoryMap, 15, 512) ?>,
        currency: {
            symbol:        <?php echo json_encode($currency['symbol'], 15, 512) ?>,
            symbolAtRight: <?php echo json_encode($currency['symbolAtRight'], 15, 512) ?>,
            decimalDigits: <?php echo json_encode($currency['decimalDigits'], 15, 512) ?>,
        },
        placeholderImage: <?php echo json_encode($placeholderImage, 15, 512) ?>,
        csrfToken: document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '',
    };

    function menuAlpine() {
        return {
            loading: false,
            dataTableProcessing: false,
            items: serverData.items,
            placeholderImage: serverData.placeholderImage,
            activeCurrency: serverData.currency.symbol,
            currencyAtRight: serverData.currency.symbolAtRight,
            decimal_degits: serverData.currency.decimalDigits,
            showModal: false,
            showMissingCategoriesModal: false,
            deleteId: null,
            notification: { show: false, type: 'success', message: '' },
            searchTerm: '',
            openCategoryFilter: false,
            selectedCategory: '',
            categories: serverData.categories,
            categoryOrderMap: serverData.categoryOrderMap,
            reinitTimeout: null,
            saveTimeout: null,
            sortKey: null,
            sortDirection: 'asc',
            dropUpCategory: false,

            showNotification(message, type = 'success', duration = 4000) {
                this.notification.message = message;
                this.notification.type = type;
                this.notification.show = true;
                setTimeout(() => { this.notification.show = false; }, duration);
            },

            getProductCountText(count) {
                return count === 1
                    ? `${count} ${translations.product_singular}`
                    : `${count} ${translations.products_plural}`;
            },

            toggleCategoryFilter() {
                this.openCategoryFilter = !this.openCategoryFilter;
                if (this.openCategoryFilter) {
                    this.$nextTick(() => {
                        const btn = this.$refs.categoryFilterButton;
                        if (!btn) return;
                        const rect = btn.getBoundingClientRect();
                        this.dropUpCategory = (window.innerHeight - rect.bottom) < 250;
                    });
                }
            },

            setCategory(category) {
                this.selectedCategory = category;
                this.openCategoryFilter = false;
            },

            initMenu() {
                this.initProductSortable();
            },

            formatPrice(item) {
                const val = (item.disPrice && item.disPrice !== 0) ? item.disPrice : item.price;
                const f   = val.toFixed(this.decimal_degits);
                if (item.disPrice && item.disPrice !== 0) {
                    const o = item.price.toFixed(this.decimal_degits);
                    return this.currencyAtRight
                        ? `${f}${this.activeCurrency} <s>${o}${this.activeCurrency}</s>`
                        : `${this.activeCurrency}${f} <s>${this.activeCurrency}${o}</s>`;
                }
                return this.currencyAtRight
                    ? `${f}${this.activeCurrency}`
                    : `${this.activeCurrency}${f}`;
            },

            async togglePublish(item) {
                this.dataTableProcessing = true;
                const newPublish = !item.publish;
                try {
                    const res = await fetch(`/api/foods/${item.id}/publish`, {
                        method: 'PATCH',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': serverData.csrfToken,
                        },
                        body: JSON.stringify({ publish: newPublish }),
                    });
                    if (!res.ok) throw new Error('Server error');
                    item.publish = newPublish;
                    this.showNotification(translations.status_updated_successfully, 'success');
                } catch (error) {
                    console.error('Error toggling publish:', error);
                    this.showNotification(translations.status_update_error, 'error');
                } finally {
                    this.dataTableProcessing = false;
                }
            },

            editUrl(id) {
                if (id === 'new') return `<?php echo e(route('foods.create')); ?>`;
                return `<?php echo e(route('foods.edit', ':id')); ?>`.replace(':id', id);
            },

            duplicateUrl(id) {
                return `<?php echo e(route('foods.create')); ?>?template=${id}`;
            },

            confirmDelete(id) {
                this.deleteId = id;
                this.showModal = true;
            },

            handleAddProduct() {
                if (this.categories.length === 0) {
                    this.showMissingCategoriesModal = true;
                } else {
                    window.location.href = this.editUrl('new');
                }
            },

            async deleteItem() {
                this.dataTableProcessing = true;
                this.showModal = false;
                try {
                    const res = await fetch(`/api/foods/${this.deleteId}`, {
                        method: 'DELETE',
                        headers: { 'X-CSRF-TOKEN': serverData.csrfToken },
                    });
                    if (!res.ok) throw new Error('Server error');
                    this.items = this.items.filter(i => i.id !== this.deleteId);
                    this.showNotification(translations.item_deleted_successfully, 'success');
                } catch (error) {
                    console.error('Error deleting item:', error);
                    this.showNotification(translations.item_delete_error, 'error');
                } finally {
                    this.dataTableProcessing = false;
                    this.deleteId = null;
                }
            },

            toggleSort(key) {
                if (this.sortKey === key) {
                    this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
                } else {
                    this.sortKey = key;
                    this.sortDirection = 'desc';
                }
            },

            get currentCategoryLabel() {
                return this.selectedCategory || "<?php echo e(trans('lang.menu_filter_all_categories')); ?>";
            },

            get filteredItems() {
                let arr = [...this.items];
                if (this.searchTerm.trim()) {
                    const st = this.searchTerm.toLowerCase();
                    arr = arr.filter(item => item.name.toLowerCase().includes(st));
                }
                if (this.selectedCategory) {
                    arr = arr.filter(item => item.category === this.selectedCategory);
                }
                if (this.sortKey) {
                    arr.sort((a, b) => {
                        let va = a[this.sortKey], vb = b[this.sortKey];
                        if (this.sortKey === 'price') {
                            va = va || (a.disPrice || 0);
                            vb = vb || (b.disPrice || 0);
                        }
                        if (this.sortDirection === 'asc') return va > vb ? 1 : (va < vb ? -1 : 0);
                        else return va < vb ? 1 : (va > vb ? -1 : 0);
                    });
                }
                return arr;
            },

            get groupedItems() {
                const groups = {};
                this.filteredItems.forEach(item => {
                    if (!groups[item.category]) {
                        groups[item.category] = {
                            categoryName: item.category,
                            subcategoryId: item.subcategoryId,
                            items: [],
                        };
                    }
                    groups[item.category].items.push(item);
                });
                Object.values(groups).forEach(group => {
                    group.items.sort((a, b) => (a.order || 0) - (b.order || 0));
                });
                return Object.values(groups).sort((a, b) => {
                    const orderA = this.categoryOrderMap[a.categoryName] ?? 999;
                    const orderB = this.categoryOrderMap[b.categoryName] ?? 999;
                    return orderA - orderB;
                });
            },

            async saveProductOrder(subcategoryId, productIds, isSilent = false) {
                try {
                    if (!isSilent) this.isLoading = true;
                    const res = await fetch('/api/foods/order', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': serverData.csrfToken,
                        },
                        body: JSON.stringify({ subcategoryId, productIds }),
                    });
                    if (!res.ok) throw new Error('Server error');
                    this.updateLocalProductOrder(subcategoryId, productIds);
                    await new Promise(resolve => setTimeout(resolve, 300));
                    if (!isSilent) {
                        this.showNotification('<?php echo e(trans("lang.product_order_updated")); ?>', 'success');
                    }
                } catch (error) {
                    console.error('Error saving product order:', error);
                    this.showNotification('<?php echo e(trans("lang.error_updating_order")); ?>', 'error');
                    window.location.reload();
                } finally {
                    if (!isSilent) this.isLoading = false;
                }
            },

            updateLocalProductOrder(subcategoryId, productIds) {
                const originalProductIds = [...productIds];
                const orderMap = {};
                productIds.forEach((productId, index) => {
                    if (productId) orderMap[String(productId)] = index + 1;
                });
                this.items.forEach(item => {
                    if (String(item.subcategoryId) === String(subcategoryId) &&
                        orderMap.hasOwnProperty(String(item.id))) {
                        item.order = orderMap[String(item.id)];
                    }
                });
                this.items = [...this.items];
                this.$nextTick(() => {
                    const container = document.querySelector(`#products-${subcategoryId}`);
                    if (container) {
                        const domOrder = Array.from(container.children)
                            .filter(row => row.dataset.productId)
                            .map(row => row.dataset.productId);
                        const isCorrect = JSON.stringify(domOrder) === JSON.stringify(originalProductIds.map(String));
                        if (!isCorrect) {
                            if (this.reinitTimeout) clearTimeout(this.reinitTimeout);
                            this.reinitTimeout = setTimeout(() => this.initProductSortable(), 100);
                        }
                    }
                });
            },

            async changeProductCategory(productId, newCategoryId, oldCategoryId, newIndex = null) {
                try {
                    this.isLoading = true;
                    const res = await fetch(`/api/foods/${productId}/category`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': serverData.csrfToken,
                        },
                        body: JSON.stringify({ newCategoryId, oldCategoryId, newIndex }),
                    });
                    if (!res.ok) throw new Error('Server error');
                    this.updateLocalProductCategory(productId, newCategoryId);
                    this.showNotification('<?php echo e(trans("lang.product_category_updated")); ?>', 'success');
                } catch (error) {
                    console.error('Error changing product category:', error);
                    this.showNotification('<?php echo e(trans("lang.error_changing_category")); ?>', 'error');
                    window.location.reload();
                } finally {
                    this.isLoading = false;
                }
            },

            updateLocalProductCategory(productId, newCategoryId) {
                const item = this.items.find(i => String(i.id) === String(productId));
                if (item) {
                    const newCategoryName = serverData.subcategoryMap[String(newCategoryId)] || 'Brak';
                    item.subcategoryId = String(newCategoryId);
                    item.category = newCategoryName;
                    item.order = 0;
                }
            },

            forceDOMUpdate() {
                this.items = [...this.items];
                this.$nextTick(() => {
                    setTimeout(() => this.initProductSortable(), 50);
                });
            },

            forceCorrectDOMOrder(container, evt) {
                const currentDOMOrder = Array.from(container.children)
                    .filter(el => el.dataset.productId)
                    .map(el => el.dataset.productId);
                const categoryId = container.id.replace('products-', '');
                this.updateLocalProductOrder(categoryId, currentDOMOrder);
                this.items = [...this.items];
                this.$nextTick(() => {
                    const newDOMOrder = Array.from(container.children)
                        .filter(el => el.dataset.productId)
                        .map(el => el.dataset.productId);
                    if (JSON.stringify(newDOMOrder) !== JSON.stringify(currentDOMOrder)) {
                        const allItems = Array.from(container.children).filter(el => el.dataset.productId);
                        allItems.forEach(item => item.remove());
                        currentDOMOrder.forEach(pid => {
                            const el = allItems.find(e => e.dataset.productId === pid);
                            if (el) container.appendChild(el);
                        });
                    }
                });
            },

            initProductSortable() {
                this.$nextTick(() => {
                    const alpineComponent = this;
                    this.groupedItems.forEach(group => {
                        const container = document.querySelector(`#products-${group.subcategoryId}`);
                        if (!container) return;
                        if (container.sortableInstance) {
                            container.sortableInstance.destroy();
                            container.sortableInstance = null;
                        }
                        container.sortableInstance = new Sortable(container, {
                            group:         'products',
                            animation:     200,
                            handle:        '.drag-handle',
                            ghostClass:    'sortable-ghost',
                            chosenClass:   'sortable-chosen',
                            dragClass:     'sortable-drag',
                            forceFallback: false,
                            swapThreshold: 0.65,
                            sort:          true,
                            disabled:      false,
                            onStart: (evt) => {
                                evt.item.classList.add('dragging');
                                setTimeout(() => {
                                    const ghostEl = document.querySelector('.sortable-ghost');
                                    if (ghostEl) ghostEl.setAttribute('x-ignore', '');
                                }, 50);
                                document.body.classList.add('is-dragging');
                                if (navigator.vibrate) navigator.vibrate(80);
                                try {
                                    const ctx  = new (window.AudioContext || window.webkitAudioContext)();
                                    const osc  = ctx.createOscillator();
                                    const gain = ctx.createGain();
                                    osc.connect(gain);
                                    gain.connect(ctx.destination);
                                    osc.frequency.value = 800;
                                    osc.type = 'sine';
                                    gain.gain.value = 0.08;
                                    osc.start();
                                    osc.stop(ctx.currentTime + 0.15);
                                } catch (e) {}
                            },
                            onMove: (evt) => {
                                document.querySelectorAll('.category-container.drag-over').forEach(el => {
                                    el.classList.remove('drag-over');
                                });
                                const targetCat = evt.to.closest('.category-container');
                                const sourceCat = evt.from.closest('.category-container');
                                if (targetCat && targetCat !== sourceCat) {
                                    targetCat.classList.add('drag-over');
                                }
                            },
                            onEnd: (evt) => {
                                evt.item.classList.remove('dragging');
                                document.body.classList.remove('is-dragging');
                                document.querySelectorAll('.category-container').forEach(el => {
                                    el.classList.remove('drag-over');
                                    el.style.position = '';
                                    el.querySelectorAll('.drop-hint').forEach(h => h.remove());
                                });
                                if (evt.oldIndex !== evt.newIndex || evt.from !== evt.to) {
                                    if (navigator.vibrate) navigator.vibrate([120, 60, 120]);
                                    try {
                                        const ctx  = new (window.AudioContext || window.webkitAudioContext)();
                                        const osc1 = ctx.createOscillator();
                                        const osc2 = ctx.createOscillator();
                                        const gain = ctx.createGain();
                                        osc1.connect(gain);
                                        osc2.connect(gain);
                                        gain.connect(ctx.destination);
                                        osc1.frequency.value = 600;
                                        osc1.type = 'sine';
                                        gain.gain.value = 0.06;
                                        osc2.frequency.value = 800;
                                        osc2.type = 'sine';
                                        osc1.start();
                                        osc1.stop(ctx.currentTime + 0.1);
                                        osc2.start(ctx.currentTime + 0.1);
                                        osc2.stop(ctx.currentTime + 0.2);
                                    } catch (e) {}
                                }
                                const fromContainer = evt.from;
                                const toContainer   = evt.to;
                                const productId = evt.item.dataset.productId || evt.item.getAttribute('data-product-id');
                                if (!productId) return;
                                alpineComponent.forceCorrectDOMOrder(toContainer, evt);
                                if (fromContainer !== toContainer) {
                                    const toCategoryId   = toContainer.id.replace('products-', '');
                                    const fromCategoryId = fromContainer.id.replace('products-', '');
                                    alpineComponent.changeProductCategory(productId, toCategoryId, fromCategoryId, evt.newIndex);
                                } else {
                                    const productIds = Array.from(toContainer.children)
                                        .filter(row => row.dataset.productId)
                                        .map(row => row.dataset.productId);
                                    const subcategoryId = toContainer.id.replace('products-', '');
                                    if (this.saveTimeout) clearTimeout(this.saveTimeout);
                                    this.saveTimeout = setTimeout(() => {
                                        alpineComponent.saveProductOrder(subcategoryId, productIds, true);
                                    }, 500);
                                }
                            },
                        });
                    });
                });
            },

            destroy() {
                if (this.saveTimeout)   clearTimeout(this.saveTimeout);
                if (this.reinitTimeout) clearTimeout(this.reinitTimeout);
                this.groupedItems.forEach(group => {
                    const container = document.querySelector(`#products-${group.subcategoryId}`);
                    if (container && container.sortableInstance) {
                        container.sortableInstance.destroy();
                        container.sortableInstance = null;
                    }
                });
                document.body.classList.remove('is-dragging');
                document.querySelectorAll('.category-container.drag-over').forEach(el => {
                    el.classList.remove('drag-over');
                });
            },
        };
    }
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\pub-and-go-merchant-np\resources\views/foods/index.blade.php ENDPATH**/ ?>