import { useState, useEffect, useContext, useRef } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import toast from 'react-hot-toast'
import client from '../api/client'
import Badge from '../ui/Badge'
import { ConfirmModal } from '../ui/Modal'
import { LicenseContext } from '../layouts/AppLayout'
import WorkdaySummaryModal from '../components/WorkdaySummaryModal'


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

function fmtTime(iso) {
  if (!iso) return '—'
  return new Date(iso).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })
}

function fmtDuration(isoStart) {
  if (!isoStart) return '—'
  const mins = Math.floor((Date.now() - new Date(isoStart).getTime()) / 60000)
  if (mins < 60) return `${mins}λ`
  const h = Math.floor(mins / 60)
  const m = mins % 60
  return m === 0 ? `${h}ω` : `${h}ω ${m}λ`
}

function fmtEuro(n) {
  return '€' + parseFloat(n || 0).toFixed(2)
}

function orderTotal(items = []) {
  return items
    .filter(i => i.status !== 'cancelled')
    .reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0)
}

function avatarColor(name) {
  const palette = ['#3758c9', '#7a44c9', '#2f9e5e', '#d94b26', '#8a6d2b', '#0d7a8a', '#c93775']
  let h = 0
  for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0
  return palette[h % palette.length]
}

function Avatar({ name, avatarUrl, size = 36 }) {
  if (avatarUrl) {
    return (
      <img src={avatarUrl} alt={name}
        style={{ width: size, height: size, borderRadius: '50%', objectFit: 'cover', flexShrink: 0 }} />
    )
  }
  const parts = (name || '?').trim().split(' ')
  const initials = (parts[0][0] + (parts[1]?.[0] || '')).toUpperCase()
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: avatarColor(name || '?'),
      color: 'white', fontSize: size * 0.38, fontWeight: 700,
      display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
    }}>{initials}</div>
  )
}

// ─── Table color tokens ────────────────────────────────────────────────────────

const TABLE_COLORS = {
  open:           { bg: '#bbf7d0', border: '#4ade80', dot: '#16a34a', text: '#14532d', label: 'Ανοιχτό' },
  partially_paid: { bg: '#e9d5ff', border: '#a855f7', dot: '#7c3aed', text: '#4c1d95', label: 'Μερική πληρ.' },
  free:           { bg: '#f4f4f2', border: '#dfe2e6', dot: '#8a9099', text: '#5a6169', label: 'Ελεύθερο' },
}

// ─── Business Day / Shift modals ───────────────────────────────────────────────

