import { useState, useEffect, useCallback } from 'react'

// ── Helpers ──────────────────────────────────────────────────────────────────

function fmt(n) {
  if (n === 0) return ''
  const s = n > 0 ? `+${n.toFixed(2)} €` : `${n.toFixed(2)} €`
  return s
}

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 }
}

// Build sorted favorites list across all item types
function buildFavorites(product) {
  const items = []
  ;(product.quick_options || []).forEach(q => {
    if (q.is_favorite) items.push({ type: 'quick', item: q, sortOrder: q.favorite_sort_order ?? 0 })
  })
  ;(product.ingredients || []).forEach(ing => {
    if (ing.is_favorite) items.push({ type: 'ingredient', item: ing, sortOrder: ing.favorite_sort_order ?? 0 })
  })
  ;(product.options || []).forEach(opt => {
    if (opt.is_favorite) items.push({ type: 'option', item: opt, sortOrder: opt.favorite_sort_order ?? 0 })
  })
  ;(product.preference_sets || []).forEach(ps => {
    if (ps.is_favorite) items.push({ type: 'pref', item: ps, sortOrder: ps.favorite_sort_order ?? 0 })
  })
  return items.sort((a, b) => a.sortOrder - b.sortOrder)
}

const QUICK_NOTES = ['Χωρίς αλάτι', 'Βγάλτε γρήγορα', 'Αλλεργία!', 'Κόψτε σε μικρά κομμάτια', 'Έξτρα χαρτοπετσέτες']

// ── Primitives ────────────────────────────────────────────────────────────────

function Stepper({ value, onChange, min = 0, max = 99 }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center',
      height: 40, borderRadius: 20,
      background: 'var(--bg2)', border: '1px solid var(--border)',
      overflow: 'hidden',
    }} onClick={e => e.stopPropagation()}>
      <button onClick={() => onChange(Math.max(min, value - 1))} disabled={value <= min}
        style={{ width: 40, height: 40, border: 'none', background: 'transparent', fontSize: 18, fontWeight: 500, cursor: value <= min ? 'default' : 'pointer', color: value <= min ? 'var(--muted)' : 'var(--text)' }}>−</button>
      <div style={{ minWidth: 28, textAlign: 'center', fontSize: 15, fontWeight: 700, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{value}</div>
      <button onClick={() => onChange(Math.min(max, value + 1))} disabled={value >= max}
        style={{ width: 40, height: 40, border: 'none', background: 'transparent', fontSize: 18, fontWeight: 500, cursor: value >= max ? 'default' : 'pointer', color: value >= max ? 'var(--muted)' : 'var(--text)' }}>+</button>
    </div>
  )
}

function CheckCircle({ selected }) {
  return (
    <div style={{
      width: 24, height: 24, borderRadius: '50%', flexShrink: 0,
      border: `2px solid ${selected ? '#f59e0b' : 'var(--border)'}`,
      background: selected ? '#f59e0b' : 'transparent',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      transition: 'all 120ms ease',
    }}>
      {selected && <svg width="13" height="13" 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: 22, height: 22, borderRadius: '50%', flexShrink: 0,
      border: `2px solid ${selected ? '#f59e0b' : 'var(--border)'}`,
      background: 'transparent',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      transition: 'all 120ms ease',
    }}>
      {selected && <div style={{ width: 10, height: 10, borderRadius: '50%', background: '#f59e0b' }} />}
    </div>
  )
}

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

// ── Shared: single quick option row ──────────────────────────────────────────

function QuickOptionRow({ opt, quickState, setQuickState, compact }) {
  const qty = quickState[opt.id] || 0
  const selected = qty > 0
  const toggleSingle = () => setQuickState(s => ({ ...s, [opt.id]: selected ? 0 : 1 }))
  return (
    <Row
      selected={selected}
      onClick={toggleSingle}
      left={<CheckCircle selected={selected} />}
      right={opt.allow_multiple ? (
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }} 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: 34, height: 34, borderRadius: '50%', background: 'var(--bg3)', border: '1px solid var(--border)', color: 'var(--text)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                <svg width="14" height="14" 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: compact ? 13 : 15, fontWeight: 500, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{opt.name}</div>
      {opt.price > 0 && <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>+{opt.price.toFixed(2)} €{opt.allow_multiple ? ' each' : ''}</div>}
    </Row>
  )
}

