/* РЕЖИМ РЕДАКТИРОВАНИЯ */
.edit-mode .order-items-container {
    padding: 15px;
}

.edit-form-container {
    background: linear-gradient(145deg, #1a1b23 0%, #16171e 100%);
    border-radius: 12px;
    border: 1px solid #24252e;
    padding: 20px;
}

.edit-form {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.form-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.form-group label {
    font-size: 12px;
    color: #8c8e9a;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}

.edit-input {
    padding: 12px 16px;
    background: rgba(12, 12, 14, 0.7);
    border: 1px solid #24252e;
    border-radius: 8px;
    color: #ffffff;
    font-size: 14px;
    transition: all 0.2s;
}

.edit-input:focus {
    outline: none;
    border-color: #4a90e2;
    box-shadow: 0 0 0 2px rgba(74, 144, 226, 0.2);
}

.edit-textarea {
    padding: 12px 16px;
    background: rgba(12, 12, 14, 0.7);
    border: 1px solid #24252e;
    border-radius: 8px;
    color: #ffffff;
    font-size: 14px;
    min-height: 80px;
    resize: vertical;
    font-family: inherit;
    transition: all 0.2s;
}

.edit-textarea:focus {
    outline: none;
    border-color: #4a90e2;
    box-shadow: 0 0 0 2px rgba(74, 144, 226, 0.2);
}

.image-upload {
    display: flex;
    align-items: center;
    gap: 12px;
}

.image-preview {
    width: 80px;
    height: 80px;
    background: linear-gradient(145deg, #24252e 0%, #1e1f27 100%);
    border-radius: 8px;
    border: 1px dashed #3a3b45;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    cursor: pointer;
    transition: all 0.2s;
}

.image-preview:hover {
    border-color: #4a90e2;
    background: linear-gradient(145deg, #2a2b35 0%, #24252e 100%);
}

.upload-btn {
    padding: 10px 16px;
    background: linear-gradient(145deg, #2a2b35 0%, #24252e 100%);
    border: 1px solid #3a3b45;
    border-radius: 6px;
    color: #8c8e9a;
    font-size: 12px;
    cursor: pointer;
    transition: all 0.2s;
}

.upload-btn:hover {
    background: linear-gradient(145deg, #3a3b45 0%, #2a2b35 100%);
    color: #ffffff;
}

.form-actions {
    display: flex;
    gap: 12px;
    margin-top: 20px;
}

.form-btn {
    flex: 1;
    padding: 14px;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}

.cancel-btn {
    background: linear-gradient(145deg, #1a1b23 0%, #16171e 100%);
    color: #8c8e9a;
    border: 1px solid #24252e;
}

.cancel-btn:hover {
    background: linear-gradient(145deg, #20212a 0%, #1c1d25 100%);
    color: #ffffff;
}

.save-btn {
    background: linear-gradient(145deg, #34c759 0%, #2db54d 100%);
    color: #ffffff;
    border: none;
}

.save-btn:hover {
    background: linear-gradient(145deg, #3cd763 0%, #32c557 100%);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(52, 199, 89, 0.3);
}

/* Кнопки в верхней панели в режиме редактирования */
.edit-mode-active .top-button {
    opacity: 0.7;
}

.edit-mode-active #editMenuButton {
    display: none !important;
}

.edit-mode-active #backofficeButton {
    display: none !important;
}

#doneEditButton {
    display: none;
    background: linear-gradient(to bottom, #34c759 0%, #2db54d 100%);
    color: #ffffff;
}

.edit-mode-active #doneEditButton {
    display: block;
}

.edit-mode-active #logoutButton {
    display: none;
}

/* Подсветка редактируемого товара */
.product-card.editing {
    border: 2px solid #4a90e2;
    box-shadow: 0 0 20px rgba(74, 144, 226, 0.4);
    transform: scale(1.02);
}

/* Товары в режиме редактирования */
.edit-mode .product-card {
    cursor: pointer;
    position: relative;
}

.edit-mode .product-card:hover::after {
    content: "✏️";
    position: absolute;
    top: 10px;
    right: 10px;
    background: rgba(74, 144, 226, 0.9);
    width: 24px;
    height: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
}

/* СТИЛИ ДЛЯ КНОПОК ДОБАВЛЕНИЯ В РЕЖИМЕ РЕДАКТИРОВАНИЯ */

/* Кнопка добавления категории */
.category-item.add-category-btn {
    background: linear-gradient(145deg, #1a1b23 0%, #16171e 100%);
    border: 1px dashed #34c759;
    color: #34c759;
    min-height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
}

.category-item.add-category-btn:hover {
    background: linear-gradient(145deg, #20212a 0%, #1c1d25 100%);
    border: 1px solid #34c759;
    transform: translateX(4px);
    box-shadow: 0 0 15px rgba(52, 199, 89, 0.3);
}

.category-item.add-category-btn .category-name {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 5px;
}

/* Карточка добавления товара */
.product-card.add-product-card {
    background: linear-gradient(145deg, #1a1b23 0%, #16171e 100%);
    border: 1px dashed #34c759;
    opacity: 0.8;
    transition: all 0.3s;
}

.product-card.add-product-card:hover {
    background: linear-gradient(145deg, #20212a 0%, #1c1d25 100%);
    border: 1px solid #34c759;
    opacity: 1;
    transform: translateY(-4px);
    box-shadow: 0 12px 24px rgba(0, 0, 0, 0.4), 
                0 0 20px rgba(52, 199, 89, 0.2);
}

.product-card.add-product-card .product-image {
    background: linear-gradient(145deg, #34c759 0%, #2db54d 100%) !important;
    border: 1px solid #34c759;
    box-shadow: 0 4px 8px rgba(52, 199, 89, 0.3);
}

/* Кнопка добавления зала */
.top-button.add-hall-btn {
    background: linear-gradient(145deg, #1a1b23 0%, #16171e 100%);
    border: 1px dashed #34c759 !important;
    color: #34c759;
    min-width: 140px;
    position: relative;
    overflow: hidden;
}

.top-button.add-hall-btn:hover {
    background: linear-gradient(145deg, #20212a 0%, #1c1d25 100%);
    border: 1px solid #34c759 !important;
    color: #ffffff;
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3),
                0 0 15px rgba(52, 199, 89, 0.2);
}

.top-button.add-hall-btn::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 0;
    height: 0;
    border-radius: 50%;
    background: rgba(52, 199, 89, 0.1);
    transform: translate(-50%, -50%);
    transition: width 0.3s, height 0.3s;
}

.top-button.add-hall-btn:hover::after {
    width: 100%;
    height: 100%;
}

/* Анимация появления кнопок добавления */
@keyframes fadeInAddButton {
    from {
        opacity: 0;
        transform: scale(0.8);
    }
    to {
        opacity: 1;
        transform: scale(1);
    }
}

.category-item.add-category-btn,
.product-card.add-product-card,
.top-button.add-hall-btn {
    animation: fadeInAddButton 0.3s ease-out;
}

/* Стили для активных кнопок добавления при наведении */
.edit-mode .category-item:not(.add-category-btn):hover {
    border-color: #4a90e2;
}

.edit-mode .product-card:not(.add-product-card):hover {
    border-color: #4a90e2;
}

/* Индикатор режима редактирования */
.edit-mode-indicator {
    position: fixed;
    top: 10px;
    right: 10px;
    background: rgba(52, 199, 89, 0.2);
    color: #34c759;
    padding: 5px 10px;
    border-radius: 5px;
    font-size: 11px;
    z-index: 1000;
    border: 1px solid rgba(52, 199, 89, 0.3);
}

/* Улучшенные стили для формы редактирования в правой панели */
.edit-mode .edit-form-container {
    animation: slideInRight 0.3s ease-out;
}

@keyframes slideInRight {
    from {
        opacity: 0;
        transform: translateX(20px);
    }
    to {
        opacity: 1;
        transform: translateX(0);
    }
}

/* Стили для контекстных подсказок */
.add-product-card .product-price {
    font-size: 11px !important;
    color: #8c8e9a !important;
    font-weight: 400;
    text-align: center;
    padding: 0 5px;
    min-height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* Скрытие ненужных полей в форме */
.form-group[style*="display: none"] {
    display: none !important;
}

/* Индикатор текущей категории */
.category-indicator {
    position: absolute;
    top: 5px;
    right: 5px;
    background: rgba(52, 199, 89, 0.2);
    color: #34c759;
    font-size: 10px;
    padding: 2px 6px;
    border-radius: 3px;
    border: 1px solid rgba(52, 199, 89, 0.3);
}

/* Индикатор текущего зала */
.hall-indicator {
    position: absolute;
    top: 5px;
    right: 5px;
    background: rgba(74, 144, 226, 0.2);
    color: #4a90e2;
    font-size: 10px;
    padding: 2px 6px;
    border-radius: 3px;
    border: 1px solid rgba(74, 144, 226, 0.3);
}

/* Анимация переключения форм */
.edit-form-container {
    transition: all 0.3s ease;
}

/* Стили для кнопок в правой панели */
.header-button.active-mode {
    border-bottom: 2px solid #34c759;
    color: #34c759;
}

/* Подсказка при наведении на кнопку добавления товара */
.add-product-card:hover::after {
    content: 'Товар будет добавлен в текущую категорию';
    position: absolute;
    bottom: -40px;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(0, 0, 0, 0.9);
    color: white;
    padding: 8px 12px;
    border-radius: 6px;
    font-size: 11px;
    white-space: nowrap;
    z-index: 100;
    pointer-events: none;
}

.add-category-btn:hover::after {
    content: 'Добавить новую категорию';
    position: absolute;
    bottom: -35px;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(0, 0, 0, 0.9);
    color: white;
    padding: 6px 10px;
    border-radius: 6px;
    font-size: 11px;
    white-space: nowrap;
    z-index: 100;
    pointer-events: none;
}

// Добавьте стили для загрузки изображений в styles.css:
/*
.image-upload-area {
    border: 2px dashed #3a3b45;
    border-radius: 10px;
    padding: 20px;
    text-align: center;
    transition: all 0.3s;
}

.image-upload-area:hover {
    border-color: #4a90e2;
    background: rgba(74, 144, 226, 0.05);
}

.image-preview {
    min-height: 120px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    border-radius: 8px;
    overflow: hidden;
}

.upload-icon {
    font-size: 40px;
    color: #8c8e9a;
    margin-bottom: 10px;
}

.upload-text {
    color: #8c8e9a;
    font-size: 14px;
}

.image-actions {
    display: flex;
    gap: 10px;
    justify-content: center;
    margin-top: 15px;
}

.upload-btn, .remove-btn {
    padding: 8px 16px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 12px;
}

.upload-btn {
    background: #4a90e2;
    color: white;
}

.remove-btn {
    background: #ff3b30;
    color: white;
}

/* Стили для управления видимостью кнопок в режиме редактирования */
.edit-mode-active .controls-section #editMenuButton {
    display: none !important;
}

.edit-mode-active .controls-section #backofficeButton {
    display: none !important;
}

.edit-mode-active .controls-section #logoutButton {
    display: none !important;
}

.edit-mode-active .controls-section #doneEditButton {
    display: block !important;
}

/* Стиль для кнопки "ГОТОВО" */
#doneEditButton {
    background: linear-gradient(to bottom, #34c759 0%, #2db54d 100%) !important;
    color: #ffffff !important;
    border: 1px solid #2db54d !important;
}

#doneEditButton:hover {
    background: linear-gradient(to bottom, #3cd763 0%, #32c557 100%) !important;
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(52, 199, 89, 0.3);
}

// edit-mode.js - с редактированием и удалением категорий и залов

let isEditMode = false;
let categoriesData = [];
let hallsData = [];
let productsData = [];
let currentEditItemId = null;
let currentEditType = null; // 'category', 'hall', 'product'

// ====================
// ИНИЦИАЛИЗАЦИЯ
// ====================

document.addEventListener('DOMContentLoaded', async function() {
    console.log('Edit mode loading...');
    
    // Загружаем данные
    await loadAllData();
    
    // Настраиваем обработчики
    setupEventListeners();
    
    // Показываем первую категорию по умолчанию
    if (categoriesData.length > 0 && !document.querySelector('.category-item.active')) {
        const firstCategory = document.querySelector('.category-item');
        if (firstCategory) {
            firstCategory.classList.add('active');
            const title = document.querySelector('.category-title span');
            if (title) {
                title.textContent = firstCategory.dataset.categoryName || 'Категория';
            }
        }
    }
    
    console.log('Edit mode ready');
});

async function loadAllData() {
    try {
        // Загружаем категории
        const catResponse = await fetch('/api/categories.php');
        categoriesData = await catResponse.json();
        console.log('Categories loaded:', categoriesData);
        
        // Загружаем залы
        const hallsResponse = await fetch('/api/halls.php');
        hallsData = await hallsResponse.json();
        console.log('Halls loaded:', hallsData);
        
        // Загружаем товары
        const productsResponse = await fetch('/api/products.php');
        productsData = await productsResponse.json();
        console.log('Products loaded:', productsData);
        
        // Обновляем интерфейс с данными из базы
        updateCategoriesFromDatabase();
        updateHallsFromDatabase();
        
        // Загружаем товары первой категории
        if (categoriesData.length > 0) {
            filterProductsByCategory(categoriesData[0].id);
        }
        
    } catch (error) {
        console.error('Error loading data:', error);
        // Если API не работает, используем демо-данные
        useDemoData();
    }
}

function useDemoData() {
    // Демо-данные для тестирования
    categoriesData = [
        { id: 1, name: 'Пиво', position: 1 },
        { id: 2, name: 'Вино', position: 2 },
        { id: 3, name: 'Коктейли', position: 3 }
    ];
    
    hallsData = [
        { id: 1, name: 'ЗАЛ', position: 1 },
        { id: 2, name: 'ТЕРРАСА', position: 2 },
        { id: 3, name: 'ВИП', position: 3 }
    ];
    
    productsData = [
        { id: 1, name: 'Indian Pale Ale', price: 390, category_id: 1, position: 1 },
        { id: 2, name: 'Czech Lager', price: 320, category_id: 1, position: 2 },
        { id: 3, name: 'Imperial Stout', price: 410, category_id: 1, position: 3 }
    ];
    
    updateCategoriesFromDatabase();
    updateHallsFromDatabase();
    filterProductsByCategory(1);
}

// ====================
// ОБНОВЛЕНИЕ ИНТЕРФЕЙСА ИЗ БАЗЫ ДАННЫХ
// ====================

function updateCategoriesFromDatabase() {
    const categoriesList = document.getElementById('categoriesList');
    if (!categoriesList) return;
    
    console.log('Updating categories from database...');
    
    // Очищаем существующие категории (кроме кнопки добавления если есть)
    const existingCategories = categoriesList.querySelectorAll('.category-item:not(.add-category-btn)');
    existingCategories.forEach(cat => cat.remove());
    
    // Сортируем категории по position
    const sortedCategories = [...categoriesData].sort((a, b) => a.position - b.position);
    
    // Добавляем категории из базы
    sortedCategories.forEach(category => {
        const categoryItem = document.createElement('div');
        categoryItem.className = 'category-item';
        categoryItem.dataset.categoryId = category.id;
        categoryItem.dataset.categoryName = category.name;
        categoryItem.dataset.categoryPosition = category.position;
        
        // Добавляем иконку редактирования при наведении
        categoryItem.innerHTML = `
            <div class="category-name">${category.name}</div>
            <div class="category-actions" style="display: none; position: absolute; right: 10px; top: 10px;">
                <button class="edit-category-btn" style="background: none; border: none; color: #4a90e2; cursor: pointer; font-size: 12px; padding: 5px; z-index: 100;">✏️</button>
            </div>
        `;
        
        // Показываем кнопку редактирования при наведении в режиме редактирования
        if (isEditMode) {
            categoryItem.addEventListener('mouseenter', function() {
                const actions = this.querySelector('.category-actions');
                if (actions) actions.style.display = 'block';
            });
            
            categoryItem.addEventListener('mouseleave', function() {
                const actions = this.querySelector('.category-actions');
                if (actions) actions.style.display = 'none';
            });
        }
        
        // Обработчик клика по категории
        categoryItem.addEventListener('click', function(e) {
            // Если кликнули по кнопке редактирования - не переключаем категорию
            if (e.target.closest('.edit-category-btn')) {
                e.stopPropagation();
                editCategory(category.id);
                return;
            }
            
            console.log('Category clicked:', category.id, category.name);
            
            // Обычный клик - переключаем категорию
            document.querySelectorAll('.category-item').forEach(item => {
                item.classList.remove('active');
            });
            
            this.classList.add('active');
            
            const title = document.querySelector('.category-title span');
            if (title) {
                title.textContent = category.name;
            }
            
            filterProductsByCategory(category.id);
            
            // Обновляем кнопку добавления товара
            updateAddProductButton();
        });
        
        // Обработчик кнопки редактирования
        const editBtn = categoryItem.querySelector('.edit-category-btn');
        if (editBtn) {
            editBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                e.preventDefault();
                editCategory(category.id);
            });
        }
        
        categoriesList.appendChild(categoryItem);
    });
    
    console.log('Categories updated');
}

function updateHallsFromDatabase() {
    const hallsSection = document.querySelector('.halls-section');
    if (!hallsSection) return;
    
    console.log('Updating halls from database...');
    
    // Очищаем существующие залы (кроме кнопки добавления если есть)
    const existingHalls = hallsSection.querySelectorAll('.hall-tab:not(.add-hall-btn)');
    existingHalls.forEach(hall => hall.remove());
    
    // Сортируем залы по position
    const sortedHalls = [...hallsData].sort((a, b) => a.position - b.position);
    
    // Добавляем залы из базы
    sortedHalls.forEach(hall => {
        const hallBtn = document.createElement('button');
        hallBtn.className = 'top-button hall-tab';
        hallBtn.textContent = hall.name.toUpperCase();
        hallBtn.dataset.hallId = hall.id;
        hallBtn.dataset.hallName = hall.name;
        hallBtn.dataset.hallPosition = hall.position;
        
        // Добавляем контекстное меню для редактирования
        hallBtn.addEventListener('contextmenu', function(e) {
            e.preventDefault();
            if (isEditMode) {
                showHallContextMenu(e, hall.id);
            }
        });
        
        // Обработчик клика
        hallBtn.addEventListener('click', function(e) {
            // Если это правый клик (контекстное меню уже обработано)
            if (e.button === 2) return;
            
            document.querySelectorAll('.hall-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            this.classList.add('active');
        });
        
        hallsSection.appendChild(hallBtn);
    });
    
    // Активируем первый зал если нет активного
    if (!document.querySelector('.hall-tab.active') && sortedHalls.length > 0) {
        const firstHall = hallsSection.querySelector('.hall-tab');
        if (firstHall) {
            firstHall.classList.add('active');
        }
    }
    
    console.log('Halls updated');
}

// Контекстное меню для залов
function showHallContextMenu(e, hallId) {
    console.log('Showing context menu for hall:', hallId);
    
    // Удаляем старое меню если есть
    const oldMenu = document.getElementById('hallContextMenu');
    if (oldMenu) oldMenu.remove();
    
    const menu = document.createElement('div');
    menu.id = 'hallContextMenu';
    menu.style.cssText = `
        position: fixed;
        background: #1a1b23;
        border: 1px solid #24252e;
        border-radius: 8px;
        padding: 8px 0;
        z-index: 10000;
        box-shadow: 0 4px 12px rgba(0,0,0,0.5);
        min-width: 150px;
    `;
    
    menu.innerHTML = `
        <div class="context-menu-item" data-action="edit" style="padding: 8px 16px; cursor: pointer; color: #8c8e9a; font-size: 12px; display: flex; align-items: center; gap: 8px;">
            <span>✏️</span> Редактировать зал
        </div>
        <div class="context-menu-item" data-action="delete" style="padding: 8px 16px; cursor: pointer; color: #ff3b30; font-size: 12px; display: flex; align-items: center; gap: 8px;">
            <span>🗑️</span> Удалить зал
        </div>
    `;
    
    // Позиционируем меню
    menu.style.left = e.pageX + 'px';
    menu.style.top = e.pageY + 'px';
    
    document.body.appendChild(menu);
    
    // Обработчики пунктов меню
    menu.querySelector('[data-action="edit"]').addEventListener('click', function() {
        console.log('Edit hall clicked:', hallId);
        editHall(hallId);
        menu.remove();
    });
    
    menu.querySelector('[data-action="delete"]').addEventListener('click', function() {
        console.log('Delete hall clicked:', hallId);
        deleteHall(hallId);
        menu.remove();
    });
    
    // Закрытие меню при клике вне его
    setTimeout(() => {
        const closeMenu = (e) => {
            if (!menu.contains(e.target)) {
                menu.remove();
                document.removeEventListener('click', closeMenu);
            }
        };
        document.addEventListener('click', closeMenu);
    }, 100);
}

// ====================
// РЕДАКТИРОВАНИЕ КАТЕГОРИЙ И ЗАЛОВ
// ====================

function editCategory(categoryId) {
    console.log('Editing category:', categoryId);
    
    const category = categoriesData.find(c => c.id == categoryId);
    if (!category) {
        alert('Категория не найдена');
        return;
    }
    
    currentEditItemId = categoryId;
    currentEditType = 'category';
    
    // Заполняем форму
    document.getElementById('editName').value = category.name || '';
    document.getElementById('editPosition').value = category.position || 0;
    document.getElementById('editProductName').textContent = `Редактирование: ${category.name}`;
    
    // Показываем только нужные поля
    showFormFields(['editName']);
    hideFormFields(['editPrice', 'editIngredients', 'editAdditives']);
    
    // Добавляем поле для позиции
    addPositionField();
    
    // Меняем кнопки
    document.getElementById('saveEditBtn').textContent = 'Обновить категорию';
    document.getElementById('saveEditBtn').onclick = updateCategory;
    
    // Кнопка удаления - делаем видимой и настраиваем
    const deleteBtn = document.getElementById('deleteProductBtn');
    if (deleteBtn) {
        deleteBtn.style.display = 'block';
        deleteBtn.textContent = 'Удалить категорию';
        deleteBtn.onclick = function() {
            deleteCategory(categoryId);
        };
    }
    
    // Фокус
    document.getElementById('editName').focus();
}

function editHall(hallId) {
    console.log('Editing hall:', hallId);
    
    const hall = hallsData.find(h => h.id == hallId);
    if (!hall) {
        alert('Зал не найден');
        return;
    }
    
    currentEditItemId = hallId;
    currentEditType = 'hall';
    
    // Заполняем форму
    document.getElementById('editName').value = hall.name || '';
    document.getElementById('editProductName').textContent = `Редактирование: ${hall.name}`;
    
    // Показываем только нужные поля
    showFormFields(['editName']);
    hideFormFields(['editPrice', 'editIngredients', 'editAdditives', 'editPosition']);
    
    // Меняем кнопки
    document.getElementById('saveEditBtn').textContent = 'Обновить зал';
    document.getElementById('saveEditBtn').onclick = updateHall;
    
    document.getElementById('deleteProductBtn').style.display = 'block';
    document.getElementById('deleteProductBtn').textContent = 'Удалить зал';
    document.getElementById('deleteProductBtn').onclick = function() {
        deleteHall(hallId);
    };
    
    // Фокус
    document.getElementById('editName').focus();
}

// ====================
// ОБНОВЛЕНИЕ КАТЕГОРИЙ И ЗАЛОВ
// ====================

async function updateCategory() {
    if (!currentEditItemId || currentEditType !== 'category') return;
    
    const name = document.getElementById('editName').value.trim();
    const position = document.getElementById('editPosition')?.value || 0;
    
    if (!name) {
        alert('Введите название категории');
        return;
    }
    
    try {
        const response = await fetch('/api/categories.php', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                id: currentEditItemId,
                name: name,
                position: parseInt(position)
            })
        });
        
        const result = await response.json();
        console.log('Update category response:', result);
        
        if (result.success) {
            // Обновляем категорию в массиве
            const index = categoriesData.findIndex(c => c.id == currentEditItemId);
            if (index !== -1) {
                categoriesData[index] = { ...categoriesData[index], name, position: parseInt(position) };
            }
            
            // Обновляем интерфейс
            updateCategoriesFromDatabase();
            
            // Очищаем форму
            clearEditForm();
            
            alert('✅ Категория обновлена успешно!');
        } else {
            alert('❌ Ошибка: ' + (result.message || 'Неизвестная ошибка'));
        }
    } catch (error) {
        console.error('Error updating category:', error);
        alert('❌ Ошибка сети при обновлении категории');
    }
}

async function updateHall() {
    if (!currentEditItemId || currentEditType !== 'hall') return;
    
    const name = document.getElementById('editName').value.trim();
    
    if (!name) {
        alert('Введите название зала');
        return;
    }
    
    try {
        const response = await fetch('/api/halls.php', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                id: currentEditItemId,
                name: name,
                position: 0
            })
        });
        
        const result = await response.json();
        console.log('Update hall response:', result);
        
        if (result.success) {
            // Обновляем зал в массиве
            const index = hallsData.findIndex(h => h.id == currentEditItemId);
            if (index !== -1) {
                hallsData[index] = { ...hallsData[index], name };
            }
            
            // Обновляем интерфейс
            updateHallsFromDatabase();
            
            // Очищаем форму
            clearEditForm();
            
            alert('✅ Зал обновлен успешно!');
        } else {
            alert('❌ Ошибка: ' + (result.message || 'Неизвестная ошибка'));
        }
    } catch (error) {
        console.error('Error updating hall:', error);
        alert('❌ Ошибка сети при обновлении зала');
    }
}

// ====================
// УДАЛЕНИЕ КАТЕГОРИЙ И ЗАЛОВ
// ====================

async function deleteCategory(categoryId) {
    if (!confirm('Внимание! При удалении категории все товары в этой категории также будут удалены.\n\nВы уверены, что хотите удалить эту категорию?')) {
        return;
    }
    
    console.log('Deleting category:', categoryId);
    
    try {
        const response = await fetch(`/api/categories.php?id=${categoryId}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        console.log('Delete category response:', result);
        
        if (result.success) {
            // Удаляем категорию из массива
            categoriesData = categoriesData.filter(c => c.id != categoryId);
            
            // Удаляем товары этой категории из массива
            productsData = productsData.filter(p => p.category_id != categoryId);
            
            // Обновляем интерфейс
            updateCategoriesFromDatabase();
            
            // Очищаем форму
            clearEditForm();
            
            alert('✅ Категория и связанные товары удалены успешно!');
        } else {
            alert('❌ Ошибка: ' + (result.message || 'Неизвестная ошибка'));
        }
    } catch (error) {
        console.error('Error deleting category:', error);
        alert('❌ Ошибка сети при удалении категории');
    }
}

async function deleteHall(hallId) {
    if (!confirm('Вы уверены, что хотите удалить этот зал?')) {
        return;
    }
    
    console.log('Deleting hall:', hallId);
    
    try {
        const response = await fetch(`/api/halls.php?id=${hallId}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        console.log('Delete hall response:', result);
        
        if (result.success) {
            // Удаляем зал из массива
            hallsData = hallsData.filter(h => h.id != hallId);
            
            // Обновляем интерфейс
            updateHallsFromDatabase();
            
            // Очищаем форму
            clearEditForm();
            
            alert('✅ Зал удален успешно!');
        } else {
            alert('❌ Ошибка: ' + (result.message || 'Неизвестная ошибка'));
        }
    } catch (error) {
        console.error('Error deleting hall:', error);
        alert('❌ Ошибка сети при удалении зала');
    }
}

// ====================
// РЕЖИМ РЕДАКТИРОВАНИЯ
// ====================

function enableEditMode() {
    if (isEditMode) return;
    
    console.log('Enabling edit mode...');
    isEditMode = true;
    
    // Добавляем класс к body для скрытия/показа кнопок
    document.body.classList.add('edit-mode-active');
    
    // Переключаем панели
    const orderPanel = document.querySelector('.current-order:not(.edit-mode)');
    const editPanel = document.getElementById('editPanel');
    
    if (orderPanel && editPanel) {
        orderPanel.style.display = 'none';
        editPanel.style.display = 'flex';
    }
    
    // Показываем кнопку ГОТОВО и скрываем другие
    const doneEditButton = document.getElementById('doneEditButton');
    if (doneEditButton) {
        doneEditButton.style.display = 'block';
    }
    
    // Меняем обработчики товаров на редактирование
    setupEditModeHandlers();
    
    // Добавляем кнопки "+"
    addPlusButtons();
    
    // Обновляем интерфейс
    updateAddProductButton();
    
    console.log('Edit mode enabled');
}

function disableEditMode() {
    if (!isEditMode) return;
    
    console.log('Disabling edit mode...');
    isEditMode = false;
    
    // Убираем класс с body
    document.body.classList.remove('edit-mode-active');
    
    // Возвращаем панели
    const orderPanel = document.querySelector('.current-order:not(.edit-mode)');
    const editPanel = document.getElementById('editPanel');
    
    if (orderPanel && editPanel) {
        editPanel.style.display = 'none';
        orderPanel.style.display = 'flex';
    }
    
    // Скрываем кнопку ГОТОВО
    const doneEditButton = document.getElementById('doneEditButton');
    if (doneEditButton) {
        doneEditButton.style.display = 'none';
    }
    
    // Возвращаем обычные обработчики
    setupNormalHandlers();
    
    // Убираем кнопки "+"
    removePlusButtons();
    
    // Скрываем кнопки редактирования в категориях
    document.querySelectorAll('.category-actions').forEach(action => {
        action.style.display = 'none';
    });
    
    console.log('Edit mode disabled');
}

// ====================
// ФИЛЬТРАЦИЯ ТОВАРОВ
// ====================

function filterProductsByCategory(categoryId) {
    const productsGrid = document.getElementById('productsGrid');
    if (!productsGrid) return;
    
    console.log('Filtering products for category:', categoryId);
    
    // Очищаем сетку (кроме кнопки добавления если есть)
    const existingProducts = productsGrid.querySelectorAll('.product-card:not(.add-product-card)');
    existingProducts.forEach(product => product.remove());
    
    // Фильтруем товары по категории
    const filteredProducts = productsData.filter(product => product.category_id == categoryId);
    
    // Сортируем по позиции
    filteredProducts.sort((a, b) => (a.position || 0) - (b.position || 0));
    
    // Добавляем товары в сетку
    filteredProducts.forEach(product => {
        const productCard = document.createElement('div');
        productCard.className = 'product-card depth-layer';
        productCard.dataset.productId = product.id;
        
        productCard.innerHTML = `
            <div class="product-image">🛒</div>
            <div class="product-name">${product.name}</div>
            <div class="product-price">${product.price} руб.</div>
        `;
        
        // Обработчик клика в режиме редактирования
        if (isEditMode) {
            productCard.style.cursor = 'pointer';
            productCard.title = 'Нажмите для редактирования';
            productCard.addEventListener('click', function() {
                editProduct(product.id);
            });
        } else {
            // Обычный обработчик - добавление в заказ
            productCard.addEventListener('click', function() {
                addToOrder(product);
            });
        }
        
        productsGrid.appendChild(productCard);
    });
    
    console.log(`Added ${filteredProducts.length} products for category ${categoryId}`);
}

// ====================
// КНОПКИ ДОБАВЛЕНИЯ "+"
// ====================

function addPlusButtons() {
    console.log('Adding plus buttons...');
    
    // Кнопка добавления категории
    const categoriesList = document.getElementById('categoriesList');
    if (categoriesList && !document.getElementById('addCategoryBtn')) {
        const addCategoryBtn = document.createElement('div');
        addCategoryBtn.id = 'addCategoryBtn';
        addCategoryBtn.className = 'category-item add-category-btn';
        addCategoryBtn.innerHTML = `
            <div class="category-name" style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%;">
                <span style="color: #34c759; font-size: 24px;">+</span>
                <div style="font-size: 12px; margin-top: 5px; color: #34c759;">Добавить категорию</div>
            </div>
        `;
        
        addCategoryBtn.addEventListener('click', function() {
            showAddCategoryForm();
        });
        
        categoriesList.appendChild(addCategoryBtn);
    }
    
    // Кнопка добавления товара
    const productsGrid = document.getElementById('productsGrid');
    if (productsGrid && !document.getElementById('addProductBtn')) {
        const addProductBtn = document.createElement('div');
        addProductBtn.id = 'addProductBtn';
        addProductBtn.className = 'product-card add-product-card depth-layer';
        
        // Определяем текущую категорию
        const activeCategory = document.querySelector('.category-item.active');
        let categoryText = 'Добавить продукт';
        
        if (activeCategory) {
            const catName = activeCategory.dataset.categoryName || activeCategory.querySelector('.category-name').textContent;
            categoryText = `Добавить в "${catName}"`;
        }
        
        addProductBtn.innerHTML = `
            <div class="product-image" style="background: linear-gradient(145deg, #34c759 0%, #2db54d 100%); display: flex; align-items: center; justify-content: center;">
                <span style="font-size: 32px; color: white;">+</span>
            </div>
            <div class="product-name" style="color: #34c759; text-align: center;">${categoryText}</div>
            <div class="product-price" style="color: #8c8e9a; font-size: 11px; text-align: center;">Нажмите для создания</div>
        `;
        
        addProductBtn.addEventListener('click', function() {
            showAddProductForm();
        });
        
        productsGrid.appendChild(addProductBtn);
    }
    
    // Кнопка добавления зала
    const hallsSection = document.querySelector('.halls-section');
    if (hallsSection && !document.getElementById('addHallBtn')) {
        const addHallBtn = document.createElement('button');
        addHallBtn.id = 'addHallBtn';
        addHallBtn.className = 'top-button hall-tab add-hall-btn';
        addHallBtn.innerHTML = '+ ДОБАВИТЬ ЗАЛ';
        addHallBtn.style.color = '#34c759';
        addHallBtn.style.border = '1px dashed #34c759';
        addHallBtn.style.minWidth = '140px';
        
        addHallBtn.addEventListener('click', function() {
            showAddHallForm();
        });
        
        hallsSection.appendChild(addHallBtn);
    }
}

function removePlusButtons() {
    ['addCategoryBtn', 'addProductBtn', 'addHallBtn'].forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.remove();
        }
    });
}

