import { useState, useRef, useCallback, useEffect } from 'react' import { useNavigate } from 'react-router-dom' import OrderDrawer from './OrderDrawer' import useWaiterFavoritesStore from '../store/waiterFavoritesStore' import { assetUrl } from '../config/server' import { money } from '../i18n' import { useTranslation } from '@xenia/i18n' const FAV_CAT_ID = '__favorites__' const SVC_CAT_ID = '__service__' function CategoriesIcon({ width = 20, height = 20 }) { return ( ) } function hexToRgba(hex, alpha) { if (!hex) return null const h = hex.replace('#', '') const r = parseInt(h.substring(0, 2), 16) const g = parseInt(h.substring(2, 4), 16) const b = parseInt(h.substring(4, 6), 16) return `rgba(${r},${g},${b},${alpha})` } // A preference set blocks QuickAdd if it has NO default choice set function productAllowsQuickAdd(product) { if (!product.quick_add_enabled) return false const sets = product.preference_sets || [] for (const ps of sets) { if (ps.default_choice_id == null) return false } return true } // Decimal unit types (add 1.0 instead of 1) const DECIMAL_UNITS = new Set(['kg', 'liter', 'gram', 'ml']) function buildQuickAddItem(product) { const qty = DECIMAL_UNITS.has(product.unit_type) ? 1.0 : 1 // Auto-resolve preference sets via their default choice const selectedOptions = [] for (const ps of (product.preference_sets || [])) { const defaultChoice = ps.choices?.find(c => c.id === ps.default_choice_id) if (defaultChoice) { selectedOptions.push({ id: defaultChoice.id, name: defaultChoice.name, price_delta: defaultChoice.extra_cost ?? 0 }) } } return { product_id: product.id, quantity: qty, unit_type: product.unit_type || 'piece', unit_price: product.base_price, notes: '', selected_options: selectedOptions, removed_ingredients: [], } } // ── Product Detail Modal (long-press) ───────────────────────────────────────── function ProductDetailModal({ product, onClose }) { // Dismiss on Escape useEffect(() => { function onKey(e) { if (e.key === 'Escape') onClose() } window.addEventListener('keydown', onKey) return () => window.removeEventListener('keydown', onKey) }, [onClose]) const initials = product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase() return ( <>
{/* Close button */} {/* Image */}
{product.image_url ? : {initials} }
{/* Info */}
{product.name}
{money(product.base_price)}
{product.description && (
{product.description}
)}
) } // ── useLongPress ────────────────────────────────────────────────────────────── function useLongPress(callback, delay = 2000) { const timerRef = useRef(null) const firedRef = useRef(false) const start = useCallback((e) => { firedRef.current = false timerRef.current = setTimeout(() => { firedRef.current = true callback(e) }, delay) }, [callback, delay]) const cancel = useCallback(() => { if (timerRef.current) { clearTimeout(timerRef.current) timerRef.current = null } }, []) // Return true if the long-press fired, so the click handler can skip normal open const didFire = useCallback(() => firedRef.current, []) return { handlers: { onPointerDown: start, onPointerUp: cancel, onPointerLeave: cancel, onPointerCancel: cancel }, didFire } } // ── Product card ────────────────────────────────────────────────────────────── function ProductCard({ product, onOpen, onQuickAdd, onShowDetail }) { const canQuickAdd = productAllowsQuickAdd(product) const onDetail = useCallback(() => onShowDetail(product), [onShowDetail, product]) const longPress = useLongPress(onDetail, 1200) function handleClick(_e) { // If a long-press just fired, don't open the drawer if (longPress.didFire()) return onOpen(product) } return (
{product.image_url ? : {product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()} }
{product.name} {product.tags?.length > 0 && (
{product.tags.map(tag => ( {tag} ))}
)} {money(product.base_price)}
{canQuickAdd && (
)}
) } // ── Service Item Card ───────────────────────────────────────────────────────── function ServiceItemCard({ product, customerCount, onAdd }) { const { t } = useTranslation('waiter') const [qty, setQty] = useState(0) function dec() { setQty(q => Math.max(0, q - 1)) } function inc() { setQty(q => q + 1) } function setToCustomerCount() { setQty(Math.max(1, customerCount ?? 1)) } const hasPrice = product.base_price != null && product.base_price > 0 const btnBase = { width: 38, height: 38, borderRadius: '50%', border: '1.5px solid var(--border)', cursor: 'pointer', fontSize: 20, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, } return (
{/* Top row: name + price */}
{product.name} {hasPrice ? money(product.base_price) : t('picker.noCharge')}
{/* Bottom row: stepper + count + ADD */}
{/* − */} {/* X = set to customer count */} {/* + */} {/* COUNT indicator */} {qty} {/* ADD button */}
) } function ServiceItemView({ products, customerCount, onAdd }) { const { t } = useTranslation('waiter') return (
{products.length === 0 ? (

{t('picker.noService')}

) : products.map(p => ( ))}
) } function ProductGrid({ products, onOpen, onQuickAdd, onShowDetail }) { if (products.length === 0) return null return (
{products.map(product => ( ))}
) } // Builds the ordered list of sections for a top-level category: // interleaves direct products (as a "General" section) and sub-categories // according to general_sort_order and each sub's sort_order. function buildSections(parent, subcategories, directProducts) { const sections = [] if (directProducts.length > 0) { sections.push({ _isGeneral: true, sort_order: parent.general_sort_order, products: directProducts }) } for (const sub of subcategories) { sections.push({ ...sub, _isGeneral: false, sort_order: sub.sort_order }) } return sections.sort((a, b) => a.sort_order - b.sort_order) } export default function ProductPicker({ categories, products, onAdd, onQuickAdd: onQuickAddProp, viewAllOpen, setViewAllOpen, customerCount, courses = [], globalCourseId = null, quickNotes }) { const { t } = useTranslation('waiter') const navigate = useNavigate() const favorites = useWaiterFavoritesStore(s => s.favorites) const serviceProducts = products.filter(p => p.is_service_item) // Service items with a category also appear in that category view const regularProducts = products.filter(p => !p.is_service_item || p.category_id) const topLevel = categories.filter(c => !c.parent_id).sort((a, b) => a.sort_order - b.sort_order) // Start on FAVORITES chip if there are any, otherwise first category const initialCatId = favorites.length > 0 ? FAV_CAT_ID : (topLevel[0]?.id ?? null) const [activeCat, setActiveCat] = useState(initialCatId) const [drawerProduct, setDrawerProduct] = useState(null) const [detailProduct, setDetailProduct] = useState(null) const [modalTab, setModalTab] = useState('categories') // 'categories' | 'tags' const [activeTag, setActiveTag] = useState(null) // Track which sub-category sections are expanded (by sub-cat id or '__general__') const [expandedSubs, setExpandedSubs] = useState(() => { if (!initialCatId || initialCatId === FAV_CAT_ID) return {} const subs = categories.filter(c => c.parent_id === initialCatId) const state = {} subs.forEach(s => { if (s.auto_expanded) state[String(s.id)] = true }) return state }) const isSvcActive = activeCat === SVC_CAT_ID const activeParent = categories.find(c => c.id === activeCat) const subcategories = activeParent ? categories.filter(c => c.parent_id === activeCat).sort((a, b) => a.sort_order - b.sort_order) : [] const hasSubcats = subcategories.length > 0 const directProducts = regularProducts.filter(p => p.category_id === activeCat) // Products for the flat view (no sub-cats) const flatProducts = regularProducts.filter(p => p.category_id === activeCat) // Build sections for accordion view const sections = hasSubcats ? buildSections(activeParent, subcategories, directProducts) : [] function buildDefaultExpanded(catId) { const subs = categories.filter(c => c.parent_id === catId) const state = {} subs.forEach(s => { if (s.auto_expanded) state[String(s.id)] = true }) return state } function selectCategory(id) { setActiveCat(id) setViewAllOpen(false) setExpandedSubs(id === FAV_CAT_ID || id === SVC_CAT_ID ? {} : buildDefaultExpanded(id)) } function toggleSub(key) { setExpandedSubs(prev => ({ ...prev, [key]: !prev[key] })) } function openDrawer(product) { setDrawerProduct(product) } function closeDrawer() { setDrawerProduct(null) } function handleQuickAdd(product) { const base = buildQuickAddItem(product) const item = product.is_service_item ? { ...base, is_service_item: true } : base if (onQuickAddProp) { onQuickAddProp(item, product) } else { onAdd(item) } } const isFavActive = activeCat === FAV_CAT_ID const favProducts = favorites.map(id => regularProducts.find(p => p.id === id)).filter(Boolean) function handleServiceAdd(item, product) { // Service items go into the cart like regular items if (onQuickAddProp) { onQuickAddProp(item, product) } else { onAdd(item) } } return (
{/* SERVICE chip — first if service items exist */} {serviceProducts.length > 0 && ( )} {/* FAVORITES chip */} {favorites.length > 0 && ( )} {topLevel.map(cat => { const isActive = activeCat === cat.id const bg = cat.color ? isActive ? cat.color : hexToRgba(cat.color, 0.35) : isActive ? 'var(--accent)' : 'var(--bg3)' const color = cat.color ? isActive ? '#fff' : 'rgba(255,255,255,0.65)' : isActive ? 'var(--accent-fg)' : 'var(--muted)' return ( ) })}
{/* Product area — service, favorites, flat grid, or accordion depending on sub-cats */}
{isSvcActive ? ( // SERVICE view ) : isFavActive ? ( // FAVORITES view favProducts.length > 0 ? ( ) : (

{t('picker.noFavorites')}

) ) : !hasSubcats ? ( // No sub-categories: original flat grid <> {flatProducts.length === 0 && (

{t('picker.noProducts')}

)} ) : ( // Has sub-categories: accordion view
{sections.map(section => { const key = section._isGeneral ? '__general__' : String(section.id) const isOpen = !!expandedSubs[key] const sectionProducts = section._isGeneral ? section.products : regularProducts.filter(p => p.category_id === section.id) if (sectionProducts.length === 0) return null // General products appear flat — no collapsible header if (section._isGeneral) { return (
) } const accentColor = section.color ?? activeParent?.color ?? null return (
{isOpen && (
)}
) })}
)}
{/* View All modal — categories + tags tabs */} {viewAllOpen && (
setViewAllOpen(false)}>
e.stopPropagation()} style={{ display: 'flex', flexDirection: 'column' }} >
{modalTab === 'categories' ? t('picker.categories') : t('picker.tags')}
{/* Tab strip */}
{['categories', 'tags'].map(tab => ( ))}
{modalTab === 'categories' && (
{favorites.length > 0 && ( )} {topLevel.map(cat => { const isActive = activeCat === cat.id const bg = cat.color || 'var(--bg3)' const overlay = isActive ? 'rgba(255,255,255,0.18)' : 'rgba(0,0,0,0.35)' return ( ) })}
)} {modalTab === 'tags' && (() => { const allTags = [...new Set(products.flatMap(p => p.tags || []))].sort() const taggedProducts = activeTag ? products.filter(p => (p.tags || []).includes(activeTag)) : [] const byCategory = taggedProducts.reduce((acc, p) => { const cat = categories.find(c => c.id === p.category_id) const key = cat?.name || t('picker.noCategory') if (!acc[key]) acc[key] = [] acc[key].push(p) return acc }, {}) return (
{allTags.length === 0 && (
{t('picker.noTags')}
)} {allTags.length > 0 && (
{allTags.map(tag => ( ))}
)} {activeTag && taggedProducts.length === 0 && (
{t('picker.noTagged')}
)} {activeTag && Object.entries(byCategory).map(([catName, prods]) => (
{catName}
{prods.map(p => ( ))}
))}
) })()}
)} { const finalItem = drawerProduct?.is_service_item ? { ...item, is_service_item: true } : item onAdd(finalItem) closeDrawer() }} courses={courses} quickNotes={quickNotes} initialState={globalCourseId != null ? { courseId: globalCourseId } : undefined} /> {detailProduct && ( setDetailProduct(null)} /> )}
) }