// ── Shared: single extra/option 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: 6 }} onClick={e => e.stopPropagation()}>
            {opt.allow_multiple && !selected && (
              <button
                onClick={e => { e.stopPropagation(); toggle() }}
                style={{ width: 34, height: 34, borderRadius: '50%', background: 'var(--bg3)', border: '1px solid var(--border)', color: 'var(--text)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/></svg>
              </button>
            )}
            {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: 36, height: 36, borderRadius: '50%', background: 'var(--bg3)', border: '1px solid var(--border)', color: 'var(--text)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                <svg width="14" height="14" 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: 15, fontWeight: 500, color: 'var(--text)' }}>{opt.name}</div>
        <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 2 }}>
          {(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: '6px 0 2px 16px', paddingLeft: 14, borderLeft: '2px solid rgba(245,158,11,0.3)', display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.6, padding: '6px 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: 14, color: 'var(--text)' }}>{sub.name}</div>
                  {(sub.extra_cost ?? 0) !== 0 && <div style={{ fontSize: 13, color: 'var(--muted)' }}>+{sub.extra_cost.toFixed(2)} €</div>}
                </div>
              </Row>
            )
          })}
        </div>
      )}
    </div>
  )
}

// ── Shared: single ingredient row ─────────────────────────────────────────────

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: 34, padding: '0 14px', borderRadius: 17,
          background: removed ? 'var(--danger)' : 'var(--bg3)',
          border: `1px solid ${removed ? 'var(--danger)' : 'var(--border)'}`,
          color: removed ? '#fff' : 'var(--text)',
          fontSize: 13, fontWeight: 600,
          display: 'inline-flex', alignItems: 'center',
          transition: 'all 120ms ease',
        }}>
          {removed ? 'Αφαιρέθηκε' : 'Αφαίρεση'}
        </div>
      }>
      <div style={{ fontSize: 15, fontWeight: 500, color: removed ? 'var(--muted)' : 'var(--text)', textDecoration: removed ? 'line-through' : 'none', transition: 'all 120ms' }}>{ing.name}</div>
    </Row>
  )
}

// ── Shared: single preference set ─────────────────────────────────────────────

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 10px' }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: complete ? 'var(--text)' : '#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: 8 }}>
        {ps.choices.map(ch => {
          const isSel = selChoice?.id === ch.id
          const hasSubs = ch.sub_choices?.length > 0
          const subMissing = isSel && hasSubs && subChoices[ch.id] == null

          return (
            <div key={ch.id}>
              <Row selected={isSel} onClick={() => selectPref(ch)} left={<RadioDot selected={isSel} />}
                right={(ch.extra_cost ?? 0) !== 0 ? <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--muted)' }}>{ch.extra_cost > 0 ? '+' : ''}{ch.extra_cost.toFixed(2)} €</div> : null}>
                <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--text)' }}>{ch.name}</div>
              </Row>

              {isSel && hasSubs && (
                <div style={{ margin: '6px 0 2px 16px', paddingLeft: 14, borderLeft: `2px solid ${subMissing ? '#ef4444' : 'rgba(245,158,11,0.3)'}`, display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {subMissing && <p style={{ fontSize: 12, color: '#ef4444', margin: '4px 2px 2px' }}>— απαιτείται επιλογή</p>}
                  {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: 13, color: 'var(--muted)' }}>+{sub.extra_cost.toFixed(2)} €</div> : null}>
                        <div style={{ fontSize: 14, color: 'var(--text)' }}>{sub.name}</div>
                      </Row>
                    )
                  })}
                </div>
              )}
            </div>
          )
        })}

        {showShared && (
          <div style={{ marginTop: 4, marginLeft: 8, paddingLeft: 14, borderLeft: '2px solid rgba(245,158,11,0.3)', display: 'flex', flexDirection: 'column', gap: 6 }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', 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: 13, color: 'var(--muted)' }}>+{sub.extra_cost.toFixed(2)} €</div> : null}>
                  <div style={{ fontSize: 14, color: 'var(--text)' }}>{sub.name}</div>
                </Row>
              )
            })}
          </div>
        )}
      </div>
    </div>
  )
}

// ── Tab: Favorites ────────────────────────────────────────────────────────────