function updateAddProductButton() {
    const addProductBtn = document.getElementById('addProductBtn');
    if (!addProductBtn) return;
    
    const activeCategory = document.querySelector('.category-item.active');
    if (activeCategory) {
        const catName = activeCategory.dataset.categoryName || activeCategory.querySelector('.category-name').textContent;
        const productName = addProductBtn.querySelector('.product-name');
        if (productName) {
            productName.textContent = `Добавить в "${catName}"`;
        }
    }
}

// ====================
// ФОРМЫ ДОБАВЛЕНИЯ
// ====================

function showAddCategoryForm() {
    console.log('Showing add category form');
    
    // Очищаем форму
    clearEditForm();
    
    // Устанавливаем заголовок
    document.getElementById('editProductName').textContent = 'Новая категория';
    currentEditType = 'category';
    currentEditItemId = null;
    
    // Показываем только нужные поля
    showFormFields(['editName']);
    hideFormFields(['editPrice', 'editIngredients', 'editAdditives']);
    
    // Добавляем поле для позиции
    addPositionField();
    
    // Меняем кнопку сохранения
    document.getElementById('saveEditBtn').textContent = 'Создать категорию';
    document.getElementById('saveEditBtn').onclick = saveNewCategory;
    
    // Скрываем кнопку удаления
    document.getElementById('deleteProductBtn').style.display = 'none';
    
    // Фокус
    document.getElementById('editName').focus();
    document.getElementById('editName').placeholder = 'Название категории';
}

