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 (
    <div style={{
      width: 22, height: 22, borderRadius: '50%', flexShrink: 0,
      border: `2px solid ${selected ? '#f59e0b' : '#d1d5db'}`,
      background: selected ? '#f59e0b' : 'transparent',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      transition: 'all 120ms ease',
    }}>
      {selected && <svg width="12" height="12" viewBox="0 0 24 24" fill="none"><path d="M5 12.5L10 17.5L19 7.5" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>}
    </div>
  )
}

function RadioDot({ selected }) {
  return (
    <div style={{
      width: 20, height: 20, borderRadius: '50%', flexShrink: 0,
      border: `2px solid ${selected ? '#f59e0b' : '#d1d5db'}`,
      background: 'transparent',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      {selected && <div style={{ width: 9, height: 9, borderRadius: '50%', background: '#f59e0b' }} />}
    </div>
  )
}

function Row({ selected, onClick, children, right, left }) {
  return (
    <div onClick={onClick} style={{
      padding: '10px 12px',
      background: selected ? 'rgba(245,158,11,0.08)' : '#f8fafc',
      border: `1px solid ${selected ? 'rgba(245,158,11,0.4)' : '#e2e8f0'}`,
      borderRadius: 10,
      display: 'flex', alignItems: 'center', gap: 10,
      cursor: onClick ? 'pointer' : 'default',
      transition: 'background 120ms ease, border-color 120ms ease',
      minHeight: 50,
    }}>
      {left && <div style={{ flexShrink: 0 }}>{left}</div>}
      <div style={{ flex: 1, minWidth: 0 }}>{children}</div>
      {right && <div style={{ flexShrink: 0 }}>{right}</div>}
    </div>
  )
}

function Stepper({ value, onChange, min = 0, max = 99 }) {
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', height: 36, borderRadius: 18, background: '#f1f5f9', border: '1px solid #e2e8f0', overflow: 'hidden' }}
      onClick={e => e.stopPropagation()}>
      <button onClick={() => onChange(Math.max(min, value - 1))} disabled={value <= min}
        style={{ width: 36, height: 36, border: 'none', background: 'transparent', fontSize: 16, fontWeight: 500, cursor: value <= min ? 'default' : 'pointer', color: value <= min ? '#94a3b8' : '#1e293b' }}>−</button>
      <div style={{ minWidth: 26, textAlign: 'center', fontSize: 14, fontWeight: 700, color: '#1e293b' }}>{value}</div>
      <button onClick={() => onChange(Math.min(max, value + 1))} disabled={value >= max}
        style={{ width: 36, height: 36, border: 'none', background: 'transparent', fontSize: 16, fontWeight: 500, cursor: value >= max ? 'default' : 'pointer', color: value >= max ? '#94a3b8' : '#1e293b' }}>+</button>
    </div>
  )
}

// ── Option rows ───────────────────────────────────────────────────────────────

function QuickOptionRow({ opt, quickState, setQuickState }) {
  const qty = quickState[opt.id] || 0
  const selected = qty > 0
  return (
    <Row selected={selected} onClick={() => setQuickState(s => ({ ...s, [opt.id]: selected ? 0 : 1 }))}
      left={<CheckCircle selected={selected} />}
      right={opt.allow_multiple ? (
        <div onClick={e => e.stopPropagation()}>
          {selected
            ? <Stepper value={qty} onChange={v => setQuickState(s => ({ ...s, [opt.id]: v }))} />
            : <button onClick={e => { e.stopPropagation(); setQuickState(s => ({ ...s, [opt.id]: 1 })) }}
                style={{ width: 30, height: 30, borderRadius: '50%', background: '#f1f5f9', border: '1px solid #e2e8f0', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none"><path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/></svg>
              </button>
          }
        </div>
      ) : null}
    >
      <div style={{ fontSize: 14, fontWeight: 500, color: '#1e293b' }}>{opt.name}</div>
      {opt.price > 0 && <div style={{ fontSize: 12, color: '#64748b', marginTop: 1 }}>+{opt.price.toFixed(2)} €</div>}
    </Row>
  )
}

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 (
    <div>
      <Row selected={selected} onClick={toggle}
        left={<CheckCircle selected={selected} />}
        right={
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }} onClick={e => e.stopPropagation()}>
            {selected && opt.allow_multiple && (
              <Stepper value={sel.qty} onChange={v => {
                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 && (
              <button onClick={e => { e.stopPropagation(); setExpandedExtra(open ? null : opt.id) }}
                style={{ width: 30, height: 30, borderRadius: '50%', background: '#f1f5f9', border: '1px solid #e2e8f0', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" style={{ transform: `rotate(${open ? 180 : 0}deg)`, transition: 'transform 180ms' }}>
                  <path d="M6 9L12 15L18 9" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
                </svg>
              </button>
            )}
          </div>
        }
      >
        <div style={{ fontSize: 14, fontWeight: 500, color: '#1e293b' }}>{opt.name}</div>
        <div style={{ fontSize: 12, color: '#64748b', marginTop: 1 }}>
          {(opt.extra_cost ?? 0) !== 0 ? `+${opt.extra_cost.toFixed(2)} €` : 'Included'}
          {subLabel && <span style={{ color: '#f59e0b', fontWeight: 600 }}> · {subLabel}</span>}
        </div>
      </Row>
      {selected && open && hasSubs && (
        <div style={{ margin: '5px 0 2px 14px', paddingLeft: 12, borderLeft: '2px solid rgba(245,158,11,0.35)', display: 'flex', flexDirection: 'column', gap: 5 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: 0.6, padding: '4px 2px 2px' }}>Επιλογή</div>
          {opt.sub_choices.map((sub, si) => {
            const isSel = sel.subName === sub.name
            return (
              <Row key={si} selected={isSel} onClick={() => setExtrasState(s => ({ ...s, [opt.id]: { ...sel, subName: sub.name } }))} left={<RadioDot selected={isSel} />}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div style={{ fontSize: 13, color: '#1e293b' }}>{sub.name}</div>
                  {(sub.extra_cost ?? 0) !== 0 && <div style={{ fontSize: 12, color: '#64748b' }}>+{sub.extra_cost.toFixed(2)} €</div>}
                </div>
              </Row>
            )
          })}
        </div>
      )}
    </div>
  )
}

function IngredientRow({ ing, removedState, setRemovedState }) {
  const removed = !!removedState[ing.id]
  return (
    <Row selected={false} onClick={() => setRemovedState(s => ({ ...s, [ing.id]: !s[ing.id] }))}
      right={
        <div style={{
          height: 30, padding: '0 12px', borderRadius: 15,
          background: removed ? '#ef4444' : '#f1f5f9',
          border: `1px solid ${removed ? '#ef4444' : '#e2e8f0'}`,
          color: removed ? '#fff' : '#475569',
          fontSize: 12, fontWeight: 600,
          display: 'inline-flex', alignItems: 'center',
        }}>
          {removed ? 'Αφαιρέθηκε' : 'Αφαίρεση'}
        </div>
      }
    >
      <div style={{ fontSize: 14, fontWeight: 500, color: removed ? '#94a3b8' : '#1e293b', textDecoration: removed ? 'line-through' : 'none' }}>{ing.name}</div>
    </Row>
  )
}

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 (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, padding: '0 2px 8px' }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: complete ? '#1e293b' : '#ef4444' }}>{ps.name}</div>
        {!complete && <div style={{ fontSize: 11, fontWeight: 700, color: '#ef4444', textTransform: 'uppercase', letterSpacing: 0.6 }}>Απαιτείται</div>}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {ps.choices.map(ch => {
          const isSel = selChoice?.id === ch.id
          const hasSubs = ch.sub_choices?.length > 0
          return (
            <div key={ch.id}>
              <Row selected={isSel} onClick={() => selectPref(ch)} left={<RadioDot selected={isSel} />}
                right={(ch.extra_cost ?? 0) !== 0 ? <div style={{ fontSize: 13, color: '#64748b' }}>{ch.extra_cost > 0 ? '+' : ''}{ch.extra_cost.toFixed(2)} €</div> : null}>
                <div style={{ fontSize: 14, fontWeight: 500, color: '#1e293b' }}>{ch.name}</div>
              </Row>
              {isSel && hasSubs && (
                <div style={{ margin: '5px 0 2px 14px', paddingLeft: 12, borderLeft: `2px solid ${subChoices[ch.id] == null ? '#ef4444' : 'rgba(245,158,11,0.35)'}`, display: 'flex', flexDirection: 'column', gap: 5 }}>
                  {ch.sub_choices.map((sub, si) => {
                    const subSel = subChoices[ch.id]?.name === sub.name
                    return (
                      <Row key={si} selected={subSel} onClick={() => setSubChoices(s => ({ ...s, [ch.id]: sub }))} left={<RadioDot selected={subSel} />}
                        right={(sub.extra_cost ?? 0) !== 0 ? <div style={{ fontSize: 12, color: '#64748b' }}>+{sub.extra_cost.toFixed(2)} €</div> : null}>
                        <div style={{ fontSize: 13, color: '#1e293b' }}>{sub.name}</div>
                      </Row>
                    )
                  })}
                </div>
              )}
            </div>
          )
        })}
        {showShared && (
          <div style={{ marginTop: 4, marginLeft: 8, paddingLeft: 12, borderLeft: '2px solid rgba(245,158,11,0.35)', display: 'flex', flexDirection: 'column', gap: 5 }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: 0.6, padding: '4px 2px 2px' }}>{ps.shared_subset.name}</div>
            {ps.shared_subset.choices.map((sub, si) => {
              const subSel = sharedSubs[ps.id]?.name === sub.name
              return (
                <Row key={si} selected={subSel} onClick={() => setSharedSubs(s => ({ ...s, [ps.id]: sub }))} left={<RadioDot selected={subSel} />}
                  right={(sub.extra_cost ?? 0) !== 0 ? <div style={{ fontSize: 12, color: '#64748b' }}>+{sub.extra_cost.toFixed(2)} €</div> : null}>
                  <div style={{ fontSize: 13, color: '#1e293b' }}>{sub.name}</div>
                </Row>
              )
            })}
          </div>
        )}
      </div>
    </div>
  )
}