function StartShiftModal({ waiters, onClose, onStart }) {
  const [waiterId, setWaiterId] = useState('')
  const [cash, setCash] = useState('')
  const [busy, setBusy] = useState(false)

  async function submit() {
    if (!waiterId) { toast.error('Επιλέξτε σερβιτόρο'); return }
    setBusy(true)
    try {
      await onStart(Number(waiterId), cash ? parseFloat(cash) : null)
      onClose()
    } catch (e) {
      toast.error(e.response?.data?.detail || 'Σφάλμα εκκίνησης βάρδιας')
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4"
      onClick={e => { if (e.target === e.currentTarget) onClose() }}>
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-sm p-6 space-y-4">
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-bold text-gray-800">Έναρξη Βάρδιας</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-xl">✕</button>
        </div>
        <div>
          <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide block mb-1">Σερβιτόρος</label>
          <select className="h-10 w-full rounded-lg border border-gray-300 bg-white px-3 text-sm text-gray-800 focus:outline-none"
            value={waiterId} onChange={e => setWaiterId(e.target.value)}>
            <option value="">— Επιλέξτε —</option>
            {waiters.map(w => <option key={w.id} value={w.id}>{w.full_name || w.username}</option>)}
          </select>
        </div>
        <div>
          <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide block mb-1">Αρχικά Μετρητά (€)</label>
          <input type="number" step="0.01" min="0" placeholder="0.00" value={cash} onChange={e => setCash(e.target.value)}
            className="h-10 w-full rounded-lg border border-gray-300 bg-white px-3 text-sm text-gray-800 focus:outline-none" />
        </div>
        <div className="flex gap-3 pt-1">
          <button onClick={onClose} className="flex-1 h-10 px-4 rounded-lg border border-gray-300 text-sm font-medium text-gray-700 hover:bg-gray-50">Ακύρωση</button>
          <button onClick={submit} disabled={busy}
            className="flex-1 h-10 px-4 rounded-lg bg-primary-600 text-white text-sm font-semibold hover:bg-primary-700 disabled:opacity-60">
            {busy ? 'Εκκίνηση…' : 'Έναρξη'}
          </button>
        </div>
      </div>
    </div>
  )
}

function CloseConfirmModal({ details, onClose, onConfirm, busy }) {
  if (!details.partially_paid) {
    return (
      <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4"
        onClick={e => { if (e.target === e.currentTarget) onClose() }}>
        <div className="bg-white rounded-2xl shadow-xl w-full max-w-md p-6 space-y-4">
          <h2 className="text-lg font-bold text-gray-800">Κλείσιμο Ημέρας</h2>
          <div className="bg-blue-50 border border-blue-200 rounded-xl p-4 text-sm text-blue-800 space-y-2">
            <p className="font-semibold">
              {details.open_orders} {details.open_orders === 1 ? 'τραπέζι είναι ακόμα ανοιχτό' : 'τραπέζια είναι ακόμα ανοιχτά'}
            </p>
            <p>Κανένα δεν έχει εκκρεμείς χρεώσεις. Θέλετε να κλείσουν όλα και να κλείσει η ημέρα;</p>
          </div>
          <div className="flex gap-3">
            <button onClick={onClose} className="flex-1 h-10 px-4 rounded-lg border border-gray-300 text-sm font-medium text-gray-700 hover:bg-gray-50">Ακύρωση</button>
            <button onClick={onConfirm} disabled={busy}
              className="flex-1 h-10 px-4 rounded-lg bg-primary-600 text-white text-sm font-semibold hover:bg-primary-700 disabled:opacity-60">
              {busy ? 'Κλείσιμο…' : 'Κλείσε Όλα & Κλείσε Ημέρα'}
            </button>
          </div>
        </div>
      </div>
    )
  }
  return (
    <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4"
      onClick={e => { if (e.target === e.currentTarget) onClose() }}>
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-md p-6 space-y-4">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center flex-shrink-0">
            <span className="text-red-600 text-lg font-bold">!</span>
          </div>
          <h2 className="text-lg font-bold text-gray-800">Εκκρεμείς Πληρωμές</h2>
        </div>
        <div className="bg-red-50 border border-red-200 rounded-xl p-4 text-sm text-red-800 space-y-2">
          <p className="font-semibold">
            {details.open_orders} {details.open_orders === 1 ? 'ανοιχτό τραπέζι' : 'ανοιχτά τραπέζια'},
            από τα οποία <span className="underline">{details.partially_paid} έχ{details.partially_paid === 1 ? 'ει' : 'ουν'} εκκρεμείς πληρωμές</span>.
          </p>
          <p>Αν κλείσετε αναγκαστικά, τα απλήρωτα ποσά θα χαθούν και δεν θα καταγραφούν στις αναφορές.</p>
        </div>
        <div className="rounded-xl border border-gray-200 p-3 text-xs text-gray-500 bg-gray-50">
          Επιλέξτε <strong>Ακύρωση</strong> για να χειριστείτε χειροκίνητα τα εκκρεμή τραπέζια πριν κλείσετε την ημέρα.
        </div>
        <div className="flex gap-3">
          <button onClick={onClose} className="flex-1 h-10 px-4 rounded-lg border border-gray-300 text-sm font-medium text-gray-700 hover:bg-gray-50">Ακύρωση</button>
          <button onClick={onConfirm} disabled={busy}
            className="flex-1 h-10 px-4 rounded-lg bg-red-600 text-white text-sm font-semibold hover:bg-red-700 disabled:opacity-60">
            {busy ? 'Κλείσιμο…' : 'Αναγκαστικό Κλείσιμο'}
          </button>
        </div>
      </div>
    </div>
  )
}

// ─── Order quick-view modal ────────────────────────────────────────────────────

function OrderQuickModal({ orderId, tableName, onClose, onOpenFull }) {
  const qc = useQueryClient()

  const { data: order, isLoading } = useQuery({
    queryKey: ['order', orderId],
    queryFn: () => client.get(`/api/orders/${orderId}`).then(r => r.data),
    enabled: !!orderId,
  })

  const { data: waiters = [] } = useQuery({
    queryKey: ['waiters'],
    queryFn: () => client.get('/api/waiters/').then(r => r.data),
    staleTime: 60_000,
  })

  const { data: printers = [] } = useQuery({
    queryKey: ['printers'],
    queryFn: () => client.get('/api/system/printers').then(r => r.data),
    staleTime: 60_000,
  })

  const { data: rawPriceEvents = [] } = useQuery({
    queryKey: ['price-events', orderId],
    queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data),
    enabled: !!orderId,
    staleTime: 30_000,
  })
  const priceEventsMap = rawPriceEvents.reduce((acc, ev) => {
    if (!acc[ev.order_item_id]) acc[ev.order_item_id] = []
    acc[ev.order_item_id].push(ev)
    return acc
  }, {})

  const [confirmAction, setConfirmAction] = useState(null)
  const [printCancelConfirm, setPrintCancelConfirm] = useState(null) // { type: 'item'|'order', payload? }
  const [printerId, setPrinterId] = useState('')

  const waiterMap = Object.fromEntries(waiters.map(w => [w.id, w.nickname || w.full_name || w.username]))

  const invalidate = () => {
    qc.invalidateQueries({ queryKey: ['order', orderId] })
    qc.invalidateQueries({ queryKey: ['orders-active'] })
  }

  const payItems = useMutation({
    mutationFn: (item_ids) => client.post(`/api/orders/${orderId}/pay`, { item_ids }),
    onSuccess: () => { toast.success('Πληρώθηκε'); invalidate() },
    onError: () => toast.error('Σφάλμα πληρωμής'),
  })

  const cancelItem = useMutation({
    mutationFn: ({ itemId, printCancellation }) =>
      client.delete(`/api/orders/${orderId}/items/${itemId}?print_cancellation=${printCancellation}`),
    onSuccess: () => { toast.success('Αντικείμενο ακυρώθηκε'); invalidate() },
    onError: () => toast.error('Σφάλμα ακύρωσης'),
  })

  const cancelOrder = useMutation({
    mutationFn: ({ printCancellation }) =>
      client.delete(`/api/orders/${orderId}?print_cancellation=${printCancellation}`),
    onSuccess: () => { toast.success('Παραγγελία ακυρώθηκε'); invalidate(); onClose() },
    onError: () => toast.error('Σφάλμα ακύρωσης παραγγελίας'),
  })

  const closeOrder = useMutation({
    mutationFn: () => client.post(`/api/orders/${orderId}/close`),
    onSuccess: () => { toast.success('Παραγγελία έκλεισε'); invalidate(); onClose() },
    onError: () => toast.error('Σφάλμα κλεισίματος'),
  })

  const printOrder = useMutation({
    mutationFn: (pid) => client.post(`/api/orders/${orderId}/print`, { printer_id: pid }),
    onSuccess: () => toast.success('Αποστολή στον εκτυπωτή…'),
    onError: () => toast.error('Σφάλμα εκτύπωσης'),
  })

  function handleConfirm() {
    if (!confirmAction) return
    const type = confirmAction.type
    const payload = confirmAction.payload
    setConfirmAction(null)
    if (type === 'cancelItem') {
      setPrintCancelConfirm({ type: 'item', payload })
      return
    }
    if (type === 'cancelOrder') {
      setPrintCancelConfirm({ type: 'order' })
      return
    }
    if (type === 'closeOrder') closeOrder.mutate()
  }

  function executeCancelWithPrint(printCancellation) {
    if (!printCancelConfirm) return
    if (printCancelConfirm.type === 'item') {
      cancelItem.mutate({ itemId: printCancelConfirm.payload, printCancellation })
    } else {
      cancelOrder.mutate({ printCancellation })
    }
    setPrintCancelConfirm(null)
  }

  const total = order ? orderTotal(order.items) : 0
  const activeItems = order ? order.items.filter(i => i.status === 'active') : []
  const isOpen = order ? ['open', 'partially_paid'].includes(order.status) : false

  return (
    <div
      className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4"
      onClick={e => { if (e.target === e.currentTarget) onClose() }}
    >
      <div style={{
        background: 'white', borderRadius: 20, width: '100%', maxWidth: 800,
        maxHeight: '90vh', display: 'flex', flexDirection: 'column',
        boxShadow: '0 20px 60px rgba(0,0,0,0.2)',
        overflow: 'hidden',
      }}>
        {/* Modal header */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '18px 22px', borderBottom: '1px solid #edeff1', flexShrink: 0,
        }}>
          <div>
            <div style={{ fontSize: 18, fontWeight: 700, color: '#111315' }}>
              Τραπέζι {tableName}
            </div>
            {order && (
              <div style={{ fontSize: 12, color: '#5a6169', marginTop: 2 }}>
                Παραγγελία #{order.id} · από {fmtTime(order.opened_at)} · {fmtDuration(order.opened_at)}
              </div>
            )}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            {order && (
              <span style={{
                fontSize: 18, fontWeight: 700,
                color: '#111315',
                fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace",
              }}>{fmtEuro(total)}</span>
            )}
            {order && (
              <Badge status={order.status} />
            )}
            <button
              onClick={onClose}
              style={{
                width: 32, height: 32, borderRadius: 8, border: '1px solid #dfe2e6',
                background: 'white', cursor: 'pointer', fontSize: 16, color: '#5a6169',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}
            >✕</button>
          </div>
        </div>

        {/* Scrollable body */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '0 0 8px' }}>
          {isLoading && (
            <div style={{ padding: 40, textAlign: 'center', color: '#8a9099' }}>Φόρτωση…</div>
          )}

          {order && (
            <>
              {/* Waiters row */}
              {order.waiters.length > 0 && (
                <div style={{ padding: '12px 22px', borderBottom: '1px solid #f4f4f2', display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontSize: 12, color: '#8a9099', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5 }}>Προσωπικό</span>
                  <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                    {order.waiters.map(w => (
                      <span key={w.waiter_id} style={{
                        padding: '3px 10px', borderRadius: 999,
                        background: '#f0f4ff', color: '#3758c9',
                        fontSize: 12, fontWeight: 600,
                      }}>{waiterMap[w.waiter_id] || `#${w.waiter_id}`}</span>
                    ))}
                  </div>
                </div>
              )}

              {/* Items list */}
              <div>
                {order.items.length === 0 && (
                  <div style={{ padding: '24px', textAlign: 'center', color: '#8a9099', fontSize: 13 }}>Κανένα αντικείμενο.</div>
                )}
                {order.items.map(item => {
                  const itemEvents = priceEventsMap[item.id] ?? []
                  const hasPriceAdj = !!(item.price_adjustment && item.price_adjustment !== 0)
                  const isDealItem = !!item.deal_id
                  const modifierEvents = itemEvents.filter(ev => ev.event_type === 'modifier_applied')
                  const discountEvents = itemEvents.filter(ev => ev.event_type === 'waiter_discount')
                  return (
                  <div key={item.id} style={{
                    borderBottom: '1px solid #f9f9f8',
                    opacity: item.status === 'cancelled' ? 0.4 : 1,
                  }}>
                    <div style={{
                      display: 'flex', alignItems: 'center', gap: 12,
                      padding: '10px 22px',
                      textDecoration: item.status === 'cancelled' ? 'line-through' : 'none',
                    }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: '#111315', display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
                        {item.product?.name ?? `#${item.product_id}`}
                        <span style={{ color: '#8a9099', fontWeight: 400 }}>×{item.quantity}</span>
                        {isDealItem && (
                          <span style={{ fontSize: 10, fontWeight: 700, padding: '1px 5px', borderRadius: 4, background: 'rgba(167,139,250,0.12)', color: '#7c3aed', border: '1px solid rgba(167,139,250,0.3)' }}>ΔΩΡΕΑΝ</span>
                        )}
                        {modifierEvents.length > 0 && (
                          <span style={{ fontSize: 10, padding: '1px 5px', borderRadius: 4, background: 'rgba(96,165,250,0.12)', color: '#2563eb', border: '1px solid rgba(96,165,250,0.3)' }}>
                            {modifierEvents[0].modifier_name || 'Τροποποιητής'}
                          </span>
                        )}
                        {discountEvents.length > 0 && (
                          <span style={{ fontSize: 10, padding: '1px 5px', borderRadius: 4, background: 'rgba(192,132,252,0.12)', color: '#7c3aed', border: '1px solid rgba(192,132,252,0.3)' }}>
                            Έκπτωση
                          </span>
                        )}
                      </div>
                      {item.notes && <div style={{ fontSize: 11, color: '#8a9099', marginTop: 1 }}>{item.notes}</div>}
                      {item.paid_by && (
                        <div style={{ fontSize: 11, color: '#2f9e5e', marginTop: 1, fontWeight: 600 }}>
                          Πληρώθηκε
                        </div>
                      )}
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
                      <span style={{
                        fontSize: 14, fontWeight: 700,
                        color: hasPriceAdj ? '#3b82f6' : '#111315',
                        fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace",
                        minWidth: 52, textAlign: 'right',
                      }}>{fmtEuro(((item.unit_price ?? 0) + (item.price_adjustment ?? 0)) * item.quantity)}</span>
                      {isOpen && item.status === 'active' && (
                        <>
                          <button
                            onClick={() => payItems.mutate([item.id])}
                            style={{
                              height: 28, padding: '0 10px', borderRadius: 6,
                              border: '1px solid #d7ecdc', background: '#eef7f0',
                              color: '#1f7042', fontSize: 11, fontWeight: 700, cursor: 'pointer',
                            }}
                          >Πληρωμή</button>
                          <button
                            onClick={() => setConfirmAction({ type: 'cancelItem', payload: item.id })}
                            style={{
                              height: 28, padding: '0 10px', borderRadius: 6,
                              border: '1px solid #fecaca', background: '#fef2f2',
                              color: '#dc2626', fontSize: 11, fontWeight: 700, cursor: 'pointer',
                            }}
                          >✕</button>
                        </>
                      )}
                    </div>
                    </div>
                    {itemEvents.filter(ev => ['modifier_applied','waiter_discount','free_item_added'].includes(ev.event_type)).map((ev, ei) => {
                      const evColor = ev.event_type === 'waiter_discount' ? '#7c3aed' : ev.event_type === 'free_item_added' ? '#16a34a' : '#2563eb'
                      const evLabel = ev.modifier_name || ev.deal_name || (ev.event_type === 'waiter_discount' ? 'Έκπτωση' : ev.event_type === 'free_item_added' ? 'Δωρεάν' : ev.event_type)
                      return (
                        <div key={ei} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '1px 22px 1px 36px', fontSize: 11, color: evColor }}>
                          <span style={{ opacity: 0.6 }}>↳</span>
                          <span style={{ flex: 1 }}>{evLabel}</span>
                          {ev.delta_amount != null && <span style={{ fontWeight: 600 }}>{ev.delta_amount > 0 ? '+' : ''}{ev.delta_amount.toFixed(2)} €</span>}
                          {ev.price_after != null && <span style={{ color: '#8a9099', marginLeft: 2 }}>→ {ev.price_after.toFixed(2)} €</span>}
                        </div>
                      )
                    })}
                  </div>
                  )
                })}
              </div>
            </>
          )}
        </div>

        {/* Footer actions */}
        {order && (
          <div style={{
            padding: '12px 22px', borderTop: '1px solid #edeff1',
            display: 'flex', gap: 8, flexWrap: 'wrap', flexShrink: 0,
            background: '#fafafa', alignItems: 'center',
          }}>
            {isOpen && activeItems.length > 0 && (
              <button
                onClick={() => payItems.mutate(activeItems.map(i => i.id))}
                style={{
                  minHeight: 36, padding: '6px 16px', borderRadius: 8,
                  background: '#3758c9', border: 'none', color: 'white',
                  fontSize: 13, fontWeight: 700, cursor: 'pointer', whiteSpace: 'nowrap',
                }}
              >Πληρωμή όλων</button>
            )}
            {isOpen && (
              <>
                <button
                  onClick={() => setConfirmAction({ type: 'closeOrder' })}
                  style={{
                    minHeight: 36, padding: '6px 14px', borderRadius: 8,
                    border: '1px solid #dfe2e6', background: 'white',
                    color: '#2b2f33', fontSize: 13, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap',
                  }}
                >Κλείσιμο</button>
                <button
                  onClick={() => setConfirmAction({ type: 'cancelOrder' })}
                  style={{
                    minHeight: 36, padding: '6px 14px', borderRadius: 8,
                    border: '1px solid #fecaca', background: '#fef2f2',
                    color: '#dc2626', fontSize: 13, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap',
                  }}
                >Ακύρωση</button>
              </>
            )}
            {printers.length > 0 && (
              <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginLeft: 'auto', flexWrap: 'wrap' }}>
                <select
                  value={printerId}
                  onChange={e => setPrinterId(e.target.value)}
                  style={{
                    height: 36, paddingLeft: 10, paddingRight: 28, borderRadius: 8,
                    border: '1px solid #dfe2e6', background: 'white',
                    color: '#2b2f33', fontSize: 12, cursor: 'pointer',
                  }}
                >
                  <option value="">Εκτυπωτής…</option>
                  {printers.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                </select>
                <button
                  onClick={() => { if (printerId) printOrder.mutate(Number(printerId)) }}
                  disabled={!printerId}
                  style={{
                    minHeight: 36, padding: '6px 14px', borderRadius: 8,
                    border: '1px solid #dfe2e6', background: 'white',
                    color: '#2b2f33', fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap',
                    cursor: printerId ? 'pointer' : 'not-allowed', opacity: printerId ? 1 : 0.5,
                  }}
                >🖨 Εκτύπωση</button>
              </div>
            )}
            <button
              onClick={onOpenFull}
              style={{
                minHeight: 36, padding: '6px 14px', borderRadius: 8,
                border: '1px solid #dfe2e6', background: 'white',
                color: '#5a6169', fontSize: 12, fontWeight: 500, cursor: 'pointer', whiteSpace: 'nowrap',
                marginLeft: printers.length > 0 ? 0 : 'auto',
              }}
            >Πλήρης εικόνα →</button>
          </div>
        )}
      </div>

      {confirmAction && (
        <ConfirmModal
          title={
            confirmAction.type === 'cancelItem' ? 'Ακύρωση αντικειμένου;' :
            confirmAction.type === 'cancelOrder' ? 'Ακύρωση παραγγελίας;' :
            'Κλείσιμο παραγγελίας;'
          }
          message={confirmAction.type === 'cancelOrder' ? 'Η παραγγελία θα ακυρωθεί οριστικά.' : undefined}
          confirmLabel={confirmAction.type === 'closeOrder' ? 'Κλείσιμο' : 'Ακύρωση'}
          confirmVariant={confirmAction.type === 'closeOrder' ? 'primary' : 'danger'}
          onConfirm={handleConfirm}
          onCancel={() => setConfirmAction(null)}
        />
      )}

      {printCancelConfirm && (
        <div style={{
          position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.5)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          borderRadius: 20, zIndex: 10,
        }}>
          <div style={{
            background: 'white', borderRadius: 14, padding: '24px 28px',
            maxWidth: 360, width: '100%', boxShadow: '0 8px 32px rgba(0,0,0,0.2)',
            textAlign: 'center',
          }}>
            <div style={{ fontSize: 28, marginBottom: 12 }}>🖨️</div>
            <p style={{ fontWeight: 700, fontSize: 16, margin: '0 0 6px', color: '#111315' }}>
              Εκτύπωση ακύρωσης;
            </p>
            <p style={{ fontSize: 13, color: '#6b7280', margin: '0 0 20px', lineHeight: 1.5 }}>
              Θέλετε να σταλεί ακυρωτικό ticket στον εκτυπωτή;
            </p>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
              <button
                onClick={() => executeCancelWithPrint(false)}
                style={{ padding: '9px 18px', borderRadius: 8, border: '1px solid #e5e7eb', background: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer', color: '#374151' }}
              >Όχι, απλή ακύρωση</button>
              <button
                onClick={() => executeCancelWithPrint(true)}
                style={{ padding: '9px 18px', borderRadius: 8, border: 'none', background: '#dc2626', color: 'white', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}
              >Ναι, εκτύπωση</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

// ─── KPI Card ─────────────────────────────────────────────────────────────────

function KpiCard({ label, value, sub, accent = '#3758c9', pct, private: isPrivate }) {
  return (
    <div style={{
      background: 'white',
      border: '1px solid #edeff1',
      borderRadius: 16,
      padding: '20px 22px',
      display: 'flex', flexDirection: 'column', gap: 6,
      boxShadow: '0 1px 2px rgba(16,20,24,0.04)',
      flex: 1,
    }}>
      <div style={{ fontSize: 11, fontWeight: 700, color: '#5a6169', textTransform: 'uppercase', letterSpacing: 0.7 }}>{label}</div>
      <div style={{
        fontSize: 30, fontWeight: 700, color: '#111315', letterSpacing: -0.5, lineHeight: 1.1,
        fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace",
        filter: isPrivate ? 'blur(8px)' : 'none',
        userSelect: isPrivate ? 'none' : 'auto',
        transition: 'filter 200ms ease',
      }}>{value}</div>
      {sub && <div style={{
        fontSize: 12, color: '#5a6169',
        filter: isPrivate ? 'blur(6px)' : 'none',
        userSelect: isPrivate ? 'none' : 'auto',
        transition: 'filter 200ms ease',
      }}>{sub}</div>}
      {pct != null && (
        <div style={{ marginTop: 4, height: 6, borderRadius: 3, background: '#edeff1', overflow: 'hidden' }}>
          <div style={{ width: `${Math.min(100, pct)}%`, height: '100%', background: accent, borderRadius: 3, transition: 'width 300ms ease' }} />
        </div>
      )}
    </div>
  )
}

// ─── Mini table chip ──────────────────────────────────────────────────────────

function TableChip({ name, status, amount, onClick }) {
  const c = TABLE_COLORS[status] || TABLE_COLORS.free
  return (
    <button
      onClick={onClick}
      title={amount != null ? fmtEuro(amount) : name}
      style={{
        aspectRatio: '1', minHeight: 52,
        borderRadius: 10,
        background: c.bg,
        border: '1px solid ' + c.border,
        color: c.text,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 12, fontWeight: 700,
        fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace",
        cursor: onClick ? 'pointer' : 'default',
        transition: 'transform 100ms ease, box-shadow 100ms ease',
      }}
      onMouseEnter={e => { if (onClick) { e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.08)' } }}
      onMouseLeave={e => { e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = '' }}
    >
      {name}
    </button>
  )
}

// ─── Shifts card ──────────────────────────────────────────────────────────────

// ─── Shift Review Modal (Overview + Details + optional close flow) ─────────────

const SWATCH = { cash: '#2f9e5e', card: '#3758c9' }

function initials(name = '') {
  const parts = name.trim().split(/\s+/)
  if (parts.length >= 2) return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase()
  return name.slice(0, 2).toUpperCase()
}

function fmtDur(ms) {
  const totalMin = Math.round(ms / 60000)
  const h = Math.floor(totalMin / 60)
  const m = totalMin % 60
  return h > 0 ? `${h}ω ${m}λ` : `${m}λ`
}

// Embedded detail views (extracted from ShiftDetailModal but self-contained here)
function classifyItem(item, shiftWaiterId) {
  if (item.status === 'cancelled')
    return { key: 'cancelled', label: 'Ακυρώθηκε', dot: '#dc2626', bg: '#fef2f2', border: '#fecaca', text: '#991b1b' }
  const orderedByMe = item.added_by_id === shiftWaiterId
  const paidToMe    = item.paid_by_id  === shiftWaiterId
  const isPaid      = item.status === 'paid'
  if (orderedByMe && paidToMe && isPaid)
    return { key: 'both',    label: 'Πλήρης',        dot: '#16a34a', bg: '#f0fdf4', border: '#bbf7d0', text: '#15803d' }
  if (!orderedByMe && paidToMe && isPaid)
    return { key: 'paid',    label: 'Μόνο Πληρώθηκε', dot: '#2563eb', bg: '#eff6ff', border: '#bfdbfe', text: '#1d4ed8' }
  if (orderedByMe && isPaid && !paidToMe)
    return { key: 'ordered', label: 'Μόνο Παρήγγειλε',dot: '#ca8a04', bg: '#fefce8', border: '#fef08a', text: '#854d0e' }
  if (orderedByMe && !isPaid)
    return { key: 'unpaid',  label: 'Ανοιχτό',        dot: '#ea580c', bg: '#fff7ed', border: '#fed7aa', text: '#c2410c' }
  return   { key: 'anomaly', label: 'Πρόβλημα',       dot: '#dc2626', bg: '#fef2f2', border: '#fecaca', text: '#b91c1c' }
}

const DETAIL_FILTER_STATUS = [
  { key: 'all',       label: 'Όλα' },
  { key: 'both',      label: 'Πλήρης' },
  { key: 'paid',      label: 'Μόνο Πληρώθηκε' },
  { key: 'ordered',   label: 'Μόνο Παρήγγειλε' },
  { key: 'unpaid',    label: 'Ανοιχτό' },
  { key: 'cancelled', label: 'Ακυρώθηκε' },
]
const DETAIL_FILTER_PAYMENT = [
  { key: 'any',  label: 'Κάθε τρόπος' },
  { key: 'cash', label: 'Μετρητά' },
  { key: 'card', label: 'Κάρτα' },
]

function DetailItemRow({ item, shiftWaiterId }) {
  const c = classifyItem(item, shiftWaiterId)
  const isCancelled = item.status === 'cancelled'
  const method = item.payment_method || 'cash'
  return (
    <div style={{
      display: 'flex', alignItems: 'flex-start', gap: 10, padding: '7px 14px',
      borderTop: '1px solid #f4f4f2', background: c.bg,
    }}>
      <div style={{ width: 7, height: 7, borderRadius: '50%', background: c.dot, flexShrink: 0, marginTop: 5 }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: isCancelled ? '#991b1b' : '#111315' }}>
            {item.product_name}
            <span style={{ fontWeight: 400, color: '#8a9099', marginLeft: 4 }}>×{item.quantity}</span>
          </span>
          <span style={{ fontSize: 13, fontWeight: 700, color: isCancelled ? '#b91c1c' : '#111315', flexShrink: 0, textDecoration: isCancelled ? 'line-through' : 'none' }}>
            {fmtEuro(item.subtotal)}
          </span>
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '2px 12px', marginTop: 2, alignItems: 'center' }}>
          <span style={{ fontSize: 11, color: '#5a6169' }}>
            Παρήγγειλε: <span style={{ fontWeight: 600, color: '#374151' }}>{item.added_by_name ?? '—'}</span>
          </span>
          {!isCancelled && (
            <span style={{ fontSize: 11, color: '#5a6169' }}>
              Πληρώθηκε: <span style={{ fontWeight: 600, color: item.paid_by_name ? '#374151' : '#9ca3af' }}>{item.paid_by_name ?? '—'}</span>
              {item.payment_method && (
                <span style={{
                  marginLeft: 6, padding: '1px 6px', borderRadius: 4, fontSize: 10, fontWeight: 700,
                  background: method === 'card' ? '#eff6ff' : '#f0fdf4',
                  color: method === 'card' ? '#1d4ed8' : '#15803d',
                  border: `1px solid ${method === 'card' ? '#bfdbfe' : '#bbf7d0'}`,
                }}>{method === 'card' ? 'Κάρτα' : 'Μετρητά'}</span>
              )}
            </span>
          )}
        </div>
        <div style={{ marginTop: 3 }}>
          <span style={{ fontSize: 10, fontWeight: 600, padding: '1px 6px', borderRadius: 4, background: c.border, color: c.text, border: `1px solid ${c.border}` }}>{c.label}</span>
        </div>
      </div>
    </div>
  )
}

function DetailOrderGroup({ order, shiftWaiterId, statusFilter, paymentFilter }) {
  const visibleItems = order.items.filter(item => {
    const statusOk = statusFilter === 'all' || classifyItem(item, shiftWaiterId).key === statusFilter
    const payOk = paymentFilter === 'any' || !item.payment_method
      ? (paymentFilter === 'any' || (paymentFilter === 'cash' && item.status === 'paid'))
      : (item.payment_method || 'cash') === paymentFilter
    // If status filter is cancelled, don't apply payment filter
    const isCancelled = item.status === 'cancelled'
    return statusOk && (isCancelled || paymentFilter === 'any' || (item.payment_method || 'cash') === paymentFilter)
  })
  if (visibleItems.length === 0) return null
  const groupTotal = visibleItems.filter(i => i.status === 'paid').reduce((s, i) => s + i.subtotal, 0)
  return (
    <div style={{ borderRadius: 10, border: '1px solid #edeff1', marginBottom: 8, overflow: 'hidden' }}>
      <div style={{ padding: '8px 14px', background: '#f9fafb', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 4 }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: '#374151' }}>
          Παραγγελία #{order.order_id}
          {order.table_name && <span style={{ color: '#8a9099', fontWeight: 400, marginLeft: 6 }}>· {order.table_name}</span>}
        </div>
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
          {order.opener_name && (
            <span style={{ fontSize: 11, color: '#5a6169' }}>
              Άνοιξε: <span style={{ fontWeight: 600, color: '#374151' }}>{order.opener_name}</span>
              {order.opened_at ? <span style={{ color: '#9ca3af' }}> {fmtTime(order.opened_at)}</span> : null}
            </span>
          )}
          {groupTotal > 0 && <span style={{ fontSize: 12, fontWeight: 700, color: '#2f9e5e' }}>{fmtEuro(groupTotal)}</span>}
        </div>
      </div>
      {visibleItems.map(item => (
        <DetailItemRow key={item.id} item={item} shiftWaiterId={shiftWaiterId} />
      ))}
    </div>
  )
}

// ─── The main modal ────────────────────────────────────────────────────────────

function ShiftReviewModal({ shift, mode, onClose, onConfirm, busy }) {
  // mode: 'stats' (view only) | 'close' (end shift flow)
  const [screen, setScreen] = useState('overview') // 'overview' | 'details'
  const [closeStep, setCloseStep] = useState(1)    // 1 = review+notes, 2 = cash handover
  const [notes, setNotes] = useState('')
  const [countedCash, setCountedCash] = useState('')
  const [statusFilter, setStatusFilter] = useState('all')
  const [paymentFilter, setPaymentFilter] = useState('any')

  // Fetch live summary (includes orders for details tab + per-shift aggregates)
  const { data: summary, isLoading } = useQuery({
    queryKey: ['shift-detail', shift.id],
    queryFn: () => client.get(`/api/shifts/${shift.id}/summary`).then(r => r.data),
    staleTime: 30 * 1000,
    refetchOnWindowFocus: false,
  })

  // Use enriched data from summary when available, fall back to shift prop
  const data = summary || shift
  const cashSales   = data.cash_sales ?? data.total_collected ?? 0
  const cardSales   = data.card_sales ?? 0
  const totalRev    = cashSales + cardSales
  const startingCash = data.starting_cash ?? 0
  const expectedDrawer = startingCash + cashSales
  const cashPct = totalRev > 0 ? Math.round((cashSales / totalRev) * 100) : 0
  const cardPct = 100 - cashPct

  // Cash handover discrepancy
  const counted = countedCash !== '' ? parseFloat(countedCash) : null
  const discrepancy = counted != null ? +(counted - expectedDrawer).toFixed(2) : null
  const isShort = discrepancy != null && discrepancy < -0.005
  const isOver  = discrepancy != null && discrepancy > 0.005
  const isClean = discrepancy != null && !isShort && !isOver

  // Duration
  const startMs = shift.started_at ? new Date(shift.started_at).getTime() : null
  const nowMs = Date.now()
  const durLabel = startMs ? fmtDur(nowMs - startMs) : '—'

  // Stats from summary
  const totalOrders = summary?.orders?.length ?? 0
  const totalItems  = summary?.orders?.reduce((s, o) => s + o.items.filter(i => i.status === 'paid').reduce((ss, i) => ss + i.quantity, 0), 0) ?? 0
  const totalTables = summary?.orders ? new Set(summary.orders.filter(o => o.table_id).map(o => o.table_id)).size : 0
  const shiftPay    = data.shift_pay

  // Per-hour bars from summary orders
  const hourBuckets = {}
  if (summary?.orders) {
    for (const o of summary.orders) {
      for (const item of o.items) {
        if (item.status !== 'paid' || !item.paid_at) continue
        const h = new Date(item.paid_at).getHours()
        hourBuckets[h] = (hourBuckets[h] || 0) + item.subtotal
      }
    }
  }
  const hourEntries = Object.entries(hourBuckets).sort((a, b) => a[0] - b[0])
  const maxHourVal  = Math.max(...hourEntries.map(([, v]) => v), 1)

  const waiterIdToUse = shift.waiter_id ?? summary?.waiter_id

  // ── Shared header ──
  const inits = initials(shift.waiter_name || '')
  const color = avatarColor(shift.waiter_name || '')
  const isClosing = mode === 'close' && closeStep === 2
  const badgeLabel = mode === 'close' ? (closeStep === 1 ? 'Κλείσιμο' : 'Κλείσιμο') : 'Σε εξέλιξη'

  return (
    <div
      style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.52)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px 16px', overflowY: 'auto' }}
      onClick={e => { if (e.target === e.currentTarget) onClose() }}
    >
      <div style={{ background: '#fff', borderRadius: 22, width: '100%', maxWidth: 660, boxShadow: '0 30px 70px rgba(20,24,36,0.22), 0 10px 24px rgba(0,0,0,0.10)', overflow: 'hidden', flexShrink: 0 }}>

        {/* ── Header ── */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '20px 24px 16px', borderBottom: '1px solid #edeff1' }}>
          <div style={{ flexShrink: 0, width: 46, height: 46, borderRadius: 13, background: `linear-gradient(150deg, ${color} 0%, ${color}cc 100%)`, display: 'grid', placeItems: 'center', color: '#fff', fontFamily: 'ui-monospace,monospace', fontWeight: 700, fontSize: 15, letterSpacing: '-0.02em', boxShadow: `0 3px 8px ${color}55` }}>
            {inits}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, flexWrap: 'wrap' }}>
              <span style={{ fontSize: 17, fontWeight: 600, letterSpacing: '-0.01em', color: '#111315' }}>{shift.waiter_name}</span>
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 5, fontFamily: 'ui-monospace,monospace', fontSize: 9.5, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', borderRadius: 999, padding: '3px 8px 3px 6px',
                background: mode === 'close' ? '#fff7ed' : '#f0fdf4',
                color:      mode === 'close' ? '#b45309'  : '#15803d',
              }}>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: mode === 'close' ? '#f59e0b' : '#22c55e', animation: mode === 'close' ? 'none' : 'srPulse 1.8s infinite' }} />
                {badgeLabel}
              </span>
            </div>
            <div style={{ fontFamily: 'ui-monospace,monospace', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.12em', color: '#8a9099', marginTop: 3 }}>
              Βάρδια #{shift.id}
            </div>
          </div>
          {/* Screen toggle */}
          <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
            {[
              { key: 'overview', title: 'Επισκόπηση', icon: '▤' },
              { key: 'details',  title: 'Λεπτομέρειες', icon: '≡' },
            ].map(({ key, title, icon }) => (
              <button
                key={key}
                title={title}
                onClick={() => setScreen(key)}
                style={{
                  width: 30, height: 30, borderRadius: 8, border: '1px solid', cursor: 'pointer',
                  fontSize: 15, display: 'grid', placeItems: 'center',
                  borderColor: screen === key ? '#3758c9' : '#dfe2e6',
                  background:  screen === key ? '#eff3ff' : '#fff',
                  color:       screen === key ? '#3758c9' : '#8a9099',
                  transition: 'all 0.14s ease',
                }}
              >{icon}</button>
            ))}
          </div>
          <button onClick={onClose} style={{ flexShrink: 0, width: 30, height: 30, borderRadius: 8, border: '1px solid #dfe2e6', background: '#fff', color: '#8a9099', cursor: 'pointer', display: 'grid', placeItems: 'center', fontSize: 15, transition: 'all 0.14s' }}>✕</button>
        </div>

        {/* ── Time strip ── */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', borderBottom: '1px solid #edeff1' }}>
          {[
            { key: 'Έναρξη',         val: fmtTime(shift.started_at) },
            { key: 'Διάρκεια',       val: durLabel },
            { key: mode === 'close' ? 'Τέλος' : 'Τρέχουσα', val: mode === 'close' ? fmtTime(new Date().toISOString()) : fmtTime(new Date().toISOString()), muted: mode !== 'close' },
          ].map(({ key, val, muted }) => (
            <div key={key} style={{ padding: '12px 22px', borderRight: '1px dashed #edeff1' }}>
              <div style={{ fontFamily: 'ui-monospace,monospace', fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.12em', color: '#9ca3af' }}>{key}</div>
              <div style={{ fontFamily: 'ui-monospace,monospace', fontWeight: 600, fontSize: 14, marginTop: 3, color: muted ? '#9ca3af' : '#111315', fontVariantNumeric: 'tabular-nums' }}>{val}</div>
            </div>
          ))}
        </div>

        {/* ── Body ── */}
        <div style={{ maxHeight: 'calc(92vh - 260px)', overflowY: 'auto' }}>

          {/* ══ OVERVIEW SCREEN ══ */}
          {screen === 'overview' && (
            <div style={{ padding: '18px 22px 20px' }}>

              {/* Hero: expected drawer */}
              <div style={{ position: 'relative', border: '1px solid #22c55e', background: 'linear-gradient(180deg,#f0fdf4 0%,#fafffe 100%)', borderRadius: 16, padding: '14px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 14, overflow: 'hidden' }}>
                <div style={{ position: 'absolute', top: 0, left: 0, bottom: 0, width: 4, background: '#22c55e', borderRadius: '16px 0 0 16px' }} />
                <div>
                  <div style={{ fontFamily: 'ui-monospace,monospace', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.12em', color: '#15803d', marginBottom: 4 }}>Αναμενόμενο στο ταμείο</div>
                  <div style={{ fontFamily: 'ui-monospace,monospace', fontWeight: 700, fontSize: 36, letterSpacing: '-0.03em', color: '#111315', fontVariantNumeric: 'tabular-nums', lineHeight: 1.1 }}>
                    <span style={{ fontSize: 20, color: '#6b7280', marginRight: 2 }}>€</span>
                    {expectedDrawer.toFixed(2)}
                  </div>
                </div>
                <div style={{ textAlign: 'right', fontFamily: 'ui-monospace,monospace', fontSize: 11, color: '#6b7280', lineHeight: 1.8, flexShrink: 0 }}>
                  Αρχικό <strong style={{ color: '#111315' }}>{fmtEuro(startingCash)}</strong><br />
                  <span style={{ color: '#9ca3af' }}>+</span> Μετρητά <strong style={{ color: '#111315' }}>{fmtEuro(cashSales)}</strong>
                </div>
              </div>

              {/* 3 tiles */}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10, marginTop: 12 }}>
                {[
                  { sw: '#9ca3af', label: 'Αρχικό ταμείο',    val: fmtEuro(startingCash), sub: 'με τι ξεκίνησε' },
                  { sw: SWATCH.cash, label: 'Μετρητά πωλήσεων', val: fmtEuro(cashSales), sub: 'είσπραξη σε μετρητά' },
                  { sw: SWATCH.card, label: 'Συνολικός τζίρος',  val: fmtEuro(totalRev),   sub: 'μετρητά + κάρτα' },
                ].map(t => (
                  <div key={t.label} style={{ border: '1px solid #edeff1', borderRadius: 13, padding: '11px 13px 13px', background: '#fff' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'ui-monospace,monospace', fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.1em', color: '#8a9099' }}>
                      <span style={{ width: 8, height: 8, borderRadius: 3, background: t.sw, flexShrink: 0 }} />
                      {t.label}
                    </div>
                    <div style={{ fontFamily: 'ui-monospace,monospace', fontWeight: 600, fontSize: 19, letterSpacing: '-0.02em', marginTop: 7, color: '#111315', fontVariantNumeric: 'tabular-nums' }}>{t.val}</div>
                    <div style={{ fontSize: 11, color: '#8a9099', marginTop: 2 }}>{t.sub}</div>
                  </div>
                ))}
              </div>

              {/* Payment split bar */}
              {totalRev > 0 && (
                <div style={{ marginTop: 18 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'ui-monospace,monospace', fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.12em', color: '#9ca3af', marginBottom: 8 }}>
                    <span>Μέθοδος πληρωμής</span>
                    <span>σύνολο {fmtEuro(totalRev)}</span>
                  </div>
                  <div style={{ display: 'flex', height: 14, borderRadius: 6, overflow: 'hidden', gap: 2 }}>
                    {cashPct > 0 && <div style={{ width: `${cashPct}%`, background: SWATCH.cash, borderRadius: 3 }} />}
                    {cardPct > 0 && <div style={{ width: `${cardPct}%`, background: SWATCH.card, borderRadius: 3 }} />}
                  </div>
                  <div style={{ display: 'flex', gap: 16, marginTop: 8, flexWrap: 'wrap' }}>
                    {[
                      { sw: SWATCH.cash, label: 'Μετρητά', amt: fmtEuro(cashSales), pct: `${cashPct}%` },
                      { sw: SWATCH.card, label: 'Κάρτα',   amt: fmtEuro(cardSales), pct: `${cardPct}%` },
                    ].map(l => (
                      <div key={l.label} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: '#5a6169' }}>
                        <span style={{ width: 9, height: 9, borderRadius: 3, background: l.sw, flexShrink: 0, display: 'inline-block' }} />
                        {l.label}
                        <span style={{ fontFamily: 'ui-monospace,monospace', fontWeight: 600, color: '#111315' }}>{l.amt}</span>
                        <span style={{ fontFamily: 'ui-monospace,monospace', fontSize: 10, color: '#9ca3af' }}>{l.pct}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Per-hour bars */}
              {hourEntries.length > 0 && (
                <div style={{ marginTop: 18 }}>
                  <div style={{ fontFamily: 'ui-monospace,monospace', fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.12em', color: '#9ca3af', marginBottom: 8 }}>Πωλήσεις ανά ώρα</div>
                  <div style={{ display: 'flex', alignItems: 'flex-end', gap: 5, height: 52, paddingBottom: 0 }}>
                    {hourEntries.map(([h, v]) => (
                      <div key={h} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, height: '100%', justifyContent: 'flex-end' }}>
                        <div title={`${h}:00 — ${fmtEuro(v)}`} style={{ width: '100%', background: 'linear-gradient(180deg,#2f9e5e 0%,#1e7a46 100%)', borderRadius: '4px 4px 2px 2px', height: `${Math.round(v / maxHourVal * 100)}%`, minHeight: 3 }} />
                        <div style={{ fontFamily: 'ui-monospace,monospace', fontSize: 8, color: '#9ca3af' }}>{h}</div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Bottom stats strip */}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', border: '1px solid #edeff1', borderRadius: 13, overflow: 'hidden', marginTop: 18 }}>
                {[
                  { val: String(totalItems),       lab: 'Είδη' },
                  { val: String(totalTables),      lab: 'Τραπέζια' },
                  { val: String(totalOrders),      lab: 'Παραγγελίες' },
                  { val: shiftPay != null ? fmtEuro(shiftPay) : '—', lab: 'Αμοιβή', sub: data.hourly_rate_snapshot ? `${fmtEuro(data.hourly_rate_snapshot)}/ώρα` : null },
                ].map((s, i) => (
                  <div key={s.lab} style={{ padding: '11px 13px', borderRight: i < 3 ? '1px solid #edeff1' : 'none' }}>
                    <div style={{ fontFamily: 'ui-monospace,monospace', fontWeight: 600, fontSize: 17, letterSpacing: '-0.02em', color: '#111315', fontVariantNumeric: 'tabular-nums' }}>{s.val}</div>
                    <div style={{ fontFamily: 'ui-monospace,monospace', fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.1em', color: '#8a9099', marginTop: 3 }}>{s.lab}</div>
                    {s.sub && <div style={{ fontSize: 10, color: '#9ca3af', marginTop: 1 }}>{s.sub}</div>}
                  </div>
                ))}
              </div>

              {/* Notes (only shown in close mode before step 2) */}
              {mode === 'close' && closeStep === 1 && (
                <div style={{ marginTop: 18 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 500, color: '#5a6169', marginBottom: 6 }}>
                    Σημειώσεις <span style={{ fontWeight: 400, color: '#9ca3af' }}>(προαιρετικό)</span>
                  </div>
                  <textarea
                    value={notes}
                    onChange={e => setNotes(e.target.value)}
                    placeholder="π.χ. παρατηρήσεις για τη βάρδια, βλάβες, ελλείψεις…"
                    rows={2}
                    style={{ width: '100%', borderRadius: 12, border: '1px solid #dfe2e6', padding: '10px 13px', fontSize: 13.5, color: '#111315', resize: 'vertical', outline: 'none', boxSizing: 'border-box', fontFamily: 'inherit', background: '#f9fafb', transition: 'border-color 0.15s' }}
                    onFocus={e => { e.target.style.borderColor = '#22c55e'; e.target.style.background = '#fff' }}
                    onBlur={e => { e.target.style.borderColor = '#dfe2e6'; e.target.style.background = '#f9fafb' }}
                  />
                </div>
              )}

              {/* Cash handover step (step 2, inline in overview) */}
              {mode === 'close' && closeStep === 2 && (
                <div style={{ marginTop: 18 }}>
                  <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: '-0.01em', color: '#111315', marginBottom: 14 }}>Πόσα μετρητά παραδίδει ο σερβιτόρος;</div>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', border: '1px solid #edeff1', borderRadius: 13, padding: '12px 16px', background: '#f9fafb', marginBottom: 12 }}>
                    <span style={{ fontFamily: 'ui-monospace,monospace', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: '#8a9099' }}>Αναμενόμενη παράδοση</span>
                    <span style={{ fontFamily: 'ui-monospace,monospace', fontWeight: 700, fontSize: 21, color: '#111315', fontVariantNumeric: 'tabular-nums' }}>{fmtEuro(expectedDrawer)}</span>
                  </div>
                  <div style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>
                    <span style={{ position: 'absolute', left: 16, fontFamily: 'ui-monospace,monospace', fontWeight: 600, fontSize: 20, color: '#8a9099', pointerEvents: 'none' }}>€</span>
                    <input
                      type="text"
                      inputMode="decimal"
                      value={countedCash}
                      onChange={e => setCountedCash(e.target.value)}
                      placeholder={expectedDrawer.toFixed(2)}
                      autoFocus
                      style={{ width: '100%', fontFamily: 'ui-monospace,monospace', fontWeight: 700, fontSize: 24, letterSpacing: '-0.02em', color: '#111315', border: '1.5px solid #dfe2e6', borderRadius: 13, padding: '13px 16px 13px 40px', background: '#fff', fontVariantNumeric: 'tabular-nums', outline: 'none', boxSizing: 'border-box', transition: 'border-color 0.15s, box-shadow 0.15s' }}
                      onFocus={e => { e.target.style.borderColor = '#22c55e'; e.target.style.boxShadow = '0 0 0 3px #f0fdf4' }}
                      onBlur={e => { e.target.style.borderColor = '#dfe2e6'; e.target.style.boxShadow = 'none' }}
                    />
                  </div>
                  {/* Quick buttons */}
                  <div style={{ display: 'flex', gap: 7, marginTop: 10, flexWrap: 'wrap' }}>
                    {[expectedDrawer, Math.floor(expectedDrawer / 10) * 10, Math.ceil(expectedDrawer / 10) * 10].filter((v, i, a) => a.indexOf(v) === i).map(v => (
                      <button key={v} onClick={() => setCountedCash(v.toFixed(2))} style={{ fontFamily: 'ui-monospace,monospace', fontSize: 11.5, fontWeight: 500, color: '#5a6169', background: '#fff', border: '1px solid #dfe2e6', borderRadius: 9, padding: '6px 11px', cursor: 'pointer', fontVariantNumeric: 'tabular-nums' }}>
                        {v === expectedDrawer ? `Ακριβές ${fmtEuro(v)}` : fmtEuro(v)}
                      </button>
                    ))}
                  </div>
                  {/* Discrepancy */}
                  {discrepancy != null && (
                    <div style={{
                      display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginTop: 14, borderRadius: 13, padding: '12px 16px',
                      border: `1px solid ${isClean ? '#22c55e' : isShort ? '#ef4444' : '#22c55e'}`,
                      background: isClean ? '#f0fdf4' : isShort ? '#fef2f2' : '#f0fdf4',
                      transition: 'all 0.18s ease',
                    }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                        <div style={{ width: 24, height: 24, borderRadius: 8, background: isClean ? '#22c55e' : isShort ? '#ef4444' : '#22c55e', display: 'grid', placeItems: 'center', color: '#fff', fontSize: 14, fontWeight: 700 }}>
                          {isClean ? '✓' : isShort ? '▼' : '▲'}
                        </div>
                        <span style={{ fontSize: 13, fontWeight: 600, color: isClean ? '#15803d' : isShort ? '#dc2626' : '#15803d' }}>
                          {isClean ? 'Ισοσκελισμένο' : isShort ? 'Έλλειμμα' : 'Πλεόνασμα'}
                        </span>
                      </div>
                      <span style={{ fontFamily: 'ui-monospace,monospace', fontWeight: 700, fontSize: 18, color: isClean ? '#15803d' : isShort ? '#dc2626' : '#15803d', fontVariantNumeric: 'tabular-nums' }}>
                        {isClean ? '€0.00' : isShort ? `−${fmtEuro(Math.abs(discrepancy))}` : `+${fmtEuro(discrepancy)}`}
                      </span>
                    </div>
                  )}
                </div>
              )}

            </div>
          )}

          {/* ══ DETAILS SCREEN ══ */}
          {screen === 'details' && (
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {isLoading && <div style={{ padding: 40, textAlign: 'center', color: '#8a9099' }}>Φόρτωση…</div>}
              {summary && (
                <>
                  {/* Filter bars */}
                  <div style={{ padding: '10px 22px 8px', borderBottom: '1px solid #edeff1', flexShrink: 0 }}>
                    {/* Status filter */}
                    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>
                      {DETAIL_FILTER_STATUS.map(opt => (
                        <button
                          key={opt.key}
                          onClick={() => setStatusFilter(opt.key)}
                          style={{
                            padding: '4px 11px', borderRadius: 20, fontSize: 12, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap',
                            border: statusFilter === opt.key ? '1.5px solid #3758c9' : '1.5px solid #e5e7eb',
                            background: statusFilter === opt.key ? '#eff3ff' : '#fff',
                            color: statusFilter === opt.key ? '#3758c9' : '#5a6169',
                          }}
                        >{opt.label}</button>
                      ))}
                    </div>
                    {/* Payment filter */}
                    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                      {DETAIL_FILTER_PAYMENT.map(opt => (
                        <button
                          key={opt.key}
                          onClick={() => setPaymentFilter(opt.key)}
                          style={{
                            padding: '3px 10px', borderRadius: 20, fontSize: 11, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap',
                            border: paymentFilter === opt.key ? `1.5px solid ${opt.key === 'cash' ? SWATCH.cash : opt.key === 'card' ? SWATCH.card : '#6b7280'}` : '1.5px solid #e5e7eb',
                            background: paymentFilter === opt.key ? (opt.key === 'cash' ? '#f0fdf4' : opt.key === 'card' ? '#eff6ff' : '#f3f4f6') : '#fff',
                            color: paymentFilter === opt.key ? (opt.key === 'cash' ? '#15803d' : opt.key === 'card' ? '#1d4ed8' : '#374151') : '#5a6169',
                            display: 'inline-flex', alignItems: 'center', gap: 5,
                          }}
                        >
                          {opt.key !== 'any' && <span style={{ width: 7, height: 7, borderRadius: 2, background: opt.key === 'cash' ? SWATCH.cash : SWATCH.card, display: 'inline-block', flexShrink: 0 }} />}
                          {opt.label}
                        </button>
                      ))}
                    </div>
                  </div>
                  {/* Orders list */}
                  <div style={{ padding: '12px 22px 16px', overflowY: 'auto', maxHeight: 380 }}>
                    {summary.orders.length === 0 ? (
                      <p style={{ color: '#b8bdc4', fontSize: 13, textAlign: 'center', padding: '24px 0' }}>Δεν υπάρχουν αντικείμενα για αυτή τη βάρδια</p>
                    ) : (
                      summary.orders.map(o => (
                        <DetailOrderGroup
                          key={o.order_id}
                          order={o}
                          shiftWaiterId={waiterIdToUse}
                          statusFilter={statusFilter}
                          paymentFilter={paymentFilter}
                        />
                      ))
                    )}
                  </div>
                </>
              )}
            </div>
          )}

        </div>

        {/* ── Footer ── */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 22px 18px', borderTop: '1px solid #edeff1', background: '#f9fafb' }}>
          {mode === 'stats' ? (
            <>
              <span style={{ fontFamily: 'ui-monospace,monospace', fontSize: 10, letterSpacing: '0.04em', color: '#9ca3af' }}>
                Ζωντανή προβολή — η βάρδια συνεχίζεται
              </span>
              <div style={{ flex: 1 }} />
              <button onClick={onClose} style={{ height: 38, padding: '0 18px', borderRadius: 11, border: '1px solid #dfe2e6', background: '#fff', color: '#5a6169', fontSize: 14, fontWeight: 600, cursor: 'pointer' }}>Κλείσιμο</button>
            </>
          ) : closeStep === 1 ? (
            <>
              <button onClick={onClose} style={{ height: 38, padding: '0 16px', borderRadius: 11, border: '1px solid #dfe2e6', background: '#fff', color: '#5a6169', fontSize: 14, fontWeight: 600, cursor: 'pointer' }}>Άκυρο</button>
              <span style={{ fontFamily: 'ui-monospace,monospace', fontSize: 10, letterSpacing: '0.04em', color: '#9ca3af' }}>Επιβεβαίωσε τα ποσά πριν το κλείσιμο</span>
              <div style={{ flex: 1 }} />
              <button onClick={() => { setScreen('overview'); setCloseStep(2) }} style={{ height: 38, padding: '0 18px', borderRadius: 11, background: 'linear-gradient(180deg,#2f9e5e 0%,#1e7a46 100%)', color: '#fff', border: 'none', fontSize: 14, fontWeight: 600, cursor: 'pointer', boxShadow: '0 2px 6px rgba(30,122,70,0.32)' }}>
                Παράδοση μετρητών →
              </button>
            </>
          ) : (
            <>
              <button onClick={() => setCloseStep(1)} style={{ height: 38, padding: '0 16px', borderRadius: 11, border: '1px solid #dfe2e6', background: '#fff', color: '#5a6169', fontSize: 14, fontWeight: 600, cursor: 'pointer' }}>← Πίσω</button>
              <div style={{ flex: 1 }} />
              <button
                onClick={() => onConfirm(notes, countedCash !== '' ? parseFloat(countedCash) : null)}
                disabled={busy}
                style={{ height: 38, padding: '0 18px', borderRadius: 11, background: 'linear-gradient(180deg,#ef4444 0%,#dc2626 100%)', color: '#fff', border: 'none', fontSize: 14, fontWeight: 600, cursor: busy ? 'not-allowed' : 'pointer', opacity: busy ? 0.6 : 1, boxShadow: '0 2px 6px rgba(220,38,38,0.30)' }}
              >
                {busy ? 'Κλείσιμο…' : 'Οριστικό κλείσιμο'}
              </button>
            </>
          )}
        </div>

      </div>
      <style>{`@keyframes srPulse { 0%{box-shadow:0 0 0 0 rgba(34,197,94,.5)} 70%{box-shadow:0 0 0 6px rgba(34,197,94,0)} 100%{box-shadow:0 0 0 0 rgba(34,197,94,0)} }`}</style>
    </div>
  )
}

// ─── Compose for single waiter (quick message from shift row) ─────────────────

function QuickMessageModal({ waiter, tables, templates, onClose, onSent }) {
  const [body, setBody] = useState('')
  const sendMut = useMutation({
    mutationFn: (payload) => client.post('/api/notifications/send', payload),
    onSuccess: () => { toast.success('Εστάλη!'); onSent(); onClose() },
    onError: () => toast.error('Σφάλμα αποστολής'),
  })
  function send() {
    if (!body.trim()) return
    sendMut.mutate({ body: body.trim(), target_waiter_ids: [waiter.id], table_ids: [] })
  }
  return (
    <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4"
      onClick={e => { if (e.target === e.currentTarget) onClose() }}>
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-sm p-5 space-y-4">
        <div className="flex items-center justify-between">
          <div style={{ fontSize: 15, fontWeight: 700, color: '#111315' }}>💬 Μήνυμα σε {waiter.name}</div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 18, cursor: 'pointer', color: '#8a9099' }}>✕</button>
        </div>
        {templates.length > 0 && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {templates.map(t => (
              <button key={t.id} onClick={() => setBody(t.body)} style={{
                height: 26, padding: '0 10px', borderRadius: 6,
                border: `1px solid ${body === t.body ? '#3758c9' : '#dfe2e6'}`,
                background: body === t.body ? '#eff3ff' : '#f9fafb',
                color: body === t.body ? '#3758c9' : '#374151',
                fontSize: 11, cursor: 'pointer', fontFamily: 'inherit',
              }}>{t.body}</button>
            ))}
          </div>
        )}
        <textarea
          placeholder="Μήνυμα…"
          value={body}
          onChange={e => setBody(e.target.value)}
          rows={3}
          style={{ width: '100%', borderRadius: 10, border: '1.5px solid #dfe2e6', padding: '10px 14px', fontSize: 14, fontFamily: 'inherit', resize: 'vertical', outline: 'none', boxSizing: 'border-box', color: '#111315' }}
        />
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <button onClick={onClose} style={{ height: 36, padding: '0 16px', borderRadius: 8, border: '1px solid #dfe2e6', background: 'white', fontSize: 13, cursor: 'pointer' }}>Άκυρο</button>
          <button onClick={send} disabled={!body.trim() || sendMut.isPending}
            style={{ height: 36, padding: '0 16px', borderRadius: 8, background: '#3758c9', color: 'white', border: 'none', fontSize: 13, fontWeight: 600, cursor: 'pointer', opacity: !body.trim() ? 0.5 : 1 }}>
            {sendMut.isPending ? 'Αποστολή…' : '📤 Αποστολή'}
          </button>
        </div>
      </div>
    </div>
  )
}

function ShiftsCard({ activeShifts, waitersWithoutShift, isOpen, onStartShift, onEndShift, onViewStats, onMessageWaiter, privacyMode }) {
  return (
    <div style={{
      background: 'white', border: '1px solid #edeff1',
      borderRadius: 16, overflow: 'hidden',
      boxShadow: '0 1px 2px rgba(16,20,24,0.04)',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '16px 20px', borderBottom: '1px solid #edeff1',
      }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: '#111315' }}>Βάρδιες σε εξέλιξη</div>
        {isOpen && waitersWithoutShift.length > 0 && (
          <button
            onClick={onStartShift}
            style={{
              height: 30, padding: '0 12px', borderRadius: 8,
              border: '1px solid #dfe2e6', background: 'white',
              color: '#2b2f33', fontSize: 12, fontWeight: 600, cursor: 'pointer',
            }}
          >+ Έναρξη</button>
        )}
      </div>
      <div style={{ padding: '12px 20px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {activeShifts.length === 0 ? (
          <p style={{ fontSize: 13, color: '#8a9099', padding: '8px 0' }}>Κανένας σερβιτόρος σε βάρδια</p>
        ) : (
          activeShifts.map(s => {
            const activeBreak = Array.isArray(s.breaks) ? s.breaks.find(b => !b.ended_at) : null
            return (
              <div key={s.id} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '10px 12px', borderRadius: 12,
                border: activeBreak ? '1px solid #fed7aa' : '1px solid #edeff1',
                background: activeBreak ? '#fff7ed' : '#fafafa',
                transition: 'background 200ms, border-color 200ms',
              }}>
                <Avatar name={s.waiter_name} avatarUrl={s.avatar_url ?? null} size={36} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                    <span style={{ fontSize: 14, fontWeight: 600, color: '#111315' }}>{s.waiter_name}</span>
                    {activeBreak && (
                      <span style={{
                        display: 'inline-flex', alignItems: 'center', gap: 4,
                        padding: '2px 8px', borderRadius: 999,
                        background: '#fed7aa', color: '#9a3412',
                        fontSize: 11, fontWeight: 700,
                      }}>
                        ☕ Διάλειμμα · {fmtDuration(activeBreak.started_at)}
                      </span>
                    )}
                  </div>
                  <div style={{ fontSize: 11, color: '#5a6169', marginTop: 1 }}>
                    από {fmtTime(s.started_at)} · {fmtDuration(s.started_at)}
                    {s.total_collected > 0 && (
                      <span style={{
                        color: '#2f9e5e', fontWeight: 600, marginLeft: 6,
                        filter: privacyMode ? 'blur(6px)' : 'none',
                        userSelect: privacyMode ? 'none' : 'auto',
                        transition: 'filter 200ms ease',
                      }}>{fmtEuro(s.total_collected)}</span>
                    )}
                  </div>
                </div>
                <button
                  onClick={() => onMessageWaiter(s)}
                  title="Αποστολή μηνύματος"
                  style={{
                    height: 28, width: 28, borderRadius: 8, flexShrink: 0,
                    border: '1px solid #dfe2e6', background: 'white',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 14, cursor: 'pointer',
                  }}
                >💬</button>
                <button
                  onClick={() => onViewStats(s)}
                  title="Στατιστικά βάρδιας"
                  style={{
                    height: 28, padding: '0 9px', borderRadius: 8, flexShrink: 0,
                    border: '1px solid #dfe2e6', background: '#fff',
                    color: '#5a6169', fontSize: 11, fontWeight: 600, cursor: 'pointer',
                  }}
                >Στατιστικά</button>
                <button
                  onClick={() => onEndShift(s)}
                  style={{
                    height: 28, padding: '0 10px', borderRadius: 8,
                    border: '1px solid #fecaca', background: '#fef2f2',
                    color: '#dc2626', fontSize: 11, fontWeight: 600, cursor: 'pointer', flexShrink: 0,
                  }}
                >Τέλος</button>
              </div>
            )
          })
        )}
      </div>
    </div>
  )
}

// ─── Revenue bar chart ─────────────────────────────────────────────────────────

function RevenueChart({ orders }) {
  const now = new Date()
  const currentHour = now.getHours()
  const buckets = {}
  for (let h = 10; h <= 23; h++) buckets[h] = 0
  orders.forEach(o => {
    const h = new Date(o.opened_at).getHours()
    if (h >= 10 && h <= 23) buckets[h] = (buckets[h] || 0) + orderTotal(o.items)
  })
  const hours = Object.keys(buckets).map(Number)
  const max = Math.max(...Object.values(buckets), 1)

  return (
    <div style={{
      background: 'white', border: '1px solid #edeff1',
      borderRadius: 16, padding: '16px 20px',
      boxShadow: '0 1px 2px rgba(16,20,24,0.04)',
    }}>
      <div style={{ fontSize: 14, fontWeight: 700, color: '#111315', marginBottom: 16 }}>Έσοδα ανά ώρα</div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 3, height: 90 }}>
        {hours.map(h => {
          const val = buckets[h]
          const heightPct = (val / max) * 100
          const isCurrent = h === currentHour
          const isFuture = h > currentHour
          return (
            <div key={h} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, height: '100%' }}>
              <div style={{ flex: 1, width: '100%', display: 'flex', alignItems: 'flex-end' }}>
                <div title={fmtEuro(val)} style={{
                  width: '100%', height: val > 0 ? `${heightPct}%` : '3px',
                  minHeight: val > 0 ? 4 : 3, borderRadius: 4,
                  background: isCurrent ? '#3758c9' : isFuture ? '#edeff1' : '#c2cff0',
                  transition: 'height 300ms ease',
                }} />
              </div>
              <div style={{
                fontSize: 9, fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace",
                color: isCurrent ? '#3758c9' : '#8a9099', fontWeight: isCurrent ? 700 : 500,
              }}>{h}</div>
            </div>
          )
        })}
      </div>
    </div>
  )
}

// ─── Reservations ─────────────────────────────────────────────────────────────

const STATUS_META = {
  pending:   { label: 'Αναμονή',    bg: '#f0f4ff', color: '#3758c9' },
  arrived:   { label: 'Έφτασε',     bg: '#eef7f0', color: '#1f7042' },
  cancelled: { label: 'Ακυρώθηκε', bg: '#fef2f2', color: '#dc2626' },
  no_show:   { label: 'Δεν ήρθε',  bg: '#fff7ed', color: '#c2410c' },
}

function ReservationRow({ res, tables, onStatusChange, onEdit }) {
  const meta = STATUS_META[res.status] || STATUS_META.pending
  const time = new Date(res.reserved_for).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })
  const dateStr = new Date(res.reserved_for).toLocaleDateString('el-GR', { day: 'numeric', month: 'short' })
  const tableLabel = res.table_label || (res.table_id ? `#${res.table_id}` : null)

  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '10px 16px',
      borderBottom: '1px solid #f3f4f6',
    }}>
      {/* Time block */}
      <div style={{
        minWidth: 44, textAlign: 'center', flexShrink: 0,
        fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace",
      }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: '#111315', lineHeight: 1 }}>{time}</div>
        <div style={{ fontSize: 10, color: '#8a9099', marginTop: 2 }}>{dateStr}</div>
      </div>

      {/* Info */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 13, fontWeight: 700, color: '#111315',
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>{res.guest_name}</div>
        <div style={{ fontSize: 11, color: '#5a6169', marginTop: 2, display: 'flex', gap: 6 }}>
          <span>👥 {res.party_size}</span>
          {tableLabel && <span>🪑 {tableLabel}</span>}
          {res.phone && <span>📞 {res.phone}</span>}
        </div>
      </div>

      {/* Status pill */}
      <span style={{
        padding: '2px 8px', borderRadius: 999, fontSize: 10, fontWeight: 700, flexShrink: 0,
        background: meta.bg, color: meta.color,
      }}>{meta.label}</span>

      {/* Actions */}
      <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
        <button onClick={() => onEdit(res)} title="Επεξεργασία" style={{
          width: 26, height: 26, borderRadius: 6, border: '1px solid #dfe2e6',
          background: 'white', cursor: 'pointer', fontSize: 12,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>✏️</button>
        {res.status === 'pending' && (
          <button onClick={() => onStatusChange(res.id, 'arrived')} title="Έφτασε" style={{
            width: 26, height: 26, borderRadius: 6, border: '1px solid #bbf7d0',
            background: '#eef7f0', cursor: 'pointer', fontSize: 12,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>✅</button>
        )}
        {(res.status === 'pending' || res.status === 'no_show') && (
          <button onClick={() => onStatusChange(res.id, 'cancelled')} title="Ακύρωση" style={{
            width: 26, height: 26, borderRadius: 6, border: '1px solid #fecaca',
            background: '#fef2f2', cursor: 'pointer', fontSize: 12,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>✖</button>
        )}
      </div>
    </div>
  )
}

function ReservationsCard({ tables, onNew }) {
  const [tab, setTab] = useState('upcoming')
  const qc = useQueryClient()

  const { data: reservations = [], isLoading } = useQuery({
    queryKey: ['reservations', tab],
    queryFn: () => client.get(`/api/reservations/?tab=${tab}`).then(r => r.data),
    refetchInterval: 30_000,
  })

  const [editTarget, setEditTarget] = useState(null)

  const statusMut = useMutation({
    mutationFn: ({ id, status }) => client.patch(`/api/reservations/${id}/status`, { status }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['reservations'] })
      qc.invalidateQueries({ queryKey: ['tables'] })
    },
    onError: () => toast.error('Σφάλμα ενημέρωσης'),
  })

  const tabStyle = (active) => ({
    height: 30, padding: '0 14px', borderRadius: 8, border: 'none',
    background: active ? '#f0f4ff' : 'transparent',
    color: active ? '#3758c9' : '#5a6169',
    fontSize: 12, fontWeight: 700, cursor: 'pointer',
  })

  return (
    <>
      <div style={{
        background: 'white', border: '1px solid #edeff1',
        borderRadius: 16, overflow: 'hidden',
        boxShadow: '0 1px 2px rgba(16,20,24,0.04)',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '12px 16px', borderBottom: '1px solid #edeff1',
        }}>
          <div style={{ display: 'flex', gap: 4 }}>
            <button style={tabStyle(tab === 'upcoming')} onClick={() => setTab('upcoming')}>Επερχόμενες</button>
            <button style={tabStyle(tab === 'history')} onClick={() => setTab('history')}>Ιστορικό</button>
          </div>
          <button onClick={onNew} style={{
            height: 28, padding: '0 12px', borderRadius: 8,
            border: '1px solid #dfe2e6', background: 'white',
            color: '#3758c9', fontSize: 12, fontWeight: 700, cursor: 'pointer',
          }}>+ Νέα</button>
        </div>

        {isLoading ? (
          <div style={{ padding: '24px', textAlign: 'center', color: '#b8bdc4', fontSize: 13 }}>Φόρτωση…</div>
        ) : reservations.length === 0 ? (
          <div style={{ padding: '32px 20px', textAlign: 'center', color: '#b8bdc4', fontSize: 13 }}>
            <div style={{ fontSize: 26, marginBottom: 8 }}>📅</div>
            {tab === 'upcoming' ? 'Καμία επερχόμενη κράτηση' : 'Κανένα ιστορικό'}
          </div>
        ) : (
          <div style={{ maxHeight: 340, overflowY: 'auto' }}>
            {reservations.map(r => (
              <ReservationRow
                key={r.id}
                res={r}
                tables={tables}
                onStatusChange={(id, s) => statusMut.mutate({ id, status: s })}
                onEdit={setEditTarget}
              />
            ))}
          </div>
        )}
      </div>

      {editTarget && (
        <ReservationModal
          tables={tables}
          initial={editTarget}
          onClose={() => setEditTarget(null)}
          onSaved={() => {
            setEditTarget(null)
            qc.invalidateQueries({ queryKey: ['reservations'] })
            qc.invalidateQueries({ queryKey: ['tables'] })
          }}
        />
      )}
    </>
  )
}

// ─── New / Edit Reservation Modal ─────────────────────────────────────────────

function toLocalISO(d) {
  const pad = n => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:00`
}

function DateTimePicker({ value, onChange }) {
  // value: Date object
  const pad = n => String(n).padStart(2, '0')
  const toLocal = (d) => {
    const y = d.getFullYear()
    const mo = pad(d.getMonth() + 1)
    const dy = pad(d.getDate())
    const h = pad(d.getHours())
    const mi = pad(d.getMinutes())
    return `${y}-${mo}-${dy}T${h}:${mi}`
  }
  const fromLocal = (s) => new Date(s)

  const quickOffsets = [
    { label: '+30λ', mins: 30 },
    { label: '+1ω', mins: 60 },
    { label: '+2ω', mins: 120 },
    { label: '+3ω', mins: 180 },
    { label: '+5ω', mins: 300 },
    { label: '+1μ', days: 1 },
    { label: '+2μ', days: 2 },
    { label: '+7μ', days: 7 },
  ]

  function applyOffset(offset) {
    const base = new Date()
    if (offset.mins) base.setMinutes(base.getMinutes() + offset.mins)
    else if (offset.days) { base.setDate(base.getDate() + offset.days); base.setSeconds(0, 0) }
    onChange(base)
  }

  return (
    <div>
      <input
        type="datetime-local"
        value={toLocal(value)}
        onChange={e => onChange(fromLocal(e.target.value))}
        style={{
          width: '100%', height: 38, borderRadius: 8,
          border: '1px solid #dfe2e6', padding: '0 12px',
          fontSize: 14, fontFamily: 'inherit', marginBottom: 8,
        }}
      />
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {quickOffsets.map(o => (
          <button key={o.label} type="button" onClick={() => applyOffset(o)} style={{
            height: 28, padding: '0 10px', borderRadius: 6,
            border: '1px solid #dfe2e6', background: '#f8f9fa',
            fontSize: 12, fontWeight: 600, color: '#374151', cursor: 'pointer',
          }}>{o.label}</button>
        ))}
      </div>
    </div>
  )
}

function GroupedTableSelect({ tables, value, onChange }) {
  // Group tables by group_id
  const groups = {}
  for (const t of tables) {
    const key = t.group?.name || 'Χωρίς ζώνη'
    if (!groups[key]) groups[key] = []
    groups[key].push(t)
  }
  return (
    <select
      value={value ?? ''}
      onChange={e => onChange(e.target.value ? Number(e.target.value) : null)}
      style={{
        width: '100%', height: 38, borderRadius: 8,
        border: '1px solid #dfe2e6', padding: '0 12px',
        fontSize: 14, fontFamily: 'inherit', background: 'white',
      }}
    >
      <option value="">— Χωρίς τραπέζι —</option>
      {Object.entries(groups).map(([groupName, gtables]) => (
        <optgroup key={groupName} label={groupName}>
          {gtables.map(t => (
            <option key={t.id} value={t.id}>
              {t.label || `T${t.number}`}
            </option>
          ))}
        </optgroup>
      ))}
    </select>
  )
}

function ReservationModal({ tables, initial, onClose, onSaved }) {
  const isEdit = !!initial?.id
  const [guestName, setGuestName] = useState(initial?.guest_name ?? '')
  const [partySize, setPartySize] = useState(initial?.party_size ?? 2)
  const [phone, setPhone] = useState(initial?.phone ?? '')
  const [email, setEmail] = useState(initial?.email ?? '')
  const [note, setNote] = useState(initial?.note ?? '')
  const [tableId, setTableId] = useState(initial?.table_id ?? null)
  const [reservedFor, setReservedFor] = useState(
    initial?.reserved_for ? new Date(initial.reserved_for) : new Date()
  )

  const saveMut = useMutation({
    mutationFn: (payload) => isEdit
      ? client.patch(`/api/reservations/${initial.id}`, payload)
      : client.post('/api/reservations/', payload),
    onSuccess: () => { toast.success(isEdit ? 'Αποθηκεύτηκε!' : 'Κράτηση δημιουργήθηκε!'); onSaved() },
    onError: () => toast.error('Σφάλμα αποθήκευσης'),
  })

  function submit(e) {
    e.preventDefault()
    if (!guestName.trim()) return toast.error('Εισάγετε όνομα')
    if (partySize < 1) return toast.error('Αριθμός ατόμων > 0')
    saveMut.mutate({
      guest_name: guestName.trim(),
      party_size: partySize,
      phone: phone.trim() || null,
      email: email.trim() || null,
      note: note.trim() || null,
      table_id: tableId,
      reserved_for: toLocalISO(reservedFor),
    })
  }

  const labelStyle = { fontSize: 12, fontWeight: 700, color: '#5a6169', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6, display: 'block' }
  const inputStyle = { width: '100%', height: 38, borderRadius: 8, border: '1px solid #dfe2e6', padding: '0 12px', fontSize: 14, fontFamily: 'inherit', boxSizing: 'border-box' }

  return (
    <div
      onClick={e => { if (e.target === e.currentTarget) onClose() }}
      style={{
        position: 'fixed', inset: 0, zIndex: 9000,
        background: 'rgba(0,0,0,0.4)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 16,
      }}
    >
      <div style={{
        background: 'white', borderRadius: 16, width: '100%', maxWidth: 520,
        boxShadow: '0 20px 60px rgba(0,0,0,0.2)',
        maxHeight: '90vh', overflowY: 'auto',
      }}>
        {/* Header */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '18px 24px', borderBottom: '1px solid #edeff1',
        }}>
          <div style={{ fontSize: 16, fontWeight: 700, color: '#111315' }}>
            {isEdit ? 'Επεξεργασία Κράτησης' : 'Νέα Κράτηση'}
          </div>
          <button onClick={onClose} style={{
            width: 30, height: 30, borderRadius: 8, border: '1px solid #edeff1',
            background: 'white', fontSize: 16, cursor: 'pointer', lineHeight: 1,
          }}>×</button>
        </div>

        <form onSubmit={submit} style={{ padding: '20px 24px', display: 'flex', flexDirection: 'column', gap: 16 }}>

          {/* Name + Party size on same row */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 12 }}>
            <div>
              <label style={labelStyle}>Όνομα</label>
              <input
                style={inputStyle}
                value={guestName}
                onChange={e => setGuestName(e.target.value)}
                placeholder="Ονοματεπώνυμο πελάτη"
                required
              />
            </div>
            <div>
              <label style={labelStyle}>Άτομα</label>
              <input
                type="number" min={1} max={999}
                style={{ ...inputStyle, width: 80 }}
                value={partySize}
                onChange={e => setPartySize(Number(e.target.value))}
              />
            </div>
          </div>

          {/* Date/time */}
          <div>
            <label style={labelStyle}>Ημερομηνία & Ώρα</label>
            <DateTimePicker value={reservedFor} onChange={setReservedFor} />
          </div>

          {/* Table */}
          <div>
            <label style={labelStyle}>Τραπέζι (προαιρετικό)</label>
            <GroupedTableSelect tables={tables} value={tableId} onChange={setTableId} />
          </div>

          {/* Phone + Email */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div>
              <label style={labelStyle}>Τηλέφωνο</label>
              <input style={inputStyle} value={phone} onChange={e => setPhone(e.target.value)} placeholder="69xxxxxxxx" />
            </div>
            <div>
              <label style={labelStyle}>Email</label>
              <input style={inputStyle} type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="email@..." />
            </div>
          </div>

          {/* Note */}
          <div>
            <label style={labelStyle}>Σημείωση</label>
            <textarea
              value={note}
              onChange={e => setNote(e.target.value)}
              placeholder="Εσωτερική σημείωση για το προσωπικό…"
              style={{
                width: '100%', minHeight: 70, borderRadius: 8,
                border: '1px solid #dfe2e6', padding: '8px 12px',
                fontSize: 14, fontFamily: 'inherit', resize: 'vertical', boxSizing: 'border-box',
              }}
            />
          </div>

          {/* Footer */}
          <div style={{
            display: 'flex', justifyContent: 'flex-end', gap: 8,
            paddingTop: 8, borderTop: '1px solid #edeff1',
          }}>
            <button type="button" onClick={onClose} style={{
              height: 38, padding: '0 18px', borderRadius: 8,
              border: '1px solid #dfe2e6', background: 'white',
              fontSize: 14, fontWeight: 600, cursor: 'pointer', color: '#374151',
            }}>Άκυρο</button>
            <button type="submit" disabled={saveMut.isPending} style={{
              height: 38, padding: '0 22px', borderRadius: 8,
              border: 'none', background: '#3758c9',
              color: 'white', fontSize: 14, fontWeight: 700, cursor: 'pointer',
            }}>{saveMut.isPending ? 'Αποθήκευση…' : isEdit ? 'Αποθήκευση' : 'Δημιουργία'}</button>
          </div>
        </form>
      </div>
    </div>
  )
}

// ─── Messages card ────────────────────────────────────────────────────────────

function ComposeModal({ waiters, tables, templates, onClose, onSent }) {
  const [selectedWaiters, setSelectedWaiters] = useState([])   // [] = all
  const [selectedTables, setSelectedTables] = useState([])
  const [body, setBody] = useState('')

  const sendMut = useMutation({
    mutationFn: (payload) => client.post('/api/notifications/send', payload),
    onSuccess: () => { toast.success('Εστάλη!'); onSent(); onClose() },
    onError: () => toast.error('Σφάλμα αποστολής'),
  })

  function toggleWaiter(id) {
    setSelectedWaiters(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id])
  }
  function toggleTable(id) {
    setSelectedTables(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id])
  }

  function send() {
    if (!body.trim()) return
    sendMut.mutate({
      body: body.trim(),
      target_waiter_ids: selectedWaiters,  // [] = broadcast all
      table_ids: selectedTables,
    })
  }

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 9999,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    }} onClick={onClose}>
      <div style={{
        background: 'white', borderRadius: 20, width: '100%', maxWidth: 520,
        padding: 24, boxShadow: '0 24px 64px rgba(0,0,0,0.22)',
      }} onClick={e => e.stopPropagation()}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
          <div style={{ fontSize: 16, fontWeight: 700, color: '#111315' }}>Νέο Μήνυμα</div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 20, cursor: 'pointer', color: '#8a9099' }}>✕</button>
        </div>

        {/* Recipients */}
        <div style={{ marginBottom: 16 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: '#5a6169', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8 }}>
            Παραλήπτες {selectedWaiters.length === 0 && <span style={{ color: '#3758c9', fontWeight: 700 }}>(Όλοι)</span>}
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {waiters.map(w => {
              const name = w.nickname || w.full_name || w.username
              const sel = selectedWaiters.includes(w.id)
              return (
                <button key={w.id} onClick={() => toggleWaiter(w.id)} style={{
                  height: 30, padding: '0 12px', borderRadius: 999,
                  border: '1.5px solid ' + (sel ? '#3758c9' : '#dfe2e6'),
                  background: sel ? '#eff3ff' : 'white',
                  color: sel ? '#3758c9' : '#374151',
                  fontSize: 12, fontWeight: sel ? 700 : 500, cursor: 'pointer',
                }}>{name}</button>
              )
            })}
          </div>
        </div>

        {/* Tables (optional) */}
        {tables.length > 0 && (
          <div style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: '#5a6169', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8 }}>
              Σχετικά Τραπέζια (προαιρετικό)
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, maxHeight: 80, overflowY: 'auto' }}>
              {tables.map(t => {
                const name = t.label || `T${t.number}`
                const sel = selectedTables.includes(t.id)
                return (
                  <button key={t.id} onClick={() => toggleTable(t.id)} style={{
                    height: 28, padding: '0 10px', borderRadius: 6,
                    border: '1.5px solid ' + (sel ? '#7a44c9' : '#dfe2e6'),
                    background: sel ? '#f5eeff' : 'white',
                    color: sel ? '#7a44c9' : '#374151',
                    fontSize: 12, fontWeight: sel ? 700 : 500, cursor: 'pointer',
                  }}>{name}</button>
                )
              })}
            </div>
          </div>
        )}

        {/* Quick templates */}
        {templates.length > 0 && (
          <div style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: '#5a6169', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8 }}>Γρήγορα Μηνύματα</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {templates.map(t => (
                <button key={t.id} onClick={() => setBody(t.body)} style={{
                  height: 28, padding: '0 12px', borderRadius: 6,
                  border: '1px solid ' + (body === t.body ? '#3758c9' : '#dfe2e6'),
                  background: body === t.body ? '#eff3ff' : '#f9fafb',
                  color: body === t.body ? '#3758c9' : '#374151',
                  fontSize: 12, cursor: 'pointer', fontFamily: 'inherit',
                }}>{t.body}</button>
              ))}
            </div>
          </div>
        )}

        {/* Custom body */}
        <textarea
          placeholder="Ή γράψτε το δικό σας μήνυμα…"
          value={body}
          onChange={e => setBody(e.target.value)}
          rows={3}
          style={{
            width: '100%', borderRadius: 10, border: '1.5px solid #dfe2e6',
            padding: '10px 14px', fontSize: 14, fontFamily: 'inherit',
            resize: 'vertical', outline: 'none', boxSizing: 'border-box',
            color: '#111315',
          }}
        />

        <div style={{ display: 'flex', gap: 10, marginTop: 16, justifyContent: 'flex-end' }}>
          <button onClick={onClose} style={{ height: 38, padding: '0 18px', borderRadius: 8, border: '1px solid #dfe2e6', background: 'white', fontSize: 13, cursor: 'pointer' }}>Άκυρο</button>
          <button
            onClick={send}
            disabled={!body.trim() || sendMut.isPending}
            style={{ height: 38, padding: '0 20px', borderRadius: 8, background: '#3758c9', color: 'white', border: 'none', fontSize: 13, fontWeight: 600, cursor: 'pointer', opacity: !body.trim() ? 0.5 : 1 }}
          >{sendMut.isPending ? 'Αποστολή…' : '📤 Αποστολή'}</button>
        </div>
      </div>
    </div>
  )
}

function MessagesCard({ waiters, tables }) {
  const qc = useQueryClient()
  const [composing, setComposing] = useState(false)

  const { data: messages = [] } = useQuery({
    queryKey: ['messages-all'],
    queryFn: () => client.get('/api/notifications/all?limit=20').then(r => r.data),
    refetchInterval: 10_000,
  })

  const { data: templates = [] } = useQuery({
    queryKey: ['quick-templates'],
    queryFn: () => client.get('/api/notifications/templates').then(r => r.data),
    staleTime: 60_000,
  })

  function parseJsonField(val) {
    if (Array.isArray(val)) return val
    try { return JSON.parse(val || '[]') } catch { return [] }
  }

  function fmtTargets(msg) {
    const ids = parseJsonField(msg.target_waiter_ids)
    if (ids.length === 0) return 'Όλοι'
    return ids.map(id => {
      const w = waiters.find(w => w.id === id)
      return w ? (w.nickname || w.full_name || w.username) : `#${id}`
    }).join(', ')
  }

  return (
    <>
      {composing && (
        <ComposeModal
          waiters={waiters}
          tables={tables}
          templates={templates}
          onClose={() => setComposing(false)}
          onSent={() => qc.invalidateQueries({ queryKey: ['messages-all'] })}
        />
      )}
      <div style={{
        background: 'white', border: '1px solid #edeff1',
        borderRadius: 16, overflow: 'hidden',
        boxShadow: '0 1px 2px rgba(16,20,24,0.04)',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '16px 20px', borderBottom: '1px solid #edeff1',
        }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: '#111315' }}>Μηνύματα</div>
          <button
            onClick={() => setComposing(true)}
            style={{
              height: 28, padding: '0 12px', borderRadius: 8,
              border: '1px solid #dfe2e6', background: 'white',
              color: '#5a6169', fontSize: 12, fontWeight: 600, cursor: 'pointer',
            }}
          >+ Νέο</button>
        </div>

        {messages.length === 0 ? (
          <div style={{ padding: '32px 20px', textAlign: 'center', color: '#b8bdc4', fontSize: 13 }}>
            <div style={{ fontSize: 28, marginBottom: 8 }}>💬</div>
            Δεν υπάρχουν μηνύματα ακόμα
          </div>
        ) : (
          <div style={{ maxHeight: 300, overflowY: 'auto' }}>
            {messages.map(msg => {
              const ackedIds = parseJsonField(msg.acked_by).length
              const totalTargets = parseJsonField(msg.target_waiter_ids).length || waiters.length
              return (
                <div key={msg.id} style={{
                  padding: '10px 20px', borderBottom: '1px solid #f4f4f2',
                  display: 'flex', gap: 12, alignItems: 'flex-start',
                }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: '#111315', marginBottom: 2 }}>{msg.body}</div>
                    <div style={{ fontSize: 11, color: '#8a9099' }}>
                      Προς: {fmtTargets(msg)} · {new Date(msg.created_at).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })}
                    </div>
                  </div>
                  <div style={{
                    fontSize: 11, fontWeight: 700,
                    color: ackedIds >= totalTargets ? '#16a34a' : '#f59e0b',
                    background: ackedIds >= totalTargets ? '#f0fdf4' : '#fffbeb',
                    border: `1px solid ${ackedIds >= totalTargets ? '#bbf7d0' : '#fde68a'}`,
                    borderRadius: 999, padding: '2px 8px', whiteSpace: 'nowrap', flexShrink: 0,
                  }}>
                    {ackedIds}/{totalTargets} ✓
                  </div>
                </div>
              )
            })}
          </div>
        )}
      </div>
    </>
  )
}