function showAddHallForm() {
    console.log('Showing add hall form');
    
    // Очищаем форму
    clearEditForm();
    
    // Устанавливаем заголовок
    document.getElementById('editProductName').textContent = 'Новый зал';
    currentEditType = 'hall';
    currentEditItemId = null;
    
    // Показываем только нужные поля
    showFormFields(['editName']);
    hideFormFields(['editPrice', 'editIngredients', 'editAdditives', 'editPosition']);
    
    // Меняем кнопку сохранения
    document.getElementById('saveEditBtn').textContent = 'Добавить зал';
    document.getElementById('saveEditBtn').onclick = saveNewHall;
    
    // Скрываем кнопку удаления
    document.getElementById('deleteProductBtn').style.display = 'none';
    
    // Фокус
    document.getElementById('editName').focus();
    document.getElementById('editName').placeholder = 'Название зала';
}

function showAddProductForm() {
    console.log('Showing add product form');
    
    // Очищаем форму
    clearEditForm();
    
    // Устанавливаем заголовок
    document.getElementById('editProductName').textContent = 'Новый товар';
    currentEditType = 'product';
    currentEditItemId = null;
    
    // Показываем все поля товара
    showFormFields(['editName', 'editPrice', 'editIngredients', 'editAdditives', 'editPosition']);
    
    // Меняем кнопку сохранения
    document.getElementById('saveEditBtn').textContent = 'Сохранить товар';
    document.getElementById('saveEditBtn').onclick = saveProduct;
    
    // Скрываем кнопку удаления
    document.getElementById('deleteProductBtn').style.display = 'none';
    
    // Фокус
    document.getElementById('editName').focus();
    document.getElementById('editName').placeholder = 'Название товара';
}

