import { useState, useEffect, useRef } from 'react' import { useCan, useMenuText } from '@xenia/access' import useWaiterFavoritesStore from '../store/waiterFavoritesStore' import { assetUrl } from '../config/server' import { money } from '../i18n' import { parseNumber, useTranslation } from '@xenia/i18n' import PriceReason from './PriceReason' import { priceReasonText } from '../logic/priceRules' import { usePriceRules } from '../hooks/usePriceRules' // ── Helpers ────────────────────────────────────────────────────────────────── function buildInitialState(product) { const preferenceSets = product.preference_sets || [] const prefs = {} const subChoices = {} const sharedSubs = {} preferenceSets.forEach(ps => { const def = ps.default_choice_id != null ? ps.choices.find(c => c.id === ps.default_choice_id) ?? null : null prefs[ps.id] = def if (def) { if (def.sub_choices?.length > 0) { subChoices[def.id] = def.sub_choices.find(s => s.is_default) ?? def.sub_choices[0] } if (ps.shared_subset?.choices?.length > 0 && !def.disables_subset) { sharedSubs[ps.id] = ps.shared_subset.choices.find(s => s.is_default) ?? ps.shared_subset.choices[0] } } }) return { prefs, subChoices, sharedSubs } } // Build sorted favorites list across all item types. // waiterOverride shape: { quick: id[], ingredients: id[], options: id[], prefs: id[] } // If provided, it fully replaces manager's is_favorite flags. // Order within each section follows the waiter's id array order. function buildFavorites(product, waiterOverride) { const items = [] if (waiterOverride) { const qi = waiterOverride.quick || [] const ii = waiterOverride.ingredients || [] const oi = waiterOverride.options || [] const pi = waiterOverride.prefs || [] qi.forEach((id, idx) => { const q = (product.quick_options || []).find(x => x.id === id) if (q) items.push({ type: 'quick', item: q, sortOrder: idx }) }) ii.forEach((id, idx) => { const ing = (product.ingredients || []).find(x => x.id === id) if (ing) items.push({ type: 'ingredient', item: ing, sortOrder: 1000 + idx }) }) oi.forEach((id, idx) => { const opt = (product.options || []).find(x => x.id === id) if (opt) items.push({ type: 'option', item: opt, sortOrder: 2000 + idx }) }) pi.forEach((id, idx) => { const ps = (product.preference_sets || []).find(x => x.id === id) if (ps) items.push({ type: 'pref', item: ps, sortOrder: 3000 + idx }) }) } else { // Fall back to manager's is_favorite flags ;(product.quick_options || []).forEach(q => { if (q.is_favorite) items.push({ type: 'quick', item: q, sortOrder: q.favorite_sort_order ?? 0 }) }) ;(product.ingredients || []).forEach(ing => { if (ing.is_favorite) items.push({ type: 'ingredient', item: ing, sortOrder: ing.favorite_sort_order ?? 0 }) }) ;(product.options || []).forEach(opt => { if (opt.is_favorite) items.push({ type: 'option', item: opt, sortOrder: opt.favorite_sort_order ?? 0 }) }) ;(product.preference_sets || []).forEach(ps => { if (ps.is_favorite) items.push({ type: 'pref', item: ps, sortOrder: ps.favorite_sort_order ?? 0 }) }) } return items.sort((a, b) => a.sortOrder - b.sortOrder) } // ── Primitives ──────────────────────────────────────────────────────────────── function Stepper({ value, onChange, min = 0, max = 99 }) { return (
e.stopPropagation()}>
{value}
) } function CheckCircle({ selected }) { return (
{selected && }
) } function RadioDot({ selected }) { return (
{selected &&
}
) } function Row({ selected, onClick, children, right, left, style = {} }) { return (
{left &&
{left}
}
{children}
{right &&
{right}
}
) } // ── Shared: single quick option row ────────────────────────────────────────── function QuickOptionRow({ opt, quickState, setQuickState, compact }) { const { t } = useTranslation('waiter') const mt = useMenuText() // 6R.L: names in the waiter's language; state and lines keep ids / stored names const qty = quickState[opt.id] || 0 const selected = qty > 0 const toggleSingle = () => setQuickState(s => ({ ...s, [opt.id]: selected ? 0 : 1 })) return ( } right={opt.allow_multiple ? (
e.stopPropagation()}> {selected ? setQuickState(s => ({ ...s, [opt.id]: v }))} /> : }
) : null} >
{mt(opt)}
{opt.price > 0 &&
+{money(opt.price)}{opt.allow_multiple ? ` ${t('drawer.each')}` : ''}
}
) } // ── Shared: single extra/option row ────────────────────────────────────────── function ExtraOptionRow({ opt, extrasState, setExtrasState, expandedExtra, setExpandedExtra, compact }) { const { t } = useTranslation('waiter') const mt = useMenuText() // 6R.L: names in the waiter's language; state and lines keep ids / stored names const sel = extrasState[opt.id] const selected = !!sel const open = expandedExtra === opt.id const hasSubs = opt.sub_choices?.length > 0 const isMultiSelect = opt.multi_select && hasSubs // Build sub label for non-multi-select mode const subLabel = (!isMultiSelect && sel) ? opt.sub_choices?.find(s => s.name === sel.subName)?.name ?? null : null // For multi-select: subs is { [subName]: qty } const subs = sel?.subs ?? {} const selectedSubCount = Object.values(subs).filter(q => q > 0).length const toggle = () => { if (selected) { setExtrasState(s => { const n = { ...s }; delete n[opt.id]; return n }) if (open) setExpandedExtra(null) } else { if (isMultiSelect) { setExtrasState(s => ({ ...s, [opt.id]: { qty: 1, subName: null, subs: {} } })) setExpandedExtra(opt.id) } else { const firstSub = hasSubs ? opt.sub_choices[0] : null setExtrasState(s => ({ ...s, [opt.id]: { qty: 1, subName: firstSub?.name ?? null, subs: {} } })) if (hasSubs) setExpandedExtra(opt.id) } } } return (
} right={
e.stopPropagation()}> {opt.allow_multiple && !selected && ( )} {selected && opt.allow_multiple && !isMultiSelect && ( { if (v === 0) { setExtrasState(s => { const n = { ...s }; delete n[opt.id]; return n }); return } setExtrasState(s => ({ ...s, [opt.id]: { ...sel, qty: v } })) }} /> )} {selected && hasSubs && ( )}
} style={compact ? { minHeight: 48 } : {}} >
{mt(opt)}
{(opt.extra_cost ?? 0) !== 0 ? `+${money(opt.extra_cost)}` : t('drawer.included')} {subLabel && · {subLabel}} {isMultiSelect && selectedSubCount > 0 && ( · {t('drawer.selectedCount', { count: selectedSubCount })} )}
{/* Single-select sub-choices (radio) */} {selected && open && hasSubs && !isMultiSelect && (
{t('drawer.choose')}
{opt.sub_choices.map((sub, si) => { const isSel = sel.subName === sub.name return (
setExtrasState(s => ({ ...s, [opt.id]: { ...sel, subName: sub.name } }))} left={} style={sub.is_compact ? { minHeight: 44 } : {}}>
{mt(sub)}
{(sub.extra_cost ?? 0) !== 0 &&
+{money(sub.extra_cost)}
}
) })}
)} {/* Multi-select sub-choices (checkboxes, optional qty stepper per sub) */} {selected && open && hasSubs && isMultiSelect && (
{t('drawer.chooseMany')}
{opt.sub_choices.map((sub, si) => { const subQty = subs[sub.name] || 0 const subSel = subQty > 0 const toggleSub = () => { const newSubs = { ...subs, [sub.name]: subSel ? 0 : 1 } setExtrasState(s => ({ ...s, [opt.id]: { ...sel, subs: newSubs } })) } return (
} right={sub.allow_multiple && subSel ? (
e.stopPropagation()}> { const newSubs = { ...subs, [sub.name]: v } setExtrasState(s => ({ ...s, [opt.id]: { ...sel, subs: newSubs } })) }} />
) : null} style={sub.is_compact ? { minHeight: 44 } : {}}>
{mt(sub)} {subQty > 1 && ×{subQty}}
{(sub.extra_cost ?? 0) !== 0 &&
+{money(sub.extra_cost)}{sub.allow_multiple ? ` ${t('drawer.each')}` : ''}
}
) })}
)}
) } // ── Shared: single ingredient row ───────────────────────────────────────────── function IngredientRow({ ing, removedState, setRemovedState, compact }) { const { t } = useTranslation('waiter') const mt = useMenuText() // 6R.L: names in the waiter's language; state and lines keep ids / stored names const removed = !!removedState[ing.id] return ( setRemovedState(s => ({ ...s, [ing.id]: !s[ing.id] }))} style={compact ? { minHeight: 48 } : {}} right={
{removed ? t('drawer.removed') : t('drawer.remove')}
}>
{mt(ing)}
) } // ── Shared: single preference set ───────────────────────────────────────────── function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) { const { t } = useTranslation('waiter') const mt = useMenuText() // 6R.L: names in the waiter's language; state and lines keep ids / stored names const selChoice = prefs[ps.id] ?? null const complete = selChoice != null && !(selChoice.sub_choices?.length > 0 && subChoices[selChoice.id] == null) && !(ps.shared_subset?.choices?.length > 0 && !selChoice.disables_subset && sharedSubs[ps.id] == null) const showShared = ps.shared_subset?.choices?.length > 0 && selChoice != null && !selChoice.disables_subset function selectPref(choice) { setPrefs(p => ({ ...p, [ps.id]: choice })) if (choice?.sub_choices?.length > 0) { setSubChoices(s => ({ ...s, [choice.id]: s[choice.id] ?? (choice.sub_choices.find(x => x.is_default) ?? choice.sub_choices[0]) })) } if (ps.shared_subset?.choices?.length > 0 && !choice?.disables_subset) { setSharedSubs(s => s[ps.id] != null ? s : { ...s, [ps.id]: ps.shared_subset.choices.find(x => x.is_default) ?? ps.shared_subset.choices[0] }) } } return (
{mt(ps)}
{!complete &&
{t('drawer.required')}
}
{ps.choices.map(ch => { const isSel = selChoice?.id === ch.id const hasSubs = ch.sub_choices?.length > 0 const subMissing = isSel && hasSubs && subChoices[ch.id] == null return (
selectPref(ch)} left={} style={ch.is_compact ? { minHeight: 48 } : {}} right={(ch.extra_cost ?? 0) !== 0 ?
{ch.extra_cost > 0 ? '+' : ''}{money(ch.extra_cost)}
: null}>
{mt(ch)}
{isSel && hasSubs && (
{subMissing &&

{t('drawer.choiceRequired')}

} {ch.sub_choices.map((sub, si) => { const subSel = subChoices[ch.id]?.name === sub.name return (
setSubChoices(s => ({ ...s, [ch.id]: sub }))} left={} style={sub.is_compact ? { minHeight: 44 } : {}} right={(sub.extra_cost ?? 0) !== 0 ?
+{money(sub.extra_cost)}
: null}>
{mt(sub)}
) })}
)}
) })} {showShared && (
{mt(ps.shared_subset)}
{ps.shared_subset.choices.map((sub, si) => { const subSel = sharedSubs[ps.id]?.name === sub.name return (
setSharedSubs(s => ({ ...s, [ps.id]: sub }))} left={} style={sub.is_compact ? { minHeight: 44 } : {}} right={(sub.extra_cost ?? 0) !== 0 ?
+{money(sub.extra_cost)}
: null}>
{mt(sub)}
) })}
)}
) } // ── Tab: Favorites ──────────────────────────────────────────────────────────── function FavoritesTab({ product, waiterOverride, quickState, setQuickState, extrasState, setExtrasState, expandedExtra, setExpandedExtra, removedState, setRemovedState, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) { const { t } = useTranslation('waiter') const favorites = buildFavorites(product, waiterOverride) if (favorites.length === 0) return (

