diff --git a/src/components/public/AiConsultant.tsx b/src/components/public/AiConsultant.tsx index ccebada..65c1835 100644 --- a/src/components/public/AiConsultant.tsx +++ b/src/components/public/AiConsultant.tsx @@ -1,6 +1,6 @@ 'use client'; -import { useState } from 'react'; +import { useMemo, useState } from 'react'; import { useLocale, useTranslations } from 'next-intl'; import type { SnapshotProduct } from '@/lib/types'; import SuggestionCarousel from './SuggestionCarousel'; @@ -13,14 +13,14 @@ export default function AiConsultant({ ordersEnabled, onAdd, resolveDish, - suggestions, + buildSuggestions, }: { slug: string; onClose: () => void; ordersEnabled: boolean; onAdd: (p: SnapshotProduct) => void; resolveDish: (name: string) => SnapshotProduct | undefined; - suggestions: SnapshotProduct[]; + buildSuggestions: (seed: number, excludeIds?: string[]) => SnapshotProduct[]; }) { const t = useTranslations('ai'); const tm = useTranslations('menu'); @@ -31,6 +31,15 @@ export default function AiConsultant({ null, ); const [error, setError] = useState(false); + // New random sample per consultant open; excludes the dishes already shown above + // (the answer's own recommendations) so the carousel never duplicates them. + const [seed] = useState(() => Date.now()); + const suggestions = useMemo(() => { + const shown = (answer?.recommendations ?? []) + .map((r) => resolveDish(r.dish)?.id) + .filter((id): id is string => !!id); + return buildSuggestions(seed, shown); + }, [buildSuggestions, seed, answer, resolveDish]); async function ask() { if (!question.trim() || loading) return; diff --git a/src/components/public/MediaThumb.tsx b/src/components/public/MediaThumb.tsx index fa2dac7..127efb3 100644 --- a/src/components/public/MediaThumb.tsx +++ b/src/components/public/MediaThumb.tsx @@ -1,5 +1,6 @@ 'use client'; +import { useState } from 'react'; import type { MediaItem } from '@/lib/types'; // Renders the first media item as a thumbnail (image or muted video poster). @@ -12,7 +13,10 @@ export default function MediaThumb({ alt: string; className?: string; }) { - if (!media) { + const [broken, setBroken] = useState(false); + + // Fallback icon when there's no media OR the file 404s / fails to load. + if (!media || broken) { return (
setBroken(true)} /> ); } // eslint-disable-next-line @next/next/no-img-element - return {alt}; + return ( + {alt} setBroken(true)} + /> + ); } diff --git a/src/components/public/PublicMenu.tsx b/src/components/public/PublicMenu.tsx index 16c1fc9..35335ec 100644 --- a/src/components/public/PublicMenu.tsx +++ b/src/components/public/PublicMenu.tsx @@ -1,6 +1,6 @@ 'use client'; -import { useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useLocale, useTranslations } from 'next-intl'; import type { Locale } from '@/i18n/config'; import type { MenuSnapshot, SnapshotProduct } from '@/lib/types'; @@ -103,11 +103,12 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s const cartCount = cart.reduce((n, l) => n + l.qty, 0); - // Suggestions are computed locally and deterministically (no API/tokens) from - // the menu structure + cart, so the carousel is always available and instant. - // Shared by the cart sheet and the consultant carousel. - const cartSuggestions = useMemo( - () => getRecommendations(menu, cart.map((l) => l.product.id), { limit: 6 }), + // Suggestions are computed locally (no API/tokens) from the menu + cart, as a + // RANDOM sample re-seeded per carousel open. Consumers pass their own seed (so + // reopening reshuffles) and extra excludeIds (e.g. the consultant's own picks). + const buildSuggestions = useCallback( + (seed: number, excludeIds: string[] = []) => + getRecommendations(menu, cart.map((l) => l.product.id), { limit: 6, seed, excludeIds }), [menu, cart], ); @@ -378,7 +379,7 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s addToCart(p); }} resolveDish={resolveDish} - suggestions={cartSuggestions} + buildSuggestions={buildSuggestions} /> )} {orderOpen && ( @@ -386,7 +387,7 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s slug={slug} cart={cart} setCart={setCart} - suggestions={cartSuggestions} + buildSuggestions={buildSuggestions} onAdd={addToCart} splitEnabled={splitEnabled} onPickSubaccount={joinExistingSubaccount} @@ -450,7 +451,7 @@ function OrderPanel({ slug, cart, setCart, - suggestions, + buildSuggestions, onAdd, splitEnabled, onPickSubaccount, @@ -461,7 +462,7 @@ function OrderPanel({ slug: string; cart: CartLine[]; setCart: React.Dispatch>; - suggestions: SnapshotProduct[]; + buildSuggestions: (seed: number, excludeIds?: string[]) => SnapshotProduct[]; onAdd: (p: SnapshotProduct) => void; splitEnabled: boolean; onPickSubaccount: (id: string, name: string | null, table: number) => void; @@ -475,6 +476,9 @@ function OrderPanel({ const [generalNote, setGeneralNote] = useState(''); const [sending, setSending] = useState(false); const [tableInSplit, setTableInSplit] = useState(false); + // New random sample each time the cart sheet opens (this component remounts). + const [seed] = useState(() => Date.now()); + const suggestions = useMemo(() => buildSuggestions(seed), [buildSuggestions, seed]); const [subaccounts, setSubaccounts] = useState<{ id: string; name: string | null }[]>([]); const [pickNew, setPickNew] = useState(false); const [newName, setNewName] = useState(''); diff --git a/src/lib/recommendations.ts b/src/lib/recommendations.ts index 699cde4..59822e6 100644 --- a/src/lib/recommendations.ts +++ b/src/lib/recommendations.ts @@ -1,13 +1,27 @@ import type { MenuSnapshot, SnapshotProduct } from './types'; // ───────────────────────────────────────────────────────────────────────────── -// Deterministic, local recommendation engine (no API, no tokens, no latency). -// The carousel only ever calls getRecommendations(menu, cartIds). Today it uses -// section-based complement rules + featured fill. Phase 2 can blend a real -// market-basket CO-OCCURRENCE signal ("who ordered X also ordered Y") WITHOUT -// touching the carousel — just pass `opts.coOccurrence` (see the seam below). +// Local recommendation engine (no API, no tokens, no latency). The carousel only +// ever calls getRecommendations(menu, cartIds, opts). Today: a RANDOM sample of +// the whole menu, lightly refined by complement rules (variety dominates). Pass +// opts.seed to re-randomize per carousel open. Phase 2 can blend a real +// market-basket CO-OCCURRENCE signal WITHOUT touching the carousel — just pass +// `opts.coOccurrence` (see the seam below). // ───────────────────────────────────────────────────────────────────────────── +// Small seeded PRNG (mulberry32) so a given seed yields a stable shuffle within a +// render but a fresh one each time the seed changes (i.e. each carousel open). +function rng(seed: number): () => number { + let a = (seed >>> 0) || 1; + return () => { + a |= 0; + a = (a + 0x6d2b79f5) | 0; + let t = Math.imul(a ^ (a >>> 15), 1 | a); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + type Category = 'drink' | 'dessert' | 'starter' | 'main'; // Keyword sets (es + en + common variants) to classify a section flexibly — @@ -60,8 +74,13 @@ export type CoOccurrenceSignal = (cartProductIds: string[]) => Map inCart.has(i.product.id)).map((i) => i.category)); + const exclude = new Set([...cartProductIds, ...(opts.excludeIds ?? [])]); + const eligible = indexed.filter((i) => !exclude.has(i.product.id)); + if (eligible.length === 0) return []; + + // Complement rules → categories to gently favor (variety still dominates). + const cartCats = new Set( + indexed.filter((i) => cartProductIds.includes(i.product.id)).map((i) => i.category), + ); const hasFood = cartCats.has('main') || cartCats.has('starter'); - const onlyDrink = cartProductIds.length > 0 && cartCats.size > 0 && [...cartCats].every((c) => c === 'drink'); - - // 1) Complement rules → ordered list of categories we want to surface. - const wanted: Category[] = []; + const onlyDrink = + cartProductIds.length > 0 && cartCats.size > 0 && [...cartCats].every((c) => c === 'drink'); + const wanted = new Set(); if (cartProductIds.length > 0) { - if (hasFood && !cartCats.has('drink')) wanted.push('drink'); - if (hasFood && !cartCats.has('dessert')) wanted.push('dessert'); - if (onlyDrink) wanted.push('starter', 'main'); - } - - const eligible = indexed.filter((i) => !inCart.has(i.product.id)); - const picked = new Map(); - - const addFrom = (pool: Indexed[]) => { - for (const i of pool) { - if (picked.size >= limit) break; - if (!picked.has(i.product.id)) picked.set(i.product.id, i.product); + if (hasFood && !cartCats.has('drink')) wanted.add('drink'); + if (hasFood && !cartCats.has('dessert')) wanted.add('dessert'); + if (onlyDrink) { + wanted.add('starter'); + wanted.add('main'); } - }; - - // Complements first, in rule order (by menu order within each category). - for (const cat of wanted) { - addFrom(eligible.filter((i) => i.category === cat).sort((a, b) => a.order - b.order)); } - // 2) Featured fill: prefer sections not represented in the cart, then price desc - // (a stable, data-free proxy for "popular" until Phase 2 supplies real data). - if (picked.size < limit) { - const featured = [...eligible].sort((a, b) => { - const aNew = cartCats.has(a.category) ? 1 : 0; - const bNew = cartCats.has(b.category) ? 1 : 0; - if (aNew !== bNew) return aNew - bNew; - if (b.product.price !== a.product.price) return b.product.price - a.product.price; - return a.order - b.order; - }); - addFrom(featured); - } + // Random sample of the WHOLE menu (high variety), with a small nudge toward + // complement categories — the nudge (+0.25) can't beat a strong random draw, so + // it only refines/orders lightly without collapsing variety. + const rand = rng(opts.seed ?? 1); + let result = eligible + .map((i) => ({ p: i.product, s: rand() + (wanted.has(i.category) ? 0.25 : 0) })) + .sort((a, b) => b.s - a.s) + .map((x) => x.p); - let result = [...picked.values()]; - - // 3) Phase-2 blend (no-op today): float products with a co-occurrence signal. + // Phase-2 blend (no-op today): float products with a co-occurrence signal. if (opts.coOccurrence) { const scores = opts.coOccurrence(cartProductIds); result = result.sort((a, b) => (scores.get(b.id) ?? 0) - (scores.get(a.id) ?? 0));