// ====================
// СОХРАНЕНИЕ НОВЫХ ЭЛЕМЕНТОВ
// ====================

async function saveNewCategory() {
    console.log('Saving new category...');
    
    const name = document.getElementById('editName').value.trim();
    const position = document.getElementById('editPosition')?.value || 0;
    
    if (!name) {
        alert('Введите название категории');
        return;
    }
    
    try {
        const response = await fetch('/api/categories.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                name: name,
                position: parseInt(position)
            })
        });
        
        const result = await response.json();
        console.log('Save category response:', result);
        
        if (result.success || result.id) {
            // Добавляем новую категорию в массив
            const newCategory = result.data || { id: result.id, name, position: parseInt(position) };
            categoriesData.push(newCategory);
            
            // Обновляем интерфейс
            updateCategoriesFromDatabase();
            
            // Очищаем форму
            clearEditForm();
            
            alert('✅ Категория создана успешно!');
        } else {
            alert('❌ Ошибка: ' + (result.message || 'Неизвестная ошибка'));
        }
    } catch (error) {
        console.error('Error saving category:', error);
        alert('❌ Ошибка сети при сохранении категории');
    }
}

async function saveNewHall() {
    console.log('Saving new hall...');
    
    const name = document.getElementById('editName').value.trim();
    
    if (!name) {
        alert('Введите название зала');
        return;
    }
    
    try {
        const response = await fetch('/api/halls.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                name: name,
                position: 0
            })
        });
        
        const result = await response.json();
        console.log('Save hall response:', result);
        
        if (result.success || result.id) {
            // Добавляем новый зал в массив
            const newHall = result.data || { id: result.id, name, position: 0 };
            hallsData.push(newHall);
            
            // Обновляем интерфейс
            updateHallsFromDatabase();
            
            // Очищаем форму
            clearEditForm();
            
            alert('✅ Зал добавлен успешно!');
        } else {
            alert('❌ Ошибка: ' + (result.message || 'Неизвестная ошибка'));
        }
    } catch (error) {
        console.error('Error saving hall:', error);
        alert('❌ Ошибка сети при сохранении зала');
    }
}