{t('drawer.empty.favorites')}

) return (
{favorites.map((fav, _fi) => { if (fav.type === 'quick') { return } if (fav.type === 'ingredient') { return } if (fav.type === 'option') { return } if (fav.type === 'pref') { return ( ) } return null })}
) } // ── Tab: Quick Options ──────────────────────────────────────────────────────── function QuickTab({ product, quickState, setQuickState }) { const { t } = useTranslation('waiter') const quickOptions = product.quick_options || [] if (quickOptions.length === 0) return (

{t('drawer.empty.quick')}

) return (
{quickOptions.map(opt => (
))}
) } // ── Shared: PWA group sticky header ────────────────────────────────────────── // Static group colours — cycle by index passed from parent const GROUP_COLORS = [ { bg: 'var(--x-info-soft)', border: 'var(--x-info-ink)', text: 'var(--x-info)' }, // indigo { bg: 'var(--x-special-soft)', border: 'var(--x-special-ink)', text: 'var(--x-special)' }, // pink { bg: 'var(--x-success-soft)', border: 'var(--x-success)', text: 'var(--x-success-soft)' }, // emerald { bg: 'var(--x-warning-soft)', border: 'var(--x-warning)', text: 'var(--x-warning)' }, // amber { bg: 'var(--x-info-soft)', border: 'var(--x-info-ink)', text: 'var(--x-info)' }, // sky { bg: 'var(--x-special-soft)', border: 'var(--x-special-ink)', text: 'var(--x-special)' }, // purple ] function PWAGroupHeader({ name, collapsed, onToggle, colorIdx = 0 }) { const c = GROUP_COLORS[colorIdx % GROUP_COLORS.length] return (
{name} ▾
) } // Partition items into { ungrouped, groups: [{group, items}] } preserving order function partitionByGroup(items, modifierGroups) { if (!modifierGroups || modifierGroups.length === 0) return { ungrouped: items, groups: [] } const groupMap = {} modifierGroups.forEach(g => { groupMap[g.id] = { group: g, items: [] } }) const ungrouped = [] items.forEach(item => { if (item.group_id != null && groupMap[item.group_id]) { groupMap[item.group_id].items.push(item) } else { ungrouped.push(item) } }) // Preserve group order from modifierGroups const groups = modifierGroups.map(g => groupMap[g.id]).filter(g => g.items.length > 0) return { ungrouped, groups } } // ── Tab: Extras ─────────────────────────────────────────────────────────────── function ExtrasTab({ product, extrasState, setExtrasState, expandedExtra, setExpandedExtra }) { const { t } = useTranslation('waiter') const mt = useMenuText() // 6R.L: names in the waiter's language; state and lines keep ids / stored names const extraGroups = (product.modifier_groups || []).filter(g => g.modifier_type === 'option') const [collapsedGroups, setCollapsedGroups] = useState(() => Object.fromEntries(extraGroups.map(g => [g.id, true]))) const options = product.options || [] if (options.length === 0) return (

