document.addEventListener('DOMContentLoaded', function() {
    // Modal functions
    window.openModal = function(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.remove('hidden');
            modal.classList.add('flex');
            // Prevent body scrolling when modal is open
            document.body.style.overflow = 'hidden';
        }
    };

    window.closeModal = function(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.remove('flex');
            modal.classList.add('hidden');
            // Restore body scrolling
            document.body.style.overflow = 'auto';
        }
    };

    // Close modal when clicking outside
    const modals = document.querySelectorAll('.modal');
    modals.forEach(modal => {
        modal.addEventListener('click', function(event) {
            if (event.target === this) {
                closeModal(this.id);
            }
        });
    });

    // Handle edit modal
    window.openEditModal = function(menuId) {
        const menu = window.menuItems.find(m => m.id === parseInt(menuId));
        if (menu) {
            document.getElementById('edit_name').value = menu.name;
            document.getElementById('edit_description').value = menu.description || '';
            document.getElementById('edit_price').value = menu.price;
            document.getElementById('edit_category_id').value = menu.category_id;
            
            // Properly set checkbox state
            const checkbox = document.getElementById('edit_is_available');
            checkbox.checked = menu.is_available;
            
            document.getElementById('editMenuForm').action = `/admin/menu/${menuId}`;
            openModal('editMenuModal');
        }
    };

    // Close modals with Escape key
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            const visibleModals = document.querySelectorAll('.modal.flex');
            visibleModals.forEach(modal => {
                closeModal(modal.id);
            });
        }
    });
}); 