import { useEffect, useState, useRef, useCallback } from 'react'
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import OrderSummary from '../components/OrderSummary'
import useAuthStore from '../store/authStore'
import useConnectionStore from '../store/connectionStore'
import client from '../api/client'
import db from '../db/posdb'
import { queueOfflineSplit, queueOfflinePayment as queueOfflinePaymentOp } from '../services/offlineOrders'
import { TransferIcon, MergeIcon, FlagsIcon, WaiterIcon, PrintIcon } from '../components/Icons'
import usePaymentSettingsStore from '../store/paymentSettingsStore'
import useTableViewStore from '../store/tableViewStore'

function fmtPrice(v) { return Number(v).toFixed(2) + ' €' }

// ─── Merge mode ───────────────────────────────────────────────────────────────

const MERGE_OFF      = 'off'
const MERGE_IDENTICAL = 'identical'   // same product + options + price
const MERGE_SAME_ITEM = 'same_item'   // same product + same effective unit price

const MERGE_LABELS = {
  [MERGE_OFF]:       'ΔΙΑΧΩΡΙΣΜΟΣ',
  [MERGE_IDENTICAL]: 'ΙΔΙΑ ITEMS',
  [MERGE_SAME_ITEM]: 'ΙΔΙΑ ΤΙΜΗ',
}

// Returns a stable string key for grouping under MERGE_IDENTICAL
function identicalKey(item) {
  const effPrice = ((item.unit_price ?? 0) + (item.price_adjustment ?? 0)).toFixed(4)
  const opts = (() => { try { return item.selected_options ?? '[]' } catch { return '[]' } })()
  const removed = (() => { try { return item.removed_ingredients ?? '[]' } catch { return '[]' } })()
  const notes = item.notes ?? ''
  return `${item.product_id}|${effPrice}|${opts}|${removed}|${notes}`
}

// Returns a grouping key for MERGE_SAME_ITEM (ignores options/removed/notes, only product + price)
function sameItemKey(item) {
  const effPrice = ((item.unit_price ?? 0) + (item.price_adjustment ?? 0)).toFixed(4)
  return `${item.product_id}|${effPrice}`
}

// Builds the display item list. When mode is OFF returns items unchanged.
// Otherwise returns virtual merged items with _isMerged, _sourceIds, _sourceItems.
function mergeItems(items, mode) {
  if (mode === MERGE_OFF) return items

  const keyFn = mode === MERGE_IDENTICAL ? identicalKey : sameItemKey
  const groups = new Map()

  items.forEach(item => {
    const k = keyFn(item)
    if (!groups.has(k)) {
      groups.set(k, {
        // Copy the first real item as template, quantity will be summed
        ...item,
        quantity: 0,
        _isMerged: true,
        _sourceIds: [],
        _sourceItems: [],
      })
    }
    const g = groups.get(k)
    g.quantity += item.quantity
    g._sourceIds.push(item.id)
    g._sourceItems.push(item)
  })

  return Array.from(groups.values())
}

// ─── Split stepper modal ──────────────────────────────────────────────────────

function SplitModal({ item, onConfirm, onClose }) {
  const [splitQty, setSplitQty] = useState(1)
  const max = item.quantity - 1

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-sheet" onClick={e => e.stopPropagation()}>
        <div className="modal-handle" />
        <h2 className="modal-title">Διαχωρισμός</h2>
        <p style={{ textAlign: 'center', color: '#94a3b8', fontSize: 14, marginBottom: 4 }}>
          {item.product?.name} ×{item.quantity}
        </p>
        <p style={{ textAlign: 'center', color: '#94a3b8', fontSize: 13, marginBottom: 16 }}>
          Χώρισε σε πόσα;
        </p>

        <div className="modal-qty" style={{ marginBottom: 8 }}>
          <button className="qty-btn" onClick={() => setSplitQty(q => Math.max(1, q - 1))}>−</button>
          <span className="qty-value">{splitQty}</span>
          <button className="qty-btn" onClick={() => setSplitQty(q => Math.min(max, q + 1))}>+</button>
        </div>

        <div style={{ display: 'flex', justifyContent: 'center', gap: 20, marginBottom: 20, fontSize: 13, color: '#94a3b8' }}>
          <span>Νέα γραμμή: <strong style={{ color: '#f59e0b' }}>×{splitQty}</strong></span>
          <span>Μένει: <strong style={{ color: '#64748b' }}>×{item.quantity - splitQty}</strong></span>
        </div>

        <div style={{ display: 'flex', gap: 12 }}>
          <button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose}>Άκυρο</button>
          <button className="btn btn--primary" style={{ flex: 1 }} onClick={() => onConfirm(splitQty)}>
            Διαχωρισμός
          </button>
        </div>
      </div>
    </div>
  )
}

// ─── Price adjust modal ───────────────────────────────────────────────────────

function PriceAdjustModal({ item, onConfirm, onClose }) {
  const basePrice = item.unit_price ?? 0
  const [adj, setAdj] = useState(item.price_adjustment ?? 0)
  const [editing, setEditing] = useState(false)
  const [rawInput, setRawInput] = useState('')
  const inputRef = useRef(null)

  const effective = basePrice + adj

  function applyDelta(delta) {
    setAdj(prev => {
      const next = Math.round((prev + delta) * 100) / 100
      return next
    })
  }

  function startEdit() {
    setRawInput(String(effective.toFixed(2)))
    setEditing(true)
    setTimeout(() => inputRef.current?.focus(), 50)
  }

  function commitEdit() {
    const parsed = parseFloat(rawInput.replace(',', '.'))
    if (!isNaN(parsed)) {
      setAdj(Math.round((parsed - basePrice) * 100) / 100)
    }
    setEditing(false)
  }

  const QUICK_DELTAS = [-5, -3, -2, -1, -0.5, -0.2, +0.2, +0.5, +1, +2, +3, +5]

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-sheet" onClick={e => e.stopPropagation()}>
        <div className="modal-handle" />
        <h2 className="modal-title">Ρύθμιση Τιμής</h2>
        <p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 16px' }}>
          {item.product?.name}
        </p>

        {/* Current effective price — tap to type */}
        <div style={{ textAlign: 'center', marginBottom: 16 }}>
          {editing ? (
            <input
              ref={inputRef}
              type="number"
              step="0.01"
              value={rawInput}
              onChange={e => setRawInput(e.target.value)}
              onBlur={commitEdit}
              onKeyDown={e => { if (e.key === 'Enter') commitEdit() }}
              style={{
                fontSize: 36, fontWeight: 800, color: adj !== 0 ? '#f59e0b' : 'var(--text)',
                background: 'var(--bg3)', border: '2px solid var(--accent)',
                borderRadius: 12, padding: '6px 16px', textAlign: 'center',
                width: '140px',
              }}
            />
          ) : (
            <button
              onClick={startEdit}
              style={{
                fontSize: 36, fontWeight: 800, color: adj !== 0 ? '#f59e0b' : 'var(--text)',
                background: 'var(--bg3)', border: '2px solid var(--border)',
                borderRadius: 12, padding: '6px 20px', cursor: 'pointer',
              }}
            >
              {effective.toFixed(2)} €
            </button>
          )}
          {adj !== 0 && (
            <div style={{ fontSize: 12, color: adj > 0 ? '#22c55e' : '#f87171', marginTop: 4 }}>
              Βασική: {basePrice.toFixed(2)} € {adj > 0 ? '+' : ''}{adj.toFixed(2)} €
            </div>
          )}
          <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 2 }}>Πάτα για πληκτρολόγιο</div>
        </div>

        {/* +/- stepper (0.1 step) */}
        <div className="modal-qty" style={{ marginBottom: 14 }}>
          <button className="qty-btn" onClick={() => applyDelta(-0.1)}>−</button>
          <span className="qty-value" style={{ fontSize: 14, color: 'var(--muted)', minWidth: 60 }}>0.10 €</span>
          <button className="qty-btn" onClick={() => applyDelta(+0.1)}>+</button>
        </div>

        {/* Quick delta buttons — 4 rows × 3 */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6, marginBottom: 18 }}>
          {QUICK_DELTAS.map(d => (
            <button
              key={d}
              onClick={() => applyDelta(d)}
              style={{
                padding: '9px 4px', borderRadius: 10, border: 'none', cursor: 'pointer',
                fontWeight: 700, fontSize: 13,
                background: d < 0 ? 'rgba(239,68,68,0.15)' : 'rgba(34,197,94,0.15)',
                color: d < 0 ? '#f87171' : '#4ade80',
              }}
            >
              {d > 0 ? '+' : ''}{d.toFixed(1).replace('.0', '')} €
            </button>
          ))}
        </div>

        {/* Reset */}
        {adj !== 0 && (
          <button
            onClick={() => setAdj(0)}
            style={{
              width: '100%', marginBottom: 8, padding: '8px 0', borderRadius: 10,
              background: 'rgba(148,163,184,0.1)', border: '1px solid var(--border)',
              color: 'var(--muted)', fontSize: 13, cursor: 'pointer',
            }}
          >
            Επαναφορά αρχικής τιμής
          </button>
        )}

        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose}>Άκυρο</button>
          <button className="btn btn--primary" style={{ flex: 1 }} onClick={() => onConfirm(adj)}>
            Εφαρμογή
          </button>
        </div>
      </div>
    </div>
  )
}

// ─── Item action modal (long-press) ──────────────────────────────────────────

