import { useState, useRef, useCallback, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import OrderDrawer from './OrderDrawer'
import useWaiterFavoritesStore from '../store/waiterFavoritesStore'

const FAV_CAT_ID = '__favorites__'
const SVC_CAT_ID = '__service__'

function CategoriesIcon({ width = 20, height = 20 }) {
  return (
    <svg width={width} height={height} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <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>
  )
}


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

// A preference set blocks QuickAdd if it has NO default choice set
function productAllowsQuickAdd(product) {
  if (!product.quick_add_enabled) return false
  const sets = product.preference_sets || []
  for (const ps of sets) {
    if (ps.default_choice_id == null) return false
  }
  return true
}

// Decimal unit types (add 1.0 instead of 1)
const DECIMAL_UNITS = new Set(['kg', 'liter', 'gram', 'ml'])

function buildQuickAddItem(product) {
  const qty = DECIMAL_UNITS.has(product.unit_type) ? 1.0 : 1

  // Auto-resolve preference sets via their default choice
  const selectedOptions = []
  for (const ps of (product.preference_sets || [])) {
    const defaultChoice = ps.choices?.find(c => c.id === ps.default_choice_id)
    if (defaultChoice) {
      selectedOptions.push({ id: defaultChoice.id, name: defaultChoice.name, price_delta: defaultChoice.extra_cost ?? 0 })
    }
  }

  return {
    product_id: product.id,
    quantity: qty,
    unit_type: product.unit_type || 'piece',
    unit_price: product.base_price,
    notes: '',
    selected_options: selectedOptions,
    removed_ingredients: [],
  }
}

// ── Product Detail Modal (long-press) ─────────────────────────────────────────
function ProductDetailModal({ product, onClose }) {
  // Dismiss on Escape
  useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') onClose() }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [onClose])

  const initials = product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()

  return (
    <>
      <div
        onClick={onClose}
        style={{
          position: 'fixed', inset: 0,
          background: 'rgba(0,0,0,0.65)',
          zIndex: 300,
        }}
      />
      <div style={{
        position: 'fixed',
        top: '50%', left: '50%',
        transform: 'translate(-50%, -50%)',
        zIndex: 301,
        width: 'min(88vw, 360px)',
        background: 'var(--bg)',
        borderRadius: 20,
        overflow: 'hidden',
        boxShadow: '0 20px 60px rgba(0,0,0,0.5)',
      }}>
        {/* Close button */}
        <button
          onClick={onClose}
          style={{
            position: 'absolute', top: 12, right: 12,
            width: 32, height: 32, borderRadius: '50%',
            background: 'rgba(0,0,0,0.45)',
            border: 'none', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            zIndex: 1,
          }}
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
            <path d="M6 6L18 18M6 18L18 6" stroke="#fff" strokeWidth="2.2" strokeLinecap="round"/>
          </svg>
        </button>

        {/* Image */}
        <div style={{
          width: '100%', height: 220,
          background: 'var(--bg2)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          overflow: 'hidden',
        }}>
          {product.image_url
            ? <img src={product.image_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            : <span style={{ fontSize: 48, fontWeight: 800, color: 'var(--muted)', letterSpacing: -2 }}>{initials}</span>
          }
        </div>

        {/* Info */}
        <div style={{ padding: '18px 20px 24px' }}>
          <div style={{ fontSize: 20, fontWeight: 800, color: 'var(--text)', lineHeight: 1.2, marginBottom: 6 }}>
            {product.name}
          </div>
          <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--accent, #f59e0b)', marginBottom: product.description ? 14 : 0 }}>
            {Number(product.base_price).toFixed(2)} €
          </div>
          {product.description && (
            <div style={{
              fontSize: 14, color: 'var(--muted)', lineHeight: 1.6,
              borderTop: '1px solid var(--border)', paddingTop: 12,
            }}>
              {product.description}
            </div>
          )}
        </div>
      </div>
    </>
  )
}

// ── useLongPress ──────────────────────────────────────────────────────────────
function useLongPress(callback, delay = 2000) {
  const timerRef = useRef(null)
  const firedRef = useRef(false)

  const start = useCallback((e) => {
    firedRef.current = false
    timerRef.current = setTimeout(() => {
      firedRef.current = true
      callback(e)
    }, delay)
  }, [callback, delay])

  const cancel = useCallback(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current)
      timerRef.current = null
    }
  }, [])

  // Return true if the long-press fired, so the click handler can skip normal open
  const didFire = useCallback(() => firedRef.current, [])

  return { handlers: { onPointerDown: start, onPointerUp: cancel, onPointerLeave: cancel, onPointerCancel: cancel }, didFire }
}