async function saveProduct() {
    console.log('Saving product...');
    
    const name = document.getElementById('editName').value.trim();
    const price = document.getElementById('editPrice').value;
    const ingredients = document.getElementById('editIngredients').value;
    const additives = document.getElementById('editAdditives').value;
    const position = document.getElementById('editPosition').value || 0;
    
    // Получаем активную категорию
    const activeCategory = document.querySelector('.category-item.active');
    if (!activeCategory) {
        alert('Сначала выберите категорию');
        return;
    }
    
    const categoryId = activeCategory.dataset.categoryId;
    
    if (!name || !price || !categoryId) {
        alert('Заполните все обязательные поля');
        return;
    }
    
    const productData = {
        name: name,
        price: parseFloat(price),
        category_id: parseInt(categoryId),
        ingredients: ingredients || '',
        additives: additives || '',
        position: parseInt(position)
    };
    
    console.log('Saving product:', productData);
    
    try {
        const response = await fetch('/api/products.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(productData)
        });
        
        const result = await response.json();
        console.log('Save product response:', result);
        
        if (result.success || result.id) {
            // Добавляем новый товар в массив
            const newProduct = result.data || { 
                id: result.id, 
                ...productData,
                category_name: activeCategory.dataset.categoryName || 'Категория'
            };
            productsData.push(newProduct);
            
            // Обновляем отображение товаров
            filterProductsByCategory(categoryId);
            
            // Очищаем форму
            clearEditForm();
            
            alert('✅ Товар сохранен успешно!');
        } else {
            alert('❌ Ошибка: ' + (result.message || 'Неизвестная ошибка'));
        }
    } catch (error) {
        console.error('Error saving product:', error);
        alert('❌ Ошибка сети при сохранении товара');
    }
}