function FavoritesTab({ product, quickState, setQuickState, extrasState, setExtrasState, expandedExtra, setExpandedExtra, removedState, setRemovedState, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) {
  const favorites = buildFavorites(product)

  if (favorites.length === 0) return (
    <p style={{ color: 'var(--muted)', textAlign: 'center', padding: '32px 0', fontSize: 14 }}>Δεν υπάρχουν αγαπημένα για αυτό το προϊόν.</p>
  )

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {favorites.map((fav, fi) => {
        if (fav.type === 'quick') {
          return <QuickOptionRow key={`quick-${fav.item.id}`} opt={fav.item} quickState={quickState} setQuickState={setQuickState} compact={false} />
        }
        if (fav.type === 'ingredient') {
          return <IngredientRow key={`ing-${fav.item.id}`} ing={fav.item} removedState={removedState} setRemovedState={setRemovedState} />
        }
        if (fav.type === 'option') {
          return <ExtraOptionRow key={`opt-${fav.item.id}`} opt={fav.item} extrasState={extrasState} setExtrasState={setExtrasState} expandedExtra={expandedExtra} setExpandedExtra={setExpandedExtra} />
        }
        if (fav.type === 'pref') {
          return (
            <PrefSetBlock key={`pref-${fav.item.id}`} ps={fav.item}
              prefs={prefs} setPrefs={setPrefs}
              subChoices={subChoices} setSubChoices={setSubChoices}
              sharedSubs={sharedSubs} setSharedSubs={setSharedSubs}
            />
          )
        }
        return null
      })}
    </div>
  )
}

// ── Tab: Quick Options ────────────────────────────────────────────────────────

function QuickTab({ product, quickState, setQuickState }) {
  const quickOptions = product.quick_options || []
  if (quickOptions.length === 0) return (
    <p style={{ color: 'var(--muted)', textAlign: 'center', padding: '32px 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} compact={opt.is_compact} />
        </div>
      ))}
    </div>
  )
}

// ── Tab: Extras ───────────────────────────────────────────────────────────────

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

// ── Tab: Υλικά (Ingredients) ─────────────────────────────────────────────────

function IngredientsTab({ product, removedState, setRemovedState }) {
  const ingredients = product.ingredients || []
  if (ingredients.length === 0) return (
    <p style={{ color: 'var(--muted)', textAlign: 'center', padding: '32px 0', fontSize: 14 }}>Δεν υπάρχουν υλικά.</p>
  )
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <div style={{ padding: '10px 14px', background: 'var(--bg3)', borderRadius: 10, fontSize: 13, color: 'var(--muted)', marginBottom: 4 }}>
        Πατήστε για να αφαιρέσετε υλικό από το πιάτο.
      </div>
      {ingredients.map(ing => (
        <IngredientRow key={ing.id} ing={ing} removedState={removedState} setRemovedState={setRemovedState} />
      ))}
    </div>
  )
}

// ── Tab: Προτιμήσεις ─────────────────────────────────────────────────────────

function PrefsTab({ product, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) {
  const preferenceSets = product.preference_sets || []
  if (preferenceSets.length === 0) return (
    <p style={{ color: 'var(--muted)', textAlign: 'center', padding: '32px 0', fontSize: 14 }}>Δεν υπάρχουν προτιμήσεις.</p>
  )

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
      {preferenceSets.map(ps => (
        <PrefSetBlock key={ps.id} ps={ps}
          prefs={prefs} setPrefs={setPrefs}
          subChoices={subChoices} setSubChoices={setSubChoices}
          sharedSubs={sharedSubs} setSharedSubs={setSharedSubs}
        />
      ))}
    </div>
  )
}

// ── Tab: Notes ────────────────────────────────────────────────────────────────

