import { useState, useEffect, useRef } from 'react'
// ── Helpers ───────────────────────────────────────────────────────────────────
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 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 }
}
const QUICK_NOTES = ['Χωρίς αλάτι', 'Βγάλτε γρήγορα', 'Αλλεργία!', 'Κόψτε σε μικρά κομμάτια', 'Έξτρα χαρτοπετσέτες']
const PRICE_DELTAS = [-5, -3, -2, -1, -0.5, -0.2, +0.2, +0.5, +1, +2, +3, +5]
// ── Primitive UI ──────────────────────────────────────────────────────────────
function CheckCircle({ selected }) {
return (
)
}
function RadioDot({ selected }) {
return (
)
}
function Row({ selected, onClick, children, right, left }) {
return (
{left &&
{left}
}
{children}
{right &&
{right}
}
)
}
function Stepper({ value, onChange, min = 0, max = 99 }) {
return (
e.stopPropagation()}>
{value}
)
}
// ── Option rows ───────────────────────────────────────────────────────────────
function QuickOptionRow({ opt, quickState, setQuickState }) {
const qty = quickState[opt.id] || 0
const selected = qty > 0
return (
setQuickState(s => ({ ...s, [opt.id]: selected ? 0 : 1 }))}
left={}
right={opt.allow_multiple ? (
e.stopPropagation()}>
{selected
?
setQuickState(s => ({ ...s, [opt.id]: v }))} />
:
}
) : null}
>
{opt.name}
{opt.price > 0 && +{opt.price.toFixed(2)} €
}
)
}
function ExtraOptionRow({ opt, extrasState, setExtrasState, expandedExtra, setExpandedExtra }) {
const sel = extrasState[opt.id]
const selected = !!sel
const open = expandedExtra === opt.id
const hasSubs = opt.sub_choices?.length > 0
const subLabel = sel ? opt.sub_choices?.find(s => s.name === sel.subName)?.name : null
const toggle = () => {
if (selected) {
setExtrasState(s => { const n = { ...s }; delete n[opt.id]; return n })
if (open) setExpandedExtra(null)
} else {
const firstSub = hasSubs ? opt.sub_choices[0] : null
setExtrasState(s => ({ ...s, [opt.id]: { qty: 1, subName: firstSub?.name ?? null } }))
if (hasSubs) setExpandedExtra(opt.id)
}
}
return (
|
}
right={
e.stopPropagation()}>
{selected && opt.allow_multiple && (
{
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 && (
)}
}
>
{opt.name}
{(opt.extra_cost ?? 0) !== 0 ? `+${opt.extra_cost.toFixed(2)} €` : 'Included'}
{subLabel && · {subLabel}}
{selected && open && hasSubs && (
Επιλογή
{opt.sub_choices.map((sub, si) => {
const isSel = sel.subName === sub.name
return (
setExtrasState(s => ({ ...s, [opt.id]: { ...sel, subName: sub.name } }))} left={}>
{sub.name}
{(sub.extra_cost ?? 0) !== 0 &&
+{sub.extra_cost.toFixed(2)} €
}
)
})}
)}
)
}
function IngredientRow({ ing, removedState, setRemovedState }) {
const removed = !!removedState[ing.id]
return (
setRemovedState(s => ({ ...s, [ing.id]: !s[ing.id] }))}
right={
{removed ? 'Αφαιρέθηκε' : 'Αφαίρεση'}
}
>
{ing.name}
)
}
function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) {
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 (
{ps.name}
{!complete &&
Απαιτείται
}
{ps.choices.map(ch => {
const isSel = selChoice?.id === ch.id
const hasSubs = ch.sub_choices?.length > 0
return (
selectPref(ch)} left={}
right={(ch.extra_cost ?? 0) !== 0 ? {ch.extra_cost > 0 ? '+' : ''}{ch.extra_cost.toFixed(2)} €
: null}>
{ch.name}
{isSel && hasSubs && (
{ch.sub_choices.map((sub, si) => {
const subSel = subChoices[ch.id]?.name === sub.name
return (
setSubChoices(s => ({ ...s, [ch.id]: sub }))} left={}
right={(sub.extra_cost ?? 0) !== 0 ? +{sub.extra_cost.toFixed(2)} €
: null}>
{sub.name}
)
})}
)}
)
})}
{showShared && (
{ps.shared_subset.name}
{ps.shared_subset.choices.map((sub, si) => {
const subSel = sharedSubs[ps.id]?.name === sub.name
return (
setSharedSubs(s => ({ ...s, [ps.id]: sub }))} left={}
right={(sub.extra_cost ?? 0) !== 0 ? +{sub.extra_cost.toFixed(2)} €
: null}>
{sub.name}
)
})}
)}
)
}
// ── Tab content ───────────────────────────────────────────────────────────────
function QuickTab({ product, quickState, setQuickState }) {
const quickOptions = product.quick_options || []
if (quickOptions.length === 0) return Δεν υπάρχουν γρήγορες επιλογές.
return (
{quickOptions.map(opt => (
))}
)
}
function ExtrasTab({ product, extrasState, setExtrasState, expandedExtra, setExpandedExtra }) {
const options = product.options || []
if (options.length === 0) return Δεν υπάρχουν extras.
return (
{options.map(opt => (
))}
)
}
function IngredientsTab({ product, removedState, setRemovedState }) {
const ingredients = product.ingredients || []
if (ingredients.length === 0) return Δεν υπάρχουν υλικά.
return (
Κάντε κλικ για να αφαιρέσετε υλικό.
{ingredients.map(ing => (
))}
)
}
function PrefsTab({ product, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) {
const preferenceSets = product.preference_sets || []
if (preferenceSets.length === 0) return Δεν υπάρχουν προτιμήσεις.
return (
{preferenceSets.map(ps => (
))}
)
}
function QuantityTab({ unitCfg, qty, setQty }) {
const [editing, setEditing] = useState(false)
const [qtyInput, setQtyInput] = useState('')
const inputRef = useRef(null)
function clamp(v) { return Math.max(unitCfg.min, Math.round(v * 1000) / 1000) }
return (
{editing ? (
setQtyInput(e.target.value)}
onBlur={() => { const v = parseFloat(qtyInput); if (!isNaN(v)) setQty(clamp(v)); setEditing(false) }}
onKeyDown={e => { if (e.key === 'Enter') e.target.blur() }}
autoFocus
style={{ width: 70, height: 48, border: 'none', background: 'transparent', textAlign: 'center', fontSize: 16, fontWeight: 700, color: '#1e293b', outline: 'none', fontFamily: 'inherit' }}
/>
) : (
{ setQtyInput(String(qty)); setEditing(true) }}
style={{ minWidth: 70, textAlign: 'center', fontSize: 16, fontWeight: 700, color: '#1e293b', cursor: 'text', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 3 }}>
{fmtDecimalQty(qty, unitCfg)}
{unitCfg.label}
)}
ΓΡΗΓΟΡΗ ΕΠΙΛΟΓΗ
{unitCfg.presets.map(v => (
))}
ΓΡΗΓΟΡΗ ΠΡΟΣΘΗΚΗ
{unitCfg.offsets.map(off => (
))}
{unitCfg.offsets.map(off => (
))}
)
}
function PriceAdjustTab({ basePrice, priceAdj, setPriceAdj }) {
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
return Math.max(-(basePrice - 0.01), next)
})
}
function commitInput() {
const v = parseFloat(rawInput.replace(',', '.'))
if (!isNaN(v) && v >= 0.01) setPriceAdj(Math.round((v - basePrice) * 100) / 100)
setEditing(false)
}
useEffect(() => { if (editing && inputRef.current) inputRef.current.focus() }, [editing])
return (
Αλλαγή τιμής μόνο για αυτό το αντικείμενο.
{editing ? (
setRawInput(e.target.value)}
onBlur={commitInput}
onKeyDown={e => { if (e.key === 'Enter') e.target.blur() }}
style={{ width: 100, height: 48, border: '2px solid #f59e0b', borderRadius: 12, background: 'white', textAlign: 'center', fontSize: 20, fontWeight: 800, color: '#f59e0b', outline: 'none', fontFamily: 'inherit' }}
/>
) : (
)}
{priceAdj !== 0 && (
Βάση: {basePrice.toFixed(2)} €
0 ? '#16a34a' : '#dc2626' }}>{priceAdj > 0 ? '+' : ''}{priceAdj.toFixed(2)} €
)}
{PRICE_DELTAS.map(d => (
))}
)
}
function NotesTab({ note, setNote }) {
return (
)
}
// ── Courses tab ───────────────────────────────────────────────────────────────
function CoursesTab({ courses, courseId, setCourseId }) {
return (
{courses.map(c => (
))}
)
}
// ── Main component ────────────────────────────────────────────────────────────
export default function ManagerOrderDrawer({ product, onClose, onAdd, initialState, courses }) {
const preferenceSets = product?.preference_sets || []
const quickOptions = product?.quick_options || []
const options = product?.options || []
const ingredients = product?.ingredients || []
const unitCfg = product ? (DECIMAL_UNIT_CONFIG[product.unit_type] ?? null) : null
const isDecimal = !!unitCfg
const hasTabs = {
quick: quickOptions.length > 0,
extras: options.length > 0,
ingredients: ingredients.length > 0,
prefs: preferenceSets.length > 0,
quantity: isDecimal,
}
const firstTab = hasTabs.quick ? 'quick'
: hasTabs.extras ? 'extras'
: hasTabs.ingredients ? 'ingredients'
: hasTabs.prefs ? 'prefs'
: hasTabs.quantity ? 'quantity'
: 'notes'
const [activeTab, setActiveTab] = useState(firstTab)
const [qty, setQty] = useState(isDecimal ? (unitCfg?.presets[0] ?? 0.1) : 1)
const [quickState, setQuickState] = useState({})
const [extrasState, setExtrasState] = useState({})
const [expandedExtra, setExpandedExtra] = useState(null)
const [removedState, setRemovedState] = useState({})
const [prefs, setPrefs] = useState({})
const [subChoices, setSubChoices] = useState({})
const [sharedSubs, setSharedSubs] = useState({})
const [note, setNote] = useState('')
const [priceAdj, setPriceAdj] = useState(0)
const [addAttempted, setAddAttempted] = useState(false)
const [courseId, setCourseId] = useState(initialState?.courseId ?? null)
// Reset when product changes
useEffect(() => {
if (!product) return
const base = buildInitialState(product)
if (initialState) {
setQty(initialState.qty ?? (isDecimal ? (unitCfg?.presets[0] ?? 0.1) : 1))
setQuickState(initialState.quickState ?? {})
setExtrasState(initialState.extrasState ?? {})
setRemovedState(initialState.removedState ?? {})
setPrefs(initialState.prefs ?? base.prefs)
setSubChoices(initialState.subChoices ?? base.subChoices)
setSharedSubs(initialState.sharedSubs ?? base.sharedSubs)
setNote(initialState.note ?? '')
setPriceAdj(initialState.priceAdj ?? 0)
setCourseId(initialState.courseId ?? null)
setActiveTab(initialState.activeTab ?? firstTab)
} else {
setQty(isDecimal ? (unitCfg?.presets[0] ?? 0.1) : 1)
setQuickState({})
setExtrasState({})
setRemovedState({})
setPrefs(base.prefs)
setSubChoices(base.subChoices)
setSharedSubs(base.sharedSubs)
setNote('')
setPriceAdj(0)
setCourseId(null)
setActiveTab(firstTab)
}
setExpandedExtra(null)
setAddAttempted(false)
}, [product?.id])
// Derived total price
const totalPrice = (() => {
if (!product) return 0
let price = product.base_price
preferenceSets.forEach(ps => {
const choice = prefs[ps.id]
if (!choice) return
const inlineSub = choice.sub_choices?.length > 0 ? (subChoices[choice.id] ?? null) : null
const sharedSub = (ps.shared_subset?.choices?.length > 0 && !choice.disables_subset) ? (sharedSubs[ps.id] ?? null) : null
price += (choice.extra_cost ?? 0) + (inlineSub?.extra_cost ?? 0) + (sharedSub?.extra_cost ?? 0)
})
quickOptions.forEach(opt => { price += (quickState[opt.id] || 0) * (opt.price ?? 0) })
options.forEach(opt => {
const sel = extrasState[opt.id]
if (!sel) return
const sub = opt.sub_choices?.find(s => s.name === sel.subName)
price += ((opt.extra_cost ?? 0) + (sub?.extra_cost ?? 0)) * sel.qty
})
return (price + priceAdj) * qty
})()
function isPrefComplete(ps) {
const choice = prefs[ps.id]
if (!choice) return false
if (choice.sub_choices?.length > 0 && subChoices[choice.id] == null) return false
if (ps.shared_subset?.choices?.length > 0 && !choice.disables_subset && sharedSubs[ps.id] == null) return false
return true
}
const allPrefsOk = preferenceSets.every(isPrefComplete)
const extrasSubsMissing = options.some(opt => {
const sel = extrasState[opt.id]
return sel && opt.sub_choices?.length > 0 && sel.subName == null
})
const canAdd = allPrefsOk && !extrasSubsMissing
function handleAdd() {
if (!canAdd) {
setAddAttempted(true)
if (!allPrefsOk && hasTabs.prefs) setActiveTab('prefs')
return
}
const prefChoices = preferenceSets.flatMap(ps => {
const choice = prefs[ps.id]
if (!choice) return []
const inlineSub = choice.sub_choices?.length > 0 ? (subChoices[choice.id] ?? null) : null
const sharedSub = ps.shared_subset?.choices?.length > 0 && !choice.disables_subset ? (sharedSubs[ps.id] ?? null) : null
const defaultChoice = ps.default_choice_id != null ? ps.choices.find(c => c.id === ps.default_choice_id) : null
const isDefaultChoice = defaultChoice && choice.id === defaultChoice.id
const defaultInlineSub = isDefaultChoice && defaultChoice.sub_choices?.length > 0
? (defaultChoice.sub_choices.find(s => s.is_default) ?? defaultChoice.sub_choices[0]) : null
const defaultSharedSub = isDefaultChoice && ps.shared_subset?.choices?.length > 0 && !choice.disables_subset
? (ps.shared_subset.choices.find(s => s.is_default) ?? ps.shared_subset.choices[0]) : null
const isFullyDefault = isDefaultChoice
&& (!inlineSub || inlineSub.name === defaultInlineSub?.name)
&& (!sharedSub || sharedSub.name === defaultSharedSub?.name)
if (isFullyDefault) return []
const entries = [{ id: choice.id, name: choice.name, price_delta: choice.extra_cost ?? 0, type: 'pref' }]
if (inlineSub) entries.push({ id: null, name: inlineSub.name, price_delta: inlineSub.extra_cost ?? 0, type: 'pref_sub' })
if (sharedSub) entries.push({ id: null, name: sharedSub.name, price_delta: sharedSub.extra_cost ?? 0, type: 'pref_sub' })
return entries
})
const optionEntries = options.flatMap(opt => {
const sel = extrasState[opt.id]
if (!sel) return []
const sub = opt.sub_choices?.find(s => s.name === sel.subName)
const entries = []
for (let i = 0; i < sel.qty; i++) {
entries.push({ id: opt.id, name: opt.name, price_delta: opt.extra_cost ?? 0, type: 'extra' })
if (sub) entries.push({ id: null, name: sub.name, price_delta: sub.extra_cost ?? 0, type: 'extra_sub' })
}
return entries
})
const quickEntries = quickOptions.flatMap(opt => {
const q = quickState[opt.id] || 0
if (q === 0) return []
return Array.from({ length: q }, () => ({ id: null, name: opt.name, price_delta: opt.price ?? 0, type: 'quick' }))
})
const removedNames = ingredients.filter(ing => removedState[ing.id]).map(ing => ing.name)
onAdd({
product_id: product.id,
quantity: qty,
unit_price: product.base_price,
selected_options: [...prefChoices, ...quickEntries, ...optionEntries],
removed_ingredients: removedNames,
notes: note,
price_adjustment: priceAdj !== 0 ? priceAdj : undefined,
course_id: courseId ?? undefined,
_drawerState: { qty, quickState, extrasState, removedState, prefs, subChoices, sharedSubs, note, priceAdj, courseId },
})
}
const tabs = [
hasTabs.quick && { id: 'quick', label: 'Quick' },
hasTabs.extras && { id: 'extras', label: 'Extras' },
hasTabs.ingredients && { id: 'ingredients', label: 'Υλικά' },
hasTabs.prefs && { id: 'prefs', label: 'Προτιμήσεις' },
hasTabs.quantity && { id: 'quantity', label: `Ποσότητα (${unitCfg?.label})` },
(courses?.length > 0) && { id: 'courses', label: 'Courses' },
{ id: 'notes', label: 'Σημείωση' },
{ id: 'price_adjust', label: '€ Τιμή' },
].filter(Boolean)
if (!product) return null
const initials = product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
return (
{/* Header */}
{product.image_url
?

:
{initials}
}
{product.name}
{priceAdj !== 0
? <>{product.base_price.toFixed(2)}→ {(product.base_price + priceAdj).toFixed(2)} €>
: <>{product.base_price.toFixed(2)} €>
}
{/* Tabs bar */}
{tabs.length > 0 && (
{tabs.map(t => {
const active = activeTab === t.id
const isAlert = t.id === 'prefs' && !allPrefsOk && addAttempted
return (
)
})}
)}
{/* Scrollable content */}
{activeTab === 'quick' &&
}
{activeTab === 'extras' &&
}
{activeTab === 'ingredients' &&
}
{activeTab === 'prefs' &&
}
{activeTab === 'quantity' && isDecimal &&
}
{activeTab === 'courses' && courses?.length > 0 &&
}
{activeTab === 'notes' &&
}
{activeTab === 'price_adjust' &&
}
{/* Footer: qty stepper + ADD button */}
{isDecimal ? (
setActiveTab('quantity')}
style={{ display: 'inline-flex', alignItems: 'center', height: 44, borderRadius: 22, background: '#f1f5f9', border: '1px solid #e2e8f0', overflow: 'hidden', flexShrink: 0, cursor: 'pointer', padding: '0 14px', gap: 4 }}>
{fmtDecimalQty(qty, unitCfg)}
{unitCfg.label}
) : (
{qty}
)}
)
}