import { useEffect, useRef, useState } from 'react'
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import ProductPicker from '../components/ProductPicker'
import OrderDrawer from '../components/OrderDrawer'
import OrderSummaryModal from '../components/OrderSummaryModal'
import client from '../api/client'
import db from '../db/posdb'
import { useProductCache } from '../hooks/useProductCache'
import useOrderingSettingsStore from '../store/orderingSettingsStore'
import useConnectionStore from '../store/connectionStore'
import useAuthStore from '../store/authStore'
import { queueOfflineOrder } from '../services/offlineOrders'

// ─── Global Course Modal ──────────────────────────────────────────────────────

function GlobalCourseModal({ courses, selected, onSelect, onClose }) {
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-sheet" onClick={e => e.stopPropagation()}>
        <div className="modal-handle" />
        <h2 className="modal-title">Set Course</h2>
        <p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 16px' }}>
          Quick-add items will use this course.
        </p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
          {courses.map(c => (
            <button
              key={c.id}
              onClick={() => { onSelect(c.id === selected ? null : c.id); onClose() }}
              style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '12px 16px',
                background: c.id === selected ? `${c.color}22` : 'var(--bg3)',
                border: `2px solid ${c.id === selected ? c.color : 'var(--border)'}`,
                borderRadius: 12, cursor: 'pointer', textAlign: 'left',
              }}
            >
              <span style={{ width: 14, height: 14, borderRadius: '50%', background: c.color, flexShrink: 0, display: 'inline-block' }} />
              <span style={{ fontSize: 15, fontWeight: c.id === selected ? 700 : 500, color: 'var(--text)', flex: 1 }}>{c.name}</span>
              {c.id === selected && (
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4L19 7" stroke="var(--accent)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
              )}
            </button>
          ))}
        </div>
        {selected != null && (
          <button
            className="btn btn--secondary"
            style={{ width: '100%', marginBottom: 8 }}
            onClick={() => { onSelect(null); onClose() }}
          >
            Clear
          </button>
        )}
        <button className="btn btn--secondary" style={{ width: '100%' }} onClick={onClose}>Cancel</button>
      </div>
    </div>
  )
}

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

