import { useRef, useState } from 'react'
import useTableViewStore from '../store/tableViewStore'

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

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

function fmtDateTime(iso) {
  if (!iso) return null
  try {
    const d = new Date(iso)
    return d.toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })
  } catch { return null }
}

// ── Icons ─────────────────────────────────────────────────────────────────────

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 ExpandArrow({ expanded, onClick }) {
  return (
    <button
      onClick={e => { e.stopPropagation(); onClick() }}
      style={{
        background: 'none', border: 'none', padding: 4, cursor: 'pointer',
        color: 'var(--muted)', display: 'flex', alignItems: 'center', flexShrink: 0,
      }}
    >
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
        style={{ transform: `rotate(${expanded ? 180 : 0}deg)`, transition: 'transform 180ms' }}>
        <path d="M6 9L12 15L18 9" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
      </svg>
    </button>
  )
}

// ── Parse selected_options into grouped sections ──────────────────────────────

function buildSections(item) {
  const sections = []
  const opts = (() => {
    try { return item.selected_options ? JSON.parse(item.selected_options) : [] } catch { return [] }
  })()
  const removed = (() => {
    try { return item.removed_ingredients ? JSON.parse(item.removed_ingredients) : [] } catch { return [] }
  })()

  const prefGroups = []
  const extraGroups = []
  const quickLines = []

  const idCount = {}
  opts.forEach(o => { if (o.id != null) idCount[o.id] = (idCount[o.id] || 0) + 1 })

  const consumedAsSubAtIndex = new Set()
  let i = 0
  while (i < opts.length) {
    const o = opts[i]
    if (consumedAsSubAtIndex.has(i)) { i++; continue }

    if (o.id == null) {
      const existing = quickLines.find(x => x.name === o.name)
      if (existing) existing._qty = (existing._qty || 1) + 1
      else quickLines.push({ name: o.name, _qty: 1 })
      i++
      continue
    }

    let subName = null
    if (i + 1 < opts.length && opts[i + 1].id == null) {
      subName = opts[i + 1].name
      consumedAsSubAtIndex.add(i + 1)
    }

    if (idCount[o.id] > 1) {
      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 {
      const value = subName ? `${o.name} · ${subName}` : o.name
      prefGroups.push({ setName: null, values: [value] })
    }
    i++
  }

  if (prefGroups.length > 0) sections.push({ type: 'prefs', lines: prefGroups })
  if (quickLines.length > 0) sections.push({ type: 'quick', lines: quickLines })
  if (extraGroups.length > 0) sections.push({ type: 'extras', lines: extraGroups })
  if (removed.length > 0) sections.push({ type: 'removed', lines: removed.map(n => ({ name: n })) })
  if (item.notes) sections.push({ type: 'note', lines: [{ name: item.notes }] })

  return sections
}

// ── KDS colour strip ──────────────────────────────────────────────────────────

const KDS_COLORS = {
  pending:   { textColor: '#f59e0b', label: 'ΕΚΚΡΕΜΕΙ',    icon: '⏳', dot: '#f59e0b' },
  preparing: { textColor: '#60a5fa', label: 'ΕΤΟΙΜΑΖΕΤΑΙ', icon: '🔥', dot: '#60a5fa' },
  done:      { textColor: '#4ade80', label: 'READY',        icon: '✓',  dot: '#4ade80' },
  served:    { textColor: null,      label: null,           icon: null, dot: null },
}

// ── Shared expanded details panel ─────────────────────────────────────────────

function OptionsPanel({ sections }) {
  return (
    <div style={{ paddingBottom: 8 }}>
      {sections.map((sec, si) => (
        <div key={si}>
          <div style={{ margin: '0 12px', height: 1, background: 'var(--border)' }} />
          <div style={{ padding: '5px 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 }}>
                  {line.setName && (
                    <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>
      ))}
    </div>
  )
}

// ── KDS badge/icon renderer ───────────────────────────────────────────────────

function KdsBadge({ kdsColor, kdsDisplayStyle }) {
  if (!kdsColor?.label) return null
  if (kdsDisplayStyle === 'icon' && kdsColor.dot) {
    return (
      <span style={{
        width: 8, height: 8, borderRadius: '50%',
        background: kdsColor.dot, flexShrink: 0, display: 'inline-block',
      }} title={kdsColor.label} />
    )
  }
  return (
    <span style={{
      fontSize: 9, fontWeight: 800, letterSpacing: 0.4,
      color: kdsColor.textColor,
      borderRadius: 3, padding: '1px 5px',
      border: `1px solid ${kdsColor.textColor}60`,
      flexShrink: 0,
    }}>{kdsColor.label}</span>
  )
}

// ── Price event label helpers ─────────────────────────────────────────────────

const PRICING_EVENT_STYLE = {
  modifier_applied:    { color: '#60a5fa', label: null },      // label comes from modifier_name
  waiter_discount:     { color: '#c084fc', label: 'Έκπτωση' },
  free_item_added:     { color: '#4ade80', label: 'Δωρεάν' },
  deal_offer_accepted: { color: '#4ade80', label: null },       // label from deal_name
}

function PricingRows({ events, layout, nameIndent = 12 }) {
  const rows = events.filter(ev =>
    ev.event_type === 'modifier_applied' ||
    ev.event_type === 'waiter_discount' ||
    ev.event_type === 'free_item_added'
  )
  if (rows.length === 0) return null

  // Match OptionsPanel container padding: section divider + inner padding
  return (
    <div>
      <div style={{ margin: `0 12px`, height: 1, background: 'var(--border)' }} />
      <div style={{ padding: `4px 12px 4px ${nameIndent}px`, display: 'flex', flexDirection: 'column', gap: 3 }}>
        {rows.map((ev, i) => {
          const evStyle = PRICING_EVENT_STYLE[ev.event_type] || { color: '#94a3b8', label: ev.event_type }
          const label = ev.modifier_name || ev.deal_name || evStyle.label || ev.event_type
          const delta = ev.delta_amount
          const afterPrice = ev.price_after

          return (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" style={{ flexShrink: 0 }}>
                <circle cx="9" cy="9" r="2" stroke={evStyle.color} strokeWidth="2"/>
                <circle cx="15" cy="15" r="2" stroke={evStyle.color} strokeWidth="2"/>
                <path d="M5 19L19 5" stroke={evStyle.color} strokeWidth="2" strokeLinecap="round"/>
              </svg>
              <span style={{ fontSize: 12, color: evStyle.color, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', lineHeight: 1.4 }}>
                {label}
              </span>
              {delta != null && (
                <span style={{ fontSize: 12, color: evStyle.color, fontWeight: 700, flexShrink: 0, marginLeft: 8 }}>
                  {delta > 0 ? '+' : ''}{delta.toFixed(2)} €
                </span>
              )}
            </div>
          )
        })}
      </div>
    </div>
  )
}

// Small badge shown on the main item row to hint that pricing changes exist
function PricingBadge({ events }) {
  if (!events || events.length === 0) return null
  const hasDiscount = events.some(ev => ev.event_type === 'waiter_discount')
  const hasModifier = events.some(ev => ev.event_type === 'modifier_applied')
  const hasFree = events.some(ev => ev.event_type === 'free_item_added')

  const icons = []
  if (hasModifier) icons.push(
    <svg key="mod" width="10" height="10" viewBox="0 0 24 24" fill="none" title="Τροποποιητής">
      <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" stroke="#60a5fa" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  )
  if (hasDiscount) icons.push(
    <svg key="disc" width="10" height="10" viewBox="0 0 24 24" fill="none" title="Έκπτωση">
      <circle cx="9" cy="9" r="2" stroke="#c084fc" strokeWidth="2"/>
      <circle cx="15" cy="15" r="2" stroke="#c084fc" strokeWidth="2"/>
      <path d="M5 19L19 5" stroke="#c084fc" strokeWidth="2" strokeLinecap="round"/>
    </svg>
  )
  if (hasFree) icons.push(
    <svg key="free" width="10" height="10" viewBox="0 0 24 24" fill="none" title="Δωρεάν">
      <path d="M20 12v10H4V12M22 7H2v5h20V7z" stroke="#4ade80" strokeWidth="2" strokeLinecap="round"/>
    </svg>
  )

  if (icons.length === 0) return null
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 2, marginLeft: 3 }}>
      {icons}
    </span>
  )
}

// Deal badge on items that triggered or were added by a deal
function DealBadge({ item }) {
  if (item.deal_id) {
    return (
      <span style={{
        fontSize: 9, fontWeight: 700, padding: '1px 5px', borderRadius: 4,
        background: 'rgba(167,139,250,0.15)', color: '#a78bfa',
        border: '1px solid rgba(167,139,250,0.4)', flexShrink: 0, letterSpacing: 0.3,
      }}>
        ΔΩΡΕΑΝ
      </span>
    )
  }
  return null
}

function MergedBadge({ item }) {
  if (!item._isMerged) return null
  return (
    <span style={{
      fontSize: 9, fontWeight: 700, padding: '1px 5px', borderRadius: 4,
      background: 'rgba(99,102,241,0.15)', color: '#a5b4fc',
      border: '1px solid rgba(99,102,241,0.35)', flexShrink: 0, letterSpacing: 0.3,
    }}>
      ∑{item._sourceIds?.length}
    </span>
  )
}

// ── ItemRow ───────────────────────────────────────────────────────────────────

function ItemRow({ item, selectable, selected, onToggle, onLongPress, isLast, kdsDisplayStyle, orderItemLayout, waiterMap, courses, priceEvents }) {
  const isPaid = item.status === 'paid'
  const isCancelled = item.status === 'cancelled'
  const effectiveKds = item.kds_status || 'pending'
  const isServed = effectiveKds === 'served'
  const kdsColor = !isCancelled && !isServed ? KDS_COLORS[effectiveKds] : null

  const sections = buildSections(item)
  const hasDetails = sections.length > 0
  const [expanded, setExpanded] = useState(false)

  const pressTimer = useRef(null)
  const didLongPress = useRef(false)
  const touchStartPos = useRef({ x: 0, y: 0 })

  const canSelect = selectable && !isCancelled

  function handleTouchStart(e) {
    if (!canSelect || !onLongPress) return
    didLongPress.current = false
    touchStartPos.current = { x: e.touches[0].clientX, y: e.touches[0].clientY }
    pressTimer.current = setTimeout(() => {
      didLongPress.current = true
      onLongPress(item)
    }, 500)
  }

  function handleTouchMove(e) {
    const dx = Math.abs(e.touches[0].clientX - touchStartPos.current.x)
    const dy = Math.abs(e.touches[0].clientY - touchStartPos.current.y)
    if (dx > 8 || dy > 8) clearTimeout(pressTimer.current)
  }

  function handleTouchEnd() { clearTimeout(pressTimer.current) }

  function handleBodyClick() {
    if (didLongPress.current) { didLongPress.current = false; return }
    if (canSelect) onToggle(item.id)
  }

  const nameColor = !isCancelled && !isServed ? kdsColor?.textColor : null
  const totalPrice = fmtPrice(((item.unit_price ?? 0) + (item.price_adjustment ?? 0)) * item.quantity)
  const unitPriceAdjusted = (item.unit_price ?? 0) + (item.price_adjustment ?? 0)
  // Cast to boolean so JSX never renders the raw number 0
  const hasPriceAdj = !!(item.price_adjustment && item.price_adjustment !== 0)

  const courseBadge = item.course_id != null && courses?.length > 0 ? (() => {
    const course = courses.find(c => c.id === item.course_id)
    if (!course) return null
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        width: 16, height: 16, borderRadius: '50%',
        background: course.color, color: '#fff',
        fontSize: 9, fontWeight: 700, flexShrink: 0, marginLeft: 4,
      }}>
        {courses.indexOf(course) + 1}
      </span>
    )
  })() : null

  const nameEl = (
    <span
      className={[
        'order-item__name',
        isCancelled ? 'order-item__name--cancelled' : '',
        isServed ? 'order-item__name--served' : '',
        effectiveKds === 'done' && !isCancelled && !isServed ? 'kds-ready-flash-text' : '',
      ].filter(Boolean).join(' ')}
      style={nameColor ? { color: nameColor } : undefined}
    >
      {item.product?.name || `#${item.product_id}`}
      {courseBadge}
    </span>
  )

  const paidBadge = isPaid && !isServed ? <span className="badge badge--paid">Paid</span> : null
  const cancelledBadge = isCancelled ? <span className="badge badge--cancelled">Cancelled</span> : null
  const draftBadge = !isPaid && !isCancelled && !item.printed
    ? <span className="badge badge--draft" title="Δεν εκτυπώθηκε ακόμα">⏳</span>
    : null

  // Whole-card click+touch handlers on the outer wrapper
  const cardHandlers = {
    onClick: handleBodyClick,
    onTouchStart: handleTouchStart,
    onTouchMove: handleTouchMove,
    onTouchEnd: handleTouchEnd,
    onTouchCancel: handleTouchEnd,
  }

  const cardClass = [
    'order-item',
    isPaid && isServed ? 'order-item--paid' : '',
    isCancelled ? 'order-item--cancelled' : '',
    selectable && selected ? 'order-item--selected' : '',
    isLast ? 'order-item--last' : '',
  ].filter(Boolean).join(' ')

  // Indent of secondary rows — lines up with the start of the item name
  const nameIndent = selectable && !isCancelled ? 44 : 12

  // ── COMPACT ──────────────────────────────────────────────────────────────────
  const hasPricingRows = priceEvents && priceEvents.some(ev => ['modifier_applied','waiter_discount','free_item_added'].includes(ev.event_type))
  const [pricingExpanded, setPricingExpanded] = useState(false)

  if (orderItemLayout === 'compact') {
    return (
      <div
        className={cardClass}
        style={{ userSelect: 'none', position: 'relative', cursor: canSelect ? 'pointer' : 'default' }}
        {...cardHandlers}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '7px 12px' }}>
          {selectable && !isCancelled && (
            <span style={{ color: selected ? '#f59e0b' : '#475569', flexShrink: 0, fontSize: 16 }}>
              {selected ? '☑' : '☐'}
            </span>
          )}

          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
              {nameEl}
              <MergedBadge item={item} />
              <DealBadge item={item} />
              <PricingBadge events={priceEvents} />
              {(hasDetails || hasPricingRows) && (
                <ExpandArrow
                  expanded={expanded || pricingExpanded}
                  onClick={() => {
                    const next = !(expanded || pricingExpanded)
                    if (hasDetails) setExpanded(next)
                    if (hasPricingRows) setPricingExpanded(next)
                  }}
                />
              )}
              {paidBadge}
              {cancelledBadge}
              {draftBadge}
            </div>
          </div>

          <KdsBadge kdsColor={kdsColor} kdsDisplayStyle={kdsDisplayStyle} />
          <span className="order-item__qty">{fmtQty(item.quantity, item.unit_type)}</span>
          <span className="order-item__price" style={hasPriceAdj ? { color: '#60a5fa' } : undefined}>
            {totalPrice}
          </span>
        </div>

        {(expanded || pricingExpanded) && hasPricingRows && (
          <PricingRows events={priceEvents} layout="compact" nameIndent={nameIndent} />
        )}
        {expanded && hasDetails && <OptionsPanel sections={sections} />}
      </div>
    )
  }

  // ── EXPANDED ─────────────────────────────────────────────────────────────────
  if (orderItemLayout === 'expanded') {
    return (
      <div
        className={cardClass}
        style={{ userSelect: 'none', position: 'relative', cursor: canSelect ? 'pointer' : 'default' }}
        {...cardHandlers}
      >
        {/* Row 1: checkbox · name · badges · expand arrow · KDS badge */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px 2px' }}>
          {selectable && !isCancelled && (
            <span style={{ color: selected ? '#f59e0b' : '#475569', flexShrink: 0, fontSize: 16 }}>
              {selected ? '☑' : '☐'}
            </span>
          )}
          <div style={{ flex: 1, minWidth: 0, display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
            {nameEl}
            <DealBadge item={item} />
            <PricingBadge events={priceEvents} />
            {(hasDetails || hasPricingRows) && (
              <ExpandArrow
                expanded={expanded || pricingExpanded}
                onClick={() => {
                  const next = !(expanded || pricingExpanded)
                  if (hasDetails) setExpanded(next)
                  if (hasPricingRows) setPricingExpanded(next)
                }}
              />
            )}
            {paidBadge}
            {cancelledBadge}
            {draftBadge}
          </div>
          <KdsBadge kdsColor={kdsColor} kdsDisplayStyle={kdsDisplayStyle} />
        </div>

        {/* Row 2: unit price · qty · total */}
        <div style={{
          display: 'flex', alignItems: 'center',
          padding: `2px 12px ${hasPricingRows && !pricingExpanded ? 2 : 8}px ${nameIndent}px`,
        }}>
          <span style={{ fontSize: 12, color: 'var(--muted)', flex: 1 }}>
            {hasPriceAdj
              ? <><span style={{ textDecoration: 'line-through', marginRight: 4, opacity: 0.6 }}>{fmtPrice(item.unit_price)}</span><span style={{ color: '#60a5fa' }}>{fmtPrice(unitPriceAdjusted)}</span></>
              : fmtPrice(unitPriceAdjusted)
            }
          </span>
          <span className="order-item__qty" style={{ textAlign: 'center', minWidth: 48 }}>
            {fmtQty(item.quantity, item.unit_type)}
          </span>
          <span className="order-item__price" style={{ minWidth: 64, textAlign: 'right', ...(hasPriceAdj ? { color: '#60a5fa' } : {}) }}>
            {totalPrice}
          </span>
        </div>

        {(pricingExpanded || expanded) && hasPricingRows && <PricingRows events={priceEvents} layout="expanded" nameIndent={nameIndent} />}
        {expanded && hasDetails && <OptionsPanel sections={sections} />}
      </div>
    )
  }

  // ── FULLY DETAILED ────────────────────────────────────────────────────────────
  const addedByName = waiterMap?.[item.added_by] ?? null
  const paidByName = waiterMap?.[item.paid_by] ?? null
  const addedAtFmt = fmtDateTime(item.added_at)
  const paidAtFmt = fmtDateTime(item.paid_at)

  return (
    <div
      className={cardClass}
      style={{ userSelect: 'none', position: 'relative', cursor: canSelect ? 'pointer' : 'default' }}
      {...cardHandlers}
    >
      {/* Row 1 */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px 2px' }}>
        {selectable && !isCancelled && (
          <span style={{ color: selected ? '#f59e0b' : '#475569', flexShrink: 0, fontSize: 16 }}>
            {selected ? '☑' : '☐'}
          </span>
        )}
        <div style={{ flex: 1, minWidth: 0, display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
          {nameEl}
          <DealBadge item={item} />
          <PricingBadge events={priceEvents} />
          {paidBadge}
          {cancelledBadge}
          {draftBadge}
        </div>
        <KdsBadge kdsColor={kdsColor} kdsDisplayStyle={kdsDisplayStyle} />
      </div>

      {/* Row 2 — pricing */}
      <div style={{
        display: 'flex', alignItems: 'center',
        padding: `2px 12px 6px ${nameIndent}px`,
      }}>
        <span style={{ fontSize: 12, color: 'var(--muted)', flex: 1 }}>
          {hasPriceAdj
            ? <><span style={{ textDecoration: 'line-through', marginRight: 4, opacity: 0.6 }}>{fmtPrice(item.unit_price)}</span><span style={{ color: '#60a5fa' }}>{fmtPrice(unitPriceAdjusted)}</span></>
            : fmtPrice(unitPriceAdjusted)
          }
        </span>
        <span className="order-item__qty" style={{ textAlign: 'center', minWidth: 48 }}>
          {fmtQty(item.quantity, item.unit_type)}
        </span>
        <span className="order-item__price" style={{ minWidth: 64, textAlign: 'right', ...(hasPriceAdj ? { color: '#60a5fa' } : {}) }}>
          {totalPrice}
        </span>
      </div>

      {hasPricingRows && <PricingRows events={priceEvents} layout="full" nameIndent={nameIndent} />}

      {/* Detail rows */}
      <div style={{
        padding: `0 12px 8px ${nameIndent}px`,
        display: 'flex', flexDirection: 'column', gap: 3,
      }}>
        <div style={{ height: 1, background: 'var(--border)', marginBottom: 4 }} />

        {/* Ordered by */}
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <span style={{ fontSize: 11, color: 'var(--muted)', minWidth: 90 }}>Παραγγέλθηκε</span>
          <span style={{ flex: 1 }} />
          <span style={{ fontSize: 11, color: 'var(--muted)', textAlign: 'right' }}>
            {addedByName && addedAtFmt ? `${addedByName} · ${addedAtFmt}` : addedByName || addedAtFmt || '—'}
          </span>
        </div>

        {/* Paid by — only if paid */}
        {isPaid && (
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <span style={{ fontSize: 11, color: 'var(--muted)', minWidth: 90 }}>Πληρώθηκε</span>
            <span style={{ flex: 1 }} />
            <span style={{ fontSize: 11, color: 'var(--muted)', textAlign: 'right' }}>
              {paidByName && paidAtFmt ? `${paidByName} · ${paidAtFmt}` : paidByName || paidAtFmt || '—'}
            </span>
          </div>
        )}

        {/* Options — inline, no expand needed */}
        {hasDetails && (
          <div style={{ marginTop: 2 }}>
            {sections.map((sec, si) => (
              <div key={si} style={{ display: 'flex', flexDirection: 'column', gap: 2, marginTop: 2 }}>
                {sec.type === 'prefs' && sec.lines.map((line, li) => (
                  <div key={li} style={{ display: 'flex', alignItems: 'flex-start', gap: 6 }}>
                    <SectionIcon type="prefs" />
                    <span style={{ fontSize: 11, lineHeight: 1.4, flex: 1, color: 'var(--text)' }}>
                      {line.setName && <span style={{ color: 'var(--muted)' }}>{line.setName}: </span>}
                      {line.values.join(' · ')}
                    </span>
                  </div>
                ))}
                {sec.type === 'quick' && sec.lines.map((line, li) => (
                  <div key={li} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <SectionIcon type="quick" />
                    <span style={{ fontSize: 11, 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: 6 }}>
                    <SectionIcon type="extras" />
                    <span style={{ fontSize: 11, 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: 6 }}>
                    <SectionIcon type="removed" />
                    <span style={{ fontSize: 11, 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: 6 }}>
                    <SectionIcon type="note" />
                    <span style={{ fontSize: 11, color: 'var(--text)', lineHeight: 1.4, flex: 1, whiteSpace: 'pre-wrap' }}>{line.name}</span>
                  </div>
                ))}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

export default function OrderSummary({ order, selectable = false, selectedIds = [], onToggle, onLongPressItem, waiterMap, courses = [], priceEventsMap = {} }) {
  const kdsDisplayStyle = useTableViewStore(s => s.kdsDisplayStyle || 'badge')
  const orderItemLayout = useTableViewStore(s => s.orderItemLayout || 'compact')
  const activeItems = order.items?.filter(i => i.status !== 'cancelled') || []
  const total = activeItems
    .filter(i => i.status !== 'cancelled')
    .reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0)
  const paidTotal = activeItems
    .filter(i => i.status === 'paid')
    .reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0)

  return (
    <div className="order-summary">
      {activeItems.length === 0 && <p style={{ color: '#64748b', textAlign: 'center' }}>Δεν υπάρχουν αντικείμενα</p>}
      {activeItems.map((item, idx) => (
        <ItemRow
          key={item.id}
          item={item}
          selectable={selectable}
          selected={selectedIds.includes(item.id)}
          onToggle={onToggle}
          onLongPress={onLongPressItem}
          isLast={idx === activeItems.length - 1}
          kdsDisplayStyle={kdsDisplayStyle}
          orderItemLayout={orderItemLayout}
          waiterMap={waiterMap}
          courses={courses}
          priceEvents={priceEventsMap[item.id] ?? []}
        />
      ))}
      <div className="order-summary__total">
        <span>Σύνολο</span>
        <span>{fmtPrice(total)}</span>
      </div>
      {paidTotal > 0 && paidTotal < total && (
        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '0 12px 8px', fontSize: 13, color: '#64748b' }}>
          <span>Πληρωμένο</span>
          <span style={{ color: '#22c55e' }}>{fmtPrice(paidTotal)}</span>
        </div>
      )}
      {paidTotal > 0 && paidTotal < total && (
        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '0 12px 8px', fontSize: 13, color: '#94a3b8' }}>
          <span>Εκκρεμεί</span>
          <span style={{ color: '#f59e0b', fontWeight: 700 }}>{fmtPrice(total - paidTotal)}</span>
        </div>
      )}
    </div>
  )
}
