import { useState, useRef, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { useProductCache } from '../hooks/useProductCache'
import useWaiterFavoritesStore from '../store/waiterFavoritesStore'
import { assetUrl } from '../config/server'
import { useFormat, useTranslation } from '@xenia/i18n'
import { money } from '../i18n'
// ── Heart icon ────────────────────────────────────────────────────────────────
function Heart({ filled, size = 22 }) {
return (
)
}
// ── Thumb (product image or initials) ─────────────────────────────────────────
function Thumb({ product, size = 42, radius = 10 }) {
return (
{product.image_url
?
})
:
{product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()}
}
)
}
// ── Item Favorites Modal ───────────────────────────────────────────────────────
// Shows all attribute sections with heart toggles.
// The waiter picks which items appear in that product's Favorites tab.
function AttrSection({ title, items, favIds, onToggle }) {
if (!items || items.length === 0) return null
return (
{title}
{items.map(item => {
const isFav = favIds.includes(item.id)
return (
{item.name}
{item.extra_cost != null && item.extra_cost !== 0 && (
+{money(item.extra_cost)}
)}
{item.price != null && item.price !== 0 && (
+{money(item.price)}
)}
)
})}
)
}
function ItemFavoritesModal({ product, waiterAttrFavs, onSave, onClose }) {
const { t } = useTranslation('waiter')
// Local state: { quick: id[], ingredients: id[], options: id[], prefs: id[] }
// Start from waiter overrides if they exist, otherwise seed from manager's is_favorite flags
function seedFromManager() {
return {
quick: (product.quick_options || []).filter(x => x.is_favorite).map(x => x.id),
ingredients: (product.ingredients || []).filter(x => x.is_favorite).map(x => x.id),
options: (product.options || []).filter(x => x.is_favorite).map(x => x.id),
prefs: (product.preference_sets|| []).filter(x => x.is_favorite).map(x => x.id),
}
}
const [local, setLocal] = useState(() => waiterAttrFavs ?? seedFromManager())
const hasAnything = (
(product.quick_options || []).length > 0 ||
(product.ingredients || []).length > 0 ||
(product.options || []).length > 0 ||
(product.preference_sets || []).length > 0
)
function toggle(section, id) {
setLocal(prev => {
const arr = prev[section] || []
return {
...prev,
[section]: arr.includes(id) ? arr.filter(x => x !== id) : [...arr, id],
}
})
}
const totalSelected = (local.quick?.length || 0) + (local.ingredients?.length || 0) + (local.options?.length || 0) + (local.prefs?.length || 0)
function handleSave() {
// If nothing selected, clear the override (fall back to manager)
const isEmpty = totalSelected === 0
onSave(isEmpty ? null : local)
onClose()
}
function handleClear() {
setLocal({ quick: [], ingredients: [], options: [], prefs: [] })
}
return (
<>
{/* Backdrop */}
{/* Sheet */}
{/* Handle bar */}
{/* Header */}
{product.name}
{waiterAttrFavs ? t('favSetup.personalOn') : t('favSetup.managerDefaults')}
{/* Body */}
{!hasAnything ? (
{t('favSetup.noOptions')}
) : (
<>
{t('favSetup.pickIntro')} ♥ {t('settings.tabs.favorites')}. {t('favSetup.pickOutro')}
toggle('quick', id)}
/>
toggle('ingredients', id)}
/>
toggle('options', id)}
/>
toggle('prefs', id)}
/>
>
)}
{/* Footer */}
{waiterAttrFavs && (
)}
>
)
}
// ── Product row (ALL tab) ─────────────────────────────────────────────────────
function ProductRow({ product, isFav, hasAttrOverride, onToggleFav, onEditAttrs }) {
const { t } = useTranslation('waiter')
const { formatMoney } = useFormat()
const hasAttrs = (
(product.quick_options || []).length > 0 ||
(product.ingredients || []).length > 0 ||
(product.options || []).length > 0 ||
(product.preference_sets || []).length > 0
)
return (
{/* Tappable area — opens attr editor */}
onEditAttrs(product) : undefined}
style={{ flex: 1, minWidth: 0, cursor: hasAttrs ? 'pointer' : 'default' }}
>
{product.name}
{hasAttrOverride && (
)}
{hasAttrs ? `${t('favSetup.options')} →` : formatMoney(Number(product.base_price))}
{/* Heart — toggles product in/out of favorites list */}
)
}
// ── Draggable favorites list (pointer-events — works on touch + mouse) ─────────
function FavoritesList({ items, products, onReorder }) {
const { t } = useTranslation('waiter')
const [dragging, setDragging] = useState(null)
const [dropIndex, setDropIndex] = useState(null)
const containerRef = useRef(null)
const stateRef = useRef({ dragging: null, dropIndex: null })
function getProductById(id) { return products.find(p => p.id === id) }
function computeDropIndex(clientY) {
if (!containerRef.current) return null
const rows = [...containerRef.current.querySelectorAll('[data-drag-row]')]
for (let i = 0; i < rows.length; i++) {
const rect = rows[i].getBoundingClientRect()
if (clientY < rect.top + rect.height * 0.51) return i
}
return rows.length
}
const onPointerDown = useCallback((e, idx) => {
e.currentTarget.setPointerCapture(e.pointerId)
stateRef.current = { dragging: idx, dropIndex: null }
setDragging(idx)
function onMove(ev) {
const di = computeDropIndex(ev.clientY)
if (di !== stateRef.current.dropIndex) {
stateRef.current.dropIndex = di
setDropIndex(di)
}
}
function onUp() {
const { dragging: from, dropIndex: to } = stateRef.current
if (from != null && to != null) {
const next = [...items]
const [moved] = next.splice(from, 1)
const insertAt = to > from ? to - 1 : to
next.splice(insertAt, 0, moved)
onReorder(next)
}
stateRef.current = { dragging: null, dropIndex: null }
setDragging(null)
setDropIndex(null)
window.removeEventListener('pointermove', onMove)
window.removeEventListener('pointerup', onUp)
}
window.addEventListener('pointermove', onMove)
window.addEventListener('pointerup', onUp)
}, [items, onReorder])
if (items.length === 0) {
return (
{t('favSetup.none')}
{t('favSetup.noneHow')}
)
}
return (
{dropIndex === 0 && dragging != null && (
)}
{items.map((productId, idx) => {
const product = getProductById(productId)
if (!product) return null
const isDragging = dragging === idx
return (
onPointerDown(e, idx)}
style={{
color: 'var(--muted)', flexShrink: 0,
display: 'flex', flexDirection: 'column', gap: 2.5, padding: '6px 4px',
cursor: 'grab', touchAction: 'none',
}}
>
{[0,1,2].map(i => )}
{product.name}
{money(product.base_price)}
{dropIndex === idx + 1 && dragging != null && dragging !== idx && (
)}
)
})}
)
}
// ── Main page ─────────────────────────────────────────────────────────────────
export default function FavoritesSetupPage() {
const { t } = useTranslation('waiter')
const navigate = useNavigate()
const { products, categories } = useProductCache()
const { favorites, toggleFavorite, reorderFavorites, itemFavorites, setItemFavorites } = useWaiterFavoritesStore()
const [tab, setTab] = useState('all')
const [editingProduct, setEditingProduct] = useState(null) // product object for ItemFavoritesModal
const topLevel = categories.filter(c => !c.parent_id).sort((a, b) => a.sort_order - b.sort_order)
return (
{/* Header */}
{t('settings.fav.setup')}
{/* Tabs */}
{[
{ key: 'all', label: t('favSetup.all') },
{ key: 'favorites', label: t('favSetup.favorites', { count: favorites.length }) },
].map(tb => (
))}
{/* Content */}
{tab === 'all' ? (
topLevel.map(cat => {
const subcats = categories.filter(c => c.parent_id === cat.id)
const directProds = products.filter(p => p.category_id === cat.id && p.is_available)
const subProds = subcats.flatMap(sc => products.filter(p => p.category_id === sc.id && p.is_available))
const allProds = [...directProds, ...subProds]
if (allProds.length === 0) return null
return (
{cat.name}
{allProds.map(p => (
))}
)
})
) : (
)}
{/* Item attribute favorites modal */}
{editingProduct && (
setItemFavorites(editingProduct.id, attrFavs)}
onClose={() => setEditingProduct(null)}
/>
)}
)
}