import { useState, useRef, useCallback, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import client from '../api/client'
import ManagerOrderDrawer from './ManagerOrderDrawer'

// ── Constants ─────────────────────────────────────────────────────────────────

const FAV_CAT_ID = '__favorites__'
const SVC_CAT_ID = '__service__'
const DECIMAL_UNITS = new Set(['kg', 'liter', 'gram', 'ml'])
const DECIMAL_UNIT_LABELS = { kg: 'kg', liter: 'L', gram: 'g', ml: 'mL' }

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

function productAllowsQuickAdd(product) {
  if (!product.quick_add_enabled) return false
  for (const ps of (product.preference_sets || [])) {
    if (ps.default_choice_id == null) return false
  }
  return true
}

function buildQuickAddItem(product) {
  const qty = DECIMAL_UNITS.has(product.unit_type) ? 1.0 : 1
  const selectedOptions = []
  for (const ps of (product.preference_sets || [])) {
    const defaultChoice = ps.choices?.find(c => c.id === ps.default_choice_id)
    if (defaultChoice) {
      selectedOptions.push({ id: defaultChoice.id, name: defaultChoice.name, price_delta: defaultChoice.extra_cost ?? 0 })
    }
  }
  return {
    product_id: product.id,
    quantity: qty,
    unit_type: product.unit_type || 'piece',
    unit_price: product.base_price,
    notes: '',
    selected_options: selectedOptions,
    removed_ingredients: [],
  }
}

function fmtQty(qty, unitType) {
  const label = DECIMAL_UNIT_LABELS[unitType]
  if (!label) return `×${qty}`
  if (unitType === 'kg' || unitType === 'liter') return `${Number(qty).toFixed(1)}${label}`
  return `${qty}${label}`
}

function hexToRgba(hex, alpha) {
  if (!hex) return null
  const h = hex.replace('#', '')
  const r = parseInt(h.substring(0, 2), 16)
  const g = parseInt(h.substring(2, 4), 16)
  const b = parseInt(h.substring(4, 6), 16)
  return `rgba(${r},${g},${b},${alpha})`
}

function buildSections(parent, subcategories, directProducts) {
  const sections = []
  if (directProducts.length > 0) {
    sections.push({ _isGeneral: true, sort_order: parent.general_sort_order, products: directProducts })
  }
  for (const sub of subcategories) {
    sections.push({ ...sub, _isGeneral: false, sort_order: sub.sort_order })
  }
  return sections.sort((a, b) => a.sort_order - b.sort_order)
}

// ── Product card for the desktop grid ─────────────────────────────────────────

function DesktopProductCard({ product, onOpen, onQuickAdd }) {
  const canQuickAdd = productAllowsQuickAdd(product)
  const initials = product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()

  return (
    <div
      onClick={() => onOpen(product)}
      style={{
        background: 'white',
        border: '1px solid #e2e8f0',
        borderRadius: 12,
        overflow: 'hidden',
        cursor: 'pointer',
        display: 'flex',
        flexDirection: 'column',
        transition: 'box-shadow 120ms ease, border-color 120ms ease',
        position: 'relative',
      }}
      onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.08)'; e.currentTarget.style.borderColor = '#cbd5e1' }}
      onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.borderColor = '#e2e8f0' }}
    >
      {/* Thumbnail */}
      <div style={{
        width: '100%', aspectRatio: '16/9', maxHeight: 80,
        background: '#f1f5f9', overflow: 'hidden',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        {product.image_url
          ? <img src={product.image_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          : <span style={{ fontSize: 22, fontWeight: 700, color: '#94a3b8', letterSpacing: -1 }}>{initials}</span>
        }
      </div>

      {/* Info */}
      <div style={{ padding: '8px 10px 10px', flex: 1, display: 'flex', flexDirection: 'column', gap: 4 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: '#1e293b', lineHeight: 1.3, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
          {product.name}
        </div>
        {product.tags?.length > 0 && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 3 }}>
            {product.tags.slice(0, 2).map(tag => (
              <span key={tag} style={{ fontSize: 10, fontWeight: 600, padding: '1px 6px', background: '#f1f5f9', borderRadius: 99, color: '#64748b', border: '1px solid #e2e8f0' }}>{tag}</span>
            ))}
          </div>
        )}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 'auto' }}>
          <span style={{ fontSize: 14, fontWeight: 700, color: '#f59e0b' }}>{Number(product.base_price).toFixed(2)} €</span>
          {canQuickAdd && (
            <button
              onClick={e => { e.stopPropagation(); onQuickAdd(product) }}
              style={{
                width: 30, height: 30, borderRadius: '50%',
                background: '#fff7ed', border: '1.5px solid #fed7aa',
                cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#f59e0b',
              }}
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                <path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="2.8" strokeLinecap="round"/>
              </svg>
            </button>
          )}
        </div>
      </div>
    </div>
  )
}