// ====================
// РЕДАКТИРОВАНИЕ ТОВАРА
// ====================

function editProduct(productId) {
    console.log('Editing product:', productId);
    
    const product = productsData.find(p => p.id == productId);
    if (!product) {
        alert('Товар не найден');
        return;
    }
    
    currentEditItemId = productId;
    currentEditType = 'product';
    
    // Заполняем форму
    document.getElementById('editName').value = product.name || '';
    document.getElementById('editPrice').value = product.price || '';
    document.getElementById('editIngredients').value = product.ingredients || '';
    document.getElementById('editAdditives').value = product.additives || '';
    document.getElementById('editPosition').value = product.position || 0;
    document.getElementById('editProductName').textContent = `Редактирование: ${product.name}`;
    
    // Показываем все поля
    showFormFields(['editName', 'editPrice', 'editIngredients', 'editAdditives', 'editPosition']);
    
    // Меняем кнопку сохранения
    document.getElementById('saveEditBtn').textContent = 'Обновить товар';
    document.getElementById('saveEditBtn').onclick = updateProduct;
    
    // Показываем кнопку удаления
    document.getElementById('deleteProductBtn').style.display = 'block';
    document.getElementById('deleteProductBtn').textContent = 'Удалить товар';
    document.getElementById('deleteProductBtn').onclick = function() {
        deleteProduct(productId);
    };
}