{t('drawer.empty.extras')}

) function toggleGroup(id) { setCollapsedGroups(s => ({ ...s, [id]: !s[id] })) } const { ungrouped, groups } = partitionByGroup(options, extraGroups) function renderOption(opt) { return (
) } return (
{ungrouped.length > 0 && (
0 ? 12 : 0 }}> {ungrouped.map(renderOption)}
)} {groups.map(({ group, items }, gi) => { const isCollapsed = collapsedGroups[group.id] ?? true return (
toggleGroup(group.id)} colorIdx={gi} /> {!isCollapsed && (
{items.map(renderOption)}
)}
) })}
) } // ── Tab: Ingredients ───────────────────────────────────────────────── function IngredientsTab({ product, removedState, setRemovedState }) { const { t } = useTranslation('waiter') const mt = useMenuText() // 6R.L: names in the waiter's language; state and lines keep ids / stored names const ingGroups = (product.modifier_groups || []).filter(g => g.modifier_type === 'ingredient') const [collapsedGroups, setCollapsedGroups] = useState(() => Object.fromEntries(ingGroups.map(g => [g.id, true]))) const ingredients = product.ingredients || [] if (ingredients.length === 0) return (

{t('drawer.empty.ingredients')}

) function toggleGroup(id) { setCollapsedGroups(s => ({ ...s, [id]: !s[id] })) } const { ungrouped, groups } = partitionByGroup(ingredients, ingGroups) function renderIng(ing) { return (
) } return (
{ungrouped.length > 0 && (
0 ? 12 : 0 }}> {ungrouped.map(renderIng)}
)} {groups.map(({ group, items }, gi) => { const isCollapsed = collapsedGroups[group.id] ?? true return (
toggleGroup(group.id)} colorIdx={gi} /> {!isCollapsed && (
{items.map(renderIng)}
)}
) })}
) } // ── Tab: Preferences ───────────────────────────────────────────────────────── function PrefsTab({ product, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) { const { t } = useTranslation('waiter') const mt = useMenuText() // 6R.L: names in the waiter's language; state and lines keep ids / stored names const prefGroups = (product.modifier_groups || []).filter(g => g.modifier_type === 'preference') const [collapsedGroups, setCollapsedGroups] = useState(() => Object.fromEntries(prefGroups.map(g => [g.id, true]))) const preferenceSets = product.preference_sets || [] if (preferenceSets.length === 0) return (