function NotesTab({ note, setNote }) {
  return (
    <div>
      <div style={{ padding: '10px 14px', background: 'var(--bg3)', borderRadius: 10, fontSize: 13, color: 'var(--muted)', marginBottom: 12 }}>
        Οτιδήποτε ειδικό για την κουζίνα.
      </div>
      <textarea
        value={note}
        onChange={e => setNote(e.target.value)}
        placeholder="π.χ. Χωρίς αλάτι, κόψτε στη μέση..."
        rows={5}
        style={{ width: '100%', padding: 14, fontSize: 15, fontFamily: 'inherit', color: 'var(--text)', background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 12, resize: 'none', outline: 'none', boxSizing: 'border-box' }}
      />
      <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.6, marginTop: 20, marginBottom: 8 }}>Γρήγορες σημειώσεις</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        {QUICK_NOTES.map(q => (
          <button key={q} onClick={() => setNote(n => n ? `${n}\n${q}` : q)}
            style={{ height: 36, padding: '0 14px', borderRadius: 18, background: 'var(--bg2)', border: '1px solid var(--border)', color: 'var(--text)', fontSize: 13, fontWeight: 500, cursor: 'pointer' }}>
            + {q}
          </button>
        ))}
      </div>
    </div>
  )
}

// ── Tab: Summary ──────────────────────────────────────────────────────────────

function SummaryTab({ product, summaryLines, note, onJumpTab }) {
  const isEmpty = summaryLines.length === 0 && !note
  const byGroup = { quick: [], extras: [], removed: [], prefs: [] }
  summaryLines.forEach(l => byGroup[l.group]?.push(l))

  const Section = ({ title, tab, lines }) => lines.length === 0 ? null : (
    <div style={{ marginBottom: 20 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0 2px 8px' }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.6 }}>{title}</div>
        <button onClick={() => onJumpTab(tab)} style={{ background: 'none', border: 'none', fontSize: 12, fontWeight: 700, color: '#f59e0b', cursor: 'pointer', textTransform: 'uppercase', letterSpacing: 0.6 }}>Αλλαγή</button>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {lines.map((l, i) => (
          <div key={i} style={{ padding: '10px 14px', background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 10, display: 'flex', alignItems: 'center', gap: 10, minHeight: 44 }}>
            <div style={{ flex: 1 }}>
              {l.group === 'prefs' ? (
                <>
                  <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 2 }}>{l.label}</div>
                  <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>{l.value}</div>
                </>
              ) : l.group === 'removed' ? (
                <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>
                  Χωρίς {l.label}
                </div>
              ) : l.group === 'extras' ? (
                <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>
                  {l.label}
                  {l.subName && <span> · {l.subName}</span>}
                  {l.qty > 1 && <span style={{ color: 'var(--muted)', marginLeft: 6, fontVariantNumeric: 'tabular-nums' }}>×{l.qty}</span>}
                </div>
              ) : (
                <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>
                  {l.qty > 1 && <span style={{ color: 'var(--muted)', marginRight: 6, fontVariantNumeric: 'tabular-nums' }}>{l.qty}×</span>}
                  {l.label}
                </div>
              )}
            </div>
            {l.price !== 0 && <div style={{ fontSize: 13, fontWeight: 600, color: l.price < 0 ? 'var(--danger)' : 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{l.price > 0 ? '+' : ''}{l.price.toFixed(2)} €</div>}
          </div>
        ))}
      </div>
    </div>
  )

  return (
    <div>
      {isEmpty ? (
        <div style={{ padding: '40px 16px', textAlign: 'center', color: 'var(--muted)', fontSize: 14 }}>
          Δεν έχει γίνει καμία προσαρμογή. Χρησιμοποιήστε τις καρτέλες για να διαμορφώσετε το προϊόν.
        </div>
      ) : (
        <>
          <Section title="Προτιμήσεις" tab="prefs" lines={byGroup.prefs} />
          <Section title="Γρήγορες Επιλογές" tab="quick" lines={byGroup.quick} />
          <Section title="Extras" tab="extras" lines={byGroup.extras} />
          <Section title="Αφαιρέθηκαν" tab="ingredients" lines={byGroup.removed} />
          {note && (
            <div style={{ marginBottom: 20 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0 2px 8px' }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.6 }}>Σημείωση</div>
                <button onClick={() => onJumpTab('notes')} style={{ background: 'none', border: 'none', fontSize: 12, fontWeight: 700, color: '#f59e0b', cursor: 'pointer', textTransform: 'uppercase', letterSpacing: 0.6 }}>Αλλαγή</button>
              </div>
              <div style={{ padding: '12px 14px', background: 'rgba(245,158,11,0.08)', border: '1px solid rgba(245,158,11,0.2)', borderRadius: 10, fontSize: 14, color: 'var(--text)', lineHeight: 1.4, whiteSpace: 'pre-wrap' }}>{note}</div>
            </div>
          )}
        </>
      )}
    </div>
  )
}

// ── Main OrderDrawer ──────────────────────────────────────────────────────────

export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialState }) {
  const preferenceSets = product?.preference_sets || []
  const quickOptions = product?.quick_options || []
  const options = product?.options || []
  const ingredients = product?.ingredients || []
  const favorites = product ? buildFavorites(product) : []

  const hasTabs = {
    favorites: favorites.length > 0,
    quick: quickOptions.length > 0,
    extras: options.length > 0,
    ingredients: ingredients.length > 0,
    prefs: preferenceSets.length > 0,
  }

  const firstTab = hasTabs.favorites ? 'favorites'
    : hasTabs.quick ? 'quick'
    : hasTabs.extras ? 'extras'
    : hasTabs.ingredients ? 'ingredients'
    : hasTabs.prefs ? 'prefs'
    : 'notes'

  const [activeTab, setActiveTab] = useState(firstTab)
  const [qty, setQty] = useState(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 [addAttempted, setAddAttempted] = useState(false)

  // Reset/init when drawer opens or product changes
  useEffect(() => {
    if (!isOpen || !product) return
    const base = buildInitialState(product)
    if (initialState) {
      setQty(initialState.qty ?? 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 ?? '')
    } else {
      setQty(1)
      setQuickState({})
      setExtrasState({})
      setRemovedState({})
      setPrefs(base.prefs)
      setSubChoices(base.subChoices)
      setSharedSubs(base.sharedSubs)
      setNote('')
    }
    setExpandedExtra(null)
    setAddAttempted(false)
    setActiveTab(initialState?.activeTab ?? firstTab)
  }, [isOpen, product?.id])

  // Derived: summary lines + price
  const { summaryLines, totalPrice } = (() => {
    if (!product) return { summaryLines: [], totalPrice: 0 }
    let price = product.base_price
    const lines = []

    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
      const delta = (choice.extra_cost ?? 0) + (inlineSub?.extra_cost ?? 0) + (sharedSub?.extra_cost ?? 0)

      // Skip if this is entirely the default selection
      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) { price += delta; return }

      const value = `${choice.name}${inlineSub ? ` · ${inlineSub.name}` : ''}${sharedSub ? ` · ${sharedSub.name}` : ''}`
      lines.push({ group: 'prefs', label: ps.name, value, qty: 1, price: delta, detail: null })
      price += delta
    })

    quickOptions.forEach(opt => {
      const q = quickState[opt.id] || 0
      if (q === 0) return
      const linePrice = opt.price * q
      lines.push({ group: 'quick', label: opt.name, qty: q, price: linePrice, detail: null })
      price += linePrice
    })

    options.forEach(opt => {
      const sel = extrasState[opt.id]
      if (!sel) return
      const sub = opt.sub_choices?.find(s => s.name === sel.subName)
      const linePrice = ((opt.extra_cost ?? 0) + (sub?.extra_cost ?? 0)) * sel.qty
      lines.push({ group: 'extras', label: opt.name, qty: sel.qty, price: linePrice, subName: sub?.name ?? null, detail: null })
      price += linePrice
    })

    ingredients.forEach(ing => {
      if (removedState[ing.id]) lines.push({ group: 'removed', label: ing.name, qty: 1, price: 0, detail: null })
    })

    return { summaryLines: lines, totalPrice: price * qty }
  })()

  // Validation
  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

  const prefsHasMandatory = hasTabs.prefs && preferenceSets.some(ps => ps.default_choice_id == null)
  const prefsTabAlert = hasTabs.prefs && !allPrefsOk && (addAttempted || prefsHasMandatory)

  // Also alert the favorites tab if it contains an incomplete pref
  const favHasIncompletePref = hasTabs.favorites && !allPrefsOk && favorites.some(f => f.type === 'pref' && !isPrefComplete(f.item))
  const favTabAlert = favHasIncompletePref && (addAttempted || prefsHasMandatory)

  function handleAdd() {
    if (!canAdd) {
      setAddAttempted(true)
      if (!allPrefsOk) {
        // Jump to favorites if the incomplete pref is there, else prefs tab
        if (favHasIncompletePref) setActiveTab('favorites')
        else if (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

      // Don't emit entries that are entirely at their defaults — nothing changed
      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,
      selected_options: [...prefChoices, ...quickEntries, ...optionEntries],
      removed_ingredients: removedNames,
      notes: note,
      _drawerState: { qty, quickState, extrasState, removedState, prefs, subChoices, sharedSubs, note },
    })
    onClose()
  }

  // Tabs definition
  const tabs = [
    hasTabs.favorites && { id: 'favorites', label: '♥ Αγαπ.' },
    hasTabs.quick && { id: 'quick', label: 'Quick' },
    hasTabs.extras && { id: 'extras', label: 'Extras' },
    hasTabs.ingredients && { id: 'ingredients', label: 'Υλικά' },
    hasTabs.prefs && { id: 'prefs', label: 'Προτιμ.' },
    { id: 'notes', label: 'Note' },
    { id: 'summary', label: 'Summary' },
  ].filter(Boolean)

  const badgeFor = id => {
    if (id === 'favorites') {
      // count favorited items that have been interacted with
      const favQuick = favorites.filter(f => f.type === 'quick' && (quickState[f.item.id] || 0) > 0).length
      const favIng = favorites.filter(f => f.type === 'ingredient' && removedState[f.item.id]).length
      const favExt = favorites.filter(f => f.type === 'option' && extrasState[f.item.id]).length
      const favPref = favorites.filter(f => f.type === 'pref' && isPrefComplete(f.item)).length
      return favQuick + favIng + favExt + favPref
    }
    if (id === 'quick') return Object.values(quickState).filter(v => v > 0).length
    if (id === 'extras') return Object.values(extrasState).filter(Boolean).length
    if (id === 'ingredients') return Object.values(removedState).filter(Boolean).length
    if (id === 'prefs') return preferenceSets.filter(isPrefComplete).length
    if (id === 'notes') return note ? 1 : 0
    if (id === 'summary') return summaryLines.length + (note ? 1 : 0)
    return 0
  }

  if (!product) return null

  return (
    <>
      {/* Backdrop */}
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0,
        background: 'rgba(0,0,0,0.6)',
        opacity: isOpen ? 1 : 0,
        pointerEvents: isOpen ? 'auto' : 'none',
        transition: 'opacity 260ms ease',
        zIndex: 40,
      }} />

      {/* Sheet */}
      <div style={{
        position: 'fixed', left: 0, right: 0, bottom: 0,
        height: '92svh',
        background: 'var(--bg)',
        borderRadius: '20px 20px 0 0',
        transform: isOpen ? 'translateY(0)' : 'translateY(100%)',
        transition: 'transform 320ms cubic-bezier(0.32, 0.72, 0, 1)',
        zIndex: 41,
        display: 'flex', flexDirection: 'column',
        overflow: 'hidden',
        boxShadow: '0 -8px 40px rgba(0,0,0,0.5)',
      }}>
        {/* Grab handle */}
        <div style={{ padding: '10px 0 4px', display: 'flex', justifyContent: 'center', flexShrink: 0 }}>
          <div style={{ width: 40, height: 4, borderRadius: 2, background: 'var(--border)' }} />
        </div>

        {/* Header */}
        <div style={{ padding: '4px 16px 0', display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
          {product.image_url && (
            <img src={`${import.meta.env.VITE_API_URL || ''}${product.image_url}`} alt=""
              style={{ width: 48, height: 48, borderRadius: 12, objectFit: 'cover', flexShrink: 0 }} />
          )}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--text)', lineHeight: 1.2 }}>{product.name}</div>
            <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 2 }}>{product.base_price.toFixed(2)} €</div>
          </div>
          <button onClick={onClose} style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--bg3)', border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0 }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="var(--text)" strokeWidth="2.2" strokeLinecap="round"/></svg>
          </button>
        </div>

        {/* Tabs bar */}
        <div style={{ marginTop: 12, borderBottom: '1px solid var(--border)', overflowX: 'auto', scrollbarWidth: 'none', flexShrink: 0 }}>
          <div style={{ display: 'flex', padding: '0 12px', gap: 2, minWidth: 'max-content' }}>
            {tabs.map(t => {
              const active = activeTab === t.id
              const badge = badgeFor(t.id)
              const isAlert = (t.id === 'prefs' && prefsTabAlert) || (t.id === 'favorites' && favTabAlert)
              const tabColor = isAlert ? '#f59e0b' : active ? '#f59e0b' : 'var(--muted)'
              return (
                <button key={t.id} onClick={() => setActiveTab(t.id)} style={{
                  padding: '12px 6px',
                  background: 'none', border: 'none',
                  borderBottom: `2px solid ${active ? '#f59e0b' : 'transparent'}`,
                  color: tabColor,
                  fontSize: 14, fontWeight: (active || isAlert) ? 700 : 500,
                  fontFamily: 'inherit', cursor: 'pointer',
                  display: 'inline-flex', alignItems: 'center', gap: 5,
                  whiteSpace: 'nowrap', marginRight: 8,
                  transition: 'color 120ms ease, border-color 120ms ease',
                  animation: isAlert ? 'tab-pulse 0.9s ease-in-out 3' : 'none',
                }}>
                  {t.label}
                  {badge > 0 && !isAlert && (
                    <span style={{
                      minWidth: 18, height: 18, padding: '0 5px',
                      borderRadius: 9,
                      background: active ? 'var(--accent)' : 'var(--bg3)',
                      color: active ? 'var(--accent-fg)' : 'var(--muted)',
                      fontSize: 11, fontWeight: 700,
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                      fontVariantNumeric: 'tabular-nums',
                    }}>{badge}</span>
                  )}
                </button>
              )
            })}
          </div>
        </div>

        {/* Scrollable content */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '16px 16px 20px', background: 'var(--bg)', WebkitOverflowScrolling: 'touch' }}>
          {activeTab === 'favorites' && (
            <FavoritesTab
              product={product}
              quickState={quickState} setQuickState={setQuickState}
              extrasState={extrasState} setExtrasState={setExtrasState}
              expandedExtra={expandedExtra} setExpandedExtra={setExpandedExtra}
              removedState={removedState} setRemovedState={setRemovedState}
              prefs={prefs} setPrefs={setPrefs}
              subChoices={subChoices} setSubChoices={setSubChoices}
              sharedSubs={sharedSubs} setSharedSubs={setSharedSubs}
            />
          )}
          {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 === 'notes' && <NotesTab note={note} setNote={setNote} />}
          {activeTab === 'summary' && <SummaryTab product={product} summaryLines={summaryLines} note={note} onJumpTab={setActiveTab} />}
        </div>

        {/* Footer: qty stepper + ΠΡΟΣΘΗΚΗ */}
        <div style={{ padding: '12px 16px 20px', background: 'var(--bg2)', borderTop: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0, boxShadow: '0 -4px 16px rgba(0,0,0,0.3)' }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', height: 52, borderRadius: 26, background: 'var(--bg3)', border: '1px solid var(--border)', overflow: 'hidden', flexShrink: 0 }}>
            <button onClick={() => setQty(q => Math.max(1, q - 1))} style={{ width: 52, height: 52, border: 'none', background: 'transparent', fontSize: 22, fontWeight: 500, cursor: qty <= 1 ? 'default' : 'pointer', color: qty <= 1 ? 'var(--muted)' : 'var(--text)' }}>−</button>
            <div style={{ minWidth: 32, textAlign: 'center', fontSize: 17, fontWeight: 700, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{qty}</div>
            <button onClick={() => setQty(q => q + 1)} style={{ width: 52, height: 52, border: 'none', background: 'transparent', fontSize: 22, fontWeight: 500, cursor: 'pointer', color: 'var(--text)' }}>+</button>
          </div>
          <button onClick={handleAdd} disabled={!canAdd} style={{
            flex: 1, height: 52, borderRadius: 26,
            background: canAdd ? 'var(--accent)' : 'var(--bg3)',
            border: 'none', color: canAdd ? 'var(--accent-fg)' : 'var(--muted)',
            fontSize: 16, fontWeight: 700, fontFamily: 'inherit',
            cursor: canAdd ? 'pointer' : 'not-allowed',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '0 20px',
            transition: 'background 150ms ease',
          }}>
            <span>ΠΡΟΣΘΗΚΗ</span>
            <span style={{ fontVariantNumeric: 'tabular-nums' }}>{totalPrice.toFixed(2)} €</span>
          </button>
        </div>
      </div>
    </>
  )
}