function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCancel, canCancel, priceAdjAllowed, onAdjustPrice, onClose }) {
  const { items, singleStacked, multiSelect } = target
  const label = multiSelect
    ? `${items.length} αντικείμενα επιλεγμένα`
    : items[0]?.product?.name || `#${items[0]?.product_id}`

  const actionRows = [
    ...(!multiSelect && priceAdjAllowed ? [{
      key: 'adjust_price',
      color: '#f59e0b',
      iconBg: 'rgba(245,158,11,0.15)',
      label: 'Ρύθμιση τιμής',
      sub: 'Αλλαγή τιμής για αυτό το αντικείμενο',
      icon: (
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
          <circle cx="12" cy="12" r="9" stroke="#f59e0b" strokeWidth="2"/>
          <path d="M12 7v10M9.5 9.5C9.5 8.12 10.62 7 12 7s2.5 1.12 2.5 2.5c0 1.38-1.12 2.5-2.5 2.5s-2.5 1.12-2.5 2.5S10.62 17 12 17s2.5-1.12 2.5-2.5" stroke="#f59e0b" strokeWidth="1.8" strokeLinecap="round"/>
        </svg>
      ),
      onClick: onAdjustPrice,
      enabled: true,
    }] : []),
    {
      key: 'order_again',
      color: '#22c55e',
      iconBg: 'rgba(34,197,94,0.15)',
      label: 'Παραγγελία ξανά',
      sub: 'Προσθήκη στο νέο καλάθι',
      icon: (
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
          <path d="M1 4v6h6M23 20v-6h-6" stroke="#22c55e" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          <path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4-4.64 4.36A9 9 0 0 1 3.51 15" stroke="#22c55e" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      ),
      onClick: onOrderAgain,
      enabled: true,
    },
    {
      key: 'move',
      color: '#f97316',
      iconBg: 'rgba(249,115,22,0.15)',
      label: 'Μεταφορά σε άλλο τραπέζι',
      sub: 'Μεταφορά επιλεγμένων αντικειμένων',
      icon: (
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
          <path d="M5 12h14M12 5l7 7-7 7" stroke="#f97316" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      ),
      onClick: onMoveToTable,
      enabled: true,
    },
    ...(singleStacked && !multiSelect ? [{
      key: 'split',
      color: '#60a5fa',
      iconBg: 'rgba(96,165,250,0.15)',
      label: 'Διαχωρισμός',
      sub: 'Χώρισμα σε δύο γραμμές',
      icon: (
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
          <path d="M16 3h5v5M4 20L21 3M21 16v5h-5M15 15l6 6M4 4l5 5" stroke="#60a5fa" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      ),
      onClick: onSplit,
      enabled: true,
    }] : []),
    {
      key: 'cancel',
      color: canCancel ? '#ef4444' : '#6b7280',
      iconBg: canCancel ? 'rgba(239,68,68,0.15)' : 'rgba(107,114,128,0.1)',
      label: 'Ακύρωση παραγγελίας',
      sub: canCancel ? 'Ακύρωση επιλεγμένων αντικειμένων' : 'Δεν επιτρέπεται η ακύρωση',
      icon: (
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
          <circle cx="12" cy="12" r="10" stroke={canCancel ? '#ef4444' : '#6b7280'} strokeWidth="2"/>
          <path d="M15 9l-6 6M9 9l6 6" stroke={canCancel ? '#ef4444' : '#6b7280'} strokeWidth="2" strokeLinecap="round"/>
        </svg>
      ),
      onClick: canCancel ? onCancel : null,
      enabled: canCancel,
    },
  ]

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-sheet" onClick={e => e.stopPropagation()} style={{ gap: 0 }}>
        <div className="modal-handle" />
        <p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 16px' }}>{label}</p>

        {actionRows.map((a, i) => (
          <button
            key={a.key}
            onClick={a.onClick ? a.onClick : undefined}
            disabled={!a.enabled}
            style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 14,
              padding: '16px 4px', background: 'none', border: 'none',
              borderBottom: i < actionRows.length - 1 ? '1px solid var(--border)' : 'none',
              cursor: a.enabled ? 'pointer' : 'not-allowed',
              opacity: a.enabled ? 1 : 0.45, textAlign: 'left',
            }}
          >
            <span style={{
              width: 38, height: 38, borderRadius: 10, flexShrink: 0,
              background: a.iconBg,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>{a.icon}</span>
            <div>
              <div style={{ fontSize: 15, fontWeight: 600, color: a.color }}>{a.label}</div>
              <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>{a.sub}</div>
            </div>
            {a.enabled && <span style={{ marginLeft: 'auto', color: 'var(--muted)', fontSize: 18 }}>›</span>}
          </button>
        ))}

        <button className="btn btn--secondary" style={{ width: '100%', marginTop: 12 }} onClick={onClose}>
          Άκυρο
        </button>
      </div>
    </div>
  )
}

// ─── Apply Discount modal ─────────────────────────────────────────────────────

function ApplyDiscountModal({ order, waiterId, onClose, onApplied }) {
  const activeItems = (order?.items ?? []).filter(i => i.status === 'active')
  const [selectedIds, setSelectedIds] = useState(activeItems.map(i => i.id))
  const [pct, setPct] = useState(10)
  const [note, setNote] = useState('')
  const [applying, setApplying] = useState(false)
  const [remaining, setRemaining] = useState(null) // { shift, workday }
  const [error, setError] = useState('')

  const PCT_PRESETS = [5, 10, 15, 20, 25, 50, 100]

  function toggleItem(id) {
    setSelectedIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id])
  }

  // Compute preview
  const selectedItems = activeItems.filter(i => selectedIds.includes(i.id))
  const discountTotal = selectedItems.reduce((s, i) => {
    const eff = (i.unit_price ?? 0) + (i.price_adjustment ?? 0)
    return s + eff * i.quantity * (pct / 100)
  }, 0)
  // Round pct to nearest 0.10 so final prices are clean
  const roundedPct = Math.round(pct * 10) / 10

  async function apply() {
    if (selectedIds.length === 0) { setError('Επιλέξτε τουλάχιστον ένα αντικείμενο'); return }
    if (roundedPct <= 0 || roundedPct > 100) { setError('Μη έγκυρο ποσοστό'); return }
    setApplying(true); setError('')
    try {
      const res = await client.post(`/api/orders/${order.id}/items/discount`, {
        item_ids: selectedIds,
        discount_percent: roundedPct,
        note: note.trim() || null,
      })
      setRemaining({
        shift: res.data.remaining_budget_shift,
        workday: res.data.remaining_budget_workday,
      })
      onApplied()
      onClose()
    } catch (e) {
      setError(e?.response?.data?.detail || 'Σφάλμα εφαρμογής έκπτωσης')
    } finally {
      setApplying(false)
    }
  }

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-sheet" onClick={e => e.stopPropagation()} style={{ gap: 0 }}>
        <div className="modal-handle" />
        <h2 className="modal-title" style={{ marginBottom: 4 }}>Εφαρμογή Έκπτωσης</h2>
        <p style={{ textAlign: 'center', fontSize: 12, color: 'var(--muted)', marginBottom: 16 }}>
          Η τελική τιμή στρογγυλοποιείται στο 0.10 €
        </p>

        {/* Item multi-select */}
        <div style={{ marginBottom: 14 }}>
          <p style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 8 }}>Αντικείμενα</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 180, overflowY: 'auto' }}>
            {activeItems.map(item => {
              const eff = (item.unit_price ?? 0) + (item.price_adjustment ?? 0)
              const checked = selectedIds.includes(item.id)
              const newPrice = Math.round((eff * (1 - roundedPct / 100)) * 10) / 10
              return (
                <button key={item.id} onClick={() => toggleItem(item.id)}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 10,
                    padding: '10px 12px', borderRadius: 10, border: 'none', cursor: 'pointer',
                    background: checked ? 'rgba(99,102,241,0.12)' : 'var(--bg3)',
                    textAlign: 'left',
                  }}>
                  <div style={{
                    width: 20, height: 20, borderRadius: 5, flexShrink: 0,
                    background: checked ? '#6366f1' : 'var(--border)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    {checked && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3" strokeLinecap="round"><path d="M20 6L9 17l-5-5"/></svg>}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {item.product?.name ?? `#${item.product_id}`}
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--muted)' }}>×{item.quantity} · {eff.toFixed(2)} €</div>
                  </div>
                  {checked && (
                    <div style={{ fontSize: 12, fontWeight: 700, color: '#4ade80', shrink: 0 }}>
                      → {newPrice.toFixed(2)} €
                    </div>
                  )}
                </button>
              )
            })}
          </div>
        </div>

        {/* Percent picker */}
        <div style={{ marginBottom: 14 }}>
          <p style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 8 }}>Ποσοστό έκπτωσης</p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 10 }}>
            {PCT_PRESETS.map(p => (
              <button key={p} onClick={() => setPct(p)}
                style={{
                  padding: '6px 12px', borderRadius: 8, border: 'none', cursor: 'pointer', fontWeight: 700, fontSize: 13,
                  background: pct === p ? '#6366f1' : 'var(--bg3)',
                  color: pct === p ? '#fff' : 'var(--text)',
                }}>
                {p}%
              </button>
            ))}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <input type="number" min={1} max={100} step={1} value={pct}
              onChange={e => setPct(Number(e.target.value))}
              style={{
                width: 80, padding: '8px 10px', borderRadius: 10,
                border: '1.5px solid var(--border)', background: 'var(--bg3)',
                color: 'var(--text)', fontSize: 16, fontWeight: 700, textAlign: 'center',
              }} />
            <span style={{ fontSize: 14, color: 'var(--muted)' }}>%</span>
            <span style={{ fontSize: 13, color: '#4ade80', fontWeight: 700 }}>
              −{discountTotal.toFixed(2)} €
            </span>
          </div>
        </div>

        {/* Note */}
        <div style={{ marginBottom: 14 }}>
          <p style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 6 }}>Σημείωση (προαιρετικό)</p>
          <input value={note} onChange={e => setNote(e.target.value)}
            placeholder="π.χ. VIP πελάτης"
            style={{
              width: '100%', padding: '9px 12px', borderRadius: 10,
              border: '1.5px solid var(--border)', background: 'var(--bg3)',
              color: 'var(--text)', fontSize: 13, boxSizing: 'border-box',
            }} />
        </div>

        {error && (
          <p style={{ fontSize: 12, color: '#f87171', textAlign: 'center', marginBottom: 10 }}>{error}</p>
        )}

        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose}>Άκυρο</button>
          <button className="btn btn--primary" style={{ flex: 1 }} onClick={apply} disabled={applying}>
            {applying ? 'Εφαρμογή…' : 'Εφαρμογή'}
          </button>
        </div>
      </div>
    </div>
  )
}

// ─── Actions top sheet ────────────────────────────────────────────────────────

function CancelIcon({ width = 20, height = 20 }) {
  return (
    <svg width={width} height={height} viewBox="0 0 24 24" fill="none">
      <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2"/>
      <path d="M15 9l-6 6M9 9l6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
    </svg>
  )
}

function CheckIcon({ width = 20, height = 20 }) {
  return (
    <svg width={width} height={height} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M20 6L9 17l-5-5"/>
    </svg>
  )
}

function DiscountIcon({ width = 20, height = 20 }) {
  return (
    <svg width={width} height={height} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="9" cy="9" r="2"/><circle cx="15" cy="15" r="2"/>
      <path d="M5 19L19 5"/>
    </svg>
  )
}

function ActionsSheet({ order, tableId, isStandalone, onClose, onTransfer, onMerge, onSetFlags, onAssignWaiter, onPrintSynopsis, onCancelOrder, onMarkAllServed, canCancel, canDiscount, onApplyDiscount }) {
  const hasOrder = !!order
  const hasServable = hasOrder && order.items?.some(i => i.kds_status === 'done')
  const hasActiveItems = hasOrder && order.items?.some(i => i.status === 'active')
  const allActions = [
    { Icon: CheckIcon,    label: 'Σήμανση Όλων ως Παραδοθέντα', sub: 'Σήμανση όλων των έτοιμων ειδών ως παραδοθέντα',
      onClick: hasServable ? onMarkAllServed : null, color: hasServable ? '#4ade80' : '#6b7280', iconBg: hasServable ? 'rgba(34,197,94,0.15)' : 'rgba(107,114,128,0.1)' },
    { Icon: DiscountIcon, label: 'Εφαρμογή Έκπτωσης', sub: canDiscount ? 'Έκπτωση σε αντικείμενα παραγγελίας' : 'Δεν επιτρέπεται η εφαρμογή έκπτωσης',
      onClick: (hasActiveItems && canDiscount) ? onApplyDiscount : null, color: (hasActiveItems && canDiscount) ? '#a78bfa' : '#6b7280', iconBg: (hasActiveItems && canDiscount) ? 'rgba(167,139,250,0.15)' : 'rgba(107,114,128,0.1)' },
    { Icon: TransferIcon, label: 'Μεταφορά Τραπεζιού',    sub: 'Μεταφορά σε άλλο τραπέζι',              onClick: hasOrder ? onTransfer : null,               color: '#6099db', iconBg: 'rgba(96,165,250,0.15)', tableOnly: true },
    { Icon: MergeIcon,    label: 'Συγχώνευση Τραπεζιού',  sub: 'Συγχώνευση με άλλο τραπέζι',            onClick: hasOrder ? onMerge : null,                   color: '#6099db', iconBg: 'rgba(96,165,250,0.15)', tableOnly: true },
    { Icon: FlagsIcon,    label: 'Ενδείξεις Τραπεζιού',   sub: 'Επιλογή σημαιών',                       onClick: onSetFlags,                                  color: '#fac823', iconBg: 'rgba(251,191,36,0.15)', tableOnly: true },
    { Icon: WaiterIcon,   label: 'Ανάθεση Σερβιτόρου',    sub: 'Προσθήκη σερβιτόρου στην παραγγελία',   onClick: hasOrder ? onAssignWaiter : null,             color: '#39b861', iconBg: 'rgba(34,197,94,0.15)'  },
    { Icon: PrintIcon,    label: 'Εκτύπωση Σύνοψης',      sub: 'Εκτύπωση σύνοψης παραγγελίας',          onClick: hasOrder ? onPrintSynopsis : null,            color: '#cbd5e1', iconBg: 'rgba(148,163,184,0.15)' },
    { Icon: CancelIcon,   label: 'Ακύρωση Παραγγελίας',   sub: canCancel ? 'Ακύρωση ολόκληρης παραγγελίας' : 'Δεν επιτρέπεται η ακύρωση',
      onClick: (hasOrder && canCancel) ? onCancelOrder : null, color: (hasOrder && canCancel) ? '#ef4444' : '#6b7280', iconBg: (hasOrder && canCancel) ? 'rgba(239,68,68,0.15)' : 'rgba(107,114,128,0.1)' },
  ]
  const actions = isStandalone ? allActions.filter(a => !a.tableOnly) : allActions

  return (
    <div className="modal-overlay modal-overlay--top" onClick={onClose}>
      <div className="modal-sheet modal-sheet--top" onClick={e => e.stopPropagation()} style={{ gap: 0 }}>
        <div className="modal-handle" />
        <h2 className="modal-title" style={{ marginBottom: 16 }}>ACTIONS</h2>
        {actions.map((a, i) => (
          <button
            key={i}
            onClick={() => { a.onClick?.(); onClose() }}
            disabled={!a.onClick}
            style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 16,
              padding: '14px 0', background: 'none', border: 'none',
              borderBottom: i < actions.length - 1 ? '1px solid var(--border)' : 'none',
              cursor: a.onClick ? 'pointer' : 'not-allowed',
              opacity: a.onClick ? 1 : 0.35, textAlign: 'left',
            }}
          >
            <span style={{
              width: 38, height: 38, borderRadius: 10, flexShrink: 0,
              background: a.iconBg,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: a.color,
            }}>
              <a.Icon width="20" height="20" />
            </span>
            <div>
              <div style={{ fontSize: 15, fontWeight: 600, color: a.color }}>{a.label}</div>
              <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>{a.sub}</div>
            </div>
            {a.onClick && <span style={{ marginLeft: 'auto', color: 'var(--muted)', fontSize: 18 }}>›</span>}
          </button>
        ))}
      </div>
    </div>
  )
}