{t('drawer.empty.prefs')}

) function toggleGroup(id) { setCollapsedGroups(s => ({ ...s, [id]: !s[id] })) } const { ungrouped, groups } = partitionByGroup(preferenceSets, prefGroups) function renderPrefSet(ps) { return ( ) } return (
{ungrouped.length > 0 && (
0 ? 16 : 0 }}> {ungrouped.map(renderPrefSet)}
)} {groups.map(({ group, items }, gi) => { const isCollapsed = collapsedGroups[group.id] ?? true return (
toggleGroup(group.id)} colorIdx={gi} /> {!isCollapsed && (
{items.map(renderPrefSet)}
)}
) })}
) } // ── Tab: Quantity (for KG / Liter / Gram / mL units) ───────────────────────── const DECIMAL_UNIT_CONFIG = { kg: { step: 0.05, min: 0.05, presets: [0.10, 0.20, 0.25, 0.50, 0.70, 1.00, 1.50, 2.00, 2.50, 3.00, 4.00, 5.00], offsets: [0.1, 0.2, 0.5, 1.0], label: 'kg' }, liter: { step: 0.05, min: 0.05, presets: [0.10, 0.20, 0.25, 0.50, 0.70, 1.00, 1.50, 2.00, 2.50, 3.00, 4.00, 5.00], offsets: [0.1, 0.2, 0.5, 1.0], label: 'L' }, gram: { step: 10, min: 10, presets: [50, 100, 150, 200, 250, 300, 400, 500], offsets: [10, 50, 100, 200], label: 'g' }, ml: { step: 5, min: 5, presets: [25, 50, 100, 150, 200, 250, 300, 500], offsets: [25, 50, 100, 200], label: 'mL' }, } function fmtDecimalQty(qty, cfg) { if (!cfg) return String(qty) if (cfg.label === 'kg' || cfg.label === 'L') { const n = Number(qty) return n % 1 === 0 ? n.toFixed(1) : (Math.round(n * 100) / 100).toFixed(2).replace(/0$/, '') } return String(qty) } function QuantityTab({ unitCfg, qty, setQty }) { const { t } = useTranslation('waiter') const [editingQty, setEditingQty] = useState(false) const [qtyInput, setQtyInput] = useState('') const inputRef = useRef(null) function clamp(v) { return Math.max(unitCfg.min, Math.round(v * 1000) / 1000) } return (
{/* Main − / value / + row */}
{editingQty ? ( setQtyInput(e.target.value)} onBlur={() => { const v = parseNumber(qtyInput, { decimals: 3, allowNegative: false }) if (v != null) setQty(clamp(v)) setEditingQty(false) }} onKeyDown={e => { if (e.key === 'Enter') e.target.blur() }} autoFocus style={{ width: 80, height: 52, border: 'none', background: 'transparent', textAlign: 'center', fontSize: 17, fontWeight: 700, color: 'var(--text)', fontVariantNumeric: 'tabular-nums', outline: 'none', fontFamily: 'inherit', }} /> ) : (
{ setQtyInput(String(qty)); setEditingQty(true) }} style={{ minWidth: 80, textAlign: 'center', fontSize: 17, fontWeight: 700, color: 'var(--text)', fontVariantNumeric: 'tabular-nums', cursor: 'text', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4 }} > {fmtDecimalQty(qty, unitCfg)} {unitCfg.label}
)}
{/* Quick presets — 3 rows of 4 */}