// ── Service item widget ───────────────────────────────────────────────────────

function ServiceItemWidget({ product, customerCount, onAdd }) {
  const [qty, setQty] = useState(0)
  const hasPrice = product.base_price != null && product.base_price > 0

  return (
    <div style={{
      background: 'white', border: '1px solid #e2e8f0', borderRadius: 12,
      padding: '12px 14px', display: 'flex', flexDirection: 'column', gap: 8,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: '#1e293b', flex: 1, minWidth: 0 }}>{product.name}</span>
        <span style={{ fontSize: 12, color: hasPrice ? '#f59e0b' : '#94a3b8', fontWeight: 600, flexShrink: 0 }}>
          {hasPrice ? `${Number(product.base_price).toFixed(2)} €` : 'no charge'}
        </span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <button onClick={() => setQty(q => Math.max(0, q - 1))}
          style={{ width: 32, height: 32, borderRadius: '50%', border: '1px solid #e2e8f0', background: qty === 0 ? '#f8fafc' : 'rgba(245,158,11,0.1)', color: qty === 0 ? '#94a3b8' : '#f59e0b', fontSize: 18, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700 }}>−</button>
        <button onClick={() => setQty(Math.max(1, customerCount ?? 1))} title={`Ορισμός σε ${customerCount ?? 1}`}
          style={{ width: 32, height: 32, borderRadius: '50%', border: '1px solid #e2e8f0', background: 'rgba(245,158,11,0.1)', color: '#f59e0b', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/>
            <path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>
          </svg>
        </button>
        <button onClick={() => setQty(q => q + 1)}
          style={{ width: 32, height: 32, borderRadius: '50%', border: '1px solid #e2e8f0', background: 'rgba(245,158,11,0.1)', color: '#f59e0b', fontSize: 18, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700 }}>+</button>
        <span style={{ fontSize: 20, fontWeight: 800, color: qty === 0 ? '#94a3b8' : '#1e293b', flex: 1, textAlign: 'center' }}>{qty}</span>
        <button
          disabled={qty === 0}
          onClick={() => {
            if (qty === 0) return
            onAdd({
              product_id: product.id,
              quantity: qty,
              unit_type: 'piece',
              unit_price: product.base_price ?? 0,
              notes: '',
              selected_options: [],
              removed_ingredients: [],
              is_service_item: true,
            })
            setQty(0)
          }}
          style={{
            padding: '6px 14px', borderRadius: 8, border: 'none',
            background: qty === 0 ? '#f1f5f9' : '#f59e0b',
            color: qty === 0 ? '#94a3b8' : '#fff',
            fontSize: 12, fontWeight: 700, cursor: qty === 0 ? 'default' : 'pointer',
          }}
        >ADD</button>
      </div>
    </div>
  )
}

// ── Cart item row ─────────────────────────────────────────────────────────────

function CartItemRow({ item, product, onRemove, onChangeQty, onEdit }) {
  const isDecimal = DECIMAL_UNITS.has(product?.unit_type)
  const optionSummary = item.selected_options?.length
    ? item.selected_options.map(o => o.name).join(', ')
    : null

  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, padding: '8px 0', borderBottom: '1px solid #f1f5f9' }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: '#1e293b', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {product?.name ?? `#${item.product_id}`}
        </div>
        {optionSummary && (
          <div style={{ fontSize: 11, color: '#94a3b8', marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {optionSummary}
          </div>
        )}
        {item.notes && (
          <div style={{ fontSize: 11, color: '#f59e0b', marginTop: 1, fontStyle: 'italic', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {item.notes}
          </div>
        )}
      </div>

      {/* Qty controls */}
      {isDecimal ? (
        <button onClick={onEdit} style={{ fontSize: 12, fontWeight: 700, color: '#f59e0b', background: '#fff7ed', border: '1px solid #fed7aa', borderRadius: 6, padding: '2px 8px', cursor: 'pointer', whiteSpace: 'nowrap' }}>
          {fmtQty(item.quantity, product?.unit_type)}
        </button>
      ) : (
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0 }}>
          <button onClick={() => onChangeQty(item.quantity - 1)}
            style={{ width: 24, height: 24, borderRadius: '50%', border: '1px solid #e2e8f0', background: '#f8fafc', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: item.quantity <= 1 ? '#ef4444' : '#475569', fontSize: 14, fontWeight: 700 }}>
            {item.quantity <= 1
              ? <svg width="10" height="10" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
              : '−'}
          </button>
          <span style={{ fontSize: 13, fontWeight: 700, color: '#1e293b', minWidth: 16, textAlign: 'center' }}>{item.quantity}</span>
          <button onClick={() => onChangeQty(item.quantity + 1)}
            style={{ width: 24, height: 24, borderRadius: '50%', border: '1px solid #e2e8f0', background: '#f8fafc', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#16a34a', fontSize: 14, fontWeight: 700 }}>+</button>
        </div>
      )}

      {/* Price */}
      <span style={{ fontSize: 13, fontWeight: 700, color: '#475569', minWidth: 50, textAlign: 'right', flexShrink: 0 }}>
        €{((item.unit_price ?? 0) * item.quantity + (item.price_adjustment ?? 0) * item.quantity).toFixed(2)}
      </span>

      {/* Edit + Remove */}
      <div style={{ display: 'flex', gap: 3, flexShrink: 0 }}>
        <button onClick={onEdit}
          style={{ padding: '2px 7px', borderRadius: 6, border: '1px solid #e2e8f0', background: '#f8fafc', color: '#64748b', fontSize: 11, cursor: 'pointer' }}>
          Επεξ.
        </button>
        <button onClick={onRemove}
          style={{ width: 24, height: 24, borderRadius: '50%', border: 'none', background: 'none', color: '#94a3b8', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
        </button>
      </div>
    </div>
  )
}

// ── Search overlay ────────────────────────────────────────────────────────────

function SearchOverlay({ products, onClose, onOpen }) {
  const [query, setQuery] = useState('')
  const inputRef = useRef(null)

  useEffect(() => {
    inputRef.current?.focus()
    function onKey(e) { if (e.key === 'Escape') onClose() }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [onClose])

  const activeProducts = products.filter(p => p.lifecycle_status !== 'archived')
  const results = query.trim().length === 0
    ? []
    : activeProducts.filter(p => p.name.toLowerCase().includes(query.trim().toLowerCase()))

  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 200 }} />
      <div style={{
        position: 'fixed', top: '15%', left: '50%', transform: 'translateX(-50%)',
        zIndex: 201, width: 'min(580px, 90vw)',
        background: 'white', borderRadius: 16,
        boxShadow: '0 20px 60px rgba(0,0,0,0.18)',
        overflow: 'hidden', display: 'flex', flexDirection: 'column',
        maxHeight: '60vh',
      }}>
        {/* Input */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px', borderBottom: '1px solid #e2e8f0', flexShrink: 0 }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" style={{ color: '#94a3b8', flexShrink: 0 }}>
            <circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="2.2"/>
            <path d="M16.5 16.5L21 21" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
          </svg>
          <input
            ref={inputRef}
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder="Αναζήτηση προϊόντος…"
            style={{ flex: 1, border: 'none', outline: 'none', fontSize: 16, color: '#1e293b', background: 'transparent', fontFamily: 'inherit' }}
          />
          <button onClick={onClose} style={{ background: '#f1f5f9', border: 'none', borderRadius: '50%', width: 30, height: 30, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: '#64748b' }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
          </button>
        </div>

        {/* Results */}
        <div style={{ flex: 1, overflowY: 'auto' }}>
          {query.trim().length === 0 ? (
            <p style={{ textAlign: 'center', color: '#94a3b8', padding: '20px', fontSize: 14 }}>Πληκτρολογήστε για αναζήτηση…</p>
          ) : results.length === 0 ? (
            <p style={{ textAlign: 'center', color: '#94a3b8', padding: '20px', fontSize: 14 }}>Δεν βρέθηκαν προϊόντα για «{query}»</p>
          ) : results.map(p => {
            const initials = p.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
            return (
              <button key={p.id} onClick={() => { onOpen(p); onClose() }}
                style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', padding: '10px 16px', background: 'none', border: 'none', cursor: 'pointer', borderBottom: '1px solid #f1f5f9', textAlign: 'left' }}
                onMouseEnter={e => { e.currentTarget.style.background = '#f8fafc' }}
                onMouseLeave={e => { e.currentTarget.style.background = 'none' }}
              >
                <div style={{ width: 38, height: 38, borderRadius: 8, flexShrink: 0, background: '#f1f5f9', overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  {p.image_url
                    ? <img src={p.image_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                    : <span style={{ fontSize: 12, fontWeight: 700, color: '#94a3b8' }}>{initials}</span>
                  }
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: '#1e293b', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.name}</div>
                  <div style={{ fontSize: 12, color: '#94a3b8', marginTop: 1 }}>{Number(p.base_price).toFixed(2)} €</div>
                </div>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ color: '#cbd5e1', flexShrink: 0 }}>
                  <path d="M9 18l6-6-6-6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
            )
          })}
        </div>
      </div>
    </>
  )
}

// ── Main component ────────────────────────────────────────────────────────────

export default function DesktopOrderingTab({ orderId, tableId, orderStatus }) {
  const qc = useQueryClient()

  const { data: productsData, isLoading: productsLoading } = useQuery({
    queryKey: ['products-ordering'],
    queryFn: async () => {
      const [prodRes, catRes] = await Promise.all([
        client.get('/api/products/'),
        client.get('/api/products/categories'),
      ])
      return { products: prodRes.data, categories: catRes.data }
    },
    staleTime: 5 * 60 * 1000,
  })

  const products = productsData?.products ?? []
  const categories = productsData?.categories ?? []

  const serviceProducts = products.filter(p => p.is_service_item)
  const regularProducts = products.filter(p => !p.is_service_item || p.category_id)
  const topLevel = categories.filter(c => !c.parent_id).sort((a, b) => a.sort_order - b.sort_order)

  const initialCatId = topLevel[0]?.id ?? null
  const [activeCat, setActiveCat] = useState(null)
  const [viewAllOpen, setViewAllOpen] = useState(false)
  const [searchOpen, setSearchOpen] = useState(false)
  const [expandedSubs, setExpandedSubs] = useState({})

  // Drawer for product customization
  const [drawerProduct, setDrawerProduct] = useState(null)
  const [editItem, setEditItem] = useState(null) // { cartKey, product, drawerState }

  // Cart
  const [cart, setCart] = useState([])
  const [orderNote, setOrderNote] = useState('')
  const [sending, setSending] = useState(false)

  // Customer count (loaded from order)
  const { data: orderData } = useQuery({
    queryKey: ['order', orderId],
    queryFn: () => client.get(`/api/orders/${orderId}`).then(r => r.data),
    enabled: !!orderId,
    staleTime: 30_000,
  })
  const customerCount = orderData?.customer_count ?? null

  // Courses settings
  const { data: posSettings } = useQuery({
    queryKey: ['pos-settings-courses'],
    queryFn: () => client.get('/api/settings/').then(r => r.data),
    staleTime: 60_000,
  })
  const coursesEnabled = posSettings?.['orders.courses_enabled']?.value === 'true'
  const courses = coursesEnabled ? (() => { try { return JSON.parse(posSettings?.['orders.courses']?.value || '[]') } catch { return [] } })() : []

  // Set initial category once products load
  useEffect(() => {
    if (activeCat === null && topLevel.length > 0) {
      const firstId = serviceProducts.length > 0 ? SVC_CAT_ID : topLevel[0]?.id
      setActiveCat(firstId ?? null)
    }
  }, [topLevel.length, serviceProducts.length])

  function buildDefaultExpanded(catId) {
    const subs = categories.filter(c => c.parent_id === catId)
    const state = {}
    subs.forEach(s => { if (s.auto_expanded) state[String(s.id)] = true })
    return state
  }

  function selectCategory(id) {
    setActiveCat(id)
    setViewAllOpen(false)
    setExpandedSubs(id === FAV_CAT_ID || id === SVC_CAT_ID ? {} : buildDefaultExpanded(id))
  }

  const isSvcActive = activeCat === SVC_CAT_ID

  const activeParent = categories.find(c => c.id === activeCat)
  const subcategories = activeParent
    ? categories.filter(c => c.parent_id === activeCat).sort((a, b) => a.sort_order - b.sort_order)
    : []
  const hasSubcats = subcategories.length > 0
  const directProducts = regularProducts.filter(p => p.category_id === activeCat)
  const sections = hasSubcats ? buildSections(activeParent, subcategories, directProducts) : []

  // Cart management
  function addToCart(item) {
    setCart(prev => {
      const { _key: _k, _drawerState: _ds, quantity: _q, ...newCore } = item
      const matchIdx = prev.findIndex(existing => {
        const { _key, _drawerState, quantity: _eq, ...existCore } = existing
        return JSON.stringify(existCore) === JSON.stringify(newCore)
      })
      if (matchIdx !== -1) {
        const next = [...prev]
        next[matchIdx] = { ...next[matchIdx], quantity: next[matchIdx].quantity + (item.quantity ?? 1) }
        return next
      }
      return [...prev, { ...item, _key: Date.now() + Math.random() }]
    })
  }

  function handleQuickAdd(product) {
    const base = buildQuickAddItem(product)
    const item = product.is_service_item ? { ...base, is_service_item: true } : base
    addToCart(item)
    toast.success(`${product.name} προστέθηκε`, { duration: 800 })
  }

  function removeFromCart(key) {
    setCart(prev => prev.filter(i => i._key !== key))
  }

  function changeCartQty(key, newQty) {
    if (newQty <= 0) removeFromCart(key)
    else setCart(prev => prev.map(i => i._key === key ? { ...i, quantity: newQty } : i))
  }

  function openEditDrawer(cartItem) {
    const product = products.find(p => p.id === cartItem.product_id)
    if (!product) return
    setEditItem({ cartKey: cartItem._key, product, drawerState: cartItem._drawerState })
    setDrawerProduct(null)
  }

  function handleDrawerAdd(item) {
    if (editItem) {
      setCart(prev => prev.map(i => i._key === editItem.cartKey ? { ...item, _key: i._key } : i))
      setEditItem(null)
    } else {
      const finalItem = drawerProduct?.is_service_item ? { ...item, is_service_item: true } : item
      addToCart(finalItem)
      setDrawerProduct(null)
    }
  }

  const cartTotal = cart.reduce((s, i) => s + (i.unit_price ?? 0) * i.quantity + (i.price_adjustment ?? 0) * i.quantity, 0)
  const isOpen = ['open', 'partially_paid'].includes(orderStatus)

  const addItemsMutation = useMutation({
    mutationFn: async () => {
      let activeOrderId = orderId
      if (!activeOrderId) {
        const { data: newOrder } = await client.post('/api/orders/', { table_id: tableId })
        activeOrderId = newOrder.id
      }
      const res = await client.post(`/api/orders/${activeOrderId}/items`, {
        items: cart.map(({ _key, _drawerState, ...item }) => item),
        order_note: orderNote || null,
      })
      return res.data
    },
    onSuccess: (data) => {
      const printResults = data.print_results ?? []
      const allOk = printResults.length === 0 || printResults.every(r => r.success)
      if (!allOk) {
        toast.error('Παραγγελία αποθηκεύτηκε αλλά κάποιος εκτυπωτής δεν ανταποκρίθηκε')
      } else {
        toast.success('Παραγγελία εστάλη επιτυχώς')
      }
      setCart([])
      setOrderNote('')
      qc.invalidateQueries({ queryKey: ['order', orderId] })
      qc.invalidateQueries({ queryKey: ['orders-active'] })
    },
    onError: (err) => {
      toast.error(err?.response?.data?.detail || 'Σφάλμα αποστολής παραγγελίας')
    },
  })

  // Keyboard shortcut for search
  useEffect(() => {
    function onKey(e) {
      if ((e.ctrlKey || e.metaKey) && e.key === 'f') { e.preventDefault(); setSearchOpen(true) }
      if (e.key === 'Escape') { setDrawerProduct(null); setEditItem(null); setSearchOpen(false) }
    }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [])

  if (productsLoading) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 200, color: '#94a3b8', fontSize: 14 }}>
        Φόρτωση προϊόντων…
      </div>
    )
  }

  if (!isOpen) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 200, color: '#94a3b8', fontSize: 14 }}>
        Η παραγγελία δεν είναι ανοιχτή.
      </div>
    )
  }

  const activeDrawerProduct = editItem ? editItem.product : drawerProduct
  const drawerOpen = !!activeDrawerProduct

  return (
    <div style={{ display: 'flex', height: '100%', minHeight: 0, gap: 0 }}>

      {/* ── LEFT: Category + Product browser ─────────────────────────────── */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, borderRight: '1px solid #e2e8f0' }}>

        {/* Toolbar */}
        <div style={{ padding: '10px 12px', borderBottom: '1px solid #e2e8f0', display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0, background: '#f8fafc' }}>
          <div style={{ flex: 1, display: 'flex', gap: 6, overflowX: 'auto', scrollbarWidth: 'none' }}>
            {/* SERVICE chip */}
            {serviceProducts.length > 0 && (
              <button onClick={() => selectCategory(SVC_CAT_ID)}
                style={{
                  height: 32, padding: '0 14px', borderRadius: 16, border: isSvcActive ? '2px solid #f59e0b' : '1px solid #e2e8f0',
                  background: isSvcActive ? '#f59e0b' : '#fff7ed', color: isSvcActive ? '#fff' : '#d97706',
                  fontSize: 12, fontWeight: 700, cursor: 'pointer', whiteSpace: 'nowrap',
                  display: 'flex', alignItems: 'center', gap: 4,
                }}
              >
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M3 11l19-9-9 19-2-8-8-2z"/>
                </svg>
                Service
              </button>
            )}
            {topLevel.map(cat => {
              const isActive = activeCat === cat.id
              const bg = cat.color
                ? isActive ? cat.color : hexToRgba(cat.color, 0.15)
                : isActive ? '#f59e0b' : '#f8fafc'
              const color = cat.color
                ? isActive ? '#fff' : cat.color
                : isActive ? '#fff' : '#64748b'
              return (
                <button key={cat.id} onClick={() => selectCategory(cat.id)}
                  style={{
                    height: 32, padding: '0 14px', borderRadius: 16,
                    border: isActive && cat.color ? `2px solid ${cat.color}` : isActive ? '2px solid #f59e0b' : '1px solid #e2e8f0',
                    background: bg, color,
                    fontSize: 12, fontWeight: 700, cursor: 'pointer', whiteSpace: 'nowrap',
                  }}
                >{cat.name}</button>
              )
            })}
            <button onClick={() => setViewAllOpen(true)}
              style={{ height: 32, padding: '0 12px', borderRadius: 16, border: '1px solid #e2e8f0', background: '#f8fafc', color: '#64748b', fontSize: 12, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0 }}>
              Όλες →
            </button>
          </div>
          <button onClick={() => setSearchOpen(true)}
            style={{ height: 32, padding: '0 12px', borderRadius: 16, border: '1px solid #e2e8f0', background: '#f8fafc', color: '#64748b', fontSize: 12, fontWeight: 600, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 5, flexShrink: 0 }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none">
              <circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="2.2"/>
              <path d="M16.5 16.5L21 21" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
            </svg>
            Αναζήτηση
          </button>
        </div>

        {/* Product area */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '12px 14px' }}>

          {isSvcActive ? (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 10 }}>
              {serviceProducts.map(p => (
                <ServiceItemWidget key={p.id} product={p} customerCount={customerCount} onAdd={item => addToCart(item)} />
              ))}
            </div>
          ) : !hasSubcats ? (
            <>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 10 }}>
                {directProducts.map(p => (
                  <DesktopProductCard key={p.id} product={p} onOpen={setDrawerProduct} onQuickAdd={handleQuickAdd} />
                ))}
              </div>
              {directProducts.length === 0 && (
                <div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0', fontSize: 14 }}>Δεν υπάρχουν προϊόντα</div>
              )}
            </>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {sections.map(section => {
                const key = section._isGeneral ? '__general__' : String(section.id)
                const isExpanded = !!expandedSubs[key]
                const sectionProducts = section._isGeneral
                  ? section.products
                  : regularProducts.filter(p => p.category_id === section.id)
                if (sectionProducts.length === 0) return null

                if (section._isGeneral) {
                  return (
                    <div key={key}>
                      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 10 }}>
                        {sectionProducts.map(p => (
                          <DesktopProductCard key={p.id} product={p} onOpen={setDrawerProduct} onQuickAdd={handleQuickAdd} />
                        ))}
                      </div>
                    </div>
                  )
                }

                const accentColor = section.color ?? activeParent?.color ?? null
                return (
                  <div key={key} style={{ border: '1px solid #e2e8f0', borderRadius: 12, overflow: 'hidden' }}>
                    <button
                      onClick={() => setExpandedSubs(prev => ({ ...prev, [key]: !prev[key] }))}
                      style={{
                        width: '100%', padding: '10px 14px', background: isExpanded ? '#f8fafc' : 'white',
                        border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8, textAlign: 'left',
                      }}
                    >
                      {accentColor && <span style={{ width: 10, height: 10, borderRadius: '50%', background: accentColor, flexShrink: 0 }} />}
                      <span style={{ flex: 1, fontSize: 13, fontWeight: 700, color: '#1e293b' }}>{section.name}</span>
                      <span style={{ fontSize: 11, color: '#94a3b8', marginRight: 4 }}>{sectionProducts.length}</span>
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ transform: `rotate(${isExpanded ? 180 : 0}deg)`, transition: 'transform 180ms', color: '#94a3b8', flexShrink: 0 }}>
                        <path d="M6 9L12 15L18 9" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                    </button>
                    {isExpanded && (
                      <div style={{ padding: '10px 12px 12px', background: '#fafbfc', borderTop: '1px solid #f1f5f9' }}>
                        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 10 }}>
                          {sectionProducts.map(p => (
                            <DesktopProductCard key={p.id} product={p} onOpen={setDrawerProduct} onQuickAdd={handleQuickAdd} />
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                )
              })}
            </div>
          )}
        </div>
      </div>

      {/* ── RIGHT: Cart panel or Drawer panel ────────────────────────────── */}
      <div style={{ width: 320, flexShrink: 0, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
        {drawerOpen ? (
          <ManagerOrderDrawer
            key={activeDrawerProduct.id}
            product={activeDrawerProduct}
            initialState={editItem?.drawerState}
            onClose={() => { setDrawerProduct(null); setEditItem(null) }}
            onAdd={handleDrawerAdd}
            courses={courses}
          />
        ) : (
          /* Cart */
          <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: '#f8fafc' }}>
            {/* Cart header */}
            <div style={{ padding: '12px 16px', borderBottom: '1px solid #e2e8f0', flexShrink: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: '#1e293b' }}>Νέα Παραγγελία</div>
              <div style={{ fontSize: 12, color: '#94a3b8', marginTop: 1 }}>
                {cart.length === 0 ? 'Επιλέξτε προϊόντα από τα αριστερά' : `${cart.length} ${cart.length === 1 ? 'προϊόν' : 'προϊόντα'}`}
              </div>
            </div>

            {/* Item list */}
            <div style={{ flex: 1, overflowY: 'auto', padding: '0 16px' }}>
              {cart.length === 0 ? (
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: 12, padding: '40px 0' }}>
                  <svg width="40" height="40" viewBox="0 0 24 24" fill="none" style={{ color: '#e2e8f0' }}>
                    <path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4zM3 6h18M16 10a4 4 0 01-8 0" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                  <p style={{ color: '#cbd5e1', fontSize: 13, textAlign: 'center' }}>Το καλάθι είναι άδειο</p>
                </div>
              ) : (
                <div>
                  {cart.map(item => {
                    const product = products.find(p => p.id === item.product_id)
                    return (
                      <CartItemRow
                        key={item._key}
                        item={item}
                        product={product}
                        onRemove={() => removeFromCart(item._key)}
                        onChangeQty={qty => changeCartQty(item._key, qty)}
                        onEdit={() => openEditDrawer(item)}
                      />
                    )
                  })}
                </div>
              )}
            </div>

            {/* Order note */}
            {cart.length > 0 && (
              <div style={{ padding: '8px 16px', flexShrink: 0 }}>
                <textarea
                  value={orderNote}
                  onChange={e => setOrderNote(e.target.value)}
                  placeholder="Σημείωση παραγγελίας (προαιρετικό)…"
                  rows={2}
                  style={{
                    width: '100%', resize: 'none', padding: '8px 10px',
                    background: 'white', border: '1px solid #e2e8f0',
                    borderRadius: 8, fontSize: 12, color: '#1e293b', lineHeight: 1.5,
                    outline: 'none', boxSizing: 'border-box', fontFamily: 'inherit',
                  }}
                />
              </div>
            )}

            {/* Cart footer */}
            <div style={{ padding: '10px 16px 16px', borderTop: '1px solid #e2e8f0', flexShrink: 0, background: 'white' }}>
              {cart.length > 0 && (
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                  <span style={{ fontSize: 13, color: '#64748b', fontWeight: 600 }}>Σύνολο</span>
                  <span style={{ fontSize: 18, fontWeight: 800, color: '#1e293b' }}>€{cartTotal.toFixed(2)}</span>
                </div>
              )}
              <button
                onClick={() => addItemsMutation.mutate()}
                disabled={cart.length === 0 || addItemsMutation.isPending}
                style={{
                  width: '100%', height: 44, borderRadius: 22,
                  background: cart.length === 0 ? '#e2e8f0' : '#f59e0b',
                  border: 'none', color: cart.length === 0 ? '#94a3b8' : '#fff',
                  fontSize: 15, fontWeight: 700, fontFamily: 'inherit',
                  cursor: cart.length === 0 ? 'default' : 'pointer',
                  transition: 'background 150ms ease',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                }}
              >
                {addItemsMutation.isPending ? 'Αποστολή…' : `ΑΠΟΣΤΟΛΗ${cart.length > 0 ? ` (${cart.length})` : ''}`}
              </button>
              {cart.length > 0 && (
                <button onClick={() => setCart([])}
                  style={{ width: '100%', marginTop: 6, padding: '6px 0', background: 'none', border: 'none', color: '#94a3b8', fontSize: 12, cursor: 'pointer' }}>
                  Εκκαθάριση καλαθιού
                </button>
              )}
            </div>
          </div>
        )}
      </div>

      {/* View all categories modal */}
      {viewAllOpen && (
        <>
          <div onClick={() => setViewAllOpen(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 200 }} />
          <div style={{
            position: 'fixed', top: '15%', left: '50%', transform: 'translateX(-50%)',
            zIndex: 201, width: 'min(500px, 90vw)',
            background: 'white', borderRadius: 16,
            boxShadow: '0 20px 60px rgba(0,0,0,0.18)',
            overflow: 'hidden',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 18px', borderBottom: '1px solid #e2e8f0' }}>
              <span style={{ fontSize: 15, fontWeight: 700, color: '#1e293b' }}>Κατηγορίες</span>
              <button onClick={() => setViewAllOpen(false)} style={{ background: 'none', border: 'none', color: '#94a3b8', cursor: 'pointer', fontSize: 18 }}>✕</button>
            </div>
            <div style={{ padding: '14px 16px', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, maxHeight: '60vh', overflowY: 'auto' }}>
              {serviceProducts.length > 0 && (
                <button onClick={() => { selectCategory(SVC_CAT_ID); setViewAllOpen(false) }}
                  style={{ padding: '14px 10px', borderRadius: 12, background: '#fff7ed', border: isSvcActive ? '2px solid #f59e0b' : '1px solid #fed7aa', cursor: 'pointer', fontSize: 13, fontWeight: 700, color: '#d97706', textAlign: 'center' }}>
                  Service
                </button>
              )}
              {topLevel.map(cat => {
                const isActive = activeCat === cat.id
                return (
                  <button key={cat.id} onClick={() => { selectCategory(cat.id); setViewAllOpen(false) }}
                    style={{
                      padding: '14px 10px', borderRadius: 12, cursor: 'pointer', fontSize: 13, fontWeight: 700, textAlign: 'center',
                      background: cat.color || '#f1f5f9',
                      color: cat.color ? '#fff' : '#475569',
                      border: isActive ? '2px solid #f59e0b' : '1px solid transparent',
                      boxShadow: cat.color ? 'inset 0 0 0 100px rgba(0,0,0,0.15)' : 'none',
                    }}>
                    {cat.name}
                  </button>
                )
              })}
            </div>
          </div>
        </>
      )}

      {/* Search modal */}
      {searchOpen && (
        <SearchOverlay
          products={products}
          onClose={() => setSearchOpen(false)}
          onOpen={p => { setDrawerProduct(p); setSearchOpen(false) }}
        />
      )}
    </div>
  )
}