// ─── Notes & Todos card ───────────────────────────────────────────────────────

function NotesCard() {
  const navigate = useNavigate()
  const hoverTimer = useRef(null)
  const [showPopover, setShowPopover] = useState(false)
  const cardRef = useRef(null)

  const { data: notes = [] } = useQuery({
    queryKey: ['dashboard-notes'],
    queryFn: () => client.get('/api/notes/').then(r => r.data),
    staleTime: 30_000,
    refetchInterval: 60_000,
  })

  const { data: todos = [] } = useQuery({
    queryKey: ['dashboard-todos'],
    queryFn: () => client.get('/api/notes/todos').then(r => r.data),
    staleTime: 30_000,
    refetchInterval: 60_000,
  })

  const pinnedNotes = notes.filter(n => n.is_pinned)
  const highTodos = todos.filter(t => !t.is_done && t.priority === 'high')
  const recentNotes = notes.filter(n => !n.is_pinned).slice(0, 3)
  const previewItems = [
    ...pinnedNotes.map(n => ({ ...n, _type: 'note' })),
    ...highTodos.map(t => ({ ...t, _type: 'todo' })),
    ...recentNotes.map(n => ({ ...n, _type: 'note' })),
  ].slice(0, 6)

  function handleMouseEnter() {
    hoverTimer.current = setTimeout(() => setShowPopover(true), 1000)
  }

  function handleMouseLeave() {
    clearTimeout(hoverTimer.current)
    setShowPopover(false)
  }

  return (
    <div
      ref={cardRef}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
      style={{ position: 'relative' }}
    >
      <div
        onClick={() => navigate('/notes')}
        style={{
          background: 'white', border: '1px solid #edeff1',
          borderRadius: 16, overflow: 'hidden',
          boxShadow: '0 1px 2px rgba(16,20,24,0.04)',
          cursor: 'pointer', transition: 'box-shadow 150ms',
        }}
        onMouseEnter={e => e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.08)'}
        onMouseLeave={e => e.currentTarget.style.boxShadow = '0 1px 2px rgba(16,20,24,0.04)'}
      >
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '16px 20px',
        }}>
          <div>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#111315' }}>Notes & Todos</div>
            <div style={{ fontSize: 12, color: '#8a9099', marginTop: 2 }}>
              {notes.length} σημειώσεις · {todos.filter(t => !t.is_done).length} εκκρεμή todos
            </div>
          </div>
          <div style={{
            display: 'flex', gap: 6,
          }}>
            {pinnedNotes.length > 0 && (
              <span style={{
                padding: '3px 8px', borderRadius: 999, fontSize: 11, fontWeight: 700,
                background: '#fef3c7', color: '#d97706',
              }}>📌 {pinnedNotes.length}</span>
            )}
            <span style={{
              padding: '3px 8px', borderRadius: 999, fontSize: 11, fontWeight: 600,
              background: '#f4f4f2', color: '#5a6169',
            }}>→</span>
          </div>
        </div>
      </div>

      {showPopover && previewItems.length > 0 && (
        <div style={{
          position: 'absolute', top: '100%', left: 0, right: 0, zIndex: 100,
          marginTop: 6,
          background: 'white',
          border: '1px solid #edeff1',
          borderRadius: 14,
          boxShadow: '0 8px 24px rgba(0,0,0,0.12)',
          overflow: 'hidden',
        }}>
          {previewItems.map((item, i) => (
            <div key={`${item._type}-${item.id}`} style={{
              padding: '10px 16px',
              borderBottom: i < previewItems.length - 1 ? '1px solid #f4f4f2' : 'none',
              display: 'flex', alignItems: 'flex-start', gap: 8,
            }}>
              <span style={{ fontSize: 12, flexShrink: 0, marginTop: 1 }}>
                {item._type === 'todo' ? (item.is_done ? '✅' : '☐') : (item.is_pinned ? '📌' : '📄')}
              </span>
              <span style={{
                fontSize: 12.5, color: '#111315', lineHeight: 1.5,
                overflow: 'hidden', display: '-webkit-box', WebkitLineClamp: 2,
                WebkitBoxOrient: 'vertical',
                textDecoration: item.is_done ? 'line-through' : 'none',
                opacity: item.is_done ? 0.5 : 1,
              }}>{item.body}</span>
            </div>
          ))}
          <div style={{
            padding: '8px 16px', background: '#fafafa', borderTop: '1px solid #f4f4f2',
            fontSize: 11, color: '#8a9099', cursor: 'pointer', textAlign: 'center',
          }}
            onClick={() => navigate('/notes')}
          >Άνοιγμα Notes →</div>
        </div>
      )}
    </div>
  )
}