{t('drawer.qty.quickPick')}

{unitCfg.presets.map(v => ( ))}
{/* Quick ± offset buttons — 2×2 grid */}

{t('drawer.qty.quickAdd')}

{unitCfg.offsets.map(off => ( ))} {unitCfg.offsets.map(off => ( ))}
) } // ── Tab: Price Adjustment ───────────────────────────────────────────────────── const PRICE_DELTAS = [-5, -3, -2, -1, -0.5, -0.2, +0.2, +0.5, +1, +2, +3, +5] function PriceAdjustTab({ basePrice, priceAdj, setPriceAdj, rules, reason, setReason, reasonMissing }) { const { t } = useTranslation('waiter') const [editing, setEditing] = useState(false) const [rawInput, setRawInput] = useState('') const inputRef = useRef(null) const effectivePrice = basePrice + priceAdj function applyDelta(d) { setPriceAdj(a => { const next = Math.round((a + d) * 100) / 100 const min = -(basePrice - 0.01) return Math.max(min, next) }) } function commitInput() { const v = parseNumber(rawInput, { decimals: 2, allowNegative: false }) if (v != null && v >= 0.01) { setPriceAdj(Math.round((v - basePrice) * 100) / 100) } setEditing(false) } useEffect(() => { if (editing && inputRef.current) inputRef.current.focus() }, [editing]) return (
{t('drawer.price.intro')}
{/* Price display / input */}
{editing ? ( setRawInput(e.target.value)} onBlur={commitInput} onKeyDown={e => { if (e.key === 'Enter') e.target.blur() }} style={{ width: 110, height: 52, border: '2px solid var(--x-warning)', borderRadius: 14, background: 'var(--bg2)', textAlign: 'center', fontSize: 22, fontWeight: 800, color: 'var(--x-warning)', outline: 'none', fontFamily: 'inherit' }} /> ) : ( )}
{priceAdj !== 0 && (
{t('drawer.price.base', { price: money(basePrice) })} 0 ? 'var(--x-success)' : 'var(--x-danger)' }}> {priceAdj > 0 ? '+' : ''}{money(priceAdj)}
)} {/* Quick delta grid — 4 rows × 3 */}
{PRICE_DELTAS.map(d => ( ))}
{/* 6F.3: the venue asks why a price changes */} {rules?.reasonRequired && priceAdj !== 0 && }
) } // ── Tab: Notes ──────────────────────────────────────────────────────────────── function NotesTab({ note, setNote, quickNotes }) { const { t } = useTranslation('waiter') quickNotes = quickNotes ?? FALLBACK_QUICK_NOTES.map(k => t(k)) return (