import { useEffect, useRef, useState } from 'react'
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import ProductPicker from '../components/ProductPicker'
import OrderDrawer from '../components/OrderDrawer'
import OrderSummaryModal from '../components/OrderSummaryModal'
import client from '../api/client'
import { apiError } from '../api/errors'
import { getVenueSettings } from '../api/venueSettings'
import db from '../db/posdb'
import { useProductCache } from '../hooks/useProductCache'
import useOrderingSettingsStore from '../store/orderingSettingsStore'
import useConnectionStore from '../store/connectionStore'
import useAuthStore from '../store/authStore'
import { queueOfflineOrder } from '../services/offlineOrders'
import { assetUrl } from '../config/server'
import { money } from '../i18n'
import { LineError, estimate, wireLine } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { useMenuText } from '@xenia/access'
import { fade } from '../logic/colour'
import SeatsHint from '../components/SeatsHint'
// A cart item whose option is not on the menu any more (4.4: lines go by id)
const lineErrorText = (err, t) => t('add.optionGone', { product: err.product, what: err.what })
// ─── Global Course Modal ──────────────────────────────────────────────────────
function GlobalCourseModal({ courses, selected, onSelect, onClose }) {
const { t } = useTranslation('waiter')
return (
{/* Product picker takes all remaining space */}
{/* Quick-add toast */}
{quickToast && (
)}
{/* ── Bottom bar: floating mini-cart + full-width SEND ─────────────── */}
{/* Floating compact cart — shown only when there are items */}
{cart.length > 0 && (
setCartOpen(true)}
style={{
background: 'var(--bg3)',
border: '1px solid var(--border)',
borderRadius: 12,
padding: '8px 12px',
marginBottom: 10,
cursor: 'pointer',
display: 'flex',
flexDirection: 'column',
gap: 4,
}}
>
{stripItems.map(item => {
const p = getProduct(item.product_id)
return (
{p ? mt(p) : `#${item.product_id}`}
{fmtDraftQty(item.quantity, p?.unit_type)}
)
})}
{hiddenCount > 0 && (
{t('add.moreSeeAll', { count: hiddenCount })}
)}
)}
{/* Full-width send button */}
summaryBeforeSend && cart.length > 0 ? setSummaryOpen(true) : sendOrder()}
disabled={cart.length === 0 || sending}
>
{sending ? t('add.sending') : summaryBeforeSend && cart.length > 0 ? t('add.summaryCount', { count: cart.length }) : cart.length > 0 ? t('add.sendCount', { count: cart.length }) : t('add.send')}
{error &&
{error}
}
{/* ── Cart side drawer ────────────────────────────────────────────────── */}
<>
{/* Backdrop */}
setCartOpen(false)}
style={{
position: 'fixed', inset: 0,
background: 'rgb(var(--x-scrim-rgb) / 0.55)',
opacity: cartOpen ? 1 : 0,
pointerEvents: cartOpen ? 'auto' : 'none',
transition: 'opacity 240ms ease',
zIndex: 50,
}}
/>
{/* Panel */}
{/* Drawer header */}
{t('add.order')}
{t('add.products', { count: cart.length })}
setCartOpen(false)} style={{ background: 'var(--bg3)', border: 'none', borderRadius: '50%', width: 34, height: 34, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: 'var(--text)' }}>
{/* Item list */}
{cart.length === 0 ? (
{t('add.empty')}
) : courses.length > 0 ? (() => {
// Group by course, ordered by course definition, "no course" last
const groups = []
courses.forEach(c => {
const items = cart.filter(i => i.course_id === c.id)
if (items.length > 0) groups.push({ course: c, items })
})
const noCourse = cart.filter(i => i.course_id == null || !courses.find(c => c.id === i.course_id))
if (noCourse.length > 0) groups.push({ course: null, items: noCourse })
return (
{groups.map((group, _gi) => (
{/* Colored left accent bar */}
{/* Group header */}
{group.course ? group.course.name : t('add.course.none')}
{group.items.map(item => {
const product = getProduct(item.product_id)
return (
openEditDrawer(item)}
onRemove={() => removeFromCart(item._key)}
onChangeQty={qty => changeCartQty(item._key, qty)}
/>
)
})}
))}
)
})() : (
{cart.map(item => {
const product = getProduct(item.product_id)
return (
openEditDrawer(item)}
onRemove={() => removeFromCart(item._key)}
onChangeQty={qty => changeCartQty(item._key, qty)}
/>
)
})}
)}
{/* Order note area */}
{cart.length > 0 && (
{orderNoteEditing ? (
) : orderNote ? (
setOrderNoteEditing(true)}
style={{ cursor: 'pointer', padding: '9px 12px', background: 'rgb(var(--x-warning-rgb) / 0.09)', border: '1.5px solid rgb(var(--x-warning-rgb) / 0.3)', borderRadius: 10, fontSize: 13, color: 'var(--text)', lineHeight: 1.5, whiteSpace: 'pre-wrap', position: 'relative' }}
>
{t('add.note.title')}
{orderNote}
✎
) : (
setOrderNoteEditing(true)}
style={{
width: '100%', padding: '9px 12px',
background: 'var(--bg3)', border: '1.5px dashed var(--border)',
borderRadius: 10, fontSize: 13, color: 'var(--muted)',
cursor: 'pointer', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 7,
}}
>
{t('add.note.add')}
)}
)}
{/* Drawer footer */}
{cart.length > 0 && (
)}
{ setCartOpen(false); if (summaryBeforeSend) setSummaryOpen(true); else sendOrder() }}
disabled={cart.length === 0 || sending}
>
{sending ? t('add.sending') : summaryBeforeSend ? t('add.summaryCount', { count: cart.length }) : t('add.sendCount', { count: cart.length })}
>
{/* Edit drawer */}
{editItem && (
setEditItem(null)}
onAdd={handleEditSave}
initialState={editItem.drawerState}
courses={courses}
quickNotes={quickNotes}
/>
)}
{/* Order summary modal (shown when summaryBeforeSend is enabled) */}
{summaryOpen && (
l.total) : estimates}
total={priced?.data ? priced.data.total : estimatedTotal}
estimated={!priced?.data}
priceError={priced?.error ?? null}
orderNote={orderNote}
setOrderNote={setOrderNote}
onSend={() => { setSummaryOpen(false); sendOrder() }}
onClose={() => setSummaryOpen(false)}
sending={sending}
/>
)}
{/* ── Search modal ─────────────────────────────────────────────────────── */}
{searchOpen && (
setSearchOpen(false)}
onAdd={item => { addToCart(item); setSearchOpen(false) }}
courses={courses}
quickNotes={quickNotes}
/>
)}
{/* Customer count modal */}
{customerCountOpen && (
setCustomerCount(v)}
onClose={() => setCustomerCountOpen(false)}
/>
)}
{/* Global course modal */}
{globalCourseOpen && courses.length > 0 && (
setGlobalCourseOpen(false)}
/>
)}
{/* Deal offer modal — shown one at a time after order is sent */}
{activeDealOffer && (
{
try {
await client.post('/api/pricing/deals/accept', {
deal_id: activeDealOffer.deal_id,
order_id: activeDealOffer._orderId,
free_items: freeItems,
trigger_item_id: activeDealOffer.target_order_item_id ?? null,
})
} catch { /* log but continue */ }
// Advance to next offer or finish
if (dealOffers.length > 0) {
setActiveDealOffer(dealOffers[0])
setDealOffers(prev => prev.slice(1))
} else {
setActiveDealOffer(null)
if (printAck?.allOk) setTimeout(() => navigate('/tables'), 600)
}
}}
onDismiss={async () => {
try {
await client.post('/api/pricing/deals/dismiss', {
deal_id: activeDealOffer.deal_id,
order_id: activeDealOffer._orderId,
})
} catch { /* ignore */ }
if (dealOffers.length > 0) {
setActiveDealOffer(dealOffers[0])
setDealOffers(prev => prev.slice(1))
} else {
setActiveDealOffer(null)
if (printAck?.allOk) setTimeout(() => navigate('/tables'), 600)
}
}}
/>
)}
{/* Full-screen success overlay — blocks all interaction while navigating */}
{printAck?.allOk && !activeDealOffer && (
{printAck._offline || printAck._pending ? (
) : (
)}
{printAck._offline ? t('add.ack.offline') : printAck._pending ? t('add.ack.printing') : t('add.ack.printed')}
)}
)
}
// ── Deal Offer Modal ──────────────────────────────────────────────────────────
function DealOfferModal({ offer, _products, onAccept, onDismiss }) {
const { t } = useTranslation('waiter')
const isFreeItem = offer.action_type === 'free_item'
const isFreeChoice = offer.action_type === 'free_choice'
const isDiscount = ['set_price','add_amount','add_percent','apply_modifier'].includes(offer.action_type)
// For free_choice: track which products are selected
const [selectedChoices, setSelectedChoices] = useState([])
const remaining = (offer.free_quantity ?? 1) - selectedChoices.length
function toggleChoice(productId) {
setSelectedChoices(prev => {
if (prev.includes(productId)) return prev.filter(x => x !== productId)
if (prev.length >= (offer.free_quantity ?? 1)) return prev // at capacity
return [...prev, productId]
})
}
function handleAccept() {
if (isFreeItem) {
onAccept([{ product_id: offer.free_item_id, quantity: offer.free_quantity ?? 1 }])
} else if (isFreeChoice) {
onAccept(selectedChoices.map(id => ({ product_id: id, quantity: 1 })))
} else {
onAccept([]) // discount deal — no free items to add
}
}
const canConfirm = isFreeChoice ? selectedChoices.length > 0 : true
return (
e.stopPropagation()} style={{ gap: 0 }}>
{/* Header */}
{t('add.deal.title')}
{offer.deal_name}
{/* Free item — single specific product */}
{isFreeItem && offer.free_item_name && (
{t('add.deal.freeProduct')}
{offer.free_item_name}
{offer.free_quantity > 1 && ×{offer.free_quantity} }
)}
{/* Free choice — pick from pool */}
{isFreeChoice && offer.free_choices?.length > 0 && (
{t('add.deal.pickFree', { count: offer.free_quantity ?? 1 })}
{remaining > 0 && {t('add.deal.remaining', { count: remaining })} }
{offer.free_choices.map(choice => {
const checked = selectedChoices.includes(choice.id)
const disabled = !checked && remaining === 0
return (
!disabled && toggleChoice(choice.id)}
style={{
display: 'flex', alignItems: 'center', gap: 10,
padding: '10px 12px', borderRadius: 10, border: 'none', cursor: disabled ? 'not-allowed' : 'pointer',
background: checked ? 'rgb(var(--x-special-rgb) / 0.15)' : 'var(--bg3)',
opacity: disabled ? 0.4 : 1, textAlign: 'left',
}}>
{choice.name}
)
})}
)}
{/* Discount deal — show before/after */}
{isDiscount && offer.price_before != null && offer.price_after != null && (
{money(offer.price_before)}
{money(offer.price_after)}
)}
{t('add.deal.skip')}
{isFreeItem ? t('add.deal.addFree') : isFreeChoice ? t('common.confirm') : t('common.apply')}
)
}
// ── Quick-Add Toast ───────────────────────────────────────────────────────────
function QuickAddToast({ product, count }) {
const { t } = useTranslation('waiter')
const mt = useMenuText()
const initials = mt(product).trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
return (
{/* Thumb */}
{product.image_url
?
:
{initials}
}
{/* Name */}
{mt(product)}
{t('add.inCart')}
{/* Count badge */}
×{count}
)
}
// ── Cart Item (used in the side drawer) ───────────────────────────────────────
const SECTION_META = {
prefs: { icon: '◉', label: null },
quick: { icon: '>', label: null },
extras: { icon: '+', label: null },
removed: { icon: '−', label: null },
note: { icon: 'i', label: null },
}
function SectionIcon({ type }) {
const icons = {
prefs:
,
quick:
,
extras:
,
removed:
,
note:
,
}
return
{icons[type] ?? null}
}
function CartItem({ item, product, summaryLines, sections, onEdit, onRemove, onChangeQty }) {
const { t } = useTranslation('waiter')
const mt = useMenuText()
const [expanded, setExpanded] = useState(false)
const hasDetails = sections.length > 0
return (
{/* Whole header row is always clickable to expand (qty stepper is always available) */}
setExpanded(e => !e)}
style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', cursor: 'pointer' }}
>
{/* Chevron — always shown */}
{/* Name */}
{product ? mt(product) : `#${item.product_id}`}
{!expanded && hasDetails && (
{summaryLines[0]}{summaryLines.length > 1 ? ` +${summaryLines.length - 1}` : ''}
)}
{/* Quantity on the right */}
{fmtDraftQty(item.quantity, product?.unit_type)}
{/* Edit — stop propagation so it doesn't toggle expand */}
{ e.stopPropagation(); onEdit() }} style={{ background: 'none', border: '1px solid var(--border)', borderRadius: 7, color: 'var(--muted)', cursor: 'pointer', padding: '3px 9px', fontSize: 12, fontWeight: 500, flexShrink: 0 }}>
{t('add.edit')}
{/* Remove */}
{ e.stopPropagation(); onRemove() }} style={{ background: 'none', border: 'none', color: 'var(--danger)', cursor: 'pointer', padding: 4, display: 'flex', alignItems: 'center', flexShrink: 0 }}>
{expanded && (
{sections.map((sec, si) => (
{sec.type === 'prefs' && sec.lines.map((line, li) => (
{line.setName}
{line.values.join(' · ')}
))}
{sec.type === 'quick' && sec.lines.map((line, li) => (
{line.name}
{line._qty > 1 && ×{line._qty} }
))}
{sec.type === 'extras' && sec.lines.map((line, li) => (
{line.name}
{line.subName && · {line.subName} }
{line.qty > 1 && ×{line.qty} }
))}
{sec.type === 'removed' && sec.lines.map((line, li) => (
{t('drawer.without', { name: line.name })}
))}
{sec.type === 'note' && sec.lines.map((line, li) => (
{line.name}
))}
))}
{/* ── Quick qty row — hidden for decimal-unit items (edit via modal instead) ── */}
{!_AI_UNIT_LABELS[product?.unit_type] && (<>
{ e.stopPropagation(); onChangeQty(item.quantity - 1) }}
style={{
width: 36, height: 36, borderRadius: '50%',
background: 'var(--bg3)', border: '1px solid var(--border)',
color: item.quantity <= 1 ? 'var(--muted)' : 'var(--danger)',
fontSize: 20, fontWeight: 700, cursor: 'pointer',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}
>
{item.quantity <= 1 ? (
) : '−'}
{item.quantity}
{ e.stopPropagation(); onChangeQty(item.quantity + 1) }}
style={{
width: 36, height: 36, borderRadius: '50%',
background: 'var(--bg3)', border: '1px solid var(--border)',
color: 'var(--x-success)',
fontSize: 20, fontWeight: 700, cursor: 'pointer',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}
>+
>)}
)}
)
}
// ── Search Modal ──────────────────────────────────────────────────────────────
function SearchModal({ products, query, setQuery, onClose, onAdd, courses = [], quickNotes }) {
const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: shown in the waiter's language, found by either
const [drawerProduct, setDrawerProduct] = useState(null)
const activeProducts = products.filter(p => p.lifecycle_status !== 'archived')
const results = query.trim().length === 0
? []
: activeProducts.filter(p => mt.matches(p, query.trim().toLowerCase()))
function openProduct(p) {
// Blur the input first so the keyboard dismisses, then open the drawer
document.activeElement?.blur()
setDrawerProduct(p)
}
// The modal is position:fixed anchored to bottom:0.
// When the soft keyboard opens on mobile the browser shrinks the visual
// viewport and fixed elements reposition automatically — the panel sits
// right on top of the keyboard without any JS measurement needed.
return (
<>
{/* Dim backdrop — tap to close */}
{/* Panel: fixed to bottom, grows upward, capped at 60vh so results don't
push the input off screen on short viewports */}
{/* Results scroll area — flex:1 so it takes space above the input */}
{query.trim().length === 0 ? (
{t('add.search.type')}
) : results.length === 0 ? (
{t('add.search.none', { query })}
) : results.map(p => {
const initials = mt(p).trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
return (
openProduct(p)}
style={{
display: 'flex', alignItems: 'center', gap: 12,
width: '100%', padding: '10px 16px',
background: 'none', border: 'none', cursor: 'pointer',
borderBottom: '1px solid var(--border)',
textAlign: 'left',
}}
>
{p.image_url
?
:
{initials}
}
{mt(p)}
{money(p.base_price)}
)
})}
{/* Search input — pinned at the bottom of the panel, above the keyboard */}
setQuery(e.target.value)}
placeholder={t('add.search.placeholder')}
style={{
flex: 1, height: 44, background: 'var(--bg2)',
border: '1px solid var(--border)', borderRadius: 12,
padding: '0 12px', fontSize: 16, color: 'var(--text)',
fontFamily: 'inherit', outline: 'none',
}}
/>
{/* Product drawer — closes search modal when item is added */}
{drawerProduct && (
setDrawerProduct(null)}
onAdd={item => { onAdd(item); setDrawerProduct(null); onClose() }}
courses={courses}
quickNotes={quickNotes}
/>
)}
>
)
}