async function updateProduct() {
    if (!currentEditItemId || currentEditType !== 'product') return;
    
    const name = document.getElementById('editName').value.trim();
    const price = document.getElementById('editPrice').value;
    const ingredients = document.getElementById('editIngredients').value;
    const additives = document.getElementById('editAdditives').value;
    const position = document.getElementById('editPosition').value || 0;
    
    if (!name || !price) {
        alert('Заполните название и цену');
        return;
    }
    
    const product = productsData.find(p => p.id == currentEditItemId);
    if (!product) {
        alert('Товар не найден');
        return;
    }
    
    const productData = {
        id: currentEditItemId,
        name: name,
        price: parseFloat(price),
        category_id: product.category_id,
        ingredients: ingredients || '',
        additives: additives || '',
        position: parseInt(position)
    };
    
    try {
        const response = await fetch('/api/products.php', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(productData)
        });
        
        const result = await response.json();
        console.log('Update product response:', result);
        
        if (result.success) {
            // Обновляем товар в массиве
            const index = productsData.findIndex(p => p.id == currentEditItemId);
            if (index !== -1) {
                productsData[index] = { ...productsData[index], ...productData };
            }
            
            // Обновляем отображение
            const activeCategory = document.querySelector('.category-item.active');
            if (activeCategory) {
                filterProductsByCategory(activeCategory.dataset.categoryId);
            }
            
            // Очищаем форму
            clearEditForm();
            
            alert('✅ Товар обновлен успешно!');
        } else {
            alert('❌ Ошибка: ' + (result.message || 'Неизвестная ошибка'));
        }
    } catch (error) {
        console.error('Error updating product:', error);
        alert('❌ Ошибка сети при обновлении товара');
    }
}