// ── Tab content ───────────────────────────────────────────────────────────────

function QuickTab({ product, quickState, setQuickState }) {
  const quickOptions = product.quick_options || []
  if (quickOptions.length === 0) return <p style={{ color: '#94a3b8', textAlign: 'center', padding: '24px 0', fontSize: 14 }}>Δεν υπάρχουν γρήγορες επιλογές.</p>
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
      {quickOptions.map(opt => (
        <div key={opt.id} style={{ width: opt.is_compact ? 'calc(50% - 4px)' : '100%', minWidth: 0 }}>
          <QuickOptionRow opt={opt} quickState={quickState} setQuickState={setQuickState} />
        </div>
      ))}
    </div>
  )
}

function ExtrasTab({ product, extrasState, setExtrasState, expandedExtra, setExpandedExtra }) {
  const options = product.options || []
  if (options.length === 0) return <p style={{ color: '#94a3b8', textAlign: 'center', padding: '24px 0', fontSize: 14 }}>Δεν υπάρχουν extras.</p>
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {options.map(opt => (
        <ExtraOptionRow key={opt.id} opt={opt} extrasState={extrasState} setExtrasState={setExtrasState} expandedExtra={expandedExtra} setExpandedExtra={setExpandedExtra} />
      ))}
    </div>
  )
}