// ─── Pending prints panel ──────────────────────────────────────────────────────

function PendingPrintsPanel({ pendingPrintOrders, onRetryAll, onRetrySingle, onViewOrder, retryingId }) {
  if (pendingPrintOrders.length === 0) return null
  return (
    <div style={{
      background: 'white', borderRadius: 16, overflow: 'hidden',
      border: '1px solid #fed7aa', boxShadow: '0 1px 2px rgba(16,20,24,0.04)',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 20px', background: '#fff7ed', borderBottom: '1px solid #fed7aa',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 18 }}>⏳</span>
          <div>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#9a3412' }}>Εκκρεμείς Εκτυπώσεις</div>
            <div style={{ fontSize: 12, color: '#c2410c', marginTop: 1 }}>
              {pendingPrintOrders.length} παραγγελί{pendingPrintOrders.length !== 1 ? 'ες' : 'α'} δεν έχ{pendingPrintOrders.length !== 1 ? 'ουν' : 'ει'} σταλεί
            </div>
          </div>
        </div>
        <button
          onClick={onRetryAll} disabled={retryingId !== null}
          style={{
            height: 32, padding: '0 14px', borderRadius: 8,
            background: '#c2410c', border: 'none', color: 'white',
            fontSize: 12, fontWeight: 600, cursor: 'pointer',
          }}
        >{retryingId !== null ? 'Αποστολή…' : 'Αποστολή Όλων'}</button>
      </div>
      {pendingPrintOrders.map(({ table, order }) => {
        const unprinted = order.items.filter(i => i.status === 'active' && !i.printed)
        const tableName = table.label || `T${table.number}`
        const openedAt = order.opened_at
          ? new Date(order.opened_at).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })
          : null
        const retryCount = order.print_jobs
          ? Math.max(0, ...order.print_jobs.filter(j => j.status === 'pending').map(j => j.retry_count || 0))
          : 0
        return (
          <div key={order.id} style={{
            display: 'flex', alignItems: 'center', gap: 14,
            padding: '10px 20px', borderBottom: '1px solid #fff7ed',
          }}>
            <div style={{
              width: 36, height: 36, borderRadius: 8, flexShrink: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontWeight: 700, fontSize: 12, background: '#fff7ed', color: '#c2410c',
              border: '1px solid #fed7aa', fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace",
            }}>{tableName}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                <span style={{ fontSize: 13, fontWeight: 600, color: '#111315' }}>
                  #{order.id}
                </span>
                {openedAt && (
                  <span style={{ fontSize: 11, color: '#5a6169' }}>{openedAt}</span>
                )}
                {retryCount > 0 && (
                  <span style={{
                    fontSize: 10, fontWeight: 700, color: '#c2410c',
                    background: '#fff7ed', border: '1px solid #fed7aa',
                    borderRadius: 6, padding: '1px 6px',
                  }}>
                    {retryCount} επαν.
                  </span>
                )}
              </div>
              <div style={{ fontSize: 11, color: '#5a6169', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {unprinted.length} αντ. εκκρεμούν · {unprinted.map(i => i.product?.name || `#${i.product_id}`).join(', ')}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
              <button onClick={() => onViewOrder(order.id)} className="btn btn-secondary text-xs">Λεπτομέρειες</button>
              <button
                onClick={() => onRetrySingle(order.id)} disabled={retryingId === order.id}
                style={{
                  height: 28, padding: '0 10px', borderRadius: 6,
                  background: '#c2410c', border: 'none', color: 'white',
                  fontSize: 11, fontWeight: 600, cursor: 'pointer',
                }}
              >{retryingId === order.id ? '…' : 'Εκτύπωση'}</button>
            </div>
          </div>
        )
      })}
    </div>
  )
}

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

export default function DashboardPage() {
  const [showStartShift, setShowStartShift] = useState(false)
  const [retryingId, setRetryingId] = useState(null)
  const [quickView, setQuickView] = useState(null)
  const [licenseBlock, setLicenseBlock] = useState(null) // { code, message } when open is blocked
  // End shift flow: confirm modal → summary modal
  const [endShiftTarget, setEndShiftTarget] = useState(null)     // shift object → close mode
  const [shiftStatsTarget, setShiftStatsTarget] = useState(null) // shift object → stats-only mode
  const [endShiftBusy, setEndShiftBusy] = useState(false)
  // Quick message to single waiter
  const [messageWaiter, setMessageWaiter] = useState(null)     // { id, name }
  const [privacyMode, setPrivacyMode] = useState(() => localStorage.getItem('privacyMode') === 'true')
  // Workday summary modal: 'close' = close-day flow, 'view' = read-only stats
  const [workdaySummaryMode, setWorkdaySummaryMode] = useState(null)
  const [showNewReservation, setShowNewReservation] = useState(false)
  const navigate = useNavigate()
  const qc = useQueryClient()
  const license = useContext(LicenseContext)

  const { data: businessDay } = useQuery({
    queryKey: ['business-day'],
    queryFn: () => client.get('/api/business-day/current').then(r => r.data),
    refetchInterval: 10_000,
  })

  const { data: activeShifts = [] } = useQuery({
    queryKey: ['active-shifts'],
    queryFn: () => client.get('/api/shifts/?active_only=true').then(r => r.data.shifts ?? []),
    refetchInterval: 10_000,
  })

  const { data: allWaiters = [] } = useQuery({
    queryKey: ['waiters'],
    queryFn: () => client.get('/api/waiters/').then(r => r.data),
    staleTime: 60_000,
  })

  const { data: quickTemplates = [] } = useQuery({
    queryKey: ['quick-templates'],
    queryFn: () => client.get('/api/notifications/templates').then(r => r.data),
    staleTime: 60_000,
  })

  const { data: tables = [], isLoading: tablesLoading } = useQuery({
    queryKey: ['tables'],
    queryFn: () => client.get('/api/tables/').then(r => r.data),
    refetchInterval: 5_000,
  })

  const { data: orders = [], isLoading: ordersLoading } = useQuery({
    queryKey: ['orders-active'],
    queryFn: () => client.get('/api/orders/').then(r => r.data),
    refetchInterval: 5_000,
  })

  const openDayMut = useMutation({
    mutationFn: () => client.post('/api/business-day/open', {}),
    onSuccess: () => { toast.success('Ημέρα ανοίχτηκε!'); qc.invalidateQueries({ queryKey: ['business-day'] }) },
    onError: (e) => {
      const detail = e.response?.data?.detail
      if (detail?.code === 'SYSTEM_LOCKED' || detail?.code === 'LICENSE_EXPIRED') {
        setLicenseBlock({ code: detail.code, message: detail.message })
      } else {
        toast.error(typeof detail === 'string' ? detail : 'Σφάλμα')
      }
    },
  })

  function handleOpenDay() {
    if (license?.isBlocked) {
      setLicenseBlock({
        code: license.lock_reason === 'admin' ? 'SYSTEM_LOCKED' : 'LICENSE_EXPIRED',
        message: license.lock_reason === 'admin'
          ? 'Το σύστημα έχει κλειδωθεί από διαχειριστή. Επικοινωνήστε με την υποστήριξη.'
          : 'Η άδεια χρήσης έχει λήξει. Ανανεώστε την άδεια ή επικοινωνήστε με την υποστήριξη.',
      })
      return
    }
    openDayMut.mutate()
  }

  async function handleEndShiftConfirm(notes, countedCashEnd) {
    if (!endShiftTarget) return
    setEndShiftBusy(true)
    try {
      await client.post(`/api/shifts/manager/end/${endShiftTarget.id}`, {
        notes: notes || null,
        counted_cash_end: countedCashEnd ?? null,
      })
      qc.invalidateQueries({ queryKey: ['active-shifts'] })
      toast.success(`Βάρδια ${endShiftTarget.waiter_name} έκλεισε`)
      setEndShiftTarget(null)
    } catch (e) {
      toast.error(e.response?.data?.detail || 'Σφάλμα')
    } finally {
      setEndShiftBusy(false)
    }
  }

  async function handleStartShift(waiterId, startingCash) {
    await client.post('/api/shifts/manager/start', { waiter_id: waiterId, starting_cash: startingCash })
    toast.success('Βάρδια ξεκίνησε!')
    qc.invalidateQueries({ queryKey: ['active-shifts'] })
  }

  async function retrySingleOrder(orderId) {
    setRetryingId(orderId)
    try {
      const res = await client.post(`/api/orders/${orderId}/retry-print`)
      const results = res.data.print_results ?? []
      const allOk = results.length === 0 || results.every(r => r.success)
      if (allOk) toast.success('Εκτυπώθηκε επιτυχώς')
      else {
        const failed = results.filter(r => !r.success).map(r => r.printer_name).join(', ')
        toast.error(`Αποτυχία: ${failed}`)
      }
      qc.invalidateQueries({ queryKey: ['orders-active'] })
    } catch {
      toast.error('Σφάλμα επικοινωνίας')
    } finally {
      setRetryingId(null)
    }
  }

  async function retryAllOrders() {
    for (const { order } of pendingPrintOrders) {
      if (order) await retrySingleOrder(order.id)
    }
  }

  const isOpen = !!businessDay

  const waitersWithoutShift = allWaiters.filter(
    w => w.role === 'waiter' && !activeShifts.some(s => s.waiter_id === w.id)
  )

  // Build table cards
  const tableCards = tables.map(table => {
    const order = orders.find(o =>
      o.table_id === table.id && ['open', 'partially_paid', 'paid'].includes(o.status)
    )
    const tableStatus = order ? order.status : 'free'
    const hasPendingPrint = order ? order.items.some(i => i.status === 'active' && !i.printed) : false
    return { table, order, tableStatus, hasPendingPrint }
  })

  const pendingPrintOrders = tableCards.filter(c => c.hasPendingPrint)

  // KPIs — revenue scoped to orders that opened after business day start
  const businessDayStart = businessDay?.opened_at ? new Date(businessDay.opened_at) : null
  const dayOrders = businessDayStart
    ? orders.filter(o => new Date(o.opened_at) >= businessDayStart)
    : orders

  const totalRevenue = dayOrders.reduce((s, o) => s + orderTotal(o.items), 0)
  const openCount = tableCards.filter(c => c.tableStatus === 'open').length
  const partialCount = tableCards.filter(c => c.tableStatus === 'partially_paid').length
  const occupiedCount = openCount + partialCount
  const freeCount = tableCards.filter(c => c.tableStatus === 'free').length

  // Avg ticket: revenue divided by number of orders with at least one paid item
  const paidOrders = dayOrders.filter(o => o.items.some(i => i.paid_by))
  const avgTicket = paidOrders.length > 0 ? totalRevenue / paidOrders.length : 0

  // Total collected by all active shifts
  const totalCollected = activeShifts.reduce((s, sh) => s + (sh.total_collected || 0), 0)

  const todayStr = new Date().toLocaleDateString('el-GR', { weekday: 'long', day: 'numeric', month: 'long' })

  if (tablesLoading || ordersLoading) {
    return <div className="flex items-center justify-center h-64 text-gray-400">Φόρτωση…</div>
  }

  return (
    <div className="overflow-y-auto h-full p-6" style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>

      {/* ── Header bar ─────────────────────────────────────────────────────── */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '4px 10px', borderRadius: 999,
              background: isOpen ? '#eef7f0' : '#f4f4f2',
              color: isOpen ? '#1f7042' : '#5a6169',
              fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5,
            }}>
              <span style={{
                width: 6, height: 6, borderRadius: 3,
                background: isOpen ? '#2f9e5e' : '#8a9099',
                boxShadow: isOpen ? '0 0 0 2px #bbf7d0' : 'none',
              }} />
              {isOpen ? 'Ημέρα Ανοιχτή' : 'Ημέρα Κλειστή'}
            </span>
          </div>
          <div style={{ fontSize: 13, color: '#5a6169', marginTop: 3 }}>
            {todayStr}
            {isOpen && businessDay?.opened_at && ` · από ${fmtTime(businessDay.opened_at)} · ${fmtDuration(businessDay.opened_at)}`}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <button
            onClick={() => setPrivacyMode(p => { const next = !p; localStorage.setItem('privacyMode', next); return next })}
            title={privacyMode ? 'Εμφάνιση ποσών' : 'Απόκρυψη ποσών'}
            style={{
              height: 38, width: 38, borderRadius: 10, flexShrink: 0,
              border: '1px solid #dfe2e6',
              background: privacyMode ? '#1e293b' : 'white',
              color: privacyMode ? '#94a3b8' : '#5a6169',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              cursor: 'pointer', fontSize: 16, transition: 'background 200ms, color 200ms',
            }}
          >
            {privacyMode ? (
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/>
                <path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/>
                <line x1="1" y1="1" x2="23" y2="23"/>
              </svg>
            ) : (
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                <circle cx="12" cy="12" r="3"/>
              </svg>
            )}
          </button>
          {isOpen ? (
            <>
              <button onClick={() => setWorkdaySummaryMode('view')} style={{
                height: 38, padding: '0 14px', borderRadius: 10,
                background: 'white', border: '1px solid #dfe2e6', color: '#374151',
                fontSize: 13, fontWeight: 600, cursor: 'pointer',
              }}>📊 Στατιστικά Ημέρας</button>
              <button onClick={() => setWorkdaySummaryMode('close')} style={{
                height: 38, padding: '0 18px', borderRadius: 10,
                background: '#dc2626', border: 'none', color: 'white',
                fontSize: 13, fontWeight: 700, cursor: 'pointer',
              }}>Κλείσιμο Ημέρας</button>
            </>
          ) : (
            <button onClick={handleOpenDay} disabled={openDayMut.isPending} style={{
              height: 38, padding: '0 18px', borderRadius: 10,
              background: '#16a34a', border: 'none', color: 'white',
              fontSize: 13, fontWeight: 700, cursor: 'pointer',
            }}>{openDayMut.isPending ? 'Άνοιγμα…' : '▶ Άνοιγμα Ημέρας'}</button>
          )}
        </div>
      </div>

      {/* ── KPI strip — full-width flex row ────────────────────────────────── */}
      <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
        <KpiCard
          label="Έσοδα ημέρας"
          value={fmtEuro(totalRevenue)}
          sub={`${dayOrders.length} παραγγελί${dayOrders.length !== 1 ? 'ες' : 'α'} · μ.ο. ${fmtEuro(avgTicket)}`}
          accent="#3758c9"
          private={privacyMode}
        />
        <KpiCard
          label="Τραπέζια σε χρήση"
          value={`${occupiedCount} / ${tables.length}`}
          sub={`${freeCount} ελεύθερα · ${partialCount} μερική πληρ.`}
          accent="#7a44c9"
          pct={tables.length > 0 ? (occupiedCount / tables.length) * 100 : 0}
        />
        <KpiCard
          label="Βάρδιες ενεργές"
          value={String(activeShifts.length)}
          sub={activeShifts.length > 0 ? activeShifts.map(s => s.waiter_name.split(' ')[0]).join(', ') : 'Κανένας σε βάρδια'}
          accent="#2f9e5e"
        />
        <KpiCard
          label="Είσπραξη βαρδιών"
          value={fmtEuro(totalCollected)}
          sub={`Σύνολο από ${activeShifts.length} βάρδι${activeShifts.length === 1 ? 'α' : 'ες'}`}
          accent="#0d7a8a"
          private={privacyMode}
        />
        {pendingPrintOrders.length > 0 && (
          <KpiCard
            label="Εκκρεμείς εκτυπώσεις"
            value={String(pendingPrintOrders.length)}
            sub="Απαιτείται προσοχή"
            accent="#d94b26"
          />
        )}
      </div>

      {/* ── Main 2-column layout: 65 / 35 ──────────────────────────────────── */}
      <div style={{ display: 'grid', gridTemplateColumns: '65fr 35fr', gap: 20, alignItems: 'start' }}>

        {/* ── Left column — Shifts + Tables + Revenue + Pending prints ───────── */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>

          {/* Shifts card — FIRST */}
          <ShiftsCard
            activeShifts={activeShifts}
            waitersWithoutShift={waitersWithoutShift}
            isOpen={isOpen}
            onStartShift={() => setShowStartShift(true)}
            onEndShift={(shift) => setEndShiftTarget(shift)}
            onViewStats={(shift) => setShiftStatsTarget(shift)}
            onMessageWaiter={(s) => setMessageWaiter({ id: s.waiter_id, name: s.waiter_name })}
            privacyMode={privacyMode}
          />

          {/* Tables overview — SECOND */}
          <div style={{
            background: 'white', border: '1px solid #edeff1',
            borderRadius: 16, overflow: 'hidden',
            boxShadow: '0 1px 2px rgba(16,20,24,0.04)',
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              padding: '16px 20px', borderBottom: '1px solid #edeff1',
            }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: '#111315' }}>Τραπέζια τώρα</div>
              <button
                onClick={() => navigate('/tables')}
                style={{
                  height: 28, padding: '0 12px', borderRadius: 8,
                  border: '1px solid #dfe2e6', background: 'white',
                  color: '#2b2f33', fontSize: 12, fontWeight: 600, cursor: 'pointer',
                }}
              >Πλήρης εικόνα →</button>
            </div>
            <div style={{ padding: '16px 20px' }}>
              <div style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(auto-fill, minmax(56px, 1fr))',
                gap: 8, marginBottom: 14,
              }}>
                {tableCards.map(({ table, tableStatus, order }) => (
                  <TableChip
                    key={table.id}
                    name={table.label || `T${table.number}`}
                    status={tableStatus}
                    amount={order ? orderTotal(order.items) : null}
                    onClick={order ? () => setQuickView({ orderId: order.id, tableName: table.label || `T${table.number}` }) : undefined}
                  />
                ))}
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {Object.entries(TABLE_COLORS).map(([key, c]) => (
                  <div key={key} style={{
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                    padding: '4px 10px', borderRadius: 999, background: '#edeff1',
                    fontSize: 12, fontWeight: 600, color: '#2b2f33',
                  }}>
                    <span style={{ width: 8, height: 8, borderRadius: 4, background: c.dot }} />
                    {c.label}
                    <span style={{ fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace", color: '#111315' }}>
                      {tableCards.filter(tc => tc.tableStatus === key).length}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Revenue chart */}
          <RevenueChart orders={dayOrders} />

          {/* Pending prints */}
          <PendingPrintsPanel
            pendingPrintOrders={pendingPrintOrders}
            onRetryAll={retryAllOrders}
            onRetrySingle={retrySingleOrder}
            onViewOrder={id => setQuickView({ orderId: id, tableName: tables.find(t => tableCards.find(tc => tc.order?.id === id)?.table.id === t.id)?.label || '—' })}
            retryingId={retryingId}
          />
        </div>

        {/* ── Right column — Notes + Reservations + Messages ───────────────── */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          <NotesCard />
          <ReservationsCard tables={tables} onNew={() => setShowNewReservation(true)} />
          <MessagesCard waiters={allWaiters} tables={tables} />
        </div>
      </div>

      {/* ── Modals ─────────────────────────────────────────────────────────── */}
      {showStartShift && (
        <StartShiftModal
          waiters={waitersWithoutShift}
          onClose={() => setShowStartShift(false)}
          onStart={handleStartShift}
        />
      )}

      {endShiftTarget && (
        <ShiftReviewModal
          shift={endShiftTarget}
          mode="close"
          onClose={() => setEndShiftTarget(null)}
          onConfirm={handleEndShiftConfirm}
          busy={endShiftBusy}
        />
      )}

      {shiftStatsTarget && (
        <ShiftReviewModal
          shift={shiftStatsTarget}
          mode="stats"
          onClose={() => setShiftStatsTarget(null)}
          onConfirm={null}
          busy={false}
        />
      )}

      {messageWaiter && (
        <QuickMessageModal
          waiter={messageWaiter}
          tables={tables}
          templates={quickTemplates}
          onClose={() => setMessageWaiter(null)}
          onSent={() => qc.invalidateQueries({ queryKey: ['messages-all'] })}
        />
      )}
      {workdaySummaryMode && (
        <WorkdaySummaryModal
          showCloseAction={workdaySummaryMode === 'close'}
          onClose={() => setWorkdaySummaryMode(null)}
          onDayClosed={() => {
            toast.success('Ημέρα έκλεισε!')
            qc.invalidateQueries({ queryKey: ['business-day'] })
            qc.invalidateQueries({ queryKey: ['active-shifts'] })
            qc.invalidateQueries({ queryKey: ['orders-active'] })
            qc.invalidateQueries({ queryKey: ['tables'] })
            qc.invalidateQueries({ queryKey: ['messages-all'] })
            setWorkdaySummaryMode(null)
          }}
        />
      )}
      {showNewReservation && (
        <ReservationModal
          tables={tables}
          initial={null}
          onClose={() => setShowNewReservation(false)}
          onSaved={() => {
            setShowNewReservation(false)
            qc.invalidateQueries({ queryKey: ['reservations'] })
            qc.invalidateQueries({ queryKey: ['tables'] })
          }}
        />
      )}
      {quickView && (
        <OrderQuickModal
          orderId={quickView.orderId}
          tableName={quickView.tableName}
          onClose={() => setQuickView(null)}
          onOpenFull={() => { navigate(`/orders/${quickView.orderId}`); setQuickView(null) }}
        />
      )}
      {licenseBlock && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-2xl p-7 w-full max-w-sm text-center space-y-4">
            <div className="flex justify-center">
              <div className={`flex h-12 w-12 items-center justify-center rounded-xl ${
                licenseBlock.code === 'SYSTEM_LOCKED' ? 'bg-red-100' : 'bg-orange-100'
              }`}>
                <span className="text-2xl">{licenseBlock.code === 'SYSTEM_LOCKED' ? '🔒' : '⚠️'}</span>
              </div>
            </div>
            <h2 className="text-[15px] font-bold text-slate-900">
              {licenseBlock.code === 'SYSTEM_LOCKED' ? 'Σύστημα Κλειδωμένο' : 'Άδεια Χρήσης Ληγμένη'}
            </h2>
            <p className="text-[13px] text-slate-600">{licenseBlock.message}</p>
            <button
              onClick={() => setLicenseBlock(null)}
              className="w-full h-10 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 text-[13px] font-semibold transition-colors"
            >
              Κλείσιμο
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