function CustomerCountModal({ value, onChange, onClose }) {
  const [count, setCount] = useState(value ?? 0)
  const QUICK = [1, 2, 3, 4, 5, 6]

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-sheet" onClick={e => e.stopPropagation()}>
        <div className="modal-handle" />
        <h2 className="modal-title">Αριθμός Πελατών</h2>
        <p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 20px' }}>
          Πόσα άτομα κάθονται στο τραπέζι;
        </p>

        {/* Quick pick */}
        <div style={{ display: 'flex', gap: 8, justifyContent: 'center', marginBottom: 20 }}>
          {QUICK.map(n => (
            <button
              key={n}
              onClick={() => setCount(n)}
              style={{
                width: 44, height: 44, borderRadius: 12, border: 'none', cursor: 'pointer',
                fontWeight: 800, fontSize: 16,
                background: count === n ? 'var(--accent)' : 'var(--bg3)',
                color: count === n ? 'var(--accent-fg)' : 'var(--text)',
              }}
            >{n}</button>
          ))}
        </div>

        {/* +/- stepper */}
        <div className="modal-qty" style={{ marginBottom: 20 }}>
          <button className="qty-btn" onClick={() => setCount(c => Math.max(0, c - 1))}>−</button>
          <span className="qty-value">{count}</span>
          <button className="qty-btn" onClick={() => setCount(c => c + 1)}>+</button>
        </div>

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

// ─────────────────────────────────────────────────────────────────────────────

const _AI_UNIT_LABELS = { kg: 'kg', liter: 'L', gram: 'g', ml: 'mL' }
function fmtDraftQty(qty, unitType) {
  const label = _AI_UNIT_LABELS[unitType]
  if (!label) return `×${qty}`
  if (unitType === 'kg' || unitType === 'liter') return `${Number(qty).toFixed(1)}${label}`
  return `${qty}${label}`
}

export default function AddItemsPage() {
  const { tableId, orderType } = useParams()
  const isStandalone = !!orderType  // true when on /standalone/:orderType/add
  const [searchParams] = useSearchParams()
  const isNewTable = searchParams.get('new') === '1'
  const navigate = useNavigate()

  const { products, categories } = useProductCache()
  const { summaryBeforeSend } = useOrderingSettingsStore()
  const isOffline = useConnectionStore(s => s.status !== 'online')
  const { user } = useAuthStore()
  const [summaryOpen, setSummaryOpen] = useState(false)

  const [cart, setCart] = useState([])
  const [orderId, setOrderId] = useState(null)
  const [tableLabel, setTableLabel] = useState('')
  const [sending, setSending] = useState(false)
  const [error, setError] = useState('')
  const [printAck, setPrintAck] = useState(null)
  const [cartOpen, setCartOpen] = useState(false)
  const [editItem, setEditItem] = useState(null) // { cartKey, product, drawerState }
  const [viewAllOpen, setViewAllOpen] = useState(false)
  const [orderNote, setOrderNote] = useState('')
  const [orderNoteEditing, setOrderNoteEditing] = useState(false)
  const [searchOpen, setSearchOpen] = useState(false)
  const [searchQuery, setSearchQuery] = useState('')
  const [quickToast, setQuickToast] = useState(null) // { product, count }
  const [customerCount, setCustomerCount] = useState(null) // number of people at table
  const [customerCountOpen, setCustomerCountOpen] = useState(false)
  const [courses, setCourses] = useState([])
  const [quickNotes, setQuickNotes] = useState(null) // null = not yet fetched; use drawer's fallback
  const [globalCourseId, setGlobalCourseId] = useState(null) // course pre-selected for quick-add
  const [globalCourseOpen, setGlobalCourseOpen] = useState(false)
  const [dealOffers, setDealOffers] = useState([]) // pending deal prompts from server
  const [activeDealOffer, setActiveDealOffer] = useState(null) // currently shown offer
  const quickToastTimer = useRef(null)

  useEffect(() => {
    async function load() {
      if (isStandalone) {
        // Standalone orders have no table — set a descriptive label
        setTableLabel(orderType === 'delivery' ? 'Delivery' : 'Takeaway')
        // If an existing order ID was passed (adding items to an existing standalone order), seed it
        const existingOrderId = searchParams.get('orderId')
        if (existingOrderId) {
          setOrderId(Number(existingOrderId))
        }
      } else {
        try {
          const statusRes = await client.get(`/api/tables/${tableId}/status`)
          setOrderId(statusRes.data.active_order_id)
          const t = statusRes.data.table
          if (t) setTableLabel(t.label || `T${t.number}`)
          // Load existing customer count from the active order
          if (statusRes.data.active_order_id) {
            const { data: o } = await client.get(`/api/orders/${statusRes.data.active_order_id}`)
            if (o.customer_count != null) setCustomerCount(o.customer_count)
          }
        } catch {
          // Offline — read table label from IDB snapshot
          const t = await db.pos_tables.get(Number(tableId))
          if (t) setTableLabel(t.label || `T${t.number}`)
          // orderId stays null — offline orders don't need a pre-existing server order
        }
      }

      // Pre-populate cart from "order again" if present
      const stored = sessionStorage.getItem('orderAgainItems')
      if (stored) {
        sessionStorage.removeItem('orderAgainItems')
        try {
          const items = JSON.parse(stored)
          const initialCart = items.map(it => ({
            ...it,
            _key: Date.now() + Math.random(),
          }))
          setCart(initialCart)
        } catch {}
      }
    }
    load()
  }, [tableId, isStandalone, orderType])

  useEffect(() => {
    client.get('/api/settings/').then(r => {
      const s = r.data
      if (s?.['orders.courses_enabled']?.value === 'true') {
        try { setCourses(JSON.parse(s?.['orders.courses']?.value || '[]')) } catch { /* ignore */ }
      }
      try {
        const qn = JSON.parse(s?.['orders.quick_notes']?.value || 'null')
        if (Array.isArray(qn)) setQuickNotes(qn)
      } catch { /* ignore */ }
    }).catch(() => {})
  }, [])

  // Back button: if this was a new table/standalone and nothing was added, go back to tables
  function handleBack() {
    if (isStandalone) {
      navigate('/tables', { replace: true })
    } else if (isNewTable && cart.length === 0) {
      navigate('/tables', { replace: true })
    } else {
      navigate(`/tables/${tableId}`)
    }
  }

  function addToCart(item) {
    setCart(prev => {
      // Stack onto an existing cart entry if everything except quantity matches.
      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(item, product) {
    const itemWithCourse = globalCourseId != null ? { ...item, course_id: globalCourseId } : item
    addToCart(itemWithCourse)
    // Compute new count after adding (cart state updates async, so read current + delta)
    const existingQty = cart
      .filter(c => c.product_id === item.product_id)
      .reduce((s, c) => s + c.quantity, 0)
    const newCount = existingQty + (item.quantity ?? 1)
    if (quickToastTimer.current) clearTimeout(quickToastTimer.current)
    setQuickToast({ product, count: newCount })
    quickToastTimer.current = setTimeout(() => setQuickToast(null), 1000)
  }

  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
    setCartOpen(false)
    setEditItem({ cartKey: cartItem._key, product, drawerState: cartItem._drawerState })
  }

  function handleEditSave(updatedItem) {
    setCart(prev => prev.map(i =>
      i._key === editItem.cartKey ? { ...updatedItem, _key: i._key } : i
    ))
    setEditItem(null)
  }

  async function sendOrder() {
    if (cart.length === 0) return
    setSending(true)
    setError('')
    setPrintAck(null)
    setCartOpen(false)

    // ── Offline path (not supported for standalone orders) ────────────────────
    if (isOffline && !isStandalone) {
      try {
        const items = cart.map(({ _key, _drawerState, ...item }) => {
          const product = products.find(p => p.id === item.product_id)
          return {
            ...item,
            _productSnapshot: product ? { name: product.name } : null,
            _unitPrice: product?.base_price ?? 0,
            _unitType: product?.unit_type ?? null,
          }
        })
        await queueOfflineOrder({
          tableId: Number(tableId),
          items,
          waiterId: user?.id ?? null,
        })
        // Show a brief success state then navigate back
        setPrintAck({ allOk: true, results: [], _offline: true })
        setTimeout(() => navigate('/tables'), 1200)
      } catch (err) {
        console.error('[offline order] save failed:', err)
        setError('Σφάλμα αποθήκευσης offline παραγγελίας')
      } finally {
        setSending(false)
      }
      return
    }

    // ── Online path ───────────────────────────────────────────────────────────
    try {
      let activeOrderId = orderId
      if (!activeOrderId) {
        const orderPayload = isStandalone
          ? { table_id: null, order_type: orderType }
          : { table_id: Number(tableId), order_type: 'here' }
        const { data: newOrder } = await client.post('/api/orders/', orderPayload)
        activeOrderId = newOrder.id
        setOrderId(activeOrderId)
      }

      const res = await client.post(`/api/orders/${activeOrderId}/items`, {
        items: cart.map(({ _key, _drawerState, ...item }) => item),
        order_note: orderNote || null,
        customer_count: customerCount ?? null,
      })
      const printResults = res.data.print_results ?? []
      const printPending = printResults.length > 0 && !printResults.every(r => r.success)
      // Show deal offers one-by-one before navigating
      const offers = res.data.deal_offers ?? []
      if (offers.length > 0) {
        const pendingOffers = offers.map(o => ({ ...o, _orderId: activeOrderId }))
        setDealOffers(pendingOffers.slice(1))
        setActiveDealOffer(pendingOffers[0])
        setPrintAck({ allOk: true, _pending: printPending })
      } else {
        setPrintAck({ allOk: true, _pending: printPending })
        setTimeout(() => navigate('/tables'), 1200)
      }
    } catch (err) {
      setError(err.response?.data?.detail || 'Σφάλμα αποστολής — η παραγγελία δεν στάλθηκε')
    } finally {
      setSending(false)
    }
  }

  function getProduct(id) { return products.find(p => p.id === id) }

  // Returns structured sections for the expanded cart view
  function buildItemSections(item, product) {
    const sections = []

    if (item.selected_options?.length) {
      const prefIds = new Set(
        (product?.preference_sets || []).flatMap(ps => ps.choices.map(c => c.id))
      )
      // Build a map: prefChoiceId → preference set name
      const prefSetByChoiceId = {}
      ;(product?.preference_sets || []).forEach(ps => {
        ps.choices.forEach(c => { prefSetByChoiceId[c.id] = ps.name })
      })
      const quickNames = new Set((product?.quick_options || []).map(o => o.name))
      const extraIds = new Set((product?.options || []).map(o => o.id))

      // Group prefs: { prefSetName, choiceName, subName }
      const prefGroups = []
      // Group extras: { name, subName, qty } — one entry per unique (id)
      const extraGroups = []
      const quickLines = []

      let i = 0
      const opts = item.selected_options
      while (i < opts.length) {
        const o = opts[i]
        if (prefIds.has(o.id)) {
          // Collect sub immediately following (id === null)
          const setName = prefSetByChoiceId[o.id] ?? ''
          let subName = null
          if (i + 1 < opts.length && opts[i + 1].id == null) {
            subName = opts[i + 1].name
            i += 2
          } else {
            i++
          }
          // Merge into existing prefGroup for same setName, or create new
          const existing = prefGroups.find(g => g.setName === setName)
          if (existing) {
            // multiple choices from same set (shouldn't normally happen, but handle gracefully)
            existing.values.push(subName ? `${o.name} · ${subName}` : o.name)
          } else {
            prefGroups.push({ setName, values: [subName ? `${o.name} · ${subName}` : o.name] })
          }
        } else if (o.id != null && extraIds.has(o.id)) {
          // Collect sub immediately following
          let subName = null
          if (i + 1 < opts.length && opts[i + 1].id == null) {
            subName = opts[i + 1].name
            i += 2
          } else {
            i++
          }
          // Merge duplicates
          const existing = extraGroups.find(g => g.id === o.id && g.subName === subName)
          if (existing) existing.qty++
          else extraGroups.push({ id: o.id, name: o.name, subName, qty: 1 })
        } else if (quickNames.has(o.name)) {
          quickLines.push(o)
          i++
        } else {
          i++
        }
      }

      // Deduplicate quick lines: multiple entries of same name → single entry with qty
      const quickDeduped = []
      quickLines.forEach(o => {
        const existing = quickDeduped.find(x => x.name === o.name)
        if (existing) existing._qty = (existing._qty || 1) + 1
        else quickDeduped.push({ ...o, _qty: 1 })
      })

      if (prefGroups.length > 0) sections.push({ type: 'prefs', lines: prefGroups })
      if (quickDeduped.length > 0) sections.push({ type: 'quick', lines: quickDeduped })
      if (extraGroups.length > 0) sections.push({ type: 'extras', lines: extraGroups })
    }

    if (item.removed_ingredients?.length) {
      sections.push({ type: 'removed', lines: item.removed_ingredients.map(n => ({ name: n })) })
    }

    if (item.notes) {
      sections.push({ type: 'note', lines: [{ name: item.notes }] })
    }

    return sections
  }

  // Simple flat summary for the collapsed one-liner
  function buildItemSummary(item) {
    const lines = []
    if (item.selected_options?.length) {
      item.selected_options.forEach(o => {
        if (o.price_delta && o.price_delta !== 0)
          lines.push(`${o.name} (${o.price_delta > 0 ? '+' : ''}${o.price_delta.toFixed(2)} €)`)
        else lines.push(o.name)
      })
    }
    if (item.removed_ingredients?.length) lines.push(`Χωρίς: ${item.removed_ingredients.join(', ')}`)
    if (item.notes) lines.push(item.notes)
    return lines
  }

  // Compact names for the strip preview (max 3 items shown)
  const stripItems = cart.slice(-3).reverse()
  const hiddenCount = cart.length > 3 ? cart.length - 3 : 0

  return (
    <div className="page" style={{ position: 'relative' }}>
      <header className="top-bar">
        <button className="icon-btn" onClick={handleBack}>←</button>
        <span className="top-bar__title">{tableLabel || (isNewTable ? 'Νέα Παραγγελία' : 'Προσθήκη')}</span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          {/* Customer count button */}
          <button
            className="icon-btn"
            style={{ position: 'relative' }}
            onClick={() => setCustomerCountOpen(true)}
            title="Αριθμός πελατών"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              <circle cx="9" cy="7" r="4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              <path d="M23 21v-2a4 4 0 0 0-3-3.87" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              <path d="M16 3.13a4 4 0 0 1 0 7.75" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
            {customerCount != null && customerCount > 0 && (
              <span style={{
                position: 'absolute', top: -2, right: -2,
                minWidth: 18, height: 18, borderRadius: 9,
                background: '#38bdf8', color: '#000',
                fontSize: 10, fontWeight: 800,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                padding: '0 4px',
              }}>{customerCount}</span>
            )}
          </button>
          {/* Course selector button — only when courses are configured */}
          {courses.length > 0 && (
            <button
              className="icon-btn"
              style={{ position: 'relative' }}
              onClick={() => setGlobalCourseOpen(true)}
              title="Set course"
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
                <path d="M12 7v5l3 3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
              {globalCourseId != null && (() => {
                const c = courses.find(c => c.id === globalCourseId)
                return c ? (
                  <span style={{
                    position: 'absolute', top: -2, right: -2,
                    minWidth: 18, height: 18, borderRadius: 9,
                    background: c.color, color: '#fff',
                    fontSize: 10, fontWeight: 800,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    padding: '0 4px',
                  }}>{c.id}</span>
                ) : null
              })()}
            </button>
          )}
          {/* Search button */}
          <button className="icon-btn" onClick={() => { setSearchQuery(''); setSearchOpen(true) }} title="Αναζήτηση">
            <svg width="20" height="20" 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>
          {/* Categories button */}
          <button className="icon-btn" onClick={() => setViewAllOpen(true)} title="Όλες οι κατηγορίες">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <rect x="3" y="3" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
              <rect x="14" y="3" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
              <rect x="3" y="14" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
              <rect x="14" y="14" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
            </svg>
          </button>
          {/* Cart button with badge */}
          <button
            className="icon-btn"
            style={{ position: 'relative' }}
            onClick={() => setCartOpen(true)}
          >
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
              <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="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
            {cart.length > 0 && (
              <span style={{
                position: 'absolute', top: -2, right: -2,
                minWidth: 18, height: 18, borderRadius: 9,
                background: 'var(--accent)', color: 'var(--accent-fg)',
                fontSize: 11, fontWeight: 800,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                padding: '0 4px',
              }}>{cart.length}</span>
            )}
          </button>
        </div>
      </header>

      {/* Product picker takes all remaining space */}
      <ProductPicker
        categories={categories}
        products={products}
        onAdd={addToCart}
        onQuickAdd={handleQuickAdd}
        viewAllOpen={viewAllOpen}
        setViewAllOpen={setViewAllOpen}
        customerCount={customerCount}
        courses={courses}
        globalCourseId={globalCourseId}
        quickNotes={quickNotes}
      />

      {/* Quick-add toast */}
      {quickToast && (
        <QuickAddToast product={quickToast.product} count={quickToast.count} />
      )}

      {/* ── Bottom bar: floating mini-cart + full-width ΑΠΟΣΤΟΛΗ ─────────────── */}
      <div style={{
        background: 'var(--bg2)',
        borderTop: '1px solid var(--border)',
        padding: '10px 12px 14px',
        flexShrink: 0,
      }}>
        {/* Floating compact cart — shown only when there are items */}
        {cart.length > 0 && (
          <div
            onClick={() => setCartOpen(true)}
            style={{
              background: 'var(--bg3)',
              border: '1px solid var(--border)',
              borderRadius: 12,
              padding: '8px 12px',
              marginBottom: 10,
              cursor: 'pointer',
              display: 'flex',
              flexDirection: 'column',
              gap: 4,
            }}
          >
            {stripItems.map(item => {
              const p = getProduct(item.product_id)
              return (
                <div key={item._key} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <span style={{ fontSize: 12, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}>{p?.name ?? `#${item.product_id}`}</span>
                  <span style={{ fontSize: 12, fontWeight: 700, color: '#f59e0b', fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>{fmtDraftQty(item.quantity, p?.unit_type)}</span>
                </div>
              )
            })}
            {hiddenCount > 0 && (
              <div style={{ fontSize: 11, color: 'var(--muted)', textAlign: 'right' }}>
                +{hiddenCount} ακόμα — δείτε όλα →
              </div>
            )}
          </div>
        )}

        {/* Full-width send button */}
        <button
          className="btn btn--primary btn--lg"
          style={{ width: '100%', opacity: cart.length === 0 ? 0.4 : 1 }}
          onClick={() => summaryBeforeSend && cart.length > 0 ? setSummaryOpen(true) : sendOrder()}
          disabled={cart.length === 0 || sending}
        >
          {sending ? 'Αποστολή…' : summaryBeforeSend && cart.length > 0 ? `ΣΥΝΟΨΗ (${cart.length})` : `ΑΠΟΣΤΟΛΗ${cart.length > 0 ? ` (${cart.length})` : ''}`}
        </button>

        {error && <p className="error-msg" style={{ marginTop: 8 }}>{error}</p>}
      </div>

      {/* ── Cart side drawer ────────────────────────────────────────────────── */}
      <>
        {/* Backdrop */}
        <div
          onClick={() => setCartOpen(false)}
          style={{
            position: 'fixed', inset: 0,
            background: 'rgba(0,0,0,0.55)',
            opacity: cartOpen ? 1 : 0,
            pointerEvents: cartOpen ? 'auto' : 'none',
            transition: 'opacity 240ms ease',
            zIndex: 50,
          }}
        />
        {/* Panel */}
        <div style={{
          position: 'fixed', top: 0, right: 0, bottom: 0,
          width: 'min(88vw, 380px)',
          background: 'var(--bg)',
          borderLeft: '1px solid var(--border)',
          transform: cartOpen ? 'translateX(0)' : 'translateX(100%)',
          transition: 'transform 280ms cubic-bezier(0.32, 0.72, 0, 1)',
          zIndex: 51,
          display: 'flex', flexDirection: 'column',
          boxShadow: cartOpen ? '-8px 0 32px rgba(0,0,0,0.4)' : 'none',
        }}>
          {/* Drawer header */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 16px', borderBottom: '1px solid var(--border)', flexShrink: 0 }}>
            <div>
              <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text)' }}>Παραγγελία</div>
              <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>{cart.length} {cart.length === 1 ? 'προϊόν' : 'προϊόντα'}</div>
            </div>
            <button onClick={() => setCartOpen(false)} style={{ background: 'var(--bg3)', border: 'none', borderRadius: '50%', width: 34, height: 34, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: 'var(--text)' }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
            </button>
          </div>

          {/* Item list */}
          <div style={{ flex: 1, overflowY: 'auto', padding: 12 }}>
            {cart.length === 0 ? (
              <p style={{ color: 'var(--muted)', textAlign: 'center', padding: '40px 0', fontSize: 14 }}>Η παραγγελία είναι κενή.</p>
            ) : courses.length > 0 ? (() => {
              // Group by course, ordered by course definition, "no course" last
              const groups = []
              courses.forEach(c => {
                const items = cart.filter(i => i.course_id === c.id)
                if (items.length > 0) groups.push({ course: c, items })
              })
              const noCourse = cart.filter(i => i.course_id == null || !courses.find(c => c.id === i.course_id))
              if (noCourse.length > 0) groups.push({ course: null, items: noCourse })

              return (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  {groups.map((group, gi) => (
                    <div key={group.course?.id ?? '__none__'} style={{ position: 'relative' }}>
                      {/* Colored left accent bar */}
                      <div style={{
                        position: 'absolute', left: 0, top: 0, bottom: 0,
                        width: 3, borderRadius: 2,
                        background: group.course ? group.course.color : 'var(--border)',
                      }} />
                      <div style={{ paddingLeft: 10 }}>
                        {/* Group header */}
                        <div style={{
                          fontSize: 10, fontWeight: 700,
                          color: group.course ? group.course.color : 'var(--muted)',
                          textTransform: 'uppercase', letterSpacing: 0.8,
                          marginBottom: 6,
                        }}>
                          {group.course ? group.course.name : 'No course'}
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                          {group.items.map(item => {
                            const product = getProduct(item.product_id)
                            return (
                              <CartItem
                                key={item._key}
                                item={item}
                                product={product}
                                summaryLines={buildItemSummary(item)}
                                sections={buildItemSections(item, product)}
                                onEdit={() => openEditDrawer(item)}
                                onRemove={() => removeFromCart(item._key)}
                                onChangeQty={qty => changeCartQty(item._key, qty)}
                              />
                            )
                          })}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )
            })() : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {cart.map(item => {
                  const product = getProduct(item.product_id)
                  return (
                    <CartItem
                      key={item._key}
                      item={item}
                      product={product}
                      summaryLines={buildItemSummary(item)}
                      sections={buildItemSections(item, product)}
                      onEdit={() => openEditDrawer(item)}
                      onRemove={() => removeFromCart(item._key)}
                      onChangeQty={qty => changeCartQty(item._key, qty)}
                    />
                  )
                })}
              </div>
            )}
          </div>

          {/* Order note area */}
          {cart.length > 0 && (
            <div style={{ padding: '0 12px 10px', flexShrink: 0 }}>
              {orderNoteEditing ? (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  <textarea
                    autoFocus
                    value={orderNote}
                    onChange={e => setOrderNote(e.target.value)}
                    placeholder="Σημείωση για ολόκληρη την παραγγελία…"
                    rows={3}
                    style={{
                      width: '100%', resize: 'none', padding: '10px 12px',
                      background: 'rgba(245,158,11,0.07)', border: '1.5px solid rgba(245,158,11,0.35)',
                      borderRadius: 10, fontSize: 14, color: 'var(--text)', lineHeight: 1.5,
                      outline: 'none', boxSizing: 'border-box', fontFamily: 'inherit',
                    }}
                  />
                  <button
                    onClick={() => setOrderNoteEditing(false)}
                    style={{ alignSelf: 'flex-end', background: 'none', border: 'none', fontSize: 12, fontWeight: 700, color: 'var(--accent)', cursor: 'pointer', padding: '2px 0' }}
                  >
                    Αποθήκευση
                  </button>
                </div>
              ) : orderNote ? (
                <div
                  onClick={() => setOrderNoteEditing(true)}
                  style={{ cursor: 'pointer', padding: '9px 12px', background: 'rgba(245,158,11,0.09)', border: '1.5px solid rgba(245,158,11,0.3)', borderRadius: 10, fontSize: 13, color: 'var(--text)', lineHeight: 1.5, whiteSpace: 'pre-wrap', position: 'relative' }}
                >
                  <span style={{ fontSize: 10, fontWeight: 700, color: '#f59e0b', textTransform: 'uppercase', letterSpacing: 0.6, display: 'block', marginBottom: 3 }}>Σημείωση Παραγγελίας</span>
                  {orderNote}
                  <span style={{ position: 'absolute', top: 8, right: 10, fontSize: 11, color: '#f59e0b', fontWeight: 700 }}>✎</span>
                </div>
              ) : (
                <button
                  onClick={() => setOrderNoteEditing(true)}
                  style={{
                    width: '100%', padding: '9px 12px',
                    background: 'var(--bg3)', border: '1.5px dashed var(--border)',
                    borderRadius: 10, fontSize: 13, color: 'var(--muted)',
                    cursor: 'pointer', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 7,
                  }}
                >
                  <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  Προσθήκη σημείωσης παραγγελίας
                </button>
              )}
            </div>
          )}

          {/* Drawer footer */}
          <div style={{ padding: '0 12px 20px', borderTop: '1px solid var(--border)', paddingTop: 12, flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
            <button
              className="btn btn--primary btn--lg"
              style={{ width: '100%' }}
              onClick={() => { setCartOpen(false); if (summaryBeforeSend) setSummaryOpen(true); else sendOrder() }}
              disabled={cart.length === 0 || sending}
            >
              {sending ? 'Αποστολή…' : summaryBeforeSend ? `ΣΥΝΟΨΗ (${cart.length})` : `ΑΠΟΣΤΟΛΗ (${cart.length})`}
            </button>
          </div>
        </div>
      </>

      {/* Edit drawer */}
      {editItem && (
        <OrderDrawer
          product={editItem.product}
          isOpen={!!editItem}
          onClose={() => setEditItem(null)}
          onAdd={handleEditSave}
          initialState={editItem.drawerState}
          courses={courses}
          quickNotes={quickNotes}
        />
      )}

      {/* Order summary modal (shown when summaryBeforeSend is enabled) */}
      {summaryOpen && (
        <OrderSummaryModal
          cart={cart}
          products={products}
          orderNote={orderNote}
          setOrderNote={setOrderNote}
          onSend={() => { setSummaryOpen(false); sendOrder() }}
          onClose={() => setSummaryOpen(false)}
          sending={sending}
        />
      )}

      {/* ── Search modal ─────────────────────────────────────────────────────── */}
      {searchOpen && (
        <SearchModal
          products={products}
          query={searchQuery}
          setQuery={setSearchQuery}
          onClose={() => setSearchOpen(false)}
          onAdd={item => { addToCart(item); setSearchOpen(false) }}
          courses={courses}
          quickNotes={quickNotes}
        />
      )}

      {/* Customer count modal */}
      {customerCountOpen && (
        <CustomerCountModal
          value={customerCount}
          onChange={v => setCustomerCount(v)}
          onClose={() => setCustomerCountOpen(false)}
        />
      )}

      {/* Global course modal */}
      {globalCourseOpen && courses.length > 0 && (
        <GlobalCourseModal
          courses={courses}
          selected={globalCourseId}
          onSelect={setGlobalCourseId}
          onClose={() => setGlobalCourseOpen(false)}
        />
      )}

      {/* Deal offer modal — shown one at a time after order is sent */}
      {activeDealOffer && (
        <DealOfferModal
          offer={activeDealOffer}
          products={products}
          onAccept={async (freeItems) => {
            try {
              await client.post('/api/pricing/deals/accept', {
                deal_id: activeDealOffer.deal_id,
                order_id: activeDealOffer._orderId,
                free_items: freeItems,
                trigger_item_id: activeDealOffer.target_order_item_id ?? null,
              })
            } catch { /* log but continue */ }
            // Advance to next offer or finish
            if (dealOffers.length > 0) {
              setActiveDealOffer(dealOffers[0])
              setDealOffers(prev => prev.slice(1))
            } else {
              setActiveDealOffer(null)
              if (printAck?.allOk) setTimeout(() => navigate('/tables'), 600)
            }
          }}
          onDismiss={async () => {
            try {
              await client.post('/api/pricing/deals/dismiss', {
                deal_id: activeDealOffer.deal_id,
                order_id: activeDealOffer._orderId,
              })
            } catch { /* ignore */ }
            if (dealOffers.length > 0) {
              setActiveDealOffer(dealOffers[0])
              setDealOffers(prev => prev.slice(1))
            } else {
              setActiveDealOffer(null)
              if (printAck?.allOk) setTimeout(() => navigate('/tables'), 600)
            }
          }}
        />
      )}

      {/* Full-screen success overlay — blocks all interaction while navigating */}
      {printAck?.allOk && !activeDealOffer && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 9999,
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
          background: 'rgba(0,0,0,0.72)',
          animation: 'fadeInOverlay 180ms ease',
        }}>
          <div style={{
            background: printAck._offline ? '#451a03' : printAck._pending ? '#1c1917' : '#14532d',
            border: `2px solid ${printAck._offline ? '#f59e0b' : printAck._pending ? '#f59e0b' : '#22c55e'}`,
            borderRadius: 20, padding: '36px 48px',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16,
            animation: 'popIn 220ms cubic-bezier(0.34,1.56,0.64,1)',
          }}>
            <svg width="56" height="56" viewBox="0 0 24 24" fill="none">
              <circle cx="12" cy="12" r="11" stroke={printAck._offline || printAck._pending ? '#f59e0b' : '#22c55e'} strokeWidth="2"/>
              {printAck._offline || printAck._pending ? (
                <path d="M12 8v5M12 16h.01" stroke="#f59e0b" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
              ) : (
                <path d="M7 12.5l3.5 3.5 6.5-7" stroke="#22c55e" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
              )}
            </svg>
            <span style={{ color: printAck._offline || printAck._pending ? '#fcd34d' : '#86efac', fontWeight: 700, fontSize: 18, letterSpacing: 0.3 }}>
              {printAck._offline ? 'Αποθηκεύτηκε Offline' : printAck._pending ? 'Στάλθηκε — Εκτύπωση σε εξέλιξη' : 'Εκτυπώθηκε Επιτυχώς'}
            </span>
          </div>
          <style>{`
            @keyframes fadeInOverlay { from { opacity: 0 } to { opacity: 1 } }
            @keyframes popIn { from { transform: scale(0.7); opacity: 0 } to { transform: scale(1); opacity: 1 } }
          `}</style>
        </div>
      )}
    </div>
  )
}

// ── Deal Offer Modal ──────────────────────────────────────────────────────────

function DealOfferModal({ offer, products, onAccept, onDismiss }) {
  const isFreeItem = offer.action_type === 'free_item'
  const isFreeChoice = offer.action_type === 'free_choice'
  const isDiscount = ['set_price','add_amount','add_percent','apply_modifier'].includes(offer.action_type)

  // For free_choice: track which products are selected
  const [selectedChoices, setSelectedChoices] = useState([])
  const remaining = (offer.free_quantity ?? 1) - selectedChoices.length

  function toggleChoice(productId) {
    setSelectedChoices(prev => {
      if (prev.includes(productId)) return prev.filter(x => x !== productId)
      if (prev.length >= (offer.free_quantity ?? 1)) return prev // at capacity
      return [...prev, productId]
    })
  }

  function handleAccept() {
    if (isFreeItem) {
      onAccept([{ product_id: offer.free_item_id, quantity: offer.free_quantity ?? 1 }])
    } else if (isFreeChoice) {
      onAccept(selectedChoices.map(id => ({ product_id: id, quantity: 1 })))
    } else {
      onAccept([]) // discount deal — no free items to add
    }
  }

  const canConfirm = isFreeChoice ? selectedChoices.length > 0 : true

  return (
    <div className="modal-overlay" style={{ zIndex: 600 }} onClick={onDismiss}>
      <div className="modal-sheet" onClick={e => e.stopPropagation()} style={{ gap: 0 }}>
        <div className="modal-handle" />

        {/* Header */}
        <div style={{ textAlign: 'center', padding: '0 8px 16px' }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            width: 48, height: 48, borderRadius: '50%',
            background: 'rgba(167,139,250,0.15)', marginBottom: 10,
          }}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
              <path d="M20 12v10H4V12M22 7H2v5h20V7zM12 22V7M12 7H7.5a2.5 2.5 0 010-5C11 2 12 7 12 7zM12 7h4.5a2.5 2.5 0 000-5C13 2 12 7 12 7z"
                stroke="#a78bfa" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <h2 style={{ margin: 0, fontSize: 17, fontWeight: 700, color: '#a78bfa' }}>Προσφορά Ενεργοποιήθηκε!</h2>
          <p style={{ margin: '6px 0 0', fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{offer.deal_name}</p>
        </div>

        {/* Free item — single specific product */}
        {isFreeItem && offer.free_item_name && (
          <div style={{
            margin: '0 0 16px', padding: '14px 16px',
            background: 'rgba(34,197,94,0.08)', border: '1.5px solid rgba(34,197,94,0.3)',
            borderRadius: 12,
          }}>
            <p style={{ margin: 0, fontSize: 13, color: 'var(--muted)', marginBottom: 4 }}>Δωρεάν προϊόν:</p>
            <p style={{ margin: 0, fontSize: 15, fontWeight: 700, color: '#4ade80' }}>
              {offer.free_item_name}
              {offer.free_quantity > 1 && <span style={{ color: '#f59e0b', marginLeft: 6 }}>×{offer.free_quantity}</span>}
            </p>
          </div>
        )}

        {/* Free choice — pick from pool */}
        {isFreeChoice && offer.free_choices?.length > 0 && (
          <div style={{ marginBottom: 16 }}>
            <p style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 8 }}>
              Επιλέξτε {offer.free_quantity ?? 1} δωρεάν {offer.free_quantity === 1 ? 'προϊόν' : 'προϊόντα'}
              {remaining > 0 && <span style={{ color: '#a78bfa', marginLeft: 4 }}>({remaining} ακόμα)</span>}
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 220, overflowY: 'auto' }}>
              {offer.free_choices.map(choice => {
                const checked = selectedChoices.includes(choice.id)
                const disabled = !checked && remaining === 0
                return (
                  <button key={choice.id} onClick={() => !disabled && toggleChoice(choice.id)}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 10,
                      padding: '10px 12px', borderRadius: 10, border: 'none', cursor: disabled ? 'not-allowed' : 'pointer',
                      background: checked ? 'rgba(167,139,250,0.15)' : 'var(--bg3)',
                      opacity: disabled ? 0.4 : 1, textAlign: 'left',
                    }}>
                    <div style={{
                      width: 20, height: 20, borderRadius: 5, flexShrink: 0,
                      background: checked ? '#a78bfa' : 'var(--border)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      {checked && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3" strokeLinecap="round"><path d="M20 6L9 17l-5-5"/></svg>}
                    </div>
                    <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{choice.name}</span>
                  </button>
                )
              })}
            </div>
          </div>
        )}

        {/* Discount deal — show before/after */}
        {isDiscount && offer.price_before != null && offer.price_after != null && (
          <div style={{
            margin: '0 0 16px', padding: '14px 16px',
            background: 'rgba(34,197,94,0.08)', border: '1.5px solid rgba(34,197,94,0.3)',
            borderRadius: 12, textAlign: 'center',
          }}>
            <span style={{ fontSize: 14, color: 'var(--muted)', textDecoration: 'line-through' }}>
              {offer.price_before.toFixed(2)} €
            </span>
            <span style={{ fontSize: 22, fontWeight: 800, color: '#4ade80', margin: '0 12px' }}>
              {offer.price_after.toFixed(2)} €
            </span>
          </div>
        )}

        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn btn--secondary" style={{ flex: 1 }} onClick={onDismiss}>
            Παράβλεψη
          </button>
          <button className="btn btn--primary" style={{ flex: 1, background: '#7c3aed', borderColor: '#7c3aed' }}
            onClick={handleAccept} disabled={!canConfirm}>
            {isFreeItem ? 'Προσθήκη Δωρεάν' : isFreeChoice ? 'Επιβεβαίωση' : 'Εφαρμογή'}
          </button>
        </div>
      </div>
    </div>
  )
}

// ── Quick-Add Toast ───────────────────────────────────────────────────────────

function QuickAddToast({ product, count }) {
  const initials = product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
  return (
    <div style={{
      position: 'fixed', top: 62, left: '50%',
      transform: 'translateX(-50%)',
      zIndex: 400,
      background: 'var(--bg)',
      border: '1px solid var(--border)',
      borderRadius: 14,
      boxShadow: '0 8px 32px rgba(0,0,0,0.35)',
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '10px 16px 10px 10px',
      minWidth: 220, maxWidth: 'min(88vw, 340px)',
      animation: 'qa-toast-in 120ms cubic-bezier(0.34,1.56,0.64,1)',
      pointerEvents: 'none',
    }}>
      {/* Thumb */}
      <div style={{
        width: 46, height: 46, borderRadius: 10, flexShrink: 0,
        background: 'var(--bg3)', overflow: 'hidden',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {product.image_url
          ? <img src={product.image_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          : <span style={{ fontSize: 16, fontWeight: 700, color: 'var(--muted)' }}>{initials}</span>
        }
      </div>
      {/* Name */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 13, fontWeight: 600, color: 'var(--text)',
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>{product.name}</div>
        <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 1 }}>στο καλάθι</div>
      </div>
      {/* Count badge */}
      <div style={{
        minWidth: 36, height: 36, borderRadius: 10,
        background: 'var(--accent)', color: 'var(--accent-fg)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 17, fontWeight: 800, flexShrink: 0,
        padding: '0 8px',
      }}>×{count}</div>
      <style>{`
        @keyframes qa-toast-in {
          from { opacity: 0; transform: translateX(-50%) scale(0.88); }
          to   { opacity: 1; transform: translateX(-50%) scale(1); }
        }
      `}</style>
    </div>
  )
}

// ── Cart Item (used in the side drawer) ───────────────────────────────────────

const SECTION_META = {
  prefs:   { icon: '◉', label: null },
  quick:   { icon: '>', label: null },
  extras:  { icon: '+', label: null },
  removed: { icon: '−', label: null },
  note:    { icon: 'i', label: null },
}

function SectionIcon({ type }) {
  const icons = {
    prefs:   <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="4" fill="#f59e0b"/><circle cx="12" cy="12" r="9" stroke="#f59e0b" strokeWidth="2"/></svg>,
    quick:   <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M5 12h14M13 6l6 6-6 6" stroke="#a3e635" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg>,
    extras:  <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M12 5v14M5 12h14" stroke="#60a5fa" strokeWidth="2.5" strokeLinecap="round"/></svg>,
    removed: <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M5 12h14" stroke="#ef4444" strokeWidth="2.5" strokeLinecap="round"/></svg>,
    note:    <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="1.5" fill="#94a3b8"/><path d="M12 7v1M12 16v1" stroke="#94a3b8" strokeWidth="2" strokeLinecap="round"/><circle cx="12" cy="12" r="9" stroke="#94a3b8" strokeWidth="1.5"/></svg>,
  }
  return <span style={{ display: 'inline-flex', alignItems: 'center', flexShrink: 0 }}>{icons[type] ?? null}</span>
}

function CartItem({ item, product, summaryLines, sections, onEdit, onRemove, onChangeQty }) {
  const [expanded, setExpanded] = useState(false)
  const hasDetails = sections.length > 0

  return (
    <div style={{ background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }}>
      {/* Whole header row is always clickable to expand (qty stepper is always available) */}
      <div
        onClick={() => setExpanded(e => !e)}
        style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', cursor: 'pointer' }}
      >
        {/* Chevron — always shown */}
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" style={{ transform: `rotate(${expanded ? 180 : 0}deg)`, transition: 'transform 180ms', flexShrink: 0, color: 'var(--muted)' }}>
          <path d="M6 9L12 15L18 9" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
        </svg>

        {/* Name */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {product?.name ?? `#${item.product_id}`}
          </div>
          {!expanded && hasDetails && (
            <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {summaryLines[0]}{summaryLines.length > 1 ? ` +${summaryLines.length - 1}` : ''}
            </div>
          )}
        </div>

        {/* Quantity on the right */}
        <span style={{ color: '#f59e0b', fontSize: 13, fontWeight: 700, fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>{fmtDraftQty(item.quantity, product?.unit_type)}</span>

        {/* Edit — stop propagation so it doesn't toggle expand */}
        <button onClick={e => { e.stopPropagation(); onEdit() }} style={{ background: 'none', border: '1px solid var(--border)', borderRadius: 7, color: 'var(--muted)', cursor: 'pointer', padding: '3px 9px', fontSize: 12, fontWeight: 500, flexShrink: 0 }}>
          Επεξ.
        </button>
        {/* Remove */}
        <button onClick={e => { e.stopPropagation(); onRemove() }} style={{ background: 'none', border: 'none', color: 'var(--danger)', cursor: 'pointer', padding: 4, display: 'flex', alignItems: 'center', flexShrink: 0 }}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
        </button>
      </div>

      {expanded && (
        <div style={{ paddingBottom: 10 }}>
          {sections.map((sec, si) => (
            <div key={si}>
              <div style={{ margin: '0 12px', height: 1, background: 'var(--border)' }} />
              <div style={{ padding: '6px 12px 2px', display: 'flex', flexDirection: 'column', gap: 4 }}>
                {sec.type === 'prefs' && sec.lines.map((line, li) => (
                  <div key={li} style={{ display: 'flex', alignItems: 'flex-start', gap: 7 }}>
                    <SectionIcon type="prefs" />
                    <span style={{ fontSize: 12, lineHeight: 1.4, flex: 1 }}>
                      <span style={{ color: 'var(--muted)', display: 'block', fontSize: 11 }}>{line.setName}</span>
                      <span style={{ color: 'var(--text)' }}>{line.values.join(' · ')}</span>
                    </span>
                  </div>
                ))}
                {sec.type === 'quick' && sec.lines.map((line, li) => (
                  <div key={li} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                    <SectionIcon type="quick" />
                    <span style={{ fontSize: 12, color: 'var(--text)', flex: 1 }}>
                      {line.name}
                      {line._qty > 1 && <span style={{ color: '#f59e0b', marginLeft: 4, fontWeight: 700 }}>×{line._qty}</span>}
                    </span>
                  </div>
                ))}
                {sec.type === 'extras' && sec.lines.map((line, li) => (
                  <div key={li} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                    <SectionIcon type="extras" />
                    <span style={{ fontSize: 12, color: 'var(--text)', flex: 1 }}>
                      {line.name}
                      {line.subName && <span> · {line.subName}</span>}
                      {line.qty > 1 && <span style={{ color: '#f59e0b', marginLeft: 4, fontWeight: 700 }}>×{line.qty}</span>}
                    </span>
                  </div>
                ))}
                {sec.type === 'removed' && sec.lines.map((line, li) => (
                  <div key={li} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                    <SectionIcon type="removed" />
                    <span style={{ fontSize: 12, color: 'var(--text)', flex: 1 }}>Χωρίς {line.name}</span>
                  </div>
                ))}
                {sec.type === 'note' && sec.lines.map((line, li) => (
                  <div key={li} style={{ display: 'flex', alignItems: 'flex-start', gap: 7 }}>
                    <SectionIcon type="note" />
                    <span style={{ fontSize: 12, color: 'var(--text)', lineHeight: 1.4, flex: 1, whiteSpace: 'pre-wrap' }}>{line.name}</span>
                  </div>
                ))}
              </div>
            </div>
          ))}

          {/* ── Quick qty row — hidden for decimal-unit items (edit via modal instead) ── */}
          {!_AI_UNIT_LABELS[product?.unit_type] && (<>
          <div style={{ margin: '8px 12px 0', height: 1, background: 'var(--border)' }} />
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16,
            padding: '10px 12px 2px',
          }}>
            <button
              onClick={e => { e.stopPropagation(); onChangeQty(item.quantity - 1) }}
              style={{
                width: 36, height: 36, borderRadius: '50%',
                background: 'var(--bg3)', border: '1px solid var(--border)',
                color: item.quantity <= 1 ? 'var(--muted)' : 'var(--danger)',
                fontSize: 20, fontWeight: 700, cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}
            >
              {item.quantity <= 1 ? (
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
              ) : '−'}
            </button>
            <span style={{ fontSize: 16, fontWeight: 700, color: 'var(--text)', minWidth: 28, textAlign: 'center' }}>
              {item.quantity}
            </span>
            <button
              onClick={e => { e.stopPropagation(); onChangeQty(item.quantity + 1) }}
              style={{
                width: 36, height: 36, borderRadius: '50%',
                background: 'var(--bg3)', border: '1px solid var(--border)',
                color: '#22c55e',
                fontSize: 20, fontWeight: 700, cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}
            >+</button>
          </div>
          </>)}
        </div>
      )}
    </div>
  )
}

// ── Search Modal ──────────────────────────────────────────────────────────────


function SearchModal({ products, query, setQuery, onClose, onAdd, courses = [], quickNotes }) {
  const [drawerProduct, setDrawerProduct] = useState(null)
  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())
      )

  function openProduct(p) {
    // Blur the input first so the keyboard dismisses, then open the drawer
    document.activeElement?.blur()
    setDrawerProduct(p)
  }

  // The modal is position:fixed anchored to bottom:0.
  // When the soft keyboard opens on mobile the browser shrinks the visual
  // viewport and fixed elements reposition automatically — the panel sits
  // right on top of the keyboard without any JS measurement needed.
  return (
    <>
      {/* Dim backdrop — tap to close */}
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 200 }} />

      {/* Panel: fixed to bottom, grows upward, capped at 60vh so results don't
          push the input off screen on short viewports */}
      <div style={{
        position: 'fixed', left: 0, right: 0, bottom: 0,
        zIndex: 201,
        background: 'var(--bg)',
        borderTop: '1px solid var(--border)',
        display: 'flex', flexDirection: 'column',
        maxHeight: '60vh',
      }}>
        {/* Results scroll area — flex:1 so it takes space above the input */}
        <div style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>
          {query.trim().length === 0 ? (
            <p style={{ textAlign: 'center', color: 'var(--muted)', padding: '16px 20px', fontSize: 14 }}>
              Πληκτρολογήστε για αναζήτηση…
            </p>
          ) : results.length === 0 ? (
            <p style={{ textAlign: 'center', color: 'var(--muted)', padding: '16px 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={() => openProduct(p)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  width: '100%', padding: '10px 16px',
                  background: 'none', border: 'none', cursor: 'pointer',
                  borderBottom: '1px solid var(--border)',
                  textAlign: 'left',
                }}
              >
                <div style={{
                  width: 40, height: 40, borderRadius: 10, flexShrink: 0,
                  background: 'var(--bg3)', 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: 13, fontWeight: 700, color: 'var(--muted)' }}>{initials}</span>
                  }
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {p.name}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>
                    {Number(p.base_price).toFixed(2)} €
                  </div>
                </div>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" style={{ color: 'var(--muted)', flexShrink: 0 }}>
                  <path d="M9 18l6-6-6-6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
            )
          })}
        </div>

        {/* Search input — pinned at the bottom of the panel, above the keyboard */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '10px 12px 12px',
          borderTop: '1px solid var(--border)',
          flexShrink: 0,
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" style={{ color: 'var(--muted)', 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
            autoFocus
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder="Αναζήτηση προϊόντος…"
            style={{
              flex: 1, height: 44, background: 'var(--bg2)',
              border: '1px solid var(--border)', borderRadius: 12,
              padding: '0 12px', fontSize: 16, color: 'var(--text)',
              fontFamily: 'inherit', outline: 'none',
            }}
          />
          <button
            onClick={onClose}
            style={{
              background: 'var(--bg3)', border: 'none', borderRadius: '50%',
              width: 36, height: 36, flexShrink: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              cursor: 'pointer', color: 'var(--text)',
            }}
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
              <path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
            </svg>
          </button>
        </div>
      </div>

      {/* Product drawer — closes search modal when item is added */}
      {drawerProduct && (
        <OrderDrawer
          product={drawerProduct}
          isOpen
          onClose={() => setDrawerProduct(null)}
          onAdd={item => { onAdd(item); setDrawerProduct(null); onClose() }}
          courses={courses}
          quickNotes={quickNotes}
        />
      )}
    </>
  )
}