function IngredientsTab({ product, removedState, setRemovedState }) {
  const ingredients = product.ingredients || []
  if (ingredients.length === 0) return <p style={{ color: '#94a3b8', textAlign: 'center', padding: '24px 0', fontSize: 14 }}>Δεν υπάρχουν υλικά.</p>
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <div style={{ padding: '8px 12px', background: '#f1f5f9', borderRadius: 8, fontSize: 12, color: '#64748b', marginBottom: 2 }}>
        Κάντε κλικ για να αφαιρέσετε υλικό.
      </div>
      {ingredients.map(ing => (
        <IngredientRow key={ing.id} ing={ing} removedState={removedState} setRemovedState={setRemovedState} />
      ))}
    </div>
  )
}

function PrefsTab({ product, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) {
  const preferenceSets = product.preference_sets || []
  if (preferenceSets.length === 0) return <p style={{ color: '#94a3b8', textAlign: 'center', padding: '24px 0', fontSize: 14 }}>Δεν υπάρχουν προτιμήσεις.</p>
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      {preferenceSets.map(ps => (
        <PrefSetBlock key={ps.id} ps={ps}
          prefs={prefs} setPrefs={setPrefs}
          subChoices={subChoices} setSubChoices={setSubChoices}
          sharedSubs={sharedSubs} setSharedSubs={setSharedSubs}
        />
      ))}
    </div>
  )
}

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 (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 0 }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', height: 48, borderRadius: 24, background: '#f1f5f9', border: '1px solid #e2e8f0', overflow: 'hidden' }}>
          <button onClick={() => setQty(q => clamp(q - unitCfg.step))}
            style={{ width: 48, height: 48, border: 'none', background: 'transparent', fontSize: 20, fontWeight: 500, cursor: 'pointer', color: '#1e293b' }}>−</button>
          {editing ? (
            <input ref={inputRef} type="number" inputMode="decimal" value={qtyInput}
              onChange={e => 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' }}
            />
          ) : (
            <div onClick={() => { 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)}
              <span style={{ fontSize: 12, fontWeight: 500, opacity: 0.65 }}>{unitCfg.label}</span>
            </div>
          )}
          <button onClick={() => setQty(q => clamp(q + unitCfg.step))}
            style={{ width: 48, height: 48, border: 'none', background: 'transparent', fontSize: 20, fontWeight: 500, cursor: 'pointer', color: '#1e293b' }}>+</button>
        </div>
      </div>
      <div>
        <p style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', letterSpacing: 0.8, marginBottom: 6, textAlign: 'center' }}>ΓΡΗΓΟΡΗ ΕΠΙΛΟΓΗ</p>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
          {unitCfg.presets.map(v => (
            <button key={v} onClick={() => setQty(v)} style={{
              padding: '8px 4px', borderRadius: 10, border: 'none',
              background: qty === v ? '#f59e0b' : '#f1f5f9',
              color: qty === v ? '#fff' : '#1e293b',
              fontSize: 12, fontWeight: 700, cursor: 'pointer',
            }}>
              {fmtDecimalQty(v, unitCfg)}{unitCfg.label}
            </button>
          ))}
        </div>
      </div>
      <div>
        <p style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', letterSpacing: 0.8, marginBottom: 6, textAlign: 'center' }}>ΓΡΗΓΟΡΗ ΠΡΟΣΘΗΚΗ</p>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6 }}>
          {unitCfg.offsets.map(off => (
            <button key={`+${off}`} onClick={() => setQty(q => clamp(q + off))} style={{
              padding: '8px 4px', borderRadius: 10, border: 'none',
              background: 'rgba(34,197,94,0.1)', color: '#16a34a',
              fontSize: 12, fontWeight: 700, cursor: 'pointer',
            }}>+{fmtDecimalQty(off, unitCfg)}{unitCfg.label}</button>
          ))}
          {unitCfg.offsets.map(off => (
            <button key={`-${off}`} onClick={() => setQty(q => clamp(q - off))} style={{
              padding: '8px 4px', borderRadius: 10, border: 'none',
              background: 'rgba(239,68,68,0.08)', color: '#dc2626',
              fontSize: 12, fontWeight: 700, cursor: 'pointer',
            }}>−{fmtDecimalQty(off, unitCfg)}{unitCfg.label}</button>
          ))}
        </div>
      </div>
    </div>
  )
}

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 (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ padding: '8px 12px', background: 'rgba(245,158,11,0.08)', border: '1px solid rgba(245,158,11,0.2)', borderRadius: 8, fontSize: 12, color: '#d97706' }}>
        Αλλαγή τιμής μόνο για αυτό το αντικείμενο.
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10 }}>
        <button onClick={() => applyDelta(-0.1)} style={{ width: 40, height: 40, borderRadius: '50%', border: '1px solid #e2e8f0', background: '#f1f5f9', fontSize: 18, fontWeight: 700, color: '#1e293b', cursor: 'pointer' }}>−</button>
        {editing ? (
          <input ref={inputRef} type="number" inputMode="decimal" value={rawInput}
            onChange={e => 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' }}
          />
        ) : (
          <button onClick={() => { setRawInput(effectivePrice.toFixed(2)); setEditing(true) }} style={{
            minWidth: 100, height: 48, borderRadius: 12,
            border: `2px solid ${priceAdj !== 0 ? '#f59e0b' : '#e2e8f0'}`,
            background: priceAdj !== 0 ? 'rgba(245,158,11,0.08)' : '#f8fafc',
            color: priceAdj !== 0 ? '#f59e0b' : '#1e293b',
            fontSize: 20, fontWeight: 800, cursor: 'pointer', fontFamily: 'inherit',
          }}>
            {effectivePrice.toFixed(2)} €
          </button>
        )}
        <button onClick={() => applyDelta(+0.1)} style={{ width: 40, height: 40, borderRadius: '50%', border: '1px solid #e2e8f0', background: '#f1f5f9', fontSize: 18, fontWeight: 700, color: '#1e293b', cursor: 'pointer' }}>+</button>
      </div>
      {priceAdj !== 0 && (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
          <span style={{ fontSize: 12, color: '#64748b' }}>Βάση: {basePrice.toFixed(2)} €</span>
          <span style={{ fontSize: 12, fontWeight: 700, color: priceAdj > 0 ? '#16a34a' : '#dc2626' }}>{priceAdj > 0 ? '+' : ''}{priceAdj.toFixed(2)} €</span>
          <button onClick={() => setPriceAdj(0)} style={{ padding: '2px 8px', borderRadius: 6, border: '1px solid #e2e8f0', background: '#f1f5f9', color: '#64748b', fontSize: 11, cursor: 'pointer' }}>Επαναφορά</button>
        </div>
      )}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
        {PRICE_DELTAS.map(d => (
          <button key={d} onClick={() => applyDelta(d)} style={{
            padding: '9px 4px', borderRadius: 10, border: 'none',
            background: d < 0 ? 'rgba(239,68,68,0.08)' : 'rgba(34,197,94,0.08)',
            color: d < 0 ? '#dc2626' : '#16a34a',
            fontSize: 13, fontWeight: 700, cursor: 'pointer',
          }}>
            {d > 0 ? '+' : ''}{d.toFixed(2 - (Number.isInteger(d) ? 2 : 0))} €
          </button>
        ))}
      </div>
    </div>
  )
}