// ── Product card ──────────────────────────────────────────────────────────────
function ProductCard({ product, onOpen, onQuickAdd, onShowDetail }) {
  const canQuickAdd = productAllowsQuickAdd(product)

  const onDetail = useCallback(() => onShowDetail(product), [onShowDetail, product])
  const longPress = useLongPress(onDetail, 1200)

  function handleClick(e) {
    // If a long-press just fired, don't open the drawer
    if (longPress.didFire()) return
    onOpen(product)
  }

  return (
    <div
      className="product-btn"
      style={{ position: 'relative' }}
      onClick={handleClick}
      {...longPress.handlers}
    >
      <div className="product-btn__thumb">
        <div className="product-btn__thumb-inner">
          {product.image_url
            ? <img src={product.image_url} alt="" className="product-btn__img" />
            : <span className="product-btn__initials">
                {product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()}
              </span>
          }
        </div>
      </div>
      <div className="product-btn__info">
        <span className="product-btn__name">{product.name}</span>
        {product.tags?.length > 0 && (
          <div className="product-btn__tags">
            {product.tags.map(tag => (
              <span key={tag} className="product-tag-pill">{tag}</span>
            ))}
          </div>
        )}
        <span className="product-btn__price">{Number(product.base_price).toFixed(2)} €</span>
      </div>

      {canQuickAdd && (
        <div style={{
          flexShrink: 0,
          width: 80, display: 'flex',
          alignItems: 'center', justifyContent: 'center',
        }}>
          <button
            onPointerDown={e => e.stopPropagation()}
            onClick={e => { e.stopPropagation(); onQuickAdd(product) }}
            style={{
              width: 44, height: 44, borderRadius: '50%',
              background: 'var(--bg3)',
              border: '1.5px solid var(--border)',
              cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
              <path d="M12 5v14M5 12h14" stroke="var(--accent)" strokeWidth="2.8" strokeLinecap="round"/>
            </svg>
          </button>
        </div>
      )}
    </div>
  )
}

// ── Service Item Card ─────────────────────────────────────────────────────────
function ServiceItemCard({ product, customerCount, onAdd }) {
  const [qty, setQty] = useState(0)

  function dec() { setQty(q => Math.max(0, q - 1)) }
  function inc() { setQty(q => q + 1) }
  function setToCustomerCount() { setQty(Math.max(1, customerCount ?? 1)) }

  const hasPrice = product.base_price != null && product.base_price > 0

  const btnBase = {
    width: 38, height: 38, borderRadius: '50%',
    border: '1.5px solid var(--border)',
    cursor: 'pointer', fontSize: 20, fontWeight: 700,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    flexShrink: 0,
  }

  return (
    <div style={{
      padding: '10px 14px',
      background: 'var(--bg2)',
      borderRadius: 14,
      border: '1.5px solid var(--border)',
      display: 'flex', flexDirection: 'column', gap: 8,
    }}>
      {/* Top row: name + price */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
        <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', lineHeight: 1.2, flex: 1, minWidth: 0 }}>
          {product.name}
        </span>
        <span style={{ fontSize: 13, fontWeight: 600, color: hasPrice ? '#f59e0b' : 'var(--muted)', flexShrink: 0 }}>
          {hasPrice ? `${Number(product.base_price).toFixed(2)} €` : 'no charge'}
        </span>
      </div>

      {/* Bottom row: stepper + count + ADD */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        {/* − */}
        <button
          onPointerDown={e => e.stopPropagation()}
          onClick={dec}
          style={{
            ...btnBase,
            background: qty === 0 ? 'var(--bg3)' : 'rgba(245,158,11,0.15)',
            color: qty === 0 ? 'var(--muted)' : '#f59e0b',
          }}
        >−</button>

        {/* X = set to customer count */}
        <button
          onPointerDown={e => e.stopPropagation()}
          onClick={setToCustomerCount}
          title={`Ορισμός σε ${customerCount ?? 1} άτομα`}
          style={{
            ...btnBase,
            background: 'rgba(245,158,11,0.12)',
            color: '#f59e0b',
            fontSize: 14, fontWeight: 800,
          }}
        >
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
            <circle cx="9" cy="7" r="4"/>
            <path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
            <path d="M16 3.13a4 4 0 0 1 0 7.75"/>
          </svg>
        </button>

        {/* + */}
        <button
          onPointerDown={e => e.stopPropagation()}
          onClick={inc}
          style={{
            ...btnBase,
            background: 'rgba(245,158,11,0.15)',
            color: '#f59e0b',
          }}
        >+</button>

        {/* COUNT indicator */}
        <span style={{
          flex: 1, textAlign: 'center',
          fontSize: 22, fontWeight: 800,
          color: qty === 0 ? 'var(--muted)' : 'var(--text)',
        }}>{qty}</span>

        {/* ADD button */}
        <button
          onPointerDown={e => e.stopPropagation()}
          onClick={() => {
            if (qty === 0) return
            onAdd({
              product_id: product.id,
              quantity: qty,
              unit_type: 'piece',
              unit_price: product.base_price ?? 0,
              notes: '',
              selected_options: [],
              removed_ingredients: [],
              is_service_item: true,
            }, product)
            setQty(0)
          }}
          disabled={qty === 0}
          style={{
            padding: '8px 16px', borderRadius: 10,
            background: qty === 0 ? 'var(--bg3)' : '#f59e0b',
            border: 'none', cursor: qty === 0 ? 'default' : 'pointer',
            fontSize: 12, fontWeight: 800,
            color: qty === 0 ? 'var(--muted)' : '#fff',
            flexShrink: 0,
          }}
        >
          ADD
        </button>
      </div>
    </div>
  )
}

function ServiceItemView({ products, customerCount, onAdd }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '12px 14px' }}>
      {products.length === 0 ? (
        <p style={{ color: 'var(--muted)', textAlign: 'center', padding: 32 }}>
          Δεν υπάρχουν service αντικείμενα
        </p>
      ) : products.map(p => (
        <ServiceItemCard
          key={p.id}
          product={p}
          customerCount={customerCount}
          onAdd={onAdd}
        />
      ))}
    </div>
  )
}

function ProductGrid({ products, onOpen, onQuickAdd, onShowDetail }) {
  if (products.length === 0) return null
  return (
    <div className="product-grid">
      {products.map(product => (
        <ProductCard
          key={product.id}
          product={product}
          onOpen={onOpen}
          onQuickAdd={onQuickAdd}
          onShowDetail={onShowDetail}
        />
      ))}
    </div>
  )
}

// Builds the ordered list of sections for a top-level category:
// interleaves direct products (as a "General" section) and sub-categories
// according to general_sort_order and each sub's sort_order.
function buildSections(parent, subcategories, directProducts) {
  const sections = []

  if (directProducts.length > 0) {
    sections.push({ _isGeneral: true, sort_order: parent.general_sort_order, products: directProducts })
  }

  for (const sub of subcategories) {
    sections.push({ ...sub, _isGeneral: false, sort_order: sub.sort_order })
  }

  return sections.sort((a, b) => a.sort_order - b.sort_order)
}

export default function ProductPicker({ categories, products, onAdd, onQuickAdd: onQuickAddProp, viewAllOpen, setViewAllOpen, customerCount, courses = [], globalCourseId = null, quickNotes }) {
  const navigate = useNavigate()
  const favorites = useWaiterFavoritesStore(s => s.favorites)

  const serviceProducts = products.filter(p => p.is_service_item)
  // Service items with a category also appear in that category view
  const regularProducts = products.filter(p => !p.is_service_item || p.category_id)

  const topLevel = categories.filter(c => !c.parent_id).sort((a, b) => a.sort_order - b.sort_order)
  // Start on FAVORITES chip if there are any, otherwise first category
  const initialCatId = favorites.length > 0 ? FAV_CAT_ID : (topLevel[0]?.id ?? null)
  const [activeCat, setActiveCat] = useState(initialCatId)
  const [drawerProduct, setDrawerProduct] = useState(null)
  const [detailProduct, setDetailProduct] = useState(null)
  const [modalTab, setModalTab] = useState('categories') // 'categories' | 'tags'
  const [activeTag, setActiveTag] = useState(null)
  // Track which sub-category sections are expanded (by sub-cat id or '__general__')
  const [expandedSubs, setExpandedSubs] = useState(() => {
    if (!initialCatId || initialCatId === FAV_CAT_ID) return {}
    const subs = categories.filter(c => c.parent_id === initialCatId)
    const state = {}
    subs.forEach(s => { if (s.auto_expanded) state[String(s.id)] = true })
    return state
  })

  const isSvcActive = activeCat === SVC_CAT_ID

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

  const directProducts = regularProducts.filter(p => p.category_id === activeCat)
  // Products for the flat view (no sub-cats)
  const flatProducts = regularProducts.filter(p => p.category_id === activeCat)

  // Build sections for accordion view
  const sections = hasSubcats ? buildSections(activeParent, subcategories, directProducts) : []

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

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

  function toggleSub(key) {
    setExpandedSubs(prev => ({ ...prev, [key]: !prev[key] }))
  }

  function openDrawer(product) { setDrawerProduct(product) }
  function closeDrawer() { setDrawerProduct(null) }

  function handleQuickAdd(product) {
    const base = buildQuickAddItem(product)
    const item = product.is_service_item ? { ...base, is_service_item: true } : base
    if (onQuickAddProp) {
      onQuickAddProp(item, product)
    } else {
      onAdd(item)
    }
  }

  const isFavActive = activeCat === FAV_CAT_ID
  const favProducts = favorites.map(id => regularProducts.find(p => p.id === id)).filter(Boolean)

  function handleServiceAdd(item, product) {
    // Service items go into the cart like regular items
    if (onQuickAddProp) {
      onQuickAddProp(item, product)
    } else {
      onAdd(item)
    }
  }

  return (
    <div className="product-picker">
      <div className="category-tabs">
        <div className="category-tabs__scroll-wrap">
          <div className="category-tabs__scroll">
          {/* SERVICE chip — first if service items exist */}
          {serviceProducts.length > 0 && (
            <button
              className="cat-tab"
              style={{
                background: isSvcActive ? '#f59e0b' : hexToRgba('#f59e0b', 0.22),
                color: isSvcActive ? '#fff' : '#b45309',
                border: isSvcActive ? '2px solid #f59e0b' : undefined,
                display: 'flex', alignItems: 'center', gap: 5,
              }}
              onClick={() => selectCategory(SVC_CAT_ID)}
            >
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M3 11l19-9-9 19-2-8-8-2z"/>
              </svg>
              Service
            </button>
          )}
          {/* FAVORITES chip */}
          {favorites.length > 0 && (
            <button
              className="cat-tab"
              style={{
                background: isFavActive ? '#ef4444' : hexToRgba('#ef4444', 0.22),
                color: isFavActive ? '#fff' : '#ef4444',
                border: isFavActive ? '2px solid #ef4444' : undefined,
                display: 'flex', alignItems: 'center', gap: 5,
              }}
              onClick={() => selectCategory(FAV_CAT_ID)}
            >
              <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round">
                <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
              </svg>
              Αγαπημένα
            </button>
          )}
          {topLevel.map(cat => {
            const isActive = activeCat === cat.id
            const bg = cat.color
              ? isActive ? cat.color : hexToRgba(cat.color, 0.35)
              : isActive ? 'var(--accent)' : 'var(--bg3)'
            const color = cat.color
              ? isActive ? '#fff' : 'rgba(255,255,255,0.65)'
              : isActive ? 'var(--accent-fg)' : 'var(--muted)'
            return (
              <button
                key={cat.id}
                className="cat-tab"
                style={{ background: bg, color, border: isActive && cat.color ? `2px solid ${cat.color}` : undefined }}
                onClick={() => selectCategory(cat.id)}
              >
                {cat.name}
              </button>
            )
          })}
          </div>
        </div>
      </div>

      {/* Product area — service, favorites, flat grid, or accordion depending on sub-cats */}
      <div className="product-area">
        {isSvcActive ? (
          // SERVICE view
          <ServiceItemView
            products={serviceProducts}
            customerCount={customerCount}
            onAdd={handleServiceAdd}
          />
        ) : isFavActive ? (
          // FAVORITES view
          favProducts.length > 0 ? (
            <ProductGrid
              products={favProducts}
              onOpen={openDrawer}
              onQuickAdd={handleQuickAdd}
              onShowDetail={setDetailProduct}
            />
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '48px 24px', gap: 14 }}>
              <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="#ef4444" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.4 }}>
                <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
              </svg>
              <p style={{ color: 'var(--muted)', fontSize: 14, textAlign: 'center', lineHeight: 1.6 }}>
                Δεν έχεις αγαπημένα ακόμα.
              </p>
              <button
                onClick={() => navigate('/settings/favorites')}
                style={{
                  padding: '10px 20px', borderRadius: 12,
                  background: 'var(--accent)', color: 'var(--accent-fg)',
                  border: 'none', fontSize: 14, fontWeight: 700, cursor: 'pointer',
                }}
              >
                Ρύθμιση Αγαπημένων
              </button>
            </div>
          )
        ) : !hasSubcats ? (
          // No sub-categories: original flat grid
          <>
            <ProductGrid
              products={flatProducts}
              onOpen={openDrawer}
              onQuickAdd={handleQuickAdd}
              onShowDetail={setDetailProduct}
            />
            {flatProducts.length === 0 && (
              <p style={{ color: '#64748b', textAlign: 'center', padding: 32 }}>
                Δεν υπάρχουν προϊόντα
              </p>
            )}
          </>
        ) : (
          // Has sub-categories: accordion view
          <div className="subcat-accordion">
            {sections.map(section => {
              const key = section._isGeneral ? '__general__' : String(section.id)
              const isOpen = !!expandedSubs[key]
              const sectionProducts = section._isGeneral
                ? section.products
                : regularProducts.filter(p => p.category_id === section.id)
              if (sectionProducts.length === 0) return null

              // General products appear flat — no collapsible header
              if (section._isGeneral) {
                return (
                  <div key={key} className="subcat-general">
                    <ProductGrid
                      products={sectionProducts}
                      onOpen={openDrawer}
                      onQuickAdd={handleQuickAdd}
                      onShowDetail={setDetailProduct}
                    />
                  </div>
                )
              }

              const accentColor = section.color ?? activeParent?.color ?? null

              return (
                <div key={key} className="subcat-section">
                  <button
                    className={`subcat-header ${isOpen ? 'subcat-header--open' : ''}`}
                    onClick={() => toggleSub(key)}
                  >
                    {accentColor && <span className="subcat-header__pill" style={{ background: accentColor }} />}
                    <span className="subcat-header__name">{section.name}</span>
                    <span className="subcat-header__count">{sectionProducts.length}</span>
                    <svg
                      className="subcat-header__chevron"
                      style={{ transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)' }}
                      width="16" height="16" viewBox="0 0 24 24" fill="none"
                    >
                      <path d="M6 9L12 15L18 9" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  </button>

                  {isOpen && (
                    <div className="subcat-body">
                      <ProductGrid
                        products={sectionProducts}
                        onOpen={openDrawer}
                        onQuickAdd={handleQuickAdd}
                        onShowDetail={setDetailProduct}
                      />
                    </div>
                  )}
                </div>
              )
            })}
          </div>
        )}
      </div>

      {/* View All modal — Κατηγορίες + Tags tabs */}
      {viewAllOpen && (
        <div className="modal-overlay" onClick={() => setViewAllOpen(false)}>
          <div
            className="cat-all-modal"
            onClick={e => e.stopPropagation()}
            style={{ display: 'flex', flexDirection: 'column' }}
          >
            <div className="cat-all-modal__header">
              <span className="cat-all-modal__title">{modalTab === 'categories' ? 'Κατηγορίες' : 'Tags'}</span>
              <button className="icon-btn" onClick={() => setViewAllOpen(false)}>✕</button>
            </div>

            {/* Tab strip */}
            <div style={{ display: 'flex', borderBottom: '1px solid var(--border)', flexShrink: 0 }}>
              {['categories', 'tags'].map(tab => (
                <button
                  key={tab}
                  onClick={() => setModalTab(tab)}
                  style={{
                    flex: 1, padding: '10px 0',
                    background: 'none', border: 'none', cursor: 'pointer',
                    fontSize: 13, fontWeight: 700,
                    color: modalTab === tab ? 'var(--accent)' : 'var(--muted)',
                    borderBottom: `2px solid ${modalTab === tab ? 'var(--accent)' : 'transparent'}`,
                    marginBottom: -1,
                    transition: 'color 0.12s',
                  }}
                >
                  {tab === 'categories' ? 'Κατηγορίες' : 'Tags'}
                </button>
              ))}
            </div>

            {modalTab === 'categories' && (
              <div className="cat-all-grid" style={{ flex: 1, overflowY: 'auto' }}>
                {favorites.length > 0 && (
                  <button
                    className={`cat-all-tile ${isFavActive ? 'cat-all-tile--active' : ''}`}
                    style={{ background: '#ef4444', boxShadow: isFavActive ? `0 0 0 3px #fff` : undefined }}
                    onClick={() => selectCategory(FAV_CAT_ID)}
                  >
                    <span className="cat-all-tile__overlay" style={{ background: isFavActive ? 'rgba(255,255,255,0.18)' : 'rgba(0,0,0,0.22)' }} />
                    <span className="cat-all-tile__name" style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="white" stroke="white" strokeWidth="1" style={{ flexShrink: 0 }}>
                        <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
                      </svg>
                      Αγαπημένα
                    </span>
                  </button>
                )}
                {topLevel.map(cat => {
                  const isActive = activeCat === cat.id
                  const bg = cat.color || 'var(--bg3)'
                  const overlay = isActive ? 'rgba(255,255,255,0.18)' : 'rgba(0,0,0,0.35)'
                  return (
                    <button
                      key={cat.id}
                      className={`cat-all-tile ${isActive ? 'cat-all-tile--active' : ''}`}
                      style={{ background: bg, boxShadow: isActive ? `0 0 0 3px #fff` : undefined }}
                      onClick={() => selectCategory(cat.id)}
                    >
                      <span className="cat-all-tile__overlay" style={{ background: overlay }} />
                      <span className="cat-all-tile__name">{cat.name}</span>
                    </button>
                  )
                })}
              </div>
            )}

            {modalTab === 'tags' && (() => {
              const allTags = [...new Set(products.flatMap(p => p.tags || []))].sort()
              const taggedProducts = activeTag ? products.filter(p => (p.tags || []).includes(activeTag)) : []
              const byCategory = taggedProducts.reduce((acc, p) => {
                const cat = categories.find(c => c.id === p.category_id)
                const key = cat?.name || 'Χωρίς Κατηγορία'
                if (!acc[key]) acc[key] = []
                acc[key].push(p)
                return acc
              }, {})

              return (
                <div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column' }}>
                  {allTags.length === 0 && (
                    <div style={{ padding: '32px 16px', textAlign: 'center', color: 'var(--muted)', fontSize: 14 }}>
                      Δεν υπάρχουν tags ακόμα.
                    </div>
                  )}
                  {allTags.length > 0 && (
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, padding: '12px 16px', borderBottom: '1px solid var(--border)' }}>
                      {allTags.map(tag => (
                        <button
                          key={tag}
                          onClick={() => setActiveTag(tag === activeTag ? null : tag)}
                          style={{
                            padding: '6px 14px', borderRadius: 20, border: 'none',
                            background: activeTag === tag ? 'var(--accent)' : 'var(--bg3)',
                            color: activeTag === tag ? 'var(--accent-fg)' : 'var(--text)',
                            fontSize: 13, fontWeight: 700, cursor: 'pointer',
                            transition: 'background 0.12s, color 0.12s',
                          }}
                        >
                          #{tag}
                        </button>
                      ))}
                    </div>
                  )}
                  {activeTag && taggedProducts.length === 0 && (
                    <div style={{ padding: '24px 16px', textAlign: 'center', color: 'var(--muted)', fontSize: 14 }}>
                      Κανένα προϊόν με αυτό το tag.
                    </div>
                  )}
                  {activeTag && Object.entries(byCategory).map(([catName, prods]) => (
                    <div key={catName}>
                      <div style={{ padding: '10px 16px 4px', fontSize: 11, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.7 }}>
                        {catName}
                      </div>
                      {prods.map(p => (
                        <button
                          key={p.id}
                          onClick={() => { setDrawerProduct(p); setViewAllOpen(false) }}
                          style={{
                            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                            width: '100%', padding: '10px 16px',
                            background: 'none', border: 'none', borderBottom: '1px solid var(--border)',
                            cursor: 'pointer', textAlign: 'left',
                          }}
                        >
                          <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{p.name}</span>
                          <span style={{ fontSize: 13, color: 'var(--muted)' }}>€{Number(p.base_price).toFixed(2)}</span>
                        </button>
                      ))}
                    </div>
                  ))}
                </div>
              )
            })()}
          </div>
        </div>
      )}

      <OrderDrawer
        product={drawerProduct}
        isOpen={!!drawerProduct}
        onClose={closeDrawer}
        onAdd={item => {
          const finalItem = drawerProduct?.is_service_item
            ? { ...item, is_service_item: true }
            : item
          onAdd(finalItem)
          closeDrawer()
        }}
        courses={courses}
        quickNotes={quickNotes}
        initialState={globalCourseId != null ? { courseId: globalCourseId } : undefined}
      />

      {detailProduct && (
        <ProductDetailModal
          product={detailProduct}
          onClose={() => setDetailProduct(null)}
        />
      )}
    </div>
  )
}