async function deleteProduct(productId) {
    if (!confirm('Вы уверены, что хотите удалить этот товар?')) {
        return;
    }
    
    console.log('Deleting product:', productId);
    
    try {
        const response = await fetch(`/api/products.php?id=${productId}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        console.log('Delete product response:', result);
        
        if (result.success) {
            // Удаляем товар из массива
            productsData = productsData.filter(p => p.id != productId);
            
            // Обновляем отображение
            const activeCategory = document.querySelector('.category-item.active');
            if (activeCategory) {
                filterProductsByCategory(activeCategory.dataset.categoryId);
            }
            
            // Очищаем форму
            clearEditForm();
            
            alert('✅ Товар удален успешно!');
        } else {
            alert('❌ Ошибка: ' + (result.message || 'Неизвестная ошибка'));
        }
   } catch (error) {
        console.error('Error deleting product:', error);
        alert('❌ Ошибка сети при удалении товара');
    }
}

// ====================
// ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ
// ====================

function setupEventListeners() {
    // Кнопка "Редактировать"
    const editMenuButton = document.getElementById('editMenuButton');
    if (editMenuButton) {
        editMenuButton.addEventListener('click', enableEditMode);
    }
    
    // Кнопка "Готово"
    const doneEditButton = document.getElementById('doneEditButton');
    if (doneEditButton) {
        doneEditButton.addEventListener('click', disableEditMode);
    }
    
    // Кнопка "Назад к продажам"
    const exitEditModeBtn = document.getElementById('exitEditModeBtn');
    if (exitEditModeBtn) {
        exitEditModeBtn.addEventListener('click', disableEditMode);
    }
    
    // Кнопка "Отмена" в форме
    const cancelEditBtn = document.getElementById('cancelEditBtn');
    if (cancelEditBtn) {
        cancelEditBtn.addEventListener('click', function() {
            clearEditForm();
        });
    }
    
    // Кнопка "Новый" в верхней панели
    const newProductBtn = document.getElementById('newProductBtn');
    if (newProductBtn) {
        newProductBtn.addEventListener('click', function() {
            showAddProductForm();
        });
    }
    
    // Кнопка "Категории" в верхней панели
    const editCategoriesBtn = document.getElementById('editCategoriesBtn');
    if (editCategoriesBtn) {
        editCategoriesBtn.addEventListener('click', function() {
            // Показываем первую категорию для редактирования
            if (categoriesData.length > 0) {
                editCategory(categoriesData[0].id);
            } else {
                showAddCategoryForm();
            }
        });
    }
    
    // Кнопка "Сохранить" в верхней панели
    const saveProductBtn = document.getElementById('saveProductBtn');
    if (saveProductBtn) {
        saveProductBtn.addEventListener('click', function() {
            // Вызываем сохранение в зависимости от текущего типа
            if (currentEditType === 'category') {
                updateCategory();
            } else if (currentEditType === 'hall') {
                updateHall();
            } else if (currentEditType === 'product') {
                updateProduct();
            } else {
                saveProduct();
            }
        });
    }
    
    // Кнопка "Удалить" в верхней панели
    const deleteProductBtn = document.getElementById('deleteProductBtn');
    if (deleteProductBtn) {
        deleteProductBtn.addEventListener('click', function() {
            // Вызываем удаление в зависимости от текущего типа
            if (currentEditType === 'category' && currentEditItemId) {
                deleteCategory(currentEditItemId);
            } else if (currentEditType === 'hall' && currentEditItemId) {
                deleteHall(currentEditItemId);
            } else if (currentEditType === 'product' && currentEditItemId) {
                deleteProduct(currentEditItemId);
            }
        });
    }
}

function setupEditModeHandlers() {
    // Меняем курсор у товаров
    const productCards = document.querySelectorAll('.product-card:not(.add-product-card)');
    productCards.forEach(card => {
        card.style.cursor = 'pointer';
        card.title = 'Нажмите для редактирования';
        
        // Сохраняем оригинальный обработчик
        card._originalClickHandler = card.onclick;
        card.onclick = null;
        
        // Добавляем обработчик редактирования
        card.addEventListener('click', function() {
            const productId = this.dataset.productId;
            if (productId) {
                editProduct(productId);
            }
        });
    });
    
    // Добавляем обработчики для категорий
    const categories = document.querySelectorAll('.category-item:not(.add-category-btn)');
    categories.forEach(cat => {
        // Показываем кнопку редактирования при наведении
        cat.addEventListener('mouseenter', function() {
            const actions = this.querySelector('.category-actions');
            if (actions) actions.style.display = 'block';
        });
        
        cat.addEventListener('mouseleave', function() {
            const actions = this.querySelector('.category-actions');
            if (actions) actions.style.display = 'none';
        });
    });
}

function setupNormalHandlers() {
    // Возвращаем обычные обработчики товаров
    const productCards = document.querySelectorAll('.product-card:not(.add-product-card)');
    productCards.forEach(card => {
        card.style.cursor = '';
        card.title = '';
        card.onclick = null;
        
        // Добавляем обработчик добавления в заказ
        card.addEventListener('click', function() {
            const productId = this.dataset.productId;
            const product = productsData.find(p => p.id == productId);
            if (product) {
                addToOrder(product);
            }
        });
    });
    
    // Скрываем кнопки редактирования в категориях
    document.querySelectorAll('.category-actions').forEach(action => {
        action.style.display = 'none';
    });
}

function clearEditForm() {
    document.getElementById('editName').value = '';
    document.getElementById('editPrice').value = '';
    document.getElementById('editIngredients').value = '';
    document.getElementById('editAdditives').value = '';
    document.getElementById('editPosition').value = '0';
    document.getElementById('editProductName').textContent = 'Выберите элемент для редактирования';
    
    // Показываем все поля
    showFormFields(['editName', 'editPrice', 'editIngredients', 'editAdditives', 'editPosition']);
    
    // Возвращаем стандартную кнопку
    document.getElementById('saveEditBtn').textContent = 'Сохранить';
    document.getElementById('saveEditBtn').onclick = saveProduct;
    
    // Скрываем кнопку удаления
    const deleteBtn = document.getElementById('deleteProductBtn');
    if (deleteBtn) {
        deleteBtn.style.display = 'none';
    }
    
    // Удаляем поле позиции если было добавлено
    const positionField = document.getElementById('positionFieldContainer');
    if (positionField) {
        positionField.remove();
    }
    
    // Сбрасываем текущие значения
    currentEditItemId = null;
    currentEditType = null;
}

function showFormFields(fieldIds) {
    fieldIds.forEach(id => {
        const element = document.getElementById(id);
        if (element && element.parentElement) {
            element.parentElement.style.display = 'block';
        }
    });
}

function hideFormFields(fieldIds) {
    fieldIds.forEach(id => {
        const element = document.getElementById(id);
        if (element && element.parentElement) {
            element.parentElement.style.display = 'none';
        }
    });
}

function addPositionField() {
    // Удаляем старое поле если есть
    const oldField = document.getElementById('positionFieldContainer');
    if (oldField) oldField.remove();
    
    // Если уже есть поле editPosition в форме, не создаем новое
    if (document.getElementById('editPosition')) {
        const positionContainer = document.getElementById('editPosition').parentElement;
        if (positionContainer) {
            positionContainer.style.display = 'block';
        }
        return;
    }
    
    // Создаем новое поле
    const positionContainer = document.createElement('div');
    positionContainer.id = 'positionFieldContainer';
    positionContainer.className = 'form-group';
    positionContainer.innerHTML = `
        <label>Порядок отображения</label>
        <input type="number" class="edit-input" id="editPosition" placeholder="0" value="0" min="0">
    `;
    
    // Вставляем после поля названия
    const nameField = document.getElementById('editName');
    if (nameField && nameField.parentElement) {
        nameField.parentElement.parentElement.insertBefore(positionContainer, nameField.parentElement.nextSibling);
    }
}

function addToOrder(product) {
    // Функция для добавления товара в заказ
    console.log('Adding to order:', product);
    alert(`Товар "${product.name}" добавлен в заказ (${product.price} руб.)`);
}

// Экспортируем функции для отладки
window.EditMode = {
    enableEditMode,
    disableEditMode,
    editCategory,
    editHall,
    updateCategory,
    updateHall,
    deleteCategory,
    deleteHall
};


/* Прокрутка для панели редактирования */
.edit-mode .current-order.edit-mode {
    overflow-y: auto;
    scrollbar-width: thin;
    scrollbar-color: #4a90e2 #1a1b23;
}

/* Контейнер формы редактирования */
.edit-mode .edit-form-container {
    padding: 15px;
    margin-bottom: 15px;
}

/* Фиксируем футер в панели редактирования */
.edit-mode .order-footer {
    position: sticky;
    bottom: 0;
    background: linear-gradient(to top, #1a1b23 0%, #16171e 100%);
    border-top: 1px solid #24252e;
    z-index: 10;
    margin-top: auto;
}

/* Обеспечиваем правильную высоту панели */
.edit-mode .current-order.edit-mode {
    height: calc(100vh - 68px);
    display: flex;
    flex-direction: column;
}

.edit-mode .order-items-container {
    flex: 1;
    overflow-y: auto;
    padding: 15px;
}

/* Стили для поля выбора принтера в категории */
#categoryPrinterDropdownContainer {
    animation: fadeIn 0.3s ease;
}

#categoryPrinterDropdownContainer select {
    background-color: #0c0c0e;
    color: #ffffff;
    border: 1px solid #24252e;
    padding: 10px;
    border-radius: 6px;
    width: 100%;
    cursor: pointer;
    appearance: none;
    background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3e%3cpath d='M7 10l5 5 5-5z'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right 10px center;
    background-size: 20px;
}

#categoryPrinterDropdownContainer select option {
    background: #1a1b23;
    color: #ffffff;
}

#categoryPrinterDropdownContainer select:hover {
    border-color: #4a90e2;
}

#categoryPrinterDropdownContainer small {
    color: #6c757d;
    font-size: 11px;
    margin-top: 5px;
    display: block;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}

console.log('Edit mode module fully loaded');