function NotesTab({ note, setNote }) {
  return (
    <div>
      <textarea
        value={note}
        onChange={e => setNote(e.target.value)}
        placeholder="π.χ. Χωρίς αλάτι, κόψτε στη μέση..."
        rows={4}
        style={{ width: '100%', padding: 12, fontSize: 14, fontFamily: 'inherit', color: '#1e293b', background: 'white', border: '1px solid #e2e8f0', borderRadius: 10, resize: 'none', outline: 'none', boxSizing: 'border-box' }}
      />
      <div style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: 0.6, marginTop: 14, marginBottom: 6 }}>Γρήγορες σημειώσεις</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
        {QUICK_NOTES.map(q => (
          <button key={q} onClick={() => setNote(n => n ? `${n}\n${q}` : q)}
            style={{ height: 32, padding: '0 12px', borderRadius: 16, background: '#f1f5f9', border: '1px solid #e2e8f0', color: '#475569', fontSize: 12, fontWeight: 500, cursor: 'pointer' }}>
            + {q}
          </button>
        ))}
      </div>
    </div>
  )
}

// ── Courses tab ───────────────────────────────────────────────────────────────

function CoursesTab({ courses, courseId, setCourseId }) {
  return (
    <div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
      <button
        onClick={() => setCourseId(null)}
        style={{
          padding: '10px 14px', borderRadius: 10, textAlign: 'left',
          background: courseId === null ? '#2563eb' : '#f8fafc',
          color: courseId === null ? '#fff' : '#1e293b',
          border: `2px solid ${courseId === null ? '#2563eb' : '#e2e8f0'}`,
          fontWeight: 600, fontSize: 14, cursor: 'pointer', fontFamily: 'inherit',
        }}
      >
        No course (fire immediately)
      </button>
      {courses.map(c => (
        <button
          key={c.id}
          onClick={() => setCourseId(courseId === c.id ? null : c.id)}
          style={{
            padding: '10px 14px', borderRadius: 10, textAlign: 'left',
            background: courseId === c.id ? c.color : '#f8fafc',
            color: courseId === c.id ? '#fff' : '#1e293b',
            border: `2px solid ${courseId === c.id ? c.color : '#e2e8f0'}`,
            fontWeight: 600, fontSize: 14, cursor: 'pointer', fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', gap: 10,
          }}
        >
          <span style={{
            width: 12, height: 12, borderRadius: '50%',
            background: courseId === c.id ? 'rgba(255,255,255,0.5)' : c.color,
            flexShrink: 0,
          }} />
          {c.name}
        </button>
      ))}
    </div>
  )
}

// ── 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 (
    <div style={{
      display: 'flex', flexDirection: 'column', height: '100%',
      background: 'white', borderLeft: '1px solid #e2e8f0',
    }}>
      {/* Header */}
      <div style={{
        padding: '16px 16px 12px',
        borderBottom: '1px solid #e2e8f0',
        flexShrink: 0,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
          <div style={{
            width: 52, height: 52, borderRadius: 12, flexShrink: 0,
            background: '#f1f5f9', overflow: 'hidden',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            {product.image_url
              ? <img src={product.image_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              : <span style={{ fontSize: 18, fontWeight: 700, color: '#94a3b8' }}>{initials}</span>
            }
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 16, fontWeight: 700, color: '#1e293b', lineHeight: 1.2, marginBottom: 3 }}>{product.name}</div>
            <div style={{ fontSize: 13, color: priceAdj !== 0 ? '#f59e0b' : '#64748b' }}>
              {priceAdj !== 0
                ? <><span style={{ textDecoration: 'line-through', opacity: 0.5, marginRight: 4 }}>{product.base_price.toFixed(2)}</span>→ {(product.base_price + priceAdj).toFixed(2)} €</>
                : <>{product.base_price.toFixed(2)} €</>
              }
            </div>
          </div>
          <button onClick={onClose} style={{
            width: 32, height: 32, borderRadius: '50%', border: '1px solid #e2e8f0',
            background: '#f8fafc', display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', flexShrink: 0, color: '#64748b',
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
          </button>
        </div>

        {/* Tabs bar */}
        {tabs.length > 0 && (
          <div style={{ display: 'flex', gap: 2, overflowX: 'auto', scrollbarWidth: 'none' }}>
            {tabs.map(t => {
              const active = activeTab === t.id
              const isAlert = t.id === 'prefs' && !allPrefsOk && addAttempted
              return (
                <button key={t.id} onClick={() => setActiveTab(t.id)} style={{
                  padding: '6px 10px',
                  background: 'none', border: 'none',
                  borderBottom: `2px solid ${active ? '#f59e0b' : 'transparent'}`,
                  color: isAlert ? '#ef4444' : active ? '#f59e0b' : '#64748b',
                  fontSize: 12, fontWeight: active ? 700 : 500,
                  fontFamily: 'inherit', cursor: 'pointer',
                  whiteSpace: 'nowrap',
                  transition: 'color 100ms, border-color 100ms',
                }}>
                  {t.label}
                </button>
              )
            })}
          </div>
        )}
      </div>

      {/* Scrollable content */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '14px 14px 10px' }}>
        {activeTab === 'quick' && <QuickTab product={product} quickState={quickState} setQuickState={setQuickState} />}
        {activeTab === 'extras' && <ExtrasTab product={product} extrasState={extrasState} setExtrasState={setExtrasState} expandedExtra={expandedExtra} setExpandedExtra={setExpandedExtra} />}
        {activeTab === 'ingredients' && <IngredientsTab product={product} removedState={removedState} setRemovedState={setRemovedState} />}
        {activeTab === 'prefs' && <PrefsTab product={product} prefs={prefs} setPrefs={setPrefs} subChoices={subChoices} setSubChoices={setSubChoices} sharedSubs={sharedSubs} setSharedSubs={setSharedSubs} />}
        {activeTab === 'quantity' && isDecimal && <QuantityTab unitCfg={unitCfg} qty={qty} setQty={setQty} />}
        {activeTab === 'courses' && courses?.length > 0 && <CoursesTab courses={courses} courseId={courseId} setCourseId={setCourseId} />}
        {activeTab === 'notes' && <NotesTab note={note} setNote={setNote} />}
        {activeTab === 'price_adjust' && <PriceAdjustTab basePrice={product.base_price} priceAdj={priceAdj} setPriceAdj={setPriceAdj} />}
      </div>

      {/* Footer: qty stepper + ADD button */}
      <div style={{
        padding: '12px 14px',
        borderTop: '1px solid #e2e8f0',
        background: '#f8fafc',
        display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0,
      }}>
        {isDecimal ? (
          <div onClick={() => 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 }}>
            <span style={{ fontSize: 16, fontWeight: 700, color: '#1e293b' }}>{fmtDecimalQty(qty, unitCfg)}</span>
            <span style={{ fontSize: 12, color: '#64748b' }}>{unitCfg.label}</span>
          </div>
        ) : (
          <div style={{ display: 'inline-flex', alignItems: 'center', height: 44, borderRadius: 22, background: '#f1f5f9', border: '1px solid #e2e8f0', overflow: 'hidden', flexShrink: 0 }}>
            <button onClick={() => setQty(q => Math.max(1, q - 1))} style={{ width: 44, height: 44, border: 'none', background: 'transparent', fontSize: 20, fontWeight: 500, cursor: qty <= 1 ? 'default' : 'pointer', color: qty <= 1 ? '#94a3b8' : '#1e293b' }}>−</button>
            <div style={{ minWidth: 28, textAlign: 'center', fontSize: 16, fontWeight: 700, color: '#1e293b' }}>{qty}</div>
            <button onClick={() => setQty(q => q + 1)} style={{ width: 44, height: 44, border: 'none', background: 'transparent', fontSize: 20, fontWeight: 500, cursor: 'pointer', color: '#1e293b' }}>+</button>
          </div>
        )}
        <button onClick={handleAdd} style={{
          flex: 1, height: 44, borderRadius: 22,
          background: canAdd ? '#f59e0b' : '#e2e8f0',
          border: 'none', color: canAdd ? '#fff' : '#94a3b8',
          fontSize: 14, fontWeight: 700, fontFamily: 'inherit',
          cursor: canAdd ? 'pointer' : 'not-allowed',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '0 18px',
          transition: 'background 150ms ease',
        }}>
          <span>ΠΡΟΣΘΗΚΗ</span>
          <span>{totalPrice.toFixed(2)} €</span>
        </button>
      </div>
    </div>
  )
}