// ─── Table picker (for transfer / merge / move-items) ─────────────────────────

function TablePicker({ title, subtitle, tables, currentTableId, onSelect, onClose, loading }) {
  return (
    <div className="modal-overlay modal-overlay--top" onClick={onClose}>
      <div className="modal-sheet modal-sheet--top" onClick={e => e.stopPropagation()}>
        <div className="modal-handle" />
        <h2 className="modal-title">{title}</h2>
        {subtitle && <p style={{ textAlign: 'center', color: '#94a3b8', fontSize: 13, marginBottom: 4 }}>{subtitle}</p>}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 0, maxHeight: '60svh', overflowY: 'auto' }}>
          {loading && (
            <p style={{ textAlign: 'center', color: '#64748b', padding: 24 }}>Φόρτωση…</p>
          )}
          {!loading && tables.length === 0 && (
            <p style={{ textAlign: 'center', color: '#64748b', padding: 24 }}>Δεν υπάρχουν διαθέσιμα τραπέζια</p>
          )}
          {!loading && tables.map(t => (
            <button
              key={t.id}
              onClick={() => onSelect(t)}
              style={{
                width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '14px 4px', background: 'none', border: 'none',
                borderBottom: '1px solid var(--border)', cursor: 'pointer', textAlign: 'left',
              }}
            >
              <div>
                <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--text)' }}>
                  {t.label || `T${t.number}`}
                </div>
                {t.orderStatus && (
                  <div style={{ fontSize: 12, color: '#f59e0b', marginTop: 2 }}>
                    {t.orderStatus === 'open' ? 'Ανοιχτό' : t.orderStatus === 'partially_paid' ? 'Μερικώς πληρωμένο' : t.orderStatus}
                  </div>
                )}
              </div>
              <span style={{ color: 'var(--muted)', fontSize: 18 }}>›</span>
            </button>
          ))}
        </div>
        <button className="btn btn--secondary" style={{ width: '100%', marginTop: 8 }} onClick={onClose}>Άκυρο</button>
      </div>
    </div>
  )
}

// ─── Flag picker ──────────────────────────────────────────────────────────────

function FlagPicker({ tableId, currentFlagIds, flagDefs, onSave, onClose, loading }) {
  const [selected, setSelected] = useState(currentFlagIds || [])

  // Sync selected when currentFlagIds loads
  useEffect(() => { setSelected(currentFlagIds || []) }, [currentFlagIds.join(',')])

  function toggle(id) {
    setSelected(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id])
  }

  return (
    <div className="modal-overlay modal-overlay--top" onClick={onClose}>
      <div className="modal-sheet modal-sheet--top" onClick={e => e.stopPropagation()}>
        <div className="modal-handle" />
        <h2 className="modal-title">Ενδείξεις Τραπεζιού</h2>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 0, marginBottom: 20 }}>
          {loading && (
            <p style={{ textAlign: 'center', color: '#64748b', padding: 16 }}>Φόρτωση…</p>
          )}
          {!loading && flagDefs.length === 0 && (
            <p style={{ textAlign: 'center', color: '#64748b', padding: 16 }}>Δεν υπάρχουν σημαίες</p>
          )}
          {!loading && flagDefs.map(f => {
            const sel = selected.includes(f.id)
            return (
              <button
                key={f.id}
                onClick={() => toggle(f.id)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 14,
                  padding: '14px 4px', background: 'none', border: 'none',
                  borderBottom: '1px solid var(--border)', cursor: 'pointer', textAlign: 'left',
                  opacity: sel ? 1 : 0.7,
                }}
              >
                <div style={{
                  width: 36, height: 36, borderRadius: '50%', flexShrink: 0,
                  background: f.color + '33', border: `2px solid ${sel ? f.color : 'transparent'}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18,
                }}>
                  {f.emoji || '🏷️'}
                </div>
                <span style={{ flex: 1, fontSize: 15, fontWeight: sel ? 700 : 500, color: sel ? f.color : 'var(--text)' }}>
                  {f.name}
                </span>
                <span style={{ fontSize: 20, color: sel ? f.color : 'var(--muted)' }}>
                  {sel ? '✓' : '○'}
                </span>
              </button>
            )
          })}
        </div>
        <div style={{ display: 'flex', gap: 12 }}>
          <button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose}>Άκυρο</button>
          <button className="btn btn--primary" style={{ flex: 1 }} onClick={() => onSave(selected)}>Αποθήκευση</button>
        </div>
      </div>
    </div>
  )
}

// ─── Assign waiter picker ─────────────────────────────────────────────────────

function AssignWaiterPicker({ orderId, currentWaiterIds, waiters, onAssigned, onClose, loading }) {
  const [saving, setSaving] = useState(false)

  async function assign(waiterId) {
    setSaving(true)
    try {
      await client.put(`/api/orders/${orderId}/assign-waiter`, { waiter_id: waiterId })
      onAssigned()
      onClose()
    } catch {
      // already assigned or error — just close
      onClose()
    } finally {
      setSaving(false)
    }
  }

  const available = waiters.filter(w => !currentWaiterIds.includes(w.id))

  return (
    <div className="modal-overlay modal-overlay--top" onClick={onClose}>
      <div className="modal-sheet modal-sheet--top" onClick={e => e.stopPropagation()}>
        <div className="modal-handle" />
        <h2 className="modal-title">Ανάθεση Σερβιτόρου</h2>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 0, marginBottom: 16, maxHeight: '60svh', overflowY: 'auto' }}>
          {loading && (
            <p style={{ textAlign: 'center', color: '#64748b', padding: 16 }}>Φόρτωση…</p>
          )}
          {!loading && available.length === 0 && (
            <p style={{ textAlign: 'center', color: '#64748b', padding: 16 }}>Όλοι οι σερβιτόροι έχουν ήδη ανατεθεί</p>
          )}
          {!loading && available.map(w => (
            <button
              key={w.id}
              onClick={() => assign(w.id)}
              disabled={saving}
              style={{
                display: 'flex', alignItems: 'center', gap: 14,
                padding: '14px 4px', background: 'none', border: 'none',
                borderBottom: '1px solid var(--border)', cursor: 'pointer', textAlign: 'left',
              }}
            >
              <div style={{
                width: 36, height: 36, borderRadius: '50%', flexShrink: 0,
                background: 'var(--bg3)', display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 16, fontWeight: 700, color: 'var(--text)',
              }}>
                {(w.nickname || w.username).charAt(0).toUpperCase()}
              </div>
              <span style={{ fontSize: 15, color: 'var(--text)' }}>{w.nickname || w.full_name || w.username}</span>
              <span style={{ marginLeft: 'auto', color: 'var(--muted)', fontSize: 18 }}>›</span>
            </button>
          ))}
        </div>
        <button className="btn btn--secondary" style={{ width: '100%' }} onClick={onClose}>Άκυρο</button>
      </div>
    </div>
  )
}

// ─── Print synopsis picker ────────────────────────────────────────────────────

function PrintSynopsisPicker({ orderId, onClose }) {
  const [printers, setPrinters] = useState([])
  const [printing, setPrinting] = useState(false)

  useEffect(() => {
    client.get('/api/system/status').then(r => setPrinters(r.data?.printers || [])).catch(() => {})
  }, [])

  async function print(printerId) {
    setPrinting(true)
    try {
      await client.post(`/api/orders/${orderId}/print-synopsis`, { printer_id: printerId })
      onClose()
    } catch {
      onClose()
    } finally {
      setPrinting(false)
    }
  }

  return (
    <div className="modal-overlay modal-overlay--top" onClick={onClose}>
      <div className="modal-sheet modal-sheet--top" onClick={e => e.stopPropagation()}>
        <div className="modal-handle" />
        <h2 className="modal-title">Εκτύπωση Σύνοψης</h2>
        <p style={{ textAlign: 'center', color: '#94a3b8', fontSize: 13, marginBottom: 8 }}>Επιλέξτε εκτυπωτή</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 0, marginBottom: 16 }}>
          {printers.filter(p => p.reachable).map(p => (
            <button
              key={p.id}
              onClick={() => print(p.id)}
              disabled={printing}
              style={{
                display: 'flex', alignItems: 'center', gap: 14,
                padding: '14px 4px', background: 'none', border: 'none',
                borderBottom: '1px solid var(--border)', cursor: 'pointer', textAlign: 'left',
              }}
            >
              <span style={{ fontSize: 20 }}>🖨️</span>
              <span style={{ fontSize: 15, color: 'var(--text)' }}>{p.name}</span>
              <span style={{ marginLeft: 'auto', color: 'var(--muted)', fontSize: 18 }}>›</span>
            </button>
          ))}
          {printers.filter(p => !p.reachable).map(p => (
            <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 4px', borderBottom: '1px solid var(--border)', opacity: 0.4 }}>
              <span style={{ fontSize: 20 }}>🖨️</span>
              <span style={{ fontSize: 15, color: 'var(--text)' }}>{p.name}</span>
              <span style={{ marginLeft: 'auto', fontSize: 11, color: '#ef4444' }}>Offline</span>
            </div>
          ))}
        </div>
        <button className="btn btn--secondary" style={{ width: '100%' }} onClick={onClose}>Άκυρο</button>
      </div>
    </div>
  )
}

// ─── Pay confirm modal ────────────────────────────────────────────────────────

function CancelConfirmModal({ itemCount, onConfirm, onClose }) {
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-sheet" onClick={e => e.stopPropagation()}>
        <div className="modal-handle" />
        <h2 className="modal-title">Ακύρωση παραγγελίας;</h2>
        <p style={{ color: '#94a3b8', textAlign: 'center', marginBottom: 24, fontSize: 14 }}>
          {itemCount === null
            ? 'Ολόκληρη η παραγγελία θα ακυρωθεί οριστικά.'
            : `${itemCount} αντικείμενο${itemCount !== 1 ? 'α' : ''} θα ακυρωθ${itemCount !== 1 ? 'ούν' : 'εί'} οριστικά.`}
        </p>
        <div style={{ display: 'flex', gap: 12 }}>
          <button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose}>Άκυρο</button>
          <button
            onClick={onConfirm}
            style={{
              flex: 1, height: 48, borderRadius: 12, border: 'none',
              background: '#dc2626', color: 'white', fontSize: 15, fontWeight: 700, cursor: 'pointer',
            }}
          >Ακύρωση ✕</button>
        </div>
      </div>
    </div>
  )
}

function PayConfirmModal({ payAll, payIds, activeItems, andClose, cardEnabled, onConfirm, onClose }) {
  const { paymentSafety } = usePaymentSettingsStore()
  const [method, setMethod] = useState('cash')
  const [secondConfirmOpen, setSecondConfirmOpen] = useState(false)
  const [longPressActive, setLongPressActive] = useState(false)
  const longPressTimer = useRef(null)

  const payTotal = activeItems
    .filter(i => payIds.includes(i.id))
    .reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0)

  const title = andClose ? 'Επιβεβαίωση Πληρωμής και Κλείσιμο' : 'Επιβεβαίωση πληρωμής'
  const subtitle = andClose
    ? 'Όλα τα αντικείμενα — το τραπέζι θα κλείσει αμέσως μετά'
    : payAll ? 'Όλα τα αντικείμενα' : `${payIds.length} αντικείμενο${payIds.length !== 1 ? 'α' : ''}`

  function handleConfirmClick() {
    if (paymentSafety === 'second_confirm') {
      setSecondConfirmOpen(true)
    } else {
      onConfirm(method)
    }
  }

  function startLongPress() {
    setLongPressActive(true)
    longPressTimer.current = setTimeout(() => {
      setLongPressActive(false)
      onConfirm(method)
    }, 800)
  }

  function cancelLongPress() {
    clearTimeout(longPressTimer.current)
    setLongPressActive(false)
  }

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-sheet" onClick={e => e.stopPropagation()}>
        <div className="modal-handle" />
        <h2 className="modal-title" style={{ fontSize: andClose ? 16 : undefined }}>{title}</h2>
        <p style={{ color: '#94a3b8', textAlign: 'center', marginBottom: 4 }}>{subtitle}</p>
        <p style={{ color: '#f59e0b', textAlign: 'center', fontSize: 28, fontWeight: 700, marginBottom: 20 }}>
          {fmtPrice(payTotal)}
        </p>

        {/* Cash / Card toggle */}
        {cardEnabled && (
          <div style={{ display: 'flex', gap: 8, marginBottom: 20 }}>
            {['cash', 'card'].map(m => (
              <button
                key={m}
                onClick={() => setMethod(m)}
                style={{
                  flex: 1, padding: '10px 0', borderRadius: 10, fontSize: 14, fontWeight: 600,
                  border: `2px solid ${method === m ? '#3b82f6' : 'rgba(255,255,255,0.1)'}`,
                  background: method === m ? 'rgba(59,130,246,0.18)' : 'rgba(255,255,255,0.04)',
                  color: method === m ? '#93c5fd' : '#94a3b8',
                  cursor: 'pointer', transition: 'all 0.12s',
                }}
              >
                {m === 'cash' ? '💵 Μετρητά' : '💳 Κάρτα'}
              </button>
            ))}
          </div>
        )}

        <div style={{ display: 'flex', gap: 12 }}>
          <button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose}>
            Άκυρο
          </button>
          {paymentSafety === 'long_press' ? (
            <button
              className="btn btn--success"
              style={{
                flex: 1, position: 'relative', overflow: 'hidden',
                transition: 'opacity 0.1s',
              }}
              onPointerDown={startLongPress}
              onPointerUp={cancelLongPress}
              onPointerLeave={cancelLongPress}
            >
              <span style={{ position: 'relative', zIndex: 1 }}>
                {longPressActive ? 'Κρατήστε…' : 'Πληρώθηκαν ✓'}
              </span>
              {longPressActive && (
                <span style={{
                  position: 'absolute', inset: 0, background: 'rgba(255,255,255,0.25)',
                  animation: 'longpress-fill 0.8s linear forwards',
                  transformOrigin: 'left',
                }} />
              )}
            </button>
          ) : (
            <button className="btn btn--success" style={{ flex: 1 }} onClick={handleConfirmClick}>
              Πληρώθηκαν ✓
            </button>
          )}
        </div>

        {/* Second confirmation dialog */}
        {secondConfirmOpen && (
          <div style={{
            position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.6)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            borderRadius: 'inherit', padding: 20,
          }} onClick={e => e.stopPropagation()}>
            <div style={{ background: 'var(--bg2,#1e293b)', borderRadius: 14, padding: 24, width: '100%' }}>
              <p style={{ color: '#f1f5f9', fontWeight: 700, fontSize: 15, textAlign: 'center', marginBottom: 8 }}>
                Είσαι σίγουρος;
              </p>
              <p style={{ color: '#94a3b8', fontSize: 13, textAlign: 'center', marginBottom: 20 }}>
                {fmtPrice(payTotal)} — {method === 'card' ? 'Κάρτα' : 'Μετρητά'}
              </p>
              <div style={{ display: 'flex', gap: 10 }}>
                <button className="btn btn--secondary" style={{ flex: 1 }} onClick={() => setSecondConfirmOpen(false)}>
                  Πίσω
                </button>
                <button className="btn btn--success" style={{ flex: 1 }} onClick={() => onConfirm(method)}>
                  Ναι, Πληρώθηκαν ✓
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}

// ─── Customer count modal ─────────────────────────────────────────────────────

function CustomerCountModal({ value, onChange, onClose }) {
  const [count, setCount] = useState(value ?? 0)
  const QUICK = [1, 2, 3, 4, 5, 6]
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-sheet" onClick={e => e.stopPropagation()}>
        <div className="modal-handle" />
        <h2 className="modal-title">Αριθμός Πελατών</h2>
        <p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 20px' }}>
          Πόσα άτομα κάθονται στο τραπέζι;
        </p>
        <div style={{ display: 'flex', gap: 8, justifyContent: 'center', marginBottom: 20 }}>
          {QUICK.map(n => (
            <button key={n} onClick={() => setCount(n)} style={{
              width: 44, height: 44, borderRadius: 12, border: 'none', cursor: 'pointer',
              fontWeight: 800, fontSize: 16,
              background: count === n ? 'var(--accent)' : 'var(--bg3)',
              color: count === n ? 'var(--accent-fg)' : 'var(--text)',
            }}>{n}</button>
          ))}
        </div>
        <div className="modal-qty" style={{ marginBottom: 20 }}>
          <button className="qty-btn" onClick={() => setCount(c => Math.max(0, c - 1))}>−</button>
          <span className="qty-value">{count}</span>
          <button className="qty-btn" onClick={() => setCount(c => c + 1)}>+</button>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose}>Άκυρο</button>
          <button className="btn btn--primary" style={{ flex: 1 }} onClick={() => { onChange(count || null); onClose() }}>
            Εφαρμογή
          </button>
        </div>
      </div>
    </div>
  )
}

// ─── Main page ────────────────────────────────────────────────────────────────

export default function TableDetailPage() {
  const { tableId, orderId: standaloneOrderId } = useParams()
  const isStandalone = !!standaloneOrderId
  const [searchParams, setSearchParams] = useSearchParams()
  const { user } = useAuthStore()
  const navigate = useNavigate()

  const [table, setTable] = useState(null)
  const [order, setOrder] = useState(null)
  const [loading, setLoading] = useState(true)
  const [paying, setPaying] = useState(false)
  const [selectedIds, setSelectedIds] = useState([])
  const [confirmClose, setConfirmClose] = useState(false)
  const [confirmPay, setConfirmPay] = useState(false)
  const [confirmPayAndClose, setConfirmPayAndClose] = useState(false)
  const [revertConfirm, setRevertConfirm] = useState(null) // null | { itemIds: [...] }
  const [cardEnabled, setCardEnabled] = useState(false)
  const [revertAllowed, setRevertAllowed] = useState(false)
  const [priceAdjAllowed, setPriceAdjAllowed] = useState(false)
  const [error, setError] = useState('')

  // Tab: 'active' | 'paid'
  const [activeTab, setActiveTab] = useState('active')

  // Actions sheet state
  const [showActions, setShowActions] = useState(false)
  const [actionsMode, setActionsMode] = useState(null)
  // actionsMode: null | 'transfer' | 'merge' | 'flags' | 'assign_waiter' | 'print_synopsis' | 'split' | 'move_items'
  const [pendingTable, setPendingTable] = useState(null)
  // pendingTable: { table, mode: 'transfer'|'merge'|'move_items' } — waiting for confirmation

  // Data for sub-flows
  const [allTables, setAllTables] = useState([])
  const [allOrders, setAllOrders] = useState([])
  const [flagDefs, setFlagDefs] = useState([])
  const [currentFlagIds, setCurrentFlagIds] = useState([])
  const [allWaiters, setAllWaiters] = useState([])
  const [actionDataLoading, setActionDataLoading] = useState(false)
  const [splitItem, setSplitItem] = useState(null)
  const [itemActionTarget, setItemActionTarget] = useState(null) // { items: [...], singleStacked: bool }
  const [priceAdjustItem, setPriceAdjustItem] = useState(null) // item being price-adjusted
  const [customerCount, setCustomerCount] = useState(null)
  const [customerCountOpen, setCustomerCountOpen] = useState(false)
  const [canCancel, setCanCancel] = useState(false)
  const [canDiscount, setCanDiscount] = useState(false)
  const [showDiscountModal, setShowDiscountModal] = useState(false)
  const [priceEventsMap, setPriceEventsMap] = useState({})
  const [cancelConfirm, setCancelConfirm] = useState(null) // null | { mode: 'items', ids: [...] } | { mode: 'order' }
  const [paidSelectedIds, setPaidSelectedIds] = useState([])

  // ── Edit mode (placeholder) ────────────────────────────────────────────────
  const [editMode, setEditMode] = useState(false)

  // ── Merge / combine mode ───────────────────────────────────────────────────
  const { mergePersist, globalMergeMode, setGlobalMergeMode } = useTableViewStore()

  // Derive the sessionStorage key once the order ID is known
  const perOrderKey = order?.id ? `mergeMode_order_${order.id}` : null

  function readPersistedMergeMode() {
    if (mergePersist === 'global') return globalMergeMode
    if (mergePersist === 'per_order' && perOrderKey) return sessionStorage.getItem(perOrderKey) || MERGE_OFF
    return MERGE_OFF
  }

  const [mergeMode, setMergeMode] = useState(() => readPersistedMergeMode())
  const [showMergeModal, setShowMergeModal] = useState(false)
  // Virtual split state — only used when mergeMode !== OFF.
  // Stores the current display list after any in-memory splits, keyed to the current mergeMode.
  const [virtualItems, setVirtualItems] = useState(null) // null = not yet initialised for current mode

  // Re-read persisted value once order loads (perOrderKey is null until order arrives)
  useEffect(() => {
    if (mergePersist === 'per_order' && perOrderKey) {
      const saved = sessionStorage.getItem(perOrderKey)
      if (saved && saved !== mergeMode) {
        setMergeMode(saved)
        setVirtualItems(null)
      }
    }
  }, [perOrderKey]) // eslint-disable-line react-hooks/exhaustive-deps

  const waiterMap = Object.fromEntries(allWaiters.map(w => [w.id, w.nickname || w.full_name || w.username || `#${w.id}`]))
  const addItemsPath = isStandalone
    ? `/standalone/${order?.order_type || 'takeaway'}/add?orderId=${order?.id}&new=0`
    : `/tables/${tableId}/add`

  const scrollRef = useRef(null)
  const isOffline = useConnectionStore(s => s.status !== 'online')

  // ── Load from IDB instantly, then revalidate from server ─────────────────────
  async function loadFromDB() {
    const tid = Number(tableId)
    const [dbTable, dbFlagDefs, dbFlagAssign] = await Promise.all([
      db.pos_tables.get(tid),
      db.flag_defs?.toArray() ?? Promise.resolve([]),
      db.flag_assignments?.where('table_id').equals(tid).toArray() ?? Promise.resolve([]),
    ])
    if (dbTable) setTable(dbTable)
    // Find the active order for this table from cached orders
    const dbOrder = await db.pos_orders.where('table_id').equals(tid).first()
    if (dbOrder && dbOrder.status !== 'closed' && dbOrder.status !== 'cancelled') {
      setOrder(dbOrder)
      setCustomerCount(dbOrder.customer_count ?? null)
    }
    setFlagDefs(dbFlagDefs)
    setCurrentFlagIds(dbFlagAssign.map(a => a.flag_id))
    if (dbTable) setLoading(false)
  }

  async function load() {
    try {
      if (isStandalone) {
        // Standalone: load order directly by ID, no table
        const [orderRes, waitersRes] = await Promise.all([
          client.get(`/api/orders/${standaloneOrderId}`),
          client.get('/api/waiters/on-shift'),
        ])
        const o = orderRes.data
        setOrder(o)
        setCustomerCount(o.customer_count ?? null)
        setTable(null)
        if (waitersRes.status === 200) setAllWaiters(waitersRes.data)
      } else {
        const [statusRes, flagDefsRes, flagAssignRes, waitersRes] = await Promise.all([
          client.get(`/api/tables/${tableId}/status`),
          client.get('/api/flags/defs'),
          client.get(`/api/flags/table/${tableId}`),
          client.get('/api/waiters/on-shift'),
        ])
        setTable(statusRes.data.table)
        if (statusRes.data.active_order_id) {
          const { data: o } = await client.get(`/api/orders/${statusRes.data.active_order_id}`)
          setOrder(o)
          setCustomerCount(o.customer_count ?? null)
          // Update IDB with fresh order
          db.pos_orders.put({ ...o, waiter_ids: o.waiters?.map(w => w.waiter_id) ?? [] }).catch(() => {})
        } else {
          setOrder(null)
          setCustomerCount(null)
        }
        setFlagDefs(flagDefsRes.data)
        setCurrentFlagIds(flagAssignRes.data.map(a => a.flag_id))
        if (waitersRes.status === 200) setAllWaiters(waitersRes.data)
      }
    } catch {
      if (!table) setError('Σφάλμα φόρτωσης')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (isStandalone) {
      load()
    } else {
      // Show IDB data instantly, then fetch fresh from server
      loadFromDB().then(() => {
        if (!isOffline) load()
      })
    }
  }, [tableId, standaloneOrderId]) // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    function onSSE(e) {
      const { type, data } = e.detail
      if ((type === 'kds_item_updated' || type === 'kds_order_updated') && order && data.order_id === order.id) {
        load()
      } else if (type === 'order_updated' && data.order_id === order?.id) {
        load()
      } else if (type === 'order_closed' && (
        (data.auto_closed && data.table_id === Number(tableId)) ||
        (isStandalone && data.order_id === order?.id)
      )) {
        navigate('/tables', { replace: true })
      } else if (type === 'order_paid' && (
        (data.auto_closed && data.table_id === Number(tableId)) ||
        (isStandalone && data.auto_closed && data.order_id === order?.id)
      )) {
        navigate('/tables', { replace: true })
      }
    }
    window.addEventListener('sse-event', onSSE)
    return () => window.removeEventListener('sse-event', onSSE)
  }, [order?.id, tableId])

  useEffect(() => {
    client.get('/api/orders/cancel-permissions')
      .then(r => setCanCancel(!!r.data.can_cancel))
      .catch(() => {})
    client.get('/api/pricing/discount-settings/me')
      .then(r => setCanDiscount(!!r.data.can_apply_discounts))
      .catch(() => {})
    client.get('/api/settings/')
      .then(r => {
        setCardEnabled(r.data?.['payments.card_enabled']?.value === 'true')
        setRevertAllowed(r.data?.['payments.waiter_revert_allowed']?.value === 'true')
        setPriceAdjAllowed(r.data?.['orders.waiter_price_adjust_allowed']?.value === 'true')
      })
      .catch(() => {})
  }, [])

  // Fetch price events for active order — rebuilds map keyed by order_item_id
  // Re-fetches when items count changes (covers deal accepts, discounts applied, cancellations)
  useEffect(() => {
    if (!order?.id) { setPriceEventsMap({}); return }
    client.get(`/api/pricing/events/order/${order.id}`)
      .then(r => {
        const map = {}
        ;(r.data || []).forEach(ev => {
          if (!map[ev.order_item_id]) map[ev.order_item_id] = []
          map[ev.order_item_id].push(ev)
        })
        setPriceEventsMap(map)
      })
      .catch(() => setPriceEventsMap({}))
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [order?.id, order?.items?.length])

  // Handle ?action= param from table list long-press quick actions
  useEffect(() => {
    const action = searchParams.get('action')
    if (!action || loading) return
    setSearchParams({}, { replace: true })
    // Load supporting data, then jump straight to the action mode
    loadActionData()
    setActionsMode(action)
  }, [loading])

  // Load supporting data for sub-flows (lazy, only when Actions opened)
  async function loadActionData() {
    setActionDataLoading(true)
    const [tablesRes, ordersRes, waitersRes] = await Promise.allSettled([
      client.get('/api/tables/'),
      client.get('/api/orders/active'),
      client.get('/api/waiters/on-shift'),
    ])
    if (tablesRes.status === 'fulfilled') setAllTables(tablesRes.value.data)
    if (ordersRes.status === 'fulfilled') setAllOrders(ordersRes.value.data)
    if (waitersRes.status === 'fulfilled') setAllWaiters(waitersRes.value.data)
    setActionDataLoading(false)
  }

  function openActions() {
    setAllTables([])
    setAllOrders([])
    setAllWaiters([])
    loadActionData()
    setShowActions(true)
  }

  const activeItems = order?.items?.filter(i => i.status === 'active') || []
  const paidItems   = order?.items?.filter(i => i.status === 'paid')   || []
  const allPaid = order && activeItems.length === 0
  const canInteract = !!order

  // The list actually shown in the active tab — either raw or merged+virtually-split
  const displayActiveItems = mergeMode === MERGE_OFF
    ? activeItems
    : (virtualItems ?? mergeItems(activeItems, mergeMode))

  const allActiveSelected = displayActiveItems.length > 0 && displayActiveItems.every(i => selectedIds.includes(i.id))

  // When mergeMode is active, expand a display item's IDs back to real source IDs for API calls
  function expandIds(displayIds) {
    if (mergeMode === MERGE_OFF) return displayIds
    const sourceIds = []
    displayIds.forEach(id => {
      const vItem = displayActiveItems.find(i => i.id === id)
      if (vItem?._isMerged) sourceIds.push(...vItem._sourceIds)
      else sourceIds.push(id)
    })
    return sourceIds
  }

  function changeMergeMode(newMode) {
    if (newMode === mergeMode) return
    setSelectedIds([])
    setVirtualItems(null)
    setMergeMode(newMode)
    if (mergePersist === 'global') setGlobalMergeMode(newMode)
    if (mergePersist === 'per_order' && perOrderKey) sessionStorage.setItem(perOrderKey, newMode)
  }

  async function openOrder() {
    try {
      await client.post('/api/orders/', { table_id: Number(tableId) })
      await load()
    } catch (err) {
      setError(err.response?.data?.detail || 'Σφάλμα ανοίγματος')
    }
  }

  async function paySelected(method = 'cash', andClose = false) {
    setPaying(true)
    setConfirmPay(false)
    setConfirmPayAndClose(false)
    // Expand any merged virtual IDs back to real source IDs for the API
    const rawIds = andClose
      ? activeItems.map(i => i.id)
      : (selectedIds.length > 0 ? expandIds(selectedIds) : activeItems.map(i => i.id))
    const idsToPayNow = rawIds

    if (isOffline) {
      try {
        await queueOfflinePaymentOp({ orderId: order.id, itemIds: idsToPayNow, paymentMethod: method })
        setSelectedIds([])
        await loadFromDB()
        const updatedOrder = await db.pos_orders.get(order.id)
        if (!updatedOrder || updatedOrder.status === 'paid') navigate('/tables', { replace: true })
      } catch {
        setError('Σφάλμα αποθήκευσης offline πληρωμής')
      } finally {
        setPaying(false)
      }
      return
    }

    try {
      const res = await client.post(`/api/orders/${order.id}/pay`, { item_ids: idsToPayNow, payment_method: method })
      setSelectedIds([])
      setVirtualItems(null)
      if (res.data?.auto_closed || andClose) {
        if (andClose && !res.data?.auto_closed) {
          // Payment succeeded, now close the order explicitly
          try { await client.post(`/api/orders/${order.id}/close`) } catch {}
        }
        navigate('/tables', { replace: true })
        return
      }
      await load()
    } catch (err) {
      const detail = err?.response?.data?.detail
      setError(detail ? `Σφάλμα πληρωμής: ${detail}` : 'Σφάλμα πληρωμής')
    } finally {
      setPaying(false)
    }
  }

  async function revertPayment(itemIds) {
    setRevertConfirm(null)
    try {
      await client.post(`/api/orders/${order.id}/revert-payment`, { item_ids: itemIds })
      setPaidSelectedIds([])
      await load()
    } catch (err) {
      setError(err.response?.data?.detail || 'Σφάλμα αναίρεσης πληρωμής')
    }
  }

  async function closeOrder() {
    try {
      await client.post(`/api/orders/${order.id}/close`)
      setConfirmClose(false)
      navigate('/tables')
    } catch (err) {
      setError(err.response?.data?.detail || 'Σφάλμα κλεισίματος')
    }
  }

  function toggleItem(id) {
    setSelectedIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id])
  }

  async function executeCancelItems(itemIds) {
    setCancelConfirm(null)
    try {
      await client.post(`/api/orders/${order.id}/cancel-items`, { item_ids: itemIds, print_cancellation: true })
      setSelectedIds([])
      setItemActionTarget(null)
      await load()
    } catch (err) {
      setError(err.response?.data?.detail || 'Σφάλμα ακύρωσης')
    }
  }

  async function executeCancelOrder() {
    setCancelConfirm(null)
    try {
      await client.delete(`/api/orders/${order.id}?print_cancellation=true`)
      navigate('/tables')
    } catch (err) {
      setError(err.response?.data?.detail || 'Σφάλμα ακύρωσης παραγγελίας')
    }
  }

  function selectAll() {
    const allActive = displayActiveItems.map(i => i.id)
    const allSelected = allActive.every(id => selectedIds.includes(id))
    setSelectedIds(allSelected ? [] : allActive)
  }

  // Mark selected items as served
  async function doMarkServed(itemIds) {
    if (!order || itemIds.length === 0) return
    try {
      await client.post(`/api/kds/orders/${order.id}/items/mark-served`, { item_ids: expandIds(itemIds) })
      setSelectedIds([])
      setPaidSelectedIds([])
      await load()
    } catch (err) {
      setError(err.response?.data?.detail || 'Σφάλμα σήμανσης')
    }
  }

  // Mark all ready items as served (from Actions sheet)
  async function doMarkAllServed() {
    if (!order) return
    setShowActions(false)
    try {
      await client.post(`/api/kds/orders/${order.id}/items/mark-all-served`)
      await load()
    } catch (err) {
      setError(err.response?.data?.detail || 'Σφάλμα σήμανσης')
    }
  }

  // Split item: called from SplitModal
  async function doSplit(qty) {
    if (!splitItem || !order) return
    setSplitItem(null)

    // In merge mode: split is in-memory only — no API call, no DB write
    if (mergeMode !== MERGE_OFF) {
      const base = virtualItems ?? mergeItems(activeItems, mergeMode)
      const updated = base.flatMap(item => {
        if (item.id !== splitItem.id) return [item]
        const remaining = item.quantity - qty
        const splitPart = { ...item, quantity: qty, id: `${item.id}_split_${Date.now()}` }
        const restPart  = { ...item, quantity: remaining }
        // distribute sourceIds proportionally (best effort — exact split is for payment)
        if (item._isMerged) {
          splitPart._sourceIds = item._sourceIds.slice(0, Math.ceil(item._sourceIds.length * qty / item.quantity))
          splitPart._sourceItems = item._sourceItems.slice(0, splitPart._sourceIds.length)
          restPart._sourceIds = item._sourceIds.slice(splitPart._sourceIds.length)
          restPart._sourceItems = item._sourceItems.slice(splitPart._sourceIds.length)
        }
        return [splitPart, restPart]
      })
      setVirtualItems(updated)
      setSelectedIds([])
      return
    }

    if (isOffline) {
      try {
        await queueOfflineSplit({ orderId: order.id, itemId: splitItem.id, quantity: qty })
        setSelectedIds([])
        await loadFromDB()
      } catch (err) {
        setError(err.message || 'Σφάλμα διαχωρισμού offline')
      }
      return
    }

    try {
      await client.post(`/api/orders/${order.id}/items/${splitItem.id}/split`, { quantity: qty })
      setSelectedIds([])
      await load()
    } catch (err) {
      setError(err.response?.data?.detail || 'Σφάλμα διαχωρισμού')
    }
  }

  // Transfer table
  async function doTransfer(targetTable) {
    if (!order) return
    setPendingTable(null)
    setActionsMode(null)
    try {
      await client.post(`/api/orders/${order.id}/transfer`, { target_table_id: targetTable.id })
      navigate('/tables')
    } catch (err) {
      setError(err.response?.data?.detail || 'Σφάλμα μεταφοράς')
    }
  }

  // Merge table
  async function doMerge(targetTable) {
    if (!order) return
    const targetOrder = allOrders.find(o => o.table_id === targetTable.id)
    if (!targetOrder) { setError('Δεν βρέθηκε παραγγελία στο τραπέζι'); return }
    setPendingTable(null)
    setActionsMode(null)
    try {
      await client.post(`/api/orders/${order.id}/merge`, { target_order_id: targetOrder.id })
      navigate('/tables')
    } catch (err) {
      setError(err.response?.data?.detail || 'Σφάλμα συγχώνευσης')
    }
  }

  // Move items to another table
  async function doMoveItems(targetTable) {
    if (!order || selectedIds.length === 0) return
    const targetOrder = allOrders.find(o => o.table_id === targetTable.id)
    if (!targetOrder) { setError('Δεν βρέθηκε παραγγελία στο τραπέζι'); return }
    setPendingTable(null)
    setActionsMode(null)
    try {
      await client.post(`/api/orders/${order.id}/move-items`, {
        item_ids: selectedIds,
        target_order_id: targetOrder.id,
      })
      setSelectedIds([])
      await load()
    } catch (err) {
      setError(err.response?.data?.detail || 'Σφάλμα μεταφοράς αντικειμένων')
    }
  }

  // Save flags
  async function doSaveFlags(flagIds) {
    try {
      await client.put(`/api/flags/table/${tableId}`, { flag_ids: flagIds })
      setCurrentFlagIds(flagIds)
      setActionsMode(null)
    } catch {
      setError('Σφάλμα αποθήκευσης σημαιών')
    }
  }

  // Tables for transfer: active tables that are free (no active order), excluding current
  const transferTargets = allTables.filter(t =>
    t.id !== Number(tableId) &&
    t.is_active &&
    !allOrders.some(o => o.table_id === t.id)
  )

  // Tables for merge: tables with active orders, excluding current
  const mergeTargets = allTables
    .filter(t => t.id !== Number(tableId) && t.is_active)
    .map(t => {
      const o = allOrders.find(ord => ord.table_id === t.id)
      return o ? { ...t, orderStatus: o.status } : null
    })
    .filter(Boolean)

  // Tables for move-items: tables with open/partially_paid orders, excluding current
  const moveItemsTargets = allTables
    .filter(t => t.id !== Number(tableId) && t.is_active)
    .map(t => {
      const o = allOrders.find(ord => ord.table_id === t.id)
      return o && (o.status === 'open' || o.status === 'partially_paid') ? { ...t, orderStatus: o.status } : null
    })
    .filter(Boolean)

  const tableName = isStandalone
    ? (order?.order_type === 'delivery' ? `Delivery #${standaloneOrderId}` : `Takeaway #${standaloneOrderId}`)
    : (table ? (table.label || `T${table.number}`) : '—')

  if (loading) return <div className="page page--centered"><p style={{ color: '#94a3b8' }}>Φόρτωση…</p></div>

  return (
    <div className="page">
      {/* Top bar */}
      <header className="top-bar">
        <button className="icon-btn" onClick={() => navigate('/tables')}>←</button>
        <span className="top-bar__title">{tableName}</span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          {/* People / customer count */}
          <button
            onClick={() => setCustomerCountOpen(true)}
            style={{
              position: 'relative',
              display: 'inline-flex', alignItems: 'center', gap: 5,
              height: 34, padding: '0 10px',
              borderRadius: 999,
              background: customerCount ? 'rgba(245,158,11,0.15)' : 'var(--bg2)',
              border: `1.5px solid ${customerCount ? 'rgba(245,158,11,0.5)' : 'var(--border)'}`,
              color: customerCount ? '#f59e0b' : 'var(--muted)',
              cursor: 'pointer', fontSize: 13, fontWeight: 700,
            }}
            title="Αριθμός πελατών"
          >
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
              <circle cx="9" cy="7" r="4"/>
              <path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
              <path d="M16 3.13a4 4 0 0 1 0 7.75"/>
            </svg>
            {customerCount ? (
              <span>{customerCount}</span>
            ) : null}
          </button>

          {/* ACTIONS */}
          {!isOffline && (
            <button
              onClick={openActions}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 5,
                height: 34, padding: '0 10px',
                borderRadius: 999,
                background: 'rgba(99,102,241,0.12)',
                border: '1.5px solid rgba(99,102,241,0.3)',
                color: 'var(--accent)',
                cursor: 'pointer', fontSize: 13, fontWeight: 700,
              }}
            >
              <span style={{ fontSize: 14 }}>⚡</span>
              <span>ACTIONS</span>
            </button>
          )}
        </div>
      </header>

      {error && <p className="error-msg" style={{ margin: 12 }}>{error}</p>}

      {/* Active flag cards */}
      {currentFlagIds.length > 0 && flagDefs.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '10px 12px 0' }}>
          {currentFlagIds.map(fid => {
            const def = flagDefs.find(d => d.id === fid)
            if (!def) return null
            return (
              <button
                key={fid}
                onClick={() => doSaveFlags(currentFlagIds.filter(id => id !== fid))}
                style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '10px 14px',
                  background: (def.color || '#6295F3') + '22',
                  border: `1px solid ${def.color || '#6295F3'}`,
                  borderRadius: 12, cursor: 'pointer', textAlign: 'left',
                  width: '100%',
                }}
              >
                <span style={{ fontSize: 20 }}>{def.emoji || '🏷️'}</span>
                <span style={{ flex: 1, fontSize: 14, fontWeight: 600, color: def.color || '#6295F3' }}>{def.name}</span>
                <span style={{ fontSize: 18, color: def.color || '#6295F3', opacity: 0.6 }}>✕</span>
              </button>
            )
          })}
        </div>
      )}

      {/* Standalone type badge */}
      {isStandalone && order && (
        <div style={{ padding: '10px 12px 0' }}>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '6px 14px', borderRadius: 20,
            background: order.order_type === 'delivery' ? 'rgba(96,165,250,0.15)' : 'rgba(245,158,11,0.15)',
            border: `1.5px solid ${order.order_type === 'delivery' ? '#60a5fa55' : '#f59e0b55'}`,
            color: order.order_type === 'delivery' ? '#93c5fd' : '#fbbf24',
            fontSize: 13, fontWeight: 700,
          }}>
            {order.order_type === 'delivery' ? '🛵 Delivery' : '🥡 Takeaway'}
          </span>
        </div>
      )}

      {!order && !isStandalone && (
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
          <p style={{ color: '#94a3b8', marginBottom: 24 }}>Δεν υπάρχει ενεργή παραγγελία</p>
          <button className="btn btn--primary btn--lg" onClick={openOrder}>
            Άνοιγμα Παραγγελίας
          </button>
        </div>
      )}

      {order && (
        <div
          className="detail-body"
          ref={scrollRef}
          style={{ overflowY: 'auto' }}
        >
          {/* ── Tabs + edit + merge buttons ── */}
          <div style={{ display: 'flex', gap: 8, margin: '10px 12px 0', alignItems: 'stretch' }}>

            {/* Edit mode button */}
            {canInteract && (
              <button
                onClick={() => setEditMode(m => !m)}
                style={{
                  width: 40, flexShrink: 0,
                  borderRadius: 10, cursor: 'pointer',
                  background: editMode ? 'rgba(251,191,36,0.2)' : 'var(--bg2)',
                  color: editMode ? '#fbbf24' : 'var(--muted)',
                  border: editMode ? '1px solid rgba(251,191,36,0.45)' : '1px solid var(--border)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  transition: 'background 0.15s, color 0.15s',
                }}
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                  <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
                </svg>
              </button>
            )}

            <div style={{
              display: 'flex', flex: 1, gap: 0,
              background: 'var(--bg2)',
              borderRadius: 10,
              border: '1px solid var(--border)',
              overflow: 'hidden',
            }}>
              <button
                onClick={() => setActiveTab('active')}
                style={{
                  flex: 1, padding: '9px 0', border: 'none', cursor: 'pointer',
                  fontWeight: 700, fontSize: 13,
                  background: activeTab === 'active' ? 'var(--accent)' : 'transparent',
                  color: activeTab === 'active' ? 'var(--accent-fg)' : 'var(--muted)',
                  transition: 'background 0.15s',
                }}
              >
                Εκκρεμή {activeItems.length > 0 && (
                  <span style={{
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    background: activeTab === 'active' ? 'rgba(0,0,0,0.2)' : 'var(--bg3)',
                    borderRadius: 999, fontSize: 11, fontWeight: 800,
                    padding: '1px 7px', marginLeft: 4,
                  }}>{activeItems.length}</span>
                )}
              </button>
              <button
                onClick={() => setActiveTab('paid')}
                style={{
                  flex: 1, padding: '9px 0', border: 'none', cursor: 'pointer',
                  fontWeight: 700, fontSize: 13,
                  background: activeTab === 'paid' ? '#14532d' : 'transparent',
                  color: activeTab === 'paid' ? '#86efac' : 'var(--muted)',
                  transition: 'background 0.15s',
                }}
              >
                Πληρωμένα {paidItems.length > 0 && (
                  <span style={{
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    background: activeTab === 'paid' ? 'rgba(0,0,0,0.2)' : 'var(--bg3)',
                    borderRadius: 999, fontSize: 11, fontWeight: 800,
                    padding: '1px 7px', marginLeft: 4,
                  }}>{paidItems.length}</span>
                )}
              </button>
            </div>

            {/* Merge view button */}
            {canInteract && (
              <button
                onClick={() => setShowMergeModal(true)}
                style={{
                  width: 40, flexShrink: 0,
                  borderRadius: 10, border: 'none', cursor: 'pointer',
                  background: mergeMode !== MERGE_OFF ? 'rgba(99,102,241,0.25)' : 'var(--bg2)',
                  color: mergeMode !== MERGE_OFF ? '#a5b4fc' : 'var(--muted)',
                  border: mergeMode !== MERGE_OFF ? '1px solid rgba(99,102,241,0.45)' : '1px solid var(--border)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  transition: 'background 0.15s, color 0.15s',
                }}
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M3 6h18M3 12h12M3 18h8"/>
                  <path d="M17 15l3 3-3 3"/>
                </svg>
              </button>
            )}
          </div>

          {activeTab === 'active' && (
            <>
              <OrderSummary
                order={{ ...order, items: displayActiveItems }}
                selectable={canInteract && !paying}
                selectedIds={selectedIds}
                onToggle={toggleItem}
                waiterMap={waiterMap}
                priceEventsMap={priceEventsMap}
                onLongPressItem={(item) => {
                  if (selectedIds.length > 1) {
                    const items = displayActiveItems.filter(i => selectedIds.includes(i.id))
                    setItemActionTarget({ items, singleStacked: false, multiSelect: true })
                  } else {
                    setItemActionTarget({ items: [item], singleStacked: item.quantity > 1, multiSelect: false })
                  }
                }}
              />

              {/* Floating controls row — only visible when items are selected */}
              {canInteract && activeItems.length > 0 && selectedIds.length > 0 && (
                <div style={{
                  display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8,
                  padding: '10px 12px 24px', flexWrap: 'wrap',
                }}>
                  {/* CLEAR */}
                  <button
                    onClick={() => setSelectedIds([])}
                    style={{
                      display: 'inline-flex', alignItems: 'center',
                      height: 36, padding: '0 14px',
                      borderRadius: 999,
                      background: 'rgba(239,68,68,0.18)', color: '#fca5a5',
                      border: 'none', cursor: 'pointer',
                      fontSize: 13, fontWeight: 700, letterSpacing: 0.5,
                    }}
                  >CLEAR</button>

                  {/* ALL */}
                  {!allActiveSelected && (
                    <button
                      onClick={selectAll}
                      style={{
                        display: 'inline-flex', alignItems: 'center',
                        height: 36, padding: '0 14px',
                        borderRadius: 999,
                        background: 'rgba(34,197,94,0.18)', color: '#86efac',
                        border: 'none', cursor: 'pointer',
                        fontSize: 13, fontWeight: 700, letterSpacing: 0.5,
                      }}
                    >ALL</button>
                  )}

                  {/* SERVED — mark selected as served */}
                  <button
                    onClick={() => doMarkServed(selectedIds)}
                    style={{
                      display: 'inline-flex', alignItems: 'center',
                      height: 36, padding: '0 14px',
                      borderRadius: 999,
                      background: 'rgba(34,197,94,0.22)', color: '#4ade80',
                      border: '1px solid rgba(34,197,94,0.3)',
                      cursor: 'pointer',
                      fontSize: 13, fontWeight: 700, letterSpacing: 0.5,
                    }}
                  >SERVED</button>

                  {/* ACTIONS — opens item action modal */}
                  <button
                    onClick={() => {
                      const items = displayActiveItems.filter(i => selectedIds.includes(i.id))
                      const singleStacked = items.length === 1 && items[0].quantity > 1
                      setItemActionTarget({ items, singleStacked, multiSelect: items.length > 1 })
                    }}
                    style={{
                      display: 'inline-flex', alignItems: 'center',
                      height: 36, padding: '0 14px',
                      borderRadius: 999,
                      background: 'rgba(148,163,184,0.18)', color: '#cbd5e1',
                      border: 'none', cursor: 'pointer',
                      fontSize: 13, fontWeight: 700, letterSpacing: 0.5,
                    }}
                  >ACTIONS</button>
                </div>
              )}
            </>
          )}

          {activeTab === 'paid' && (
            <div style={{ padding: '8px 0' }}>
              {paidItems.length === 0 ? (
                <p style={{ color: '#64748b', textAlign: 'center', padding: '24px 0', fontSize: 14 }}>
                  Δεν υπάρχουν πληρωμένα αντικείμενα
                </p>
              ) : (
                <>
                  <OrderSummary
                    order={{ ...order, items: paidItems }}
                    selectable={canInteract}
                    selectedIds={paidSelectedIds}
                    waiterMap={waiterMap}
                    priceEventsMap={priceEventsMap}
                    onToggle={id => setPaidSelectedIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id])}
                    onLongPressItem={revertAllowed ? (item) => {
                      const ids = paidSelectedIds.length > 1 && paidSelectedIds.includes(item.id)
                        ? paidSelectedIds
                        : [item.id]
                      setRevertConfirm({ itemIds: ids })
                    } : undefined}
                  />
                  {/* Paid tab floating controls */}
                  {canInteract && paidSelectedIds.length > 0 && (
                    <div style={{
                      display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8,
                      padding: '10px 12px 24px', flexWrap: 'wrap',
                    }}>
                      <button
                        onClick={() => setPaidSelectedIds([])}
                        style={{
                          display: 'inline-flex', alignItems: 'center',
                          height: 36, padding: '0 14px',
                          borderRadius: 999,
                          background: 'rgba(239,68,68,0.18)', color: '#fca5a5',
                          border: 'none', cursor: 'pointer',
                          fontSize: 13, fontWeight: 700, letterSpacing: 0.5,
                        }}
                      >CLEAR</button>

                      <button
                        onClick={() => doMarkServed(paidSelectedIds)}
                        style={{
                          display: 'inline-flex', alignItems: 'center',
                          height: 36, padding: '0 14px',
                          borderRadius: 999,
                          background: 'rgba(34,197,94,0.22)', color: '#4ade80',
                          border: '1px solid rgba(34,197,94,0.3)',
                          cursor: 'pointer',
                          fontSize: 13, fontWeight: 700, letterSpacing: 0.5,
                        }}
                      >SERVED</button>

                      <button
                        onClick={() => {
                          const items = paidItems.filter(i => paidSelectedIds.includes(i.id))
                          sessionStorage.setItem('orderAgainItems', JSON.stringify(
                            items.map(it => ({
                              product_id: it.product_id,
                              quantity: it.quantity,
                              selected_options: (() => { try { return JSON.parse(it.selected_options || '[]') } catch { return [] } })(),
                              removed_ingredients: (() => { try { return JSON.parse(it.removed_ingredients || '[]') } catch { return [] } })(),
                              notes: it.notes || '',
                            }))
                          ))
                          setPaidSelectedIds([])
                          navigate(addItemsPath)
                        }}
                        style={{
                          display: 'inline-flex', alignItems: 'center',
                          height: 36, padding: '0 14px',
                          borderRadius: 999,
                          background: 'rgba(96,165,250,0.18)', color: '#93c5fd',
                          border: 'none', cursor: 'pointer',
                          fontSize: 13, fontWeight: 700, letterSpacing: 0.5,
                        }}
                      >REORDER</button>

                      {revertAllowed && (
                        <button
                          onClick={() => setRevertConfirm({ itemIds: paidSelectedIds })}
                          style={{
                            display: 'inline-flex', alignItems: 'center',
                            height: 36, padding: '0 14px',
                            borderRadius: 999,
                            background: 'rgba(251,191,36,0.15)', color: '#fbbf24',
                            border: '1px solid rgba(251,191,36,0.25)',
                            cursor: 'pointer',
                            fontSize: 13, fontWeight: 700, letterSpacing: 0.5,
                          }}
                        >ΑΝΑΙΡΕΣΗ</button>
                      )}
                    </div>
                  )}
                </>
              )}
            </div>
          )}

        </div>
      )}

      {/* Action bar — sticky at bottom, only when there's an active order on the active tab */}
      {order && canInteract && activeTab === 'active' && (
        <div className="action-bar">
          <button
            className="btn btn--accent"
            onClick={() => navigate(addItemsPath)}
            style={{ borderRadius: 999, flex: 1 }}
          >
            <span style={{ marginRight: 6 }}>＋</span>ADD
          </button>

          <button
            className="btn btn--success"
            onClick={() => setConfirmPay(true)}
            disabled={paying}
            style={{ borderRadius: 999, flex: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}
          >
            {paying ? '…' : (
              <>
                <span>€ PAY</span>
                {selectedIds.length > 0 && (
                  <span style={{
                    background: 'rgba(0,0,0,0.25)', color: 'white',
                    borderRadius: 999, fontSize: 11, fontWeight: 700,
                    padding: '1px 7px',
                  }}>{selectedIds.length}</span>
                )}
              </>
            )}
          </button>

          <button
            className="btn btn--danger"
            onClick={() => {
              if (isOffline) return
              if (!allPaid) setConfirmPayAndClose(true)
              else setConfirmClose(true)
            }}
            disabled={isOffline}
            style={{ borderRadius: 999, flex: 1, opacity: isOffline ? 0.4 : 1 }}
            title={isOffline ? 'Μη διαθέσιμο offline' : undefined}
          >
            <span style={{ marginRight: 6 }}>✕</span>CLOSE
          </button>
        </div>
      )}

      {/* Merge mode picker modal */}
      {showMergeModal && (
        <div className="modal-overlay" onClick={() => setShowMergeModal(false)} style={{ alignItems: 'flex-end' }}>
          <div className="modal-sheet" onClick={e => e.stopPropagation()} style={{ borderRadius: '20px 20px 0 0', paddingBottom: 40, gap: 0 }}>
            <div className="modal-handle" />
            <p style={{ fontSize: 17, fontWeight: 700, color: 'var(--text)', marginBottom: 20, paddingTop: 4 }}>Εμφάνιση Αντικειμένων</p>

            {[
              { mode: MERGE_OFF,       label: 'ΑΡΧΙΚΗ',                  desc: 'Ακριβώς όπως παραγγέλθηκαν' },
              { mode: MERGE_IDENTICAL, label: 'ΣΥΓΧΩΝΕΥΣΗ ΠΑΡΟΜΟΙΩΝ',    desc: 'Ίδιο προϊόν, ίδιες επιλογές, ίδια τιμή' },
              { mode: MERGE_SAME_ITEM, label: 'ΣΥΓΧΩΝΕΥΣΗ ΟΛΩΝ',         desc: 'Ίδιο προϊόν με ίδια τελική τιμή' },
            ].map(({ mode, label, desc }) => {
              const active = mergeMode === mode
              return (
                <button
                  key={mode}
                  onClick={() => { changeMergeMode(mode); setShowMergeModal(false) }}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 14,
                    padding: '14px 4px', borderRadius: 0, border: 'none',
                    borderBottom: '1px solid var(--border)',
                    background: 'transparent', cursor: 'pointer', width: '100%', textAlign: 'left',
                  }}
                >
                  <div style={{
                    width: 36, height: 36, borderRadius: '50%', flexShrink: 0,
                    background: active ? 'rgba(99,102,241,0.25)' : 'var(--bg3)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    border: active ? '2px solid #6366f1' : '2px solid transparent',
                  }}>
                    {active && (
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#a5b4fc" strokeWidth="2.5" strokeLinecap="round">
                        <path d="M20 6L9 17l-5-5"/>
                      </svg>
                    )}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: active ? '#a5b4fc' : 'var(--text)', marginBottom: 2 }}>{label}</div>
                    <div style={{ fontSize: 12, color: 'var(--muted)' }}>{desc}</div>
                  </div>
                </button>
              )
            })}

            <button className="btn btn--secondary" style={{ width: '100%', marginTop: 20 }} onClick={() => setShowMergeModal(false)}>
              Άκυρο
            </button>
          </div>
        </div>
      )}

      {/* Item action modal (long-press or ACTIONS pill) */}
      {itemActionTarget && (
        <ItemActionModal
          target={itemActionTarget}
          canCancel={canCancel && !isOffline}
          priceAdjAllowed={priceAdjAllowed}
          onOrderAgain={() => {
            const items = itemActionTarget.items
            sessionStorage.setItem('orderAgainItems', JSON.stringify(
              items.map(it => ({
                product_id: it.product_id,
                quantity: it.quantity,
                selected_options: (() => { try { return JSON.parse(it.selected_options || '[]') } catch { return [] } })(),
                removed_ingredients: (() => { try { return JSON.parse(it.removed_ingredients || '[]') } catch { return [] } })(),
                notes: it.notes || '',
              }))
            ))
            setItemActionTarget(null)
            navigate(addItemsPath)
          }}
          onSplit={() => {
            setSplitItem(itemActionTarget.items[0])
            setItemActionTarget(null)
          }}
          onMoveToTable={() => {
            setItemActionTarget(null)
            setAllTables([])
            setAllOrders([])
            loadActionData()
            setActionsMode('move_items')
          }}
          onAdjustPrice={() => {
            const item = itemActionTarget.items[0]
            setItemActionTarget(null)
            setPriceAdjustItem(item)
          }}
          onCancel={() => {
            const ids = itemActionTarget.items.map(i => i.id)
            setItemActionTarget(null)
            setCancelConfirm({ mode: 'items', ids })
          }}
          onClose={() => setItemActionTarget(null)}
        />
      )}

      {/* Price adjust modal */}
      {priceAdjustItem && (
        <PriceAdjustModal
          item={priceAdjustItem}
          onConfirm={async (adj) => {
            try {
              await client.patch(`/api/orders/${order.id}/items/${priceAdjustItem.id}/price-adjust`, {
                price_adjustment: adj,
              })
              setPriceAdjustItem(null)
              await load()
            } catch (err) {
              console.error('[price-adjust] failed:', err)
              setPriceAdjustItem(null)
            }
          }}
          onClose={() => setPriceAdjustItem(null)}
        />
      )}

      {/* Cancel confirmation */}
      {cancelConfirm && (
        <CancelConfirmModal
          itemCount={cancelConfirm.mode === 'items' ? cancelConfirm.ids.length : null}
          onConfirm={() => {
            if (cancelConfirm.mode === 'items') executeCancelItems(cancelConfirm.ids)
            else executeCancelOrder()
          }}
          onClose={() => setCancelConfirm(null)}
        />
      )}

      {/* Split stepper modal */}
      {splitItem && (
        <SplitModal
          item={splitItem}
          onConfirm={doSplit}
          onClose={() => setSplitItem(null)}
        />
      )}

      {/* Customer count modal */}
      {customerCountOpen && (
        <CustomerCountModal
          value={customerCount}
          onChange={async (v) => {
            setCustomerCount(v)
            if (order) {
              try {
                await client.patch(`/api/orders/${order.id}/customer-count`, { customer_count: v })
              } catch {}
            }
          }}
          onClose={() => setCustomerCountOpen(false)}
        />
      )}

      {/* Pay confirmation */}
      {confirmPay && (
        <PayConfirmModal
          payAll={selectedIds.length === 0}
          payIds={selectedIds.length === 0 ? displayActiveItems.map(i => i.id) : selectedIds}
          activeItems={displayActiveItems}
          cardEnabled={cardEnabled}
          onConfirm={(method) => paySelected(method, false)}
          onClose={() => setConfirmPay(false)}
        />
      )}

      {/* Pay-and-close confirmation */}
      {confirmPayAndClose && (
        <PayConfirmModal
          payAll
          payIds={displayActiveItems.map(i => i.id)}
          activeItems={displayActiveItems}
          andClose
          cardEnabled={cardEnabled}
          onConfirm={(method) => paySelected(method, true)}
          onClose={() => setConfirmPayAndClose(false)}
        />
      )}

      {/* Revert payment confirmation */}
      {revertConfirm && (
        <div className="modal-overlay" onClick={() => setRevertConfirm(null)}>
          <div className="modal-sheet" onClick={e => e.stopPropagation()}>
            <div className="modal-handle" />
            <h2 className="modal-title">Αναίρεση Πληρωμής;</h2>
            <p style={{ color: '#94a3b8', textAlign: 'center', marginBottom: 24 }}>
              {revertConfirm.itemIds.length === 1
                ? '1 αντικείμενο θα επιστραφεί σε μη πληρωμένο.'
                : `${revertConfirm.itemIds.length} αντικείμενα θα επιστραφούν σε μη πληρωμένα.`}
            </p>
            <div style={{ display: 'flex', gap: 12 }}>
              <button className="btn btn--secondary" style={{ flex: 1 }} onClick={() => setRevertConfirm(null)}>
                Άκυρο
              </button>
              <button
                className="btn btn--danger"
                style={{ flex: 1 }}
                onClick={() => revertPayment(revertConfirm.itemIds)}
              >
                Αναίρεση ✓
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Close confirmation */}
      {confirmClose && (
        <div className="modal-overlay" onClick={() => setConfirmClose(false)}>
          <div className="modal-sheet" onClick={e => e.stopPropagation()}>
            <div className="modal-handle" />
            <h2 className="modal-title">Κλείσιμο παραγγελίας;</h2>
            <p style={{ color: '#94a3b8', textAlign: 'center', marginBottom: 24 }}>
              Αυτή η ενέργεια δεν αναιρείται.
            </p>
            <div style={{ display: 'flex', gap: 12 }}>
              <button className="btn btn--secondary" style={{ flex: 1 }} onClick={() => setConfirmClose(false)}>
                Άκυρο
              </button>
              <button className="btn btn--danger" style={{ flex: 1 }} onClick={closeOrder}>
                CLOSE
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Actions top sheet */}
      {showActions && actionsMode === null && (
        <ActionsSheet
          order={order}
          tableId={tableId}
          isStandalone={isStandalone}
          canCancel={canCancel}
          canDiscount={canDiscount}
          onClose={() => setShowActions(false)}
          onTransfer={() => { setShowActions(false); setActionsMode('transfer') }}
          onMerge={() => { setShowActions(false); setActionsMode('merge') }}
          onSetFlags={() => { setShowActions(false); setActionsMode('flags') }}
          onAssignWaiter={() => { setShowActions(false); setActionsMode('assign_waiter') }}
          onPrintSynopsis={() => { setShowActions(false); setActionsMode('print_synopsis') }}
          onCancelOrder={() => { setShowActions(false); setCancelConfirm({ mode: 'order' }) }}
          onMarkAllServed={doMarkAllServed}
          onApplyDiscount={() => { setShowActions(false); setShowDiscountModal(true) }}
        />
      )}

      {/* Apply discount modal */}
      {showDiscountModal && order && (
        <ApplyDiscountModal
          order={order}
          onClose={() => setShowDiscountModal(false)}
          onApplied={() => { load(); setShowDiscountModal(false) }}
        />
      )}

      {/* Transfer picker */}
      {actionsMode === 'transfer' && !pendingTable && (
        <TablePicker
          title="Μεταφορά Τραπεζιού"
          subtitle="Επιλέξτε κενό τραπέζι"
          tables={transferTargets}
          currentTableId={Number(tableId)}
          onSelect={t => setPendingTable({ table: t, mode: 'transfer' })}
          onClose={() => setActionsMode(null)}
          loading={actionDataLoading}
        />
      )}

      {/* Merge picker */}
      {actionsMode === 'merge' && !pendingTable && (
        <TablePicker
          title="Συγχώνευση Τραπεζιού"
          subtitle="Τα αντικείμενα μεταφέρονται στο επιλεγμένο τραπέζι"
          tables={mergeTargets}
          currentTableId={Number(tableId)}
          onSelect={t => setPendingTable({ table: t, mode: 'merge' })}
          onClose={() => setActionsMode(null)}
          loading={actionDataLoading}
        />
      )}

      {/* Move items picker */}
      {actionsMode === 'move_items' && !pendingTable && (
        <TablePicker
          title="Μεταφορά Αντικειμένων"
          subtitle={`Μεταφορά ${selectedIds.length} αντικειμένου${selectedIds.length !== 1 ? 'ων' : ''} σε τραπέζι`}
          tables={moveItemsTargets}
          currentTableId={Number(tableId)}
          onSelect={t => setPendingTable({ table: t, mode: 'move_items' })}
          onClose={() => setActionsMode(null)}
          loading={actionDataLoading}
        />
      )}

      {/* Transfer / Merge / Move-items confirmation */}
      {pendingTable && (
        <div className="modal-overlay modal-overlay--top" onClick={() => setPendingTable(null)}>
          <div className="modal-sheet modal-sheet--top" onClick={e => e.stopPropagation()}>
            <div className="modal-handle" />
            <h2 className="modal-title">
              {pendingTable.mode === 'transfer' ? 'Επιβεβαίωση Μεταφοράς'
               : pendingTable.mode === 'merge'  ? 'Επιβεβαίωση Συγχώνευσης'
               : 'Επιβεβαίωση Μεταφοράς Αντικειμένων'}
            </h2>
            <p style={{ textAlign: 'center', color: '#94a3b8', fontSize: 14, marginBottom: 4 }}>
              {pendingTable.mode === 'transfer' ? 'Μεταφορά παραγγελίας στο τραπέζι'
               : pendingTable.mode === 'merge'  ? 'Συγχώνευση παραγγελίας με το τραπέζι'
               : `Μεταφορά ${selectedIds.length} αντικειμένου${selectedIds.length !== 1 ? 'ων' : ''} στο τραπέζι`}
            </p>
            <p style={{ textAlign: 'center', fontSize: 22, fontWeight: 700, color: 'var(--accent)', marginBottom: 20 }}>
              {pendingTable.table.label || `T${pendingTable.table.number}`}
            </p>
            <div style={{ display: 'flex', gap: 12 }}>
              <button className="btn btn--secondary" style={{ flex: 1 }} onClick={() => setPendingTable(null)}>
                Άκυρο
              </button>
              <button
                className="btn btn--primary"
                style={{ flex: 1 }}
                onClick={() => {
                  if (pendingTable.mode === 'transfer') doTransfer(pendingTable.table)
                  else if (pendingTable.mode === 'merge') doMerge(pendingTable.table)
                  else doMoveItems(pendingTable.table)
                }}
              >
                {pendingTable.mode === 'transfer' ? 'Μεταφορά ✓'
                 : pendingTable.mode === 'merge'   ? 'Συγχώνευση ✓'
                 : 'Μεταφορά ✓'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Flag picker */}
      {actionsMode === 'flags' && (
        <FlagPicker
          tableId={tableId}
          currentFlagIds={currentFlagIds}
          flagDefs={flagDefs}
          onSave={doSaveFlags}
          onClose={() => setActionsMode(null)}
          loading={actionDataLoading}
        />
      )}

      {/* Assign waiter */}
      {actionsMode === 'assign_waiter' && order && (
        <AssignWaiterPicker
          orderId={order.id}
          currentWaiterIds={order.waiters.map(w => w.waiter_id)}
          waiters={allWaiters}
          onAssigned={load}
          onClose={() => setActionsMode(null)}
          loading={actionDataLoading}
        />
      )}

      {/* Print synopsis */}
      {actionsMode === 'print_synopsis' && order && (
        <PrintSynopsisPicker
          orderId={order.id}
          onClose={() => setActionsMode(null)}
        />
      )}
    </div>
  )
}
