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

// ── Small helpers ─────────────────────────────────────────────────────────────
function moveItem(arr, i, dir) {
  const j = i + dir
  if (j < 0 || j >= arr.length) return arr
  const next = [...arr]
  ;[next[i], next[j]] = [next[j], next[i]]
  return next
}

function HeartIcon({ filled, className = '' }) {
  return (
    <svg aria-hidden="true" viewBox="0 0 24 24" className={`inline-block shrink-0 ${className}`}
      fill={filled ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="1.8"
      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>
  )
}

function ReorderBtns({ onUp, onDown, disableUp, disableDown }) {
  return (
    <div className="flex flex-col shrink-0">
      <button type="button" onClick={onUp} disabled={disableUp}
        className="text-gray-400 hover:text-gray-600 disabled:opacity-20 leading-none px-1 py-0.5 text-xs">▲</button>
      <button type="button" onClick={onDown} disabled={disableDown}
        className="text-gray-400 hover:text-gray-600 disabled:opacity-20 leading-none px-1 py-0.5 text-xs">▼</button>
    </div>
  )
}

function DefaultBtn({ isDefault, onClick }) {
  return (
    <button type="button" onClick={onClick}
      className={`w-6 h-6 rounded-full border-2 flex items-center justify-center shrink-0 transition-all ${
        isDefault ? 'border-primary-600 bg-primary-600' : 'border-gray-300 bg-white hover:border-primary-400'
      }`}>
      {isDefault && <span className="w-2.5 h-2.5 rounded-full bg-white block" />}
    </button>
  )
}

function FavoriteBtn({ isFavorite, onClick }) {
  return (
    <button type="button" onClick={onClick}
      className={`w-7 h-7 rounded-full flex items-center justify-center shrink-0 transition-all ${
        isFavorite ? 'text-rose-500 hover:text-rose-400' : 'text-gray-300 hover:text-rose-400'
      }`}>
      <HeartIcon filled={isFavorite} className="w-4 h-4" />
    </button>
  )
}

function PriceInput({ value, onChange, placeholder, className = '', allowNegative = false }) {
  const step = 0.10
  const num = parseFloat(value) || 0
  function inc() { onChange(Math.round((num + step) * 100) / 100) }
  function dec() {
    const next = Math.round((num - step) * 100) / 100
    onChange(allowNegative ? next : Math.max(0, next))
  }
  return (
    <div className={`flex items-center border border-gray-300 rounded-lg overflow-hidden h-10 ${className}`}>
      <button type="button" onClick={dec}
        className="px-2 h-full text-gray-500 hover:bg-gray-100 border-r border-gray-300 text-sm font-bold shrink-0">−</button>
      <input type="number" step="0.10" value={value} onChange={e => onChange(e.target.value)}
        placeholder={placeholder ?? '0.00'}
        className="flex-1 min-w-0 text-center text-sm outline-none bg-transparent px-1 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none" />
      <button type="button" onClick={inc}
        className="px-2 h-full text-gray-500 hover:bg-gray-100 border-l border-gray-300 text-sm font-bold shrink-0">+</button>
    </div>
  )
}

function SubChoiceRows({ subChoices, onMove, onToggleDefault, onChange, onRemove, onAdd, parentLabel, showMultiple = false }) {
  if (!subChoices || subChoices.length === 0) return null
  return (
    <div className="border-t border-gray-100 bg-indigo-50/40 px-3 py-2 space-y-2">
      <p className="text-xs text-indigo-500 font-medium mb-1">
        Υπο-επιλογές του «{parentLabel || '…'}»
      </p>
      {subChoices.map((sc, sci) => (
        <div key={sci} className="flex items-center gap-2 ml-4 flex-wrap">
          <ReorderBtns onUp={() => onMove(sci, -1)} onDown={() => onMove(sci, 1)}
            disableUp={sci === 0} disableDown={sci === subChoices.length - 1} />
          <DefaultBtn isDefault={sc.is_default} onClick={() => onToggleDefault(sci)} />
          <input className="input flex-1 min-w-28 text-sm" placeholder="π.χ. Καραμέλα"
            value={sc.name} onChange={e => onChange(sci, 'name', e.target.value)} />
          <PriceInput value={sc.extra_cost} onChange={v => onChange(sci, 'extra_cost', v)}
            allowNegative className="w-28 text-sm" />
          {showMultiple && (
            <label className="flex items-center gap-1 text-xs text-gray-600 cursor-pointer shrink-0 select-none">
              <input type="checkbox" checked={sc.allow_multiple ?? false}
                onChange={e => onChange(sci, 'allow_multiple', e.target.checked)}
                className="accent-primary-700 w-3.5 h-3.5" />
              Πολλαπλά
            </label>
          )}
          <label className="flex items-center gap-1 text-xs cursor-pointer shrink-0 select-none" style={{ color: sc.is_compact ? '#7c3aed' : '#6b7280' }}>
            <input type="checkbox" checked={sc.is_compact ?? false}
              onChange={e => onChange(sci, 'is_compact', e.target.checked)}
              className="w-3.5 h-3.5" style={{ accentColor: '#7c3aed' }} />
            Compact
          </label>
          <button onClick={() => onRemove(sci)} className="btn btn-danger px-2 min-h-0 h-9 text-sm shrink-0">✕</button>
        </div>
      ))}
      <button onClick={onAdd} className="ml-4 btn btn-secondary text-xs px-2 py-1 min-h-0 h-7">
        + Υπο-επιλογή
      </button>
    </div>
  )
}

// ── Group helpers ─────────────────────────────────────────────────────────────
function GroupHeader({ group, onRename, onDelete, collapsed, onToggle }) {
  const [editing, setEditing] = useState(false)
  const [val, setVal] = useState(group.name)
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 8 }}>
      <button type="button" onClick={onToggle}
        className="flex items-center gap-2 flex-1 px-3 py-2 rounded-lg bg-indigo-50 border border-indigo-200 text-indigo-700 font-semibold text-sm text-left hover:bg-indigo-100 transition-colors">
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"
          style={{ transform: collapsed ? 'rotate(-90deg)' : 'rotate(0deg)', transition: 'transform 180ms', flexShrink: 0 }}>
          <path d="M6 9L12 15L18 9" strokeLinecap="round"/>
        </svg>
        {editing ? (
          <input
            className="input flex-1 text-sm py-0 h-6 min-w-0"
            value={val}
            onChange={e => setVal(e.target.value)}
            onBlur={() => { onRename(val); setEditing(false) }}
            onKeyDown={e => { if (e.key === 'Enter') e.target.blur() }}
            onClick={e => e.stopPropagation()}
            autoFocus
          />
        ) : (
          <span className="flex-1 truncate">{group.name || '(αχρησιμοποίητη ομάδα)'}</span>
        )}
      </button>
      <button type="button" onClick={e => { e.stopPropagation(); setVal(group.name); setEditing(true) }}
        className="w-7 h-7 rounded text-gray-400 hover:text-indigo-600 hover:bg-indigo-50 flex items-center justify-center text-xs">✎</button>
      <button type="button" onClick={onDelete}
        className="w-7 h-7 rounded text-gray-400 hover:text-red-500 hover:bg-red-50 flex items-center justify-center text-xs">✕</button>
    </div>
  )
}

// ── Form builder ──────────────────────────────────────────────────────────────
function buildFormFromProduct(product) {
  return {
    name: product.name || '',
    description: product.description || '',
    category_id: product.category_id ?? '',
    base_price: product.base_price ?? '',
    unit_type: product.unit_type ?? 'piece',
    is_available: product.is_available ?? true,
    lifecycle_status: product.lifecycle_status ?? 'active',
    prep_zone_ids: product.prep_zone_ids ?? [],
    quick_options: product.quick_options?.map(q => ({
      name: q.name, price: q.price ?? 0, allow_multiple: q.allow_multiple ?? false,
      sort_order: q.sort_order ?? 0, is_favorite: q.is_favorite ?? false,
      favorite_sort_order: q.favorite_sort_order ?? 0, is_compact: q.is_compact ?? false,
    })) ?? [],
    options: product.options?.map(o => ({
      name: o.name, extra_cost: o.extra_cost ?? 0, allow_multiple: o.allow_multiple ?? false,
      multi_select: o.multi_select ?? false, is_compact: o.is_compact ?? false,
      sub_choices: o.sub_choices?.map(s => ({ name: s.name, extra_cost: s.extra_cost ?? 0, is_default: s.is_default ?? false, allow_multiple: s.allow_multiple ?? false, is_compact: s.is_compact ?? false })) ?? [],
      is_favorite: o.is_favorite ?? false, favorite_sort_order: o.favorite_sort_order ?? 0,
      group_id: o.group_id ?? null,
    })) ?? [],
    ingredients: product.ingredients?.map(i => ({
      name: i.name, extra_cost: i.extra_cost ?? 0,
      is_favorite: i.is_favorite ?? false, favorite_sort_order: i.favorite_sort_order ?? 0,
      is_compact: i.is_compact ?? false, group_id: i.group_id ?? null,
    })) ?? [],
    preference_sets: product.preference_sets?.map(ps => ({
      name: ps.name,
      default_choice_index: ps.choices ? ps.choices.findIndex(c => c.id === ps.default_choice_id) : -1,
      choices: ps.choices?.map(c => ({
        name: c.name, extra_cost: c.extra_cost ?? 0, disables_subset: c.disables_subset ?? false,
        is_compact: c.is_compact ?? false,
        sub_choices: c.sub_choices?.map(s => ({ name: s.name, extra_cost: s.extra_cost ?? 0, is_default: s.is_default ?? false, is_compact: s.is_compact ?? false })) ?? [],
      })) ?? [],
      group_id: ps.group_id ?? null,
      shared_subset: ps.shared_subset ? {
        name: ps.shared_subset.name,
        choices: ps.shared_subset.choices?.map(s => ({ name: s.name, extra_cost: s.extra_cost ?? 0, is_default: s.is_default ?? false })) ?? [],
      } : null,
      is_favorite: ps.is_favorite ?? false, favorite_sort_order: ps.favorite_sort_order ?? 0,
      allow_multi_select: ps.allow_multi_select ?? false,
      allow_choice_quantity: ps.allow_choice_quantity ?? false,
    })) ?? [],
    digital_visible: product.digital_visible ?? true,
    digital_available: product.digital_available ?? true,
    digital_name: product.digital_name ?? '',
    digital_description: product.digital_description ?? '',
    digital_image_url: product.digital_image_url ?? '',
    digital_price: product.digital_price ?? '',
    digital_discount: product.digital_discount ?? '',
    // Phase 2A — cost tracking
    cost_mode: product.cost_breakdown?.length ? 'detailed' : 'simple',
    cost_simple: product.cost_simple ?? '',
    cost_breakdown: product.cost_breakdown?.length
      ? product.cost_breakdown.map(e => ({ label: e.label, amount: e.amount }))
      : [],
    // Quick Add
    quick_add_enabled: product.quick_add_enabled ?? true,
    // Tags
    tags: product.tags ?? [],
    tagsInput: '',
    // Service items
    is_service_item: product.is_service_item ?? false,
    // Fiscal printer (ΦΗΜ)
    fiscal_name: product.fiscal_name ?? '',
    fiscal_vat_group_id: product.fiscal_vat_group_id ?? null,
    // Modifier groups (folders) — keyed by _tempId in form, id from server
    modifier_groups: (product.modifier_groups || []).map(g => ({ _tempId: g.id, id: g.id, modifier_type: g.modifier_type, name: g.name, sort_order: g.sort_order })),
  }
}

function buildFavoritesList(form) {
  const items = []
  form.quick_options.forEach((q, i) => { if (q.is_favorite) items.push({ type: 'quick', idx: i, favorite_sort_order: q.favorite_sort_order ?? 0 }) })
  form.ingredients.forEach((ing, i) => { if (ing.is_favorite) items.push({ type: 'ingredient', idx: i, favorite_sort_order: ing.favorite_sort_order ?? 0 }) })
  form.options.forEach((o, i) => { if (o.is_favorite) items.push({ type: 'option', idx: i, favorite_sort_order: o.favorite_sort_order ?? 0 }) })
  form.preference_sets.forEach((ps, i) => { if (ps.is_favorite) items.push({ type: 'pref', idx: i, favorite_sort_order: ps.favorite_sort_order ?? 0 }) })
  return items.sort((a, b) => a.favorite_sort_order - b.favorite_sort_order)
}

function setFavSortField(form, type, idx, value) {
  if (type === 'quick') return { ...form, quick_options: form.quick_options.map((q, i) => i === idx ? { ...q, favorite_sort_order: value } : q) }
  if (type === 'ingredient') return { ...form, ingredients: form.ingredients.map((ing, i) => i === idx ? { ...ing, favorite_sort_order: value } : ing) }
  if (type === 'option') return { ...form, options: form.options.map((o, i) => i === idx ? { ...o, favorite_sort_order: value } : o) }
  if (type === 'pref') return { ...form, preference_sets: form.preference_sets.map((ps, i) => i === idx ? { ...ps, favorite_sort_order: value } : ps) }
  return form
}

function getItemLabel(form, type, idx) {
  if (type === 'quick') return form.quick_options[idx]?.name || '(χωρίς όνομα)'
  if (type === 'ingredient') return form.ingredients[idx]?.name || '(χωρίς όνομα)'
  if (type === 'option') return form.options[idx]?.name || '(χωρίς όνομα)'
  if (type === 'pref') return form.preference_sets[idx]?.name || '(χωρίς όνομα)'
  return ''
}

function getItemTypeLabel(type) {
  if (type === 'quick') return 'Γρήγορη'
  if (type === 'ingredient') return 'Υλικό'
  if (type === 'option') return 'Έξτρα'
  if (type === 'pref') return 'Προτίμηση'
  return ''
}

// ── Main modal ────────────────────────────────────────────────────────────────
export default function ProductFormModal({ product, categories, printers, prepZones = [], onSave, onCopy, onClose }) {
  const [form, setForm] = useState(() => buildFormFromProduct(product))
  const [activeTab, setActiveTab] = useState('favorites')
  const [leftTab, setLeftTab] = useState('info')
  const [imageFile, setImageFile] = useState(null)
  const [uploading, setUploading] = useState(false)
  const qc = useQueryClient()

  // Fetch fiscal VAT groups from settings (needed for the Ταμειακή tab dropdown)
  const { data: settingsData } = useQuery({
    queryKey: ['pos-settings'],
    queryFn: () => client.get('/api/settings/').then(r => r.data),
    staleTime: 60_000,
  })
  const fiscalEnabled = settingsData?.['fiscal.enabled']?.value === 'true'
  const vatGroups = (() => {
    try { return JSON.parse(settingsData?.['fiscal.vat_groups']?.value || '[]') } catch { return [] }
  })()

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

  useEffect(() => {
    setForm(buildFormFromProduct(product))
    setActiveTab('favorites')
    setLeftTab('info')
    setImageFile(null)
  }, [product.id, product.name])

  function setField(k, v) { setForm(f => ({ ...f, [k]: v })) }

  // Favorites reorder
  function moveFavorite(favList, favIdx, dir) {
    const newList = [...favList]
    const swapIdx = favIdx + dir
    if (swapIdx < 0 || swapIdx >= newList.length) return
    const aOrder = newList[favIdx].favorite_sort_order
    const bOrder = newList[swapIdx].favorite_sort_order
    setForm(f => {
      let next = setFavSortField(f, newList[favIdx].type, newList[favIdx].idx, bOrder)
      next = setFavSortField(next, newList[swapIdx].type, newList[swapIdx].idx, aOrder)
      return next
    })
  }

  function toggleFavorite(type, idx) {
    setForm(f => {
      const currentFavs = buildFavoritesList(f)
      const isFav = (() => {
        if (type === 'quick') return f.quick_options[idx]?.is_favorite
        if (type === 'ingredient') return f.ingredients[idx]?.is_favorite
        if (type === 'option') return f.options[idx]?.is_favorite
        if (type === 'pref') return f.preference_sets[idx]?.is_favorite
      })()
      const newSortOrder = isFav ? 0 : (currentFavs.length > 0 ? Math.max(...currentFavs.map(x => x.favorite_sort_order)) + 1 : 0)
      if (type === 'quick') return { ...f, quick_options: f.quick_options.map((q, i) => i === idx ? { ...q, is_favorite: !isFav, favorite_sort_order: isFav ? 0 : newSortOrder } : q) }
      if (type === 'ingredient') return { ...f, ingredients: f.ingredients.map((ing, i) => i === idx ? { ...ing, is_favorite: !isFav, favorite_sort_order: isFav ? 0 : newSortOrder } : ing) }
      if (type === 'option') return { ...f, options: f.options.map((o, i) => i === idx ? { ...o, is_favorite: !isFav, favorite_sort_order: isFav ? 0 : newSortOrder } : o) }
      if (type === 'pref') return { ...f, preference_sets: f.preference_sets.map((ps, i) => i === idx ? { ...ps, is_favorite: !isFav, favorite_sort_order: isFav ? 0 : newSortOrder } : ps) }
      return f
    })
  }

  // Quick Options
  function addQuickOption() { setForm(f => ({ ...f, quick_options: [...f.quick_options, { name: '', price: 0, allow_multiple: false, sort_order: f.quick_options.length, is_favorite: false, favorite_sort_order: 0, is_compact: false }] })) }
  function removeQuickOption(i) { setForm(f => ({ ...f, quick_options: f.quick_options.filter((_, idx) => idx !== i) })) }
  function setQuickOption(i, k, v) { setForm(f => ({ ...f, quick_options: f.quick_options.map((q, idx) => idx === i ? { ...q, [k]: v } : q) })) }
  function moveQuickOption(i, dir) { setForm(f => ({ ...f, quick_options: moveItem(f.quick_options, i, dir) })) }

  // Options
  function addOption() { setForm(f => ({ ...f, options: [...f.options, { name: '', extra_cost: 0, allow_multiple: false, multi_select: false, is_compact: false, sub_choices: [], is_favorite: false, favorite_sort_order: 0 }] })) }
  function removeOption(i) { setForm(f => ({ ...f, options: f.options.filter((_, idx) => idx !== i) })) }
  function setOption(i, k, v) { setForm(f => ({ ...f, options: f.options.map((o, idx) => idx === i ? { ...o, [k]: v } : o) })) }
  function moveOption(i, dir) { setForm(f => ({ ...f, options: moveItem(f.options, i, dir) })) }

  function addOptionSubChoice(oi) {
    setForm(f => ({ ...f, options: f.options.map((o, idx) =>
      idx !== oi ? o : { ...o, sub_choices: [...(o.sub_choices || []), { name: '', extra_cost: 0, is_default: false, allow_multiple: false, is_compact: false }] }
    )}))
  }
  function removeOptionSubChoice(oi, sci) {
    setForm(f => ({ ...f, options: f.options.map((o, idx) =>
      idx !== oi ? o : { ...o, sub_choices: o.sub_choices.filter((_, i) => i !== sci) }
    )}))
  }
  function setOptionSubChoice(oi, sci, k, v) {
    setForm(f => ({ ...f, options: f.options.map((o, idx) =>
      idx !== oi ? o : {
        ...o, sub_choices: o.sub_choices.map((sc, scidx) => {
          if (scidx !== sci) return k === 'is_default' && v === true ? { ...sc, is_default: false } : sc
          return { ...sc, [k]: v }
        })
      }
    )}))
  }
  function moveOptionSubChoice(oi, sci, dir) {
    setForm(f => ({ ...f, options: f.options.map((o, idx) =>
      idx !== oi ? o : { ...o, sub_choices: moveItem(o.sub_choices, sci, dir) }
    )}))
  }
  function toggleOptionSubDefault(oi, sci) {
    const sc = form.options[oi]?.sub_choices?.[sci]
    setOptionSubChoice(oi, sci, 'is_default', !sc?.is_default)
  }

  // Ingredients
  function addIngredient() { setForm(f => ({ ...f, ingredients: [...f.ingredients, { name: '', extra_cost: 0, is_favorite: false, favorite_sort_order: 0, is_compact: false }] })) }
  function removeIngredient(i) { setForm(f => ({ ...f, ingredients: f.ingredients.filter((_, idx) => idx !== i) })) }
  function setIngredient(i, k, v) { setForm(f => ({ ...f, ingredients: f.ingredients.map((ing, idx) => idx === i ? { ...ing, [k]: v } : ing) })) }
  function moveIngredient(i, dir) { setForm(f => ({ ...f, ingredients: moveItem(f.ingredients, i, dir) })) }

  // Preference sets
  function addPrefSet() {
    setForm(f => ({ ...f, preference_sets: [...f.preference_sets, { name: '', default_choice_index: -1, choices: [], shared_subset: null, is_favorite: false, favorite_sort_order: 0, allow_multi_select: false, allow_choice_quantity: false }] }))
    setActiveTab(form.preference_sets.length)
  }
  function removePrefSet(si) {
    setForm(f => ({ ...f, preference_sets: f.preference_sets.filter((_, idx) => idx !== si) }))
    setActiveTab('favorites')
  }
  function setPrefSetField(si, k, v) {
    setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => idx === si ? { ...ps, [k]: v } : ps) }))
  }
  function addChoice(si) {
    setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) =>
      idx === si ? { ...ps, choices: [...ps.choices, { name: '', extra_cost: 0, disables_subset: false, is_compact: false, sub_choices: [] }] } : ps
    )}))
  }
  function removeChoice(si, ci) {
    setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => {
      if (idx !== si) return ps
      const newChoices = ps.choices.filter((_, cidx) => cidx !== ci)
      const d = ps.default_choice_index
      const newDefault = d === ci ? -1 : d > ci ? d - 1 : d
      return { ...ps, choices: newChoices, default_choice_index: newDefault }
    })}))
  }
  function setChoice(si, ci, k, v) {
    setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) =>
      idx === si ? { ...ps, choices: ps.choices.map((ch, cidx) => cidx === ci ? { ...ch, [k]: v } : ch) } : ps
    )}))
  }
  function moveChoice(si, ci, dir) {
    setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => {
      if (idx !== si) return ps
      const newChoices = moveItem(ps.choices, ci, dir)
      const j = ci + dir
      let nd = ps.default_choice_index
      if (nd === ci) nd = j; else if (nd === j) nd = ci
      return { ...ps, choices: newChoices, default_choice_index: nd }
    })}))
  }
  function toggleDefaultChoice(si, ci) {
    setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) =>
      idx !== si ? ps : { ...ps, default_choice_index: ps.default_choice_index === ci ? -1 : ci }
    )}))
  }
  function addSubChoice(si, ci) {
    setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, pidx) =>
      pidx !== si ? ps : { ...ps, choices: ps.choices.map((ch, cidx) =>
        cidx !== ci ? ch : { ...ch, sub_choices: [...(ch.sub_choices || []), { name: '', extra_cost: 0, is_default: false, is_compact: false }] }
      )}
    )}))
  }
  function removeSubChoice(si, ci, sci) {
    setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, pidx) =>
      pidx !== si ? ps : { ...ps, choices: ps.choices.map((ch, cidx) =>
        cidx !== ci ? ch : { ...ch, sub_choices: ch.sub_choices.filter((_, i) => i !== sci) }
      )}
    )}))
  }
  function setSubChoice(si, ci, sci, k, v) {
    setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, pidx) =>
      pidx !== si ? ps : { ...ps, choices: ps.choices.map((ch, cidx) =>
        cidx !== ci ? ch : { ...ch, sub_choices: ch.sub_choices.map((sc, scidx) => {
          if (scidx !== sci) return k === 'is_default' && v === true ? { ...sc, is_default: false } : sc
          return { ...sc, [k]: v }
        })}
      )}
    )}))
  }
  function moveSubChoice(si, ci, sci, dir) {
    setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, pidx) =>
      pidx !== si ? ps : { ...ps, choices: ps.choices.map((ch, cidx) =>
        cidx !== ci ? ch : { ...ch, sub_choices: moveItem(ch.sub_choices, sci, dir) }
      )}
    )}))
  }
  function setSharedSubsetName(si, name) {
    setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => {
      if (idx !== si) return ps
      return { ...ps, shared_subset: ps.shared_subset ? { ...ps.shared_subset, name } : { name, choices: [] } }
    })}))
  }
  function addSharedSubsetChoice(si) {
    setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => {
      if (idx !== si) return ps
      const ss = ps.shared_subset || { name: '', choices: [] }
      return { ...ps, shared_subset: { ...ss, choices: [...ss.choices, { name: '', extra_cost: 0, is_default: false }] } }
    })}))
  }
  function removeSharedSubsetChoice(si, sci) {
    setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => {
      if (idx !== si) return ps
      const newChoices = ps.shared_subset.choices.filter((_, i) => i !== sci)
      return { ...ps, shared_subset: newChoices.length ? { ...ps.shared_subset, choices: newChoices } : null }
    })}))
  }
  function setSharedSubsetChoice(si, sci, k, v) {
    setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => {
      if (idx !== si) return ps
      const newChoices = ps.shared_subset.choices.map((sc, scidx) => {
        if (scidx !== sci) return k === 'is_default' && v === true ? { ...sc, is_default: false } : sc
        return { ...sc, [k]: v }
      })
      return { ...ps, shared_subset: { ...ps.shared_subset, choices: newChoices } }
    })}))
  }
  function moveSharedSubsetChoice(si, sci, dir) {
    setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) =>
      idx !== si ? ps : { ...ps, shared_subset: { ...ps.shared_subset, choices: moveItem(ps.shared_subset.choices, sci, dir) } }
    )}))
  }

  // Modifier groups
  const _nextTempId = useRef(-1)
  function addModifierGroup(modifier_type) {
    const _tempId = _nextTempId.current--
    setForm(f => ({ ...f, modifier_groups: [...f.modifier_groups, { _tempId, id: null, modifier_type, name: 'Νέα ομάδα', sort_order: f.modifier_groups.length }] }))
  }
  function renameModifierGroup(_tempId, name) {
    setForm(f => ({ ...f, modifier_groups: f.modifier_groups.map(g => g._tempId === _tempId ? { ...g, name } : g) }))
  }
  function deleteModifierGroup(_tempId) {
    setForm(f => {
      const next = { ...f, modifier_groups: f.modifier_groups.filter(g => g._tempId !== _tempId) }
      // Un-assign all items that belonged to this group
      next.options = f.options.map(o => o.group_id === _tempId ? { ...o, group_id: null } : o)
      next.ingredients = f.ingredients.map(i => i.group_id === _tempId ? { ...i, group_id: null } : i)
      next.preference_sets = f.preference_sets.map(ps => ps.group_id === _tempId ? { ...ps, group_id: null } : ps)
      return next
    })
  }
  function setItemGroup(listKey, idx, _tempId) {
    setForm(f => ({ ...f, [listKey]: f[listKey].map((item, i) => i === idx ? { ...item, group_id: _tempId } : item) }))
  }
  const [collapsedGroups, setCollapsedGroups] = useState({})
  function toggleGroupCollapsed(_tempId) {
    setCollapsedGroups(s => ({ ...s, [_tempId]: !s[_tempId] }))
  }

  function buildBody() {
    return {
      name: form.name,
      description: form.description || null,
      category_id: form.category_id ? Number(form.category_id) : null,
      base_price: form.base_price !== '' && form.base_price !== null && form.base_price !== undefined ? parseFloat(form.base_price) : 0,
      unit_type: form.unit_type || 'piece',
      is_available: form.is_available,
      lifecycle_status: form.lifecycle_status,
      prep_zone_ids: form.prep_zone_ids,
      quick_options: form.quick_options.map((q, i) => ({
        name: q.name, price: parseFloat(q.price) || 0, allow_multiple: q.allow_multiple ?? false,
        sort_order: i, is_favorite: q.is_favorite ?? false, favorite_sort_order: q.favorite_sort_order ?? 0, is_compact: q.is_compact ?? false,
      })),
      modifier_groups: form.modifier_groups.map((g, gi) => ({ modifier_type: g.modifier_type, name: g.name, sort_order: gi })),
      options: form.options.map(o => ({
        name: o.name, extra_cost: parseFloat(o.extra_cost) || 0, allow_multiple: o.allow_multiple ?? false,
        multi_select: o.multi_select ?? false, is_compact: o.is_compact ?? false,
        sub_choices: (o.sub_choices || []).map(s => ({ name: s.name, extra_cost: parseFloat(s.extra_cost) || 0, is_default: s.is_default ?? false, allow_multiple: s.allow_multiple ?? false, is_compact: s.is_compact ?? false })),
        is_favorite: o.is_favorite ?? false, favorite_sort_order: o.favorite_sort_order ?? 0,
        group_id: o.group_id != null ? form.modifier_groups.findIndex(g => g._tempId === o.group_id) : null,
      })),
      ingredients: form.ingredients.map(i => ({
        name: i.name, extra_cost: parseFloat(i.extra_cost) || 0,
        is_favorite: i.is_favorite ?? false, favorite_sort_order: i.favorite_sort_order ?? 0,
        is_compact: i.is_compact ?? false,
        group_id: i.group_id != null ? form.modifier_groups.findIndex(g => g._tempId === i.group_id) : null,
      })),
      preference_sets: form.preference_sets.map(ps => ({
        name: ps.name,
        default_choice_index: ps.default_choice_index >= 0 ? ps.default_choice_index : null,
        shared_subset: ps.shared_subset?.choices?.length ? {
          name: ps.shared_subset.name || '',
          choices: ps.shared_subset.choices.map(s => ({ name: s.name, extra_cost: parseFloat(s.extra_cost) || 0, is_default: s.is_default ?? false })),
        } : null,
        choices: ps.choices.map(c => ({
          name: c.name, extra_cost: parseFloat(c.extra_cost) || 0, disables_subset: c.disables_subset ?? false,
          is_compact: c.is_compact ?? false,
          sub_choices: (c.sub_choices || []).map(s => ({ name: s.name, extra_cost: parseFloat(s.extra_cost) || 0, is_default: s.is_default ?? false, is_compact: s.is_compact ?? false })),
        })),
        is_favorite: ps.is_favorite ?? false, favorite_sort_order: ps.favorite_sort_order ?? 0,
        group_id: ps.group_id != null ? form.modifier_groups.findIndex(g => g._tempId === ps.group_id) : null,
        allow_multi_select: ps.allow_multi_select ?? false,
        allow_choice_quantity: ps.allow_choice_quantity ?? false,
      })),
      digital_visible: form.digital_visible,
      digital_available: form.digital_available,
      digital_name: form.digital_name || null,
      digital_description: form.digital_description || null,
      digital_image_url: form.digital_image_url || null,
      digital_price: form.digital_price !== '' ? parseFloat(form.digital_price) : null,
      digital_discount: form.digital_discount !== '' ? parseFloat(form.digital_discount) : null,
      // Phase 2A — cost tracking
      cost_simple: form.cost_mode === 'simple' && form.cost_simple !== '' ? parseFloat(form.cost_simple) : null,
      cost_breakdown: form.cost_mode === 'detailed' && form.cost_breakdown.length > 0
        ? form.cost_breakdown.map(e => ({ label: e.label, amount: parseFloat(e.amount) || 0 }))
        : null,
      // Quick Add
      quick_add_enabled: form.quick_add_enabled,
      // Tags
      tags: form.tags || [],
      // Service items
      is_service_item: form.is_service_item ?? false,
      // Fiscal printer (ΦΗΜ)
      fiscal_name: form.fiscal_name?.trim() || null,
      fiscal_vat_group_id: form.fiscal_vat_group_id ? parseInt(form.fiscal_vat_group_id, 10) : null,
    }
  }

  async function submit() {
    if (!imageFile) { onSave(buildBody()); return }
    if (!isNew) {
      onSave(buildBody())
      setUploading(true)
      try {
        const fd = new FormData(); fd.append('file', imageFile)
        await client.post(`/api/products/${product.id}/image`, fd)
        qc.invalidateQueries({ queryKey: ['products-all'] })
      } catch { toast.error('Σφάλμα ανεβάσματος εικόνας') }
      finally { setUploading(false) }
    } else {
      setUploading(true)
      try {
        const res = await client.post('/api/products/', buildBody())
        const newId = res.data.id
        const fd = new FormData(); fd.append('file', imageFile)
        await client.post(`/api/products/${newId}/image`, fd)
        qc.invalidateQueries({ queryKey: ['products-all'] })
        onClose()
      } catch { toast.error('Σφάλμα αποθήκευσης') }
      finally { setUploading(false) }
    }
  }

  const isNew = !product.id
  const canSave = form.name.trim() && (form.is_service_item || (form.base_price !== '' && form.base_price !== null && form.base_price !== undefined))
  const favCount = buildFavoritesList(form).length
  const prefGroups = form.modifier_groups.filter(g => g.modifier_type === 'preference')
  const tabs = [
    { key: 'favorites', label: 'Αγαπημένα', count: favCount, isFavTab: true },
    { key: 'quick', label: 'Γρήγορες', count: form.quick_options.length },
    { key: 'ingredients', label: 'Υλικά', count: form.ingredients.length },
    { key: 'options', label: 'Έξτρα', count: form.options.length },
    ...form.preference_sets.map((ps, i) => ({ key: i, label: ps.name || `Προτ. ${i + 1}`, count: ps.choices.length })),
    { key: '__add_pref__', label: '＋ Προτίμηση', isAdd: true },
    { key: '__add_pref_group__', label: '＋ Ομάδα', isAddGroup: true },
  ]
  const favList = buildFavoritesList(form)

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl shadow-2xl flex flex-col overflow-hidden" style={{ width: '90vw', height: '92vh' }}>

        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100 shrink-0">
          <h2 className="font-bold text-gray-800 text-lg">
            {isNew ? 'Νέο προϊόν' : `Επεξεργασία — ${product.name}`}
          </h2>
          <button onClick={onClose} className="w-8 h-8 rounded-full hover:bg-gray-100 flex items-center justify-center text-gray-500 text-lg">✕</button>
        </div>

        {/* Body */}
        <div className="flex-1 flex overflow-hidden">

          {/* LEFT: tabbed product info — 25% normally, 100% for service items */}
          <div className="shrink-0 border-r border-gray-100 bg-gray-50/50 flex flex-col overflow-hidden" style={{ width: form.is_service_item ? '100%' : '25%' }}>
            {/* Left tab bar */}
            <div className="flex border-b border-gray-200 shrink-0 bg-white">
              {[
                { key: 'info', label: 'Πληροφορίες' },
                ...(!form.is_service_item ? [
                  { key: 'digital', label: 'Digital Menu' },
                  { key: 'cost', label: 'Κόστος' },
                  ...(fiscalEnabled ? [{ key: 'fiscal', label: 'Ταμειακή' }] : []),
                ] : []),
              ].map(t => (
                <button key={t.key} onClick={() => setLeftTab(t.key)}
                  className={`flex-1 px-4 py-3 text-sm font-medium whitespace-nowrap border-b-2 transition-colors ${
                    leftTab === t.key
                      ? 'border-primary-600 text-primary-700 bg-primary-50/50'
                      : 'border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                  }`}>
                  {t.label}
                </button>
              ))}
            </div>

            {/* Left tab content */}
            <div className="flex-1 overflow-y-auto px-5 py-5 flex flex-col gap-3">

              {/* Tab 1: Main Info */}
              {leftTab === 'info' && (<>
                {/* Service Item toggle */}
                <button
                  type="button"
                  onClick={() => setField('is_service_item', !form.is_service_item)}
                  className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-sm font-medium transition-colors w-full ${
                    form.is_service_item
                      ? 'bg-amber-50 border-amber-400 text-amber-800'
                      : 'bg-gray-100 border-gray-300 text-gray-500 hover:bg-gray-200'
                  }`}
                >
                  <svg width="15" height="15" 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>
                  {form.is_service_item ? 'Service Item' : 'Κανονικό προϊόν'}
                </button>

                {form.is_service_item && (
                  <p className="text-xs text-amber-700 -mt-1 px-1">
                    {form.base_price && parseFloat(form.base_price) > 0
                      ? 'Τυπώνεται σε ξεχωριστή ενότητα SERVICE. Καταγράφεται στα έσοδα.'
                      : 'Τυπώνεται μία φορά — δεν αποθηκεύεται στην παραγγελία, δεν καταγράφεται στα έσοδα.'}
                  </p>
                )}

                <div>
                  <label className="label">Όνομα *</label>
                  <input className="input" value={form.name} onChange={e => setField('name', e.target.value)} autoFocus placeholder={form.is_service_item ? 'π.χ. Σερβίτσιο' : 'π.χ. Espresso'} />
                </div>

                {!form.is_service_item && <div>
                  <label className="label">Περιγραφή <span className="text-gray-400 font-normal normal-case">(προαιρετική)</span></label>
                  <textarea
                    className="input resize-none"
                    rows={3}
                    value={form.description}
                    onChange={e => setField('description', e.target.value)}
                    placeholder="π.χ. Φρέσκος καφές με γάλα βρώμης, εξαιρετικά αρώματα…"
                    style={{ lineHeight: 1.5, fontSize: 13 }}
                  />
                  <p className="text-xs text-gray-400 mt-1">Χρήσιμο για ψηφιακό μενού ή ενημέρωση σερβιτόρων.</p>
                </div>}

                {!form.is_service_item && <div>
                  <label className="label">Tags <span className="text-gray-400 font-normal normal-case">(προαιρετικά)</span></label>
                  <div className="flex flex-wrap gap-1.5 mb-1.5">
                    {(form.tags || []).map((tag, ti) => (
                      <span key={ti} className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-indigo-50 border border-indigo-200 text-xs font-medium text-indigo-700">
                        {tag}
                        <button type="button" onClick={() => setField('tags', form.tags.filter((_, i) => i !== ti))}
                          className="hover:text-indigo-900 leading-none">×</button>
                      </span>
                    ))}
                  </div>
                  <input
                    className="input text-sm"
                    value={form.tagsInput || ''}
                    onChange={e => setField('tagsInput', e.target.value)}
                    onKeyDown={e => {
                      if ((e.key === 'Enter' || e.key === ',') && form.tagsInput?.trim()) {
                        e.preventDefault()
                        const tag = form.tagsInput.trim().toLowerCase().replace(/,/g, '')
                        if (tag && !(form.tags || []).includes(tag)) setField('tags', [...(form.tags || []), tag])
                        setField('tagsInput', '')
                      }
                    }}
                    onBlur={() => {
                      if (form.tagsInput?.trim()) {
                        const tag = form.tagsInput.trim().toLowerCase()
                        if (!(form.tags || []).includes(tag)) setField('tags', [...(form.tags || []), tag])
                        setField('tagsInput', '')
                      }
                    }}
                    placeholder="π.χ. vegan, gluten-free — Enter ή κόμμα"
                  />
                  <p className="text-xs text-gray-400 mt-1">Πάτα Enter ή κόμμα για να προσθέσεις tag.</p>
                </div>}

                {!form.is_service_item && <div>
                  <label className="label">Μονάδα μέτρησης</label>
                  <select className="input" value={form.unit_type} onChange={e => setField('unit_type', e.target.value)}>
                    <option value="piece">Τεμάχιο (pc)</option>
                    <option value="portion">Μερίδα (portion)</option>
                    <option value="kg">Κιλό (kg)</option>
                    <option value="liter">Λίτρο (L)</option>
                    <option value="gram">Γραμμάριο (g)</option>
                    <option value="ml">Χιλιοστόλιτρο (mL)</option>
                  </select>
                  {(form.unit_type === 'kg' || form.unit_type === 'liter' || form.unit_type === 'gram' || form.unit_type === 'ml') && (
                    <p className="text-xs text-indigo-600 mt-1">Η ποσότητα θα εισάγεται ως δεκαδικός αριθμός στην εφαρμογή σερβιτόρων.</p>
                  )}
                </div>}

                <div>
                  <label className="label">{form.is_service_item ? 'Τιμή (€) — προαιρετική' : 'Βασική Τιμή (€) *'}</label>
                  <PriceInput value={form.base_price} onChange={v => setField('base_price', v)} className="w-full" />
                </div>

                <div>
                  <label className="label">
                    Κατηγορία
                    {form.is_service_item && <span className="text-gray-400 font-normal normal-case ml-1">(προαιρετική — εμφανίζεται και εκεί)</span>}
                  </label>
                  <select className="input" value={form.category_id} onChange={e => setField('category_id', e.target.value)}>
                    <option value="">— Χωρίς κατηγορία —</option>
                    {categories.filter(c => !c.parent_id).sort((a, b) => a.sort_order - b.sort_order).flatMap(parent => {
                      const subs = categories.filter(c => c.parent_id === parent.id).sort((a, b) => a.sort_order - b.sort_order)
                      return [
                        <option key={parent.id} value={parent.id}>{parent.name}</option>,
                        ...subs.map(s => <option key={s.id} value={s.id}>&nbsp;&nbsp;↳ {s.name}</option>),
                      ]
                    })}
                  </select>
                </div>

                <div>
                  <label className="label">Ζώνη Προετοιμασίας</label>
                  <div className="flex flex-col gap-1.5 mt-1">
                    {prepZones.length === 0 ? (
                      <p className="text-xs text-gray-400 italic">Δεν υπάρχουν ζώνες. <a href="/management/prep-zones" className="underline text-primary-600">Δημιουργήστε μια ζώνη</a>.</p>
                    ) : (
                      prepZones.map(z => {
                        const selected = form.prep_zone_ids.includes(z.id)
                        return (
                          <label key={z.id} className={`flex items-center gap-2.5 px-3 py-2 rounded-lg border cursor-pointer transition-colors select-none text-sm ${selected ? 'border-primary-300 bg-primary-50 text-primary-700' : 'border-gray-200 bg-white text-gray-700 hover:border-gray-300'}`}>
                            <input
                              type="checkbox"
                              checked={selected}
                              onChange={() => {
                                const ids = form.prep_zone_ids.includes(z.id)
                                  ? form.prep_zone_ids.filter(id => id !== z.id)
                                  : [...form.prep_zone_ids, z.id]
                                setField('prep_zone_ids', ids)
                              }}
                              className="w-3.5 h-3.5 accent-primary-600 shrink-0"
                            />
                            <span className="font-medium">{z.name}</span>
                            {z.description && <span className="text-xs text-gray-400 ml-1">— {z.description}</span>}
                          </label>
                        )
                      })
                    )}
                  </div>
                </div>

                {!form.is_service_item && <div className="flex items-center gap-3 flex-wrap">
                  <button type="button" onClick={() => setField('is_available', !form.is_available)}
                    className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-sm font-medium transition-colors ${
                      form.is_available ? 'bg-green-50 border-green-300 text-green-700 hover:bg-green-100'
                        : 'bg-gray-100 border-gray-300 text-gray-500 hover:bg-gray-200'
                    }`}>
                    <span className={`w-2.5 h-2.5 rounded-full ${form.is_available ? 'bg-green-500' : 'bg-gray-400'}`} />
                    {form.is_available ? 'Διαθέσιμο' : 'Μη διαθέσιμο'}
                  </button>

                  <button type="button" onClick={() => setField('quick_add_enabled', !form.quick_add_enabled)}
                    className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-sm font-medium transition-colors ${
                      form.quick_add_enabled ? 'bg-blue-50 border-blue-300 text-blue-700 hover:bg-blue-100'
                        : 'bg-gray-100 border-gray-300 text-gray-500 hover:bg-gray-200'
                    }`}>
                    <span className={`w-2.5 h-2.5 rounded-full ${form.quick_add_enabled ? 'bg-blue-500' : 'bg-gray-400'}`} />
                    {form.quick_add_enabled ? 'Quick Add: Ενεργό' : 'Quick Add: Ανενεργό'}
                  </button>
                </div>}

                {!form.is_service_item && <div>
                  <label className="label">Εικόνα προϊόντος</label>
                  {product.image_url && (
                    <img src={product.image_url}
                      className="w-16 h-16 rounded-xl object-cover border border-gray-200 mb-2" alt="" />
                  )}
                  {imageFile && <div className="text-xs text-primary-700 font-medium mb-1 break-all">{imageFile.name}</div>}
                  <label className="cursor-pointer inline-flex items-center gap-2 px-3 py-2 rounded-lg border border-gray-300 bg-white hover:bg-gray-50 text-sm text-gray-600 transition-colors">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M17 8l-5-5-5 5M12 3v12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                    {imageFile ? 'Αλλαγή εικόνας' : 'Επιλογή εικόνας'}
                    <input type="file" accept="image/*" className="sr-only" onChange={e => setImageFile(e.target.files[0] ?? null)} />
                  </label>
                </div>}
              </>)}

              {/* Tab 2: Digital Menu */}
              {leftTab === 'digital' && (() => {
                const basePrice = parseFloat(form.base_price) || 0
                const dp = form.digital_price !== '' ? parseFloat(form.digital_price) : null
                const disc = form.digital_discount !== '' ? parseFloat(form.digital_discount) : null
                let customerPrice = basePrice
                if (dp !== null && !isNaN(dp)) customerPrice = dp
                else if (disc !== null && !isNaN(disc) && disc > 0) customerPrice = Math.round(basePrice * (1 - disc / 100) * 100) / 100

                return (
                  <div className="space-y-6">
                    <div>
                      <p className="text-xs font-semibold text-gray-400 uppercase tracking-widest mb-3">Ορατότητα</p>
                      <div className="space-y-3">
                        <label className="flex items-center gap-3 cursor-pointer select-none">
                          <input type="checkbox" checked={form.digital_visible}
                            onChange={e => setField('digital_visible', e.target.checked)}
                            className="w-4 h-4 accent-primary-700" />
                          <span className="text-sm font-medium text-gray-700">Show on digital menu</span>
                        </label>
                        <div>
                          <label className="flex items-center gap-3 cursor-pointer select-none">
                            <input type="checkbox" checked={form.digital_available}
                              onChange={e => setField('digital_available', e.target.checked)}
                              className="w-4 h-4 accent-primary-700" />
                            <span className="text-sm font-medium text-gray-700">Available for ordering</span>
                          </label>
                          <p className="text-xs text-gray-400 mt-1 ml-7">Uncheck to show as &lsquo;Out of stock&rsquo;</p>
                        </div>
                      </div>
                    </div>

                    <div>
                      <p className="text-xs font-semibold text-gray-400 uppercase tracking-widest mb-1">Display overrides</p>
                      <p className="text-xs text-gray-400 mb-3">Leave blank to use the standard product value</p>
                      <div className="space-y-3">
                        <div>
                          <label className="label">Display name (override)</label>
                          <input className="input" value={form.digital_name}
                            onChange={e => setField('digital_name', e.target.value)}
                            placeholder={form.name || 'Leave blank to use product name'} />
                        </div>
                        <div>
                          <label className="label">Description</label>
                          <textarea className="input resize-none" rows={3}
                            value={form.digital_description}
                            onChange={e => setField('digital_description', e.target.value)}
                            placeholder="Leave blank to use product description"
                            style={{ lineHeight: 1.5, fontSize: 13 }} />
                        </div>
                        <div>
                          <label className="label">Image URL</label>
                          <input className="input" value={form.digital_image_url}
                            onChange={e => setField('digital_image_url', e.target.value)}
                            placeholder="https://…" />
                        </div>
                      </div>
                    </div>

                    <div>
                      <p className="text-xs font-semibold text-gray-400 uppercase tracking-widest mb-3">Pricing</p>
                      <div className="space-y-3">
                        <div>
                          <label className="label">Online price (override)</label>
                          <input type="number" step="0.01" min="0" className="input w-40"
                            value={form.digital_price}
                            onChange={e => setField('digital_price', e.target.value)}
                            placeholder="e.g. 9.50" />
                        </div>
                        <div>
                          <label className="label">Discount %</label>
                          <input type="number" step="1" min="0" max="100" className="input w-40"
                            value={form.digital_discount}
                            onChange={e => setField('digital_discount', e.target.value)}
                            placeholder="e.g. 10 for 10% off" />
                        </div>
                        <div className="rounded-lg bg-green-50 border border-green-200 px-4 py-3 text-sm text-green-800">
                          Customer sees: <span className="font-bold">€{customerPrice.toFixed(2)}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                )
              })()}

              {/* Tab 3: Cost */}
              {leftTab === 'cost' && (
                <div className="space-y-3">
                  <p className="text-xs text-gray-400">Το κόστος καταγράφεται στιγμιότυπα σε κάθε παραγγελία για υπολογισμό κέρδους.</p>
                  <div className="rounded-xl border border-gray-200 bg-white overflow-hidden">
                    <div className="flex items-center justify-between px-3 py-2.5 bg-gray-50 border-b border-gray-200">
                      <span className="text-xs font-semibold text-gray-500 uppercase tracking-widest">Τύπος κόστους</span>
                      <div className="flex gap-1">
                        {['simple', 'detailed'].map(mode => (
                          <button key={mode} type="button"
                            onClick={() => setField('cost_mode', mode)}
                            className={`px-2 py-0.5 rounded text-xs font-medium transition-colors ${
                              form.cost_mode === mode
                                ? 'bg-primary-600 text-white'
                                : 'text-gray-500 hover:bg-gray-100'
                            }`}>
                            {mode === 'simple' ? 'Απλό' : 'Ανάλυση'}
                          </button>
                        ))}
                      </div>
                    </div>
                    <div className="p-3 space-y-2">
                      {form.cost_mode === 'simple' ? (
                        <div>
                          <label className="label text-xs">Κόστος ανά μονάδα (€)</label>
                          <PriceInput value={form.cost_simple} onChange={v => setField('cost_simple', v)} className="w-full" />
                          {form.cost_simple !== '' && parseFloat(form.base_price) > 0 && parseFloat(form.cost_simple) > 0 && (() => {
                            const margin = ((parseFloat(form.base_price) - parseFloat(form.cost_simple)) / parseFloat(form.base_price) * 100)
                            const isError = parseFloat(form.cost_simple) > parseFloat(form.base_price)
                            return (
                              <p className={`text-xs mt-1 font-medium ${isError ? 'text-red-500' : 'text-green-600'}`}>
                                {isError ? '⚠ Κόστος > Τιμή' : `Περιθώριο: ${margin.toFixed(1)}%`}
                              </p>
                            )
                          })()}
                        </div>
                      ) : (
                        <div className="space-y-2">
                          {form.cost_breakdown.map((entry, bi) => (
                            <div key={bi} className="flex gap-2 items-center">
                              <input className="input flex-1 text-sm" placeholder="π.χ. Γάλα"
                                value={entry.label}
                                onChange={e => setForm(f => ({ ...f, cost_breakdown: f.cost_breakdown.map((x, i) => i === bi ? { ...x, label: e.target.value } : x) }))} />
                              <PriceInput value={entry.amount}
                                onChange={v => setForm(f => ({ ...f, cost_breakdown: f.cost_breakdown.map((x, i) => i === bi ? { ...x, amount: v } : x) }))}
                                className="w-28" />
                              <button type="button"
                                onClick={() => setForm(f => ({ ...f, cost_breakdown: f.cost_breakdown.filter((_, i) => i !== bi) }))}
                                className="text-gray-400 hover:text-red-500 px-1.5 text-sm shrink-0">✕</button>
                            </div>
                          ))}
                          <button type="button"
                            onClick={() => setForm(f => ({ ...f, cost_breakdown: [...f.cost_breakdown, { label: '', amount: 0 }] }))}
                            className="text-xs text-primary-600 hover:text-primary-800 font-medium">+ Γραμμή κόστους</button>
                          {form.cost_breakdown.length > 0 && (() => {
                            const total = form.cost_breakdown.reduce((s, e) => s + (parseFloat(e.amount) || 0), 0)
                            const price = parseFloat(form.base_price) || 0
                            const isError = total > price && price > 0
                            const margin = price > 0 ? ((price - total) / price * 100) : null
                            return (
                              <div className={`text-xs font-medium ${isError ? 'text-red-500' : 'text-gray-600'}`}>
                                Σύνολο: €{total.toFixed(2)}
                                {margin !== null && !isError && <span className="text-green-600 ml-2">({margin.toFixed(1)}% περιθώριο)</span>}
                                {isError && <span className="ml-1">— Κόστος &gt; Τιμή!</span>}
                              </div>
                            )
                          })()}
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              )}

              {/* Tab 4: Fiscal (ΦΗΜ) — only shown when fiscal.enabled = true */}
              {leftTab === 'fiscal' && (
                <div className="space-y-4">
                  <div className="rounded-lg bg-blue-50 border border-blue-200 px-3 py-2 text-xs text-blue-800">
                    Τα πεδία αυτά χρησιμοποιούνται κατά την αυτόματη αποστολή αποδείξεων στη ΦΗΜ.
                  </div>

                  <div>
                    <label className="label">Όνομα ΦΗΜ <span className="text-gray-400 font-normal normal-case">(προαιρετικό)</span></label>
                    <input
                      className="input font-mono uppercase"
                      placeholder={form.name?.toUpperCase() || 'ΧΡΗΣΙΜΟΠΟΙΕΊ ΤΟ ΚΑΝΟΝΙΚΟ ΟΝΟΜΑ'}
                      value={form.fiscal_name}
                      maxLength={30}
                      onChange={e => setField('fiscal_name', e.target.value.toUpperCase())}
                    />
                    <p className="text-xs text-gray-400 mt-1">
                      Σύντομο όνομα για την απόδειξη. Αν αφεθεί κενό, χρησιμοποιείται το κανονικό όνομα.
                    </p>
                  </div>

                  <div>
                    <label className="label">Ομάδα ΦΠΑ ΦΗΜ *</label>
                    {vatGroups.length === 0 ? (
                      <p className="text-xs text-amber-600 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2">
                        Δεν έχουν οριστεί ομάδες ΦΠΑ. Πηγαίνετε στις <strong>Ρυθμίσεις → Ταμειακή</strong> για να τις ρυθμίσετε.
                      </p>
                    ) : (
                      <select
                        className="input"
                        value={form.fiscal_vat_group_id ?? ''}
                        onChange={e => setField('fiscal_vat_group_id', e.target.value ? parseInt(e.target.value, 10) : null)}
                      >
                        <option value="">— Χωρίς ανάθεση —</option>
                        {vatGroups.map(g => (
                          <option key={g.machine_id} value={g.machine_id}>
                            {g.machine_id} — {g.friendly_name}
                          </option>
                        ))}
                      </select>
                    )}
                    {!form.fiscal_vat_group_id && (
                      <p className="text-xs text-red-500 mt-1">
                        Απαιτείται για πληρωμή με ΦΗΜ ενεργή.
                      </p>
                    )}
                  </div>
                </div>
              )}

            </div>
          </div>

          {/* RIGHT: ingredient/option tabs — 70% (hidden for service items) */}
          <div className="flex flex-col overflow-hidden" style={{ width: '75%', display: form.is_service_item ? 'none' : undefined }}>
            <div className="flex border-b border-gray-200 overflow-x-auto shrink-0 bg-white">
              {tabs.map(tab => {
                if (tab.isAddGroup) return (
                  <button key="__add_pref_group__" onClick={() => addModifierGroup('preference')}
                    className="px-4 py-3 text-sm font-medium text-indigo-600 hover:bg-indigo-50 whitespace-nowrap border-b-2 border-transparent transition-colors">
                    {tab.label}
                  </button>
                )
                if (tab.isAdd) return (
                  <button key="__add_pref__" onClick={addPrefSet}
                    className="px-4 py-3 text-sm font-medium text-primary-600 hover:bg-primary-50 whitespace-nowrap border-b-2 border-transparent transition-colors">
                    {tab.label}
                  </button>
                )
                const isActive = activeTab === tab.key
                return (
                  <button key={String(tab.key)} onClick={() => setActiveTab(tab.key)}
                    className={`px-4 py-3 text-sm font-medium whitespace-nowrap border-b-2 transition-colors flex items-center gap-1.5 ${
                      isActive ? 'border-primary-600 text-primary-700 bg-primary-50/50' : 'border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                    }`}>
                    {tab.isFavTab && <HeartIcon filled={favCount > 0} className={`w-3.5 h-3.5 ${favCount > 0 ? 'text-rose-500' : 'text-gray-400'}`} />}
                    {tab.label}
                    {tab.count > 0 && (
                      <span className={`text-xs px-1.5 py-0.5 rounded-full font-mono ${isActive ? 'bg-primary-100 text-primary-700' : 'bg-gray-100 text-gray-500'}`}>
                        {tab.count}
                      </span>
                    )}
                  </button>
                )
              })}
            </div>

            <div className="flex-1 overflow-y-auto px-6 py-5">

              {/* Favorites */}
              {activeTab === 'favorites' && (
                <div>
                  <p className="text-sm text-gray-500 mb-4">Αγαπημένα — εμφανίζονται πρώτα στον σερβιτόρο.</p>
                  {favList.length === 0 && <p className="text-sm text-gray-400 text-center py-12">Δεν υπάρχουν αγαπημένα.</p>}
                  <div className="space-y-2">
                    {favList.map((fav, fi) => (
                      <div key={`${fav.type}-${fav.idx}`} className="flex items-center gap-3 border border-rose-100 bg-rose-50/30 rounded-xl p-3">
                        <ReorderBtns onUp={() => moveFavorite(favList, fi, -1)} onDown={() => moveFavorite(favList, fi, 1)}
                          disableUp={fi === 0} disableDown={fi === favList.length - 1} />
                        <HeartIcon filled className="w-4 h-4 text-rose-400 shrink-0" />
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium text-gray-800 truncate">{getItemLabel(form, fav.type, fav.idx)}</p>
                          <p className="text-xs text-gray-400">{getItemTypeLabel(fav.type)}</p>
                        </div>
                        <button type="button" onClick={() => toggleFavorite(fav.type, fav.idx)}
                          className="text-xs text-gray-400 hover:text-red-500 px-2 py-1 rounded hover:bg-red-50">Αφαίρεση</button>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Quick Options */}
              {activeTab === 'quick' && (
                <div>
                  <div className="flex items-center justify-between mb-3">
                    <p className="text-sm text-gray-500">Γρήγορες επιλογές.</p>
                    <button onClick={addQuickOption} className="btn btn-secondary text-sm px-3 py-1.5 min-h-0 h-9">+ Επιλογή</button>
                  </div>
                  {!form.quick_options.length && <p className="text-sm text-gray-400 text-center py-8">Δεν υπάρχουν γρήγορες επιλογές.</p>}
                  <div className="space-y-2">
                    {form.quick_options.map((q, i) => (
                      <div key={i} className={`flex gap-2 items-center border rounded-xl p-3 bg-white ${q.is_favorite ? 'border-rose-200' : 'border-gray-200'}`}>
                        <ReorderBtns onUp={() => moveQuickOption(i, -1)} onDown={() => moveQuickOption(i, 1)}
                          disableUp={i === 0} disableDown={i === form.quick_options.length - 1} />
                        <FavoriteBtn isFavorite={q.is_favorite} onClick={() => toggleFavorite('quick', i)} />
                        <input className="input flex-1" placeholder="π.χ. Extra Bacon" value={q.name} onChange={e => setQuickOption(i, 'name', e.target.value)} />
                        <PriceInput value={q.price} onChange={v => setQuickOption(i, 'price', v)} className="w-32" />
                        <label className="flex items-center gap-1.5 text-sm text-gray-600 cursor-pointer shrink-0 select-none">
                          <input type="checkbox" checked={q.allow_multiple} onChange={e => setQuickOption(i, 'allow_multiple', e.target.checked)} className="accent-primary-700 w-4 h-4" />
                          Πολλαπλά
                        </label>
                        <label className="flex items-center gap-1.5 text-sm cursor-pointer shrink-0 select-none" style={{ color: q.is_compact ? '#7c3aed' : '#6b7280' }}>
                          <input type="checkbox" checked={q.is_compact ?? false} onChange={e => setQuickOption(i, 'is_compact', e.target.checked)} className="w-4 h-4" style={{ accentColor: '#7c3aed' }} />
                          Compact
                        </label>
                        <button onClick={() => removeQuickOption(i)} className="btn btn-danger px-3 min-h-0 h-10">✕</button>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Ingredients */}
              {activeTab === 'ingredients' && (() => {
                const ingGroups = form.modifier_groups.filter(g => g.modifier_type === 'ingredient')
                const ungrouped = form.ingredients.map((ing, i) => ({ ing, i })).filter(({ ing }) => ing.group_id == null)
                const renderIngRow = (ing, i) => (
                  <div key={i} className={`flex gap-2 items-center border rounded-xl p-3 bg-white flex-wrap ${ing.is_favorite ? 'border-rose-200' : 'border-gray-200'}`}>
                    <ReorderBtns onUp={() => moveIngredient(i, -1)} onDown={() => moveIngredient(i, 1)}
                      disableUp={i === 0} disableDown={i === form.ingredients.length - 1} />
                    <FavoriteBtn isFavorite={ing.is_favorite} onClick={() => toggleFavorite('ingredient', i)} />
                    <input className="input flex-1 min-w-40" placeholder="Όνομα υλικού" value={ing.name} onChange={e => setIngredient(i, 'name', e.target.value)} />
                    <PriceInput value={ing.extra_cost} onChange={v => setIngredient(i, 'extra_cost', v)} allowNegative className="w-32" />
                    <label className="flex items-center gap-1.5 text-sm cursor-pointer shrink-0 select-none" style={{ color: ing.is_compact ? '#7c3aed' : '#6b7280' }}>
                      <input type="checkbox" checked={ing.is_compact ?? false} onChange={e => setIngredient(i, 'is_compact', e.target.checked)} className="w-4 h-4" style={{ accentColor: '#7c3aed' }} />
                      Compact
                    </label>
                    {ingGroups.length > 0 && (
                      <select className="input text-xs px-2 h-9 shrink-0" style={{ width: 120 }}
                        value={form.ingredients[i].group_id ?? ''}
                        onChange={e => setItemGroup('ingredients', i, e.target.value === '' ? null : Number(e.target.value))}>
                        <option value="">— χωρίς ομάδα —</option>
                        {ingGroups.map(g => <option key={g._tempId} value={g._tempId}>{g.name}</option>)}
                      </select>
                    )}
                    <button onClick={() => removeIngredient(i)} className="btn btn-danger px-3 min-h-0 h-10">✕</button>
                  </div>
                )
                return (
                  <div>
                    <div className="flex items-center justify-between mb-3 gap-2 flex-wrap">
                      <p className="text-sm text-gray-500">Υλικά που ο πελάτης μπορεί να αφαιρέσει.</p>
                      <div className="flex gap-2">
                        <button onClick={() => addModifierGroup('ingredient')} className="btn btn-secondary text-sm px-3 py-1.5 min-h-0 h-9">+ Ομάδα</button>
                        <button onClick={addIngredient} className="btn btn-secondary text-sm px-3 py-1.5 min-h-0 h-9">+ Υλικό</button>
                      </div>
                    </div>
                    {!form.ingredients.length && <p className="text-sm text-gray-400 text-center py-8">Δεν υπάρχουν υλικά.</p>}
                    <div className="space-y-2">
                      {ungrouped.map(({ ing, i }) => renderIngRow(ing, i))}
                      {ingGroups.map(g => {
                        const members = form.ingredients.map((ing, i) => ({ ing, i })).filter(({ ing }) => ing.group_id === g._tempId)
                        const collapsed = collapsedGroups[g._tempId]
                        return (
                          <div key={g._tempId}>
                            <GroupHeader group={g} collapsed={collapsed} onToggle={() => toggleGroupCollapsed(g._tempId)}
                              onRename={name => renameModifierGroup(g._tempId, name)}
                              onDelete={() => deleteModifierGroup(g._tempId)} />
                            {!collapsed && (
                              <div className="ml-4 border-l-2 border-indigo-100 pl-3 mt-1 space-y-2">
                                {members.length === 0 && <p className="text-xs text-gray-400 py-2">Χωρίς υλικά — αλλάξτε ομάδα από κάθε υλικό.</p>}
                                {members.map(({ ing, i }) => renderIngRow(ing, i))}
                              </div>
                            )}
                          </div>
                        )
                      })}
                    </div>
                  </div>
                )
              })()}

              {/* Options/Extras */}
              {activeTab === 'options' && (() => {
                const optGroups = form.modifier_groups.filter(g => g.modifier_type === 'option')
                const ungrouped = form.options.map((opt, i) => ({ opt, i })).filter(({ opt }) => opt.group_id == null)
                const renderOptRow = (opt, i) => (
                  <div key={i} className={`border rounded-xl overflow-hidden ${opt.is_favorite ? 'border-rose-200' : 'border-gray-200'}`}>
                    <div className="flex gap-2 items-center p-3 bg-white flex-wrap">
                      <ReorderBtns onUp={() => moveOption(i, -1)} onDown={() => moveOption(i, 1)}
                        disableUp={i === 0} disableDown={i === form.options.length - 1} />
                      <FavoriteBtn isFavorite={opt.is_favorite} onClick={() => toggleFavorite('option', i)} />
                      <input className="input flex-1 min-w-40" placeholder="π.χ. Κανέλα" value={opt.name} onChange={e => setOption(i, 'name', e.target.value)} />
                      <PriceInput value={opt.extra_cost} onChange={v => setOption(i, 'extra_cost', v)} allowNegative className="w-32" />
                      <label className="flex items-center gap-1.5 text-sm text-gray-600 cursor-pointer shrink-0 select-none">
                        <input type="checkbox" checked={opt.allow_multiple} onChange={e => setOption(i, 'allow_multiple', e.target.checked)} className="accent-primary-700 w-4 h-4" />
                        Πολλαπλά
                      </label>
                      <label className="flex items-center gap-1.5 text-sm cursor-pointer shrink-0 select-none" style={{ color: opt.multi_select ? '#0891b2' : '#6b7280' }}>
                        <input type="checkbox" checked={opt.multi_select ?? false} onChange={e => setOption(i, 'multi_select', e.target.checked)} className="w-4 h-4" style={{ accentColor: '#0891b2' }} />
                        Multi-select
                      </label>
                      <label className="flex items-center gap-1.5 text-sm cursor-pointer shrink-0 select-none" style={{ color: opt.is_compact ? '#7c3aed' : '#6b7280' }}>
                        <input type="checkbox" checked={opt.is_compact ?? false} onChange={e => setOption(i, 'is_compact', e.target.checked)} className="w-4 h-4" style={{ accentColor: '#7c3aed' }} />
                        Compact
                      </label>
                      {optGroups.length > 0 && (
                        <select className="input text-xs px-2 h-9 shrink-0" style={{ width: 120 }}
                          value={form.options[i].group_id ?? ''}
                          onChange={e => setItemGroup('options', i, e.target.value === '' ? null : Number(e.target.value))}>
                          <option value="">— χωρίς ομάδα —</option>
                          {optGroups.map(g => <option key={g._tempId} value={g._tempId}>{g.name}</option>)}
                        </select>
                      )}
                      <button onClick={() => addOptionSubChoice(i)} className="btn btn-secondary text-xs px-2 min-h-0 h-9 shrink-0 whitespace-nowrap">+ Υπο-επιλογές</button>
                      <button onClick={() => removeOption(i)} className="btn btn-danger px-3 min-h-0 h-10">✕</button>
                    </div>
                    <SubChoiceRows subChoices={opt.sub_choices} parentLabel={opt.name}
                      showMultiple={opt.multi_select}
                      onMove={(sci, dir) => moveOptionSubChoice(i, sci, dir)}
                      onToggleDefault={sci => toggleOptionSubDefault(i, sci)}
                      onChange={(sci, k, v) => setOptionSubChoice(i, sci, k, v)}
                      onRemove={sci => removeOptionSubChoice(i, sci)}
                      onAdd={() => addOptionSubChoice(i)} />
                  </div>
                )
                return (
                  <div>
                    <div className="flex items-center justify-between mb-3 gap-2 flex-wrap">
                      <p className="text-sm text-gray-500">Έξτρα (checkbox). Κάθε extra μπορεί να έχει υπο-επιλογές.</p>
                      <div className="flex gap-2">
                        <button onClick={() => addModifierGroup('option')} className="btn btn-secondary text-sm px-3 py-1.5 min-h-0 h-9">+ Ομάδα</button>
                        <button onClick={addOption} className="btn btn-secondary text-sm px-3 py-1.5 min-h-0 h-9">+ Έξτρα</button>
                      </div>
                    </div>
                    {!form.options.length && <p className="text-sm text-gray-400 text-center py-8">Δεν υπάρχουν extras.</p>}
                    <div className="space-y-3">
                      {ungrouped.map(({ opt, i }) => renderOptRow(opt, i))}
                      {optGroups.map(g => {
                        const members = form.options.map((opt, i) => ({ opt, i })).filter(({ opt }) => opt.group_id === g._tempId)
                        const collapsed = collapsedGroups[g._tempId]
                        return (
                          <div key={g._tempId}>
                            <GroupHeader group={g} collapsed={collapsed} onToggle={() => toggleGroupCollapsed(g._tempId)}
                              onRename={name => renameModifierGroup(g._tempId, name)}
                              onDelete={() => deleteModifierGroup(g._tempId)} />
                            {!collapsed && (
                              <div className="ml-4 border-l-2 border-indigo-100 pl-3 mt-1 space-y-3">
                                {members.length === 0 && <p className="text-xs text-gray-400 py-2">Χωρίς extras — αλλάξτε ομάδα από κάθε extra.</p>}
                                {members.map(({ opt, i }) => renderOptRow(opt, i))}
                              </div>
                            )}
                          </div>
                        )
                      })}
                    </div>
                  </div>
                )
              })()}

              {/* Preference set tab */}
              {typeof activeTab === 'number' && form.preference_sets[activeTab] && (() => {
                const si = activeTab
                const ps = form.preference_sets[si]
                const hasSharedSubset = !!ps.shared_subset
                return (
                  <div>
                    <div className="flex items-center gap-3 mb-4 flex-wrap">
                      <input className="input flex-1 font-semibold text-base min-w-32" placeholder="π.χ. Ζάχαρη" value={ps.name}
                        onChange={e => setPrefSetField(si, 'name', e.target.value)} autoFocus />
                      {prefGroups.length > 0 && (
                        <select className="input text-xs px-2 h-9 shrink-0" style={{ width: 140 }}
                          value={ps.group_id ?? ''}
                          onChange={e => setPrefSetField(si, 'group_id', e.target.value === '' ? null : Number(e.target.value))}>
                          <option value="">— χωρίς ομάδα —</option>
                          {prefGroups.map(g => <option key={g._tempId} value={g._tempId}>{g.name}</option>)}
                        </select>
                      )}
                      <FavoriteBtn isFavorite={ps.is_favorite} onClick={() => toggleFavorite('pref', si)} />
                      <button onClick={() => removePrefSet(si)} className="btn btn-danger px-3 min-h-0 h-10 shrink-0">Διαγραφή</button>
                    </div>
                    {/* Pref groups management (only show if any exist) */}
                    {prefGroups.length > 0 && (
                      <div className="mb-4 p-3 bg-indigo-50/50 border border-indigo-100 rounded-xl space-y-1">
                        <p className="text-xs font-semibold text-indigo-600 mb-2">Ομάδες προτιμήσεων</p>
                        {prefGroups.map(g => (
                          <GroupHeader key={g._tempId} group={g}
                            collapsed={collapsedGroups[g._tempId]}
                            onToggle={() => toggleGroupCollapsed(g._tempId)}
                            onRename={name => renameModifierGroup(g._tempId, name)}
                            onDelete={() => deleteModifierGroup(g._tempId)} />
                        ))}
                      </div>
                    )}
                    <div className="flex items-center gap-5 mb-3 flex-wrap">
                      <label className="flex items-center gap-2 cursor-pointer select-none">
                        <input type="checkbox" checked={ps.allow_multi_select ?? false}
                          onChange={e => setPrefSetField(si, 'allow_multi_select', e.target.checked)}
                          className="w-4 h-4" style={{ accentColor: '#6366f1' }} />
                        <span className="text-sm font-medium" style={{ color: ps.allow_multi_select ? '#6366f1' : '#6b7280' }}>
                          Πολλαπλή επιλογή
                        </span>
                      </label>
                      <label className="flex items-center gap-2 cursor-pointer select-none">
                        <input type="checkbox" checked={ps.allow_choice_quantity ?? false}
                          onChange={e => setPrefSetField(si, 'allow_choice_quantity', e.target.checked)}
                          className="w-4 h-4" style={{ accentColor: '#6366f1' }} />
                        <span className="text-sm font-medium" style={{ color: ps.allow_choice_quantity ? '#6366f1' : '#6b7280' }}>
                          Ποσότητα ανά επιλογή
                        </span>
                      </label>
                    </div>
                    <p className="text-xs text-gray-400 mb-3">● = προεπιλογή · ⊘ = απενεργοποιεί κοινό υπο-σύνολο</p>
                    <div className="space-y-3 mb-5">
                      {ps.choices.map((ch, ci) => (
                        <div key={ci} className="border border-gray-200 rounded-xl overflow-hidden">
                          <div className="flex items-center gap-2 p-3 bg-white flex-wrap">
                            <ReorderBtns onUp={() => moveChoice(si, ci, -1)} onDown={() => moveChoice(si, ci, 1)}
                              disableUp={ci === 0} disableDown={ci === ps.choices.length - 1} />
                            <DefaultBtn isDefault={ps.default_choice_index === ci} onClick={() => toggleDefaultChoice(si, ci)} />
                            <input className="input flex-1 min-w-32" placeholder="π.χ. Σκέτος" value={ch.name} onChange={e => setChoice(si, ci, 'name', e.target.value)} />
                            <PriceInput value={ch.extra_cost} onChange={v => setChoice(si, ci, 'extra_cost', v)} allowNegative className="w-32" />
                            <label className="flex items-center gap-1 text-xs cursor-pointer shrink-0 select-none" style={{ color: ch.is_compact ? '#7c3aed' : '#6b7280' }}>
                              <input type="checkbox" checked={ch.is_compact ?? false} onChange={e => setChoice(si, ci, 'is_compact', e.target.checked)} className="w-3.5 h-3.5" style={{ accentColor: '#7c3aed' }} />
                              Compact
                            </label>
                            {hasSharedSubset && (
                              <button type="button" onClick={() => setChoice(si, ci, 'disables_subset', !ch.disables_subset)}
                                className={`w-7 h-7 rounded-full flex items-center justify-center shrink-0 text-sm ${ch.disables_subset ? 'bg-red-100 text-red-500' : 'text-gray-300 hover:text-red-400'}`}>⊘</button>
                            )}
                            <button onClick={() => addSubChoice(si, ci)} className="btn btn-secondary text-xs px-2 min-h-0 h-9 shrink-0 whitespace-nowrap">+ Υπο-επιλογές</button>
                            <button onClick={() => removeChoice(si, ci)} className="btn btn-danger px-2 min-h-0 h-9 shrink-0">✕</button>
                          </div>
                          <SubChoiceRows subChoices={ch.sub_choices} parentLabel={ch.name}
                            onMove={(sci, dir) => moveSubChoice(si, ci, sci, dir)}
                            onToggleDefault={sci => setSubChoice(si, ci, sci, 'is_default', !ch.sub_choices[sci]?.is_default)}
                            onChange={(sci, k, v) => setSubChoice(si, ci, sci, k, v)}
                            onRemove={sci => removeSubChoice(si, ci, sci)}
                            onAdd={() => addSubChoice(si, ci)} />
                        </div>
                      ))}
                    </div>
                    <button onClick={() => addChoice(si)} className="btn btn-secondary text-sm px-4 py-1.5 min-h-0 h-9">+ Επιλογή</button>
                    <div className="mt-6 border-t border-gray-100 pt-5">
                      <div className="flex items-center justify-between mb-3">
                        <div>
                          <p className="text-sm font-semibold text-gray-700">Κοινό υπο-σύνολο</p>
                          <p className="text-xs text-gray-400">Εμφανίζεται για όλες εκτός αυτών με ⊘</p>
                        </div>
                        {!ps.shared_subset
                          ? <button onClick={() => setSharedSubsetName(si, '')} className="btn btn-secondary text-sm px-3 py-1.5 min-h-0 h-9">+ Κοινό υπο-σύνολο</button>
                          : <button onClick={() => setPrefSetField(si, 'shared_subset', null)} className="btn btn-danger text-sm px-3 py-1.5 min-h-0 h-9">Αφαίρεση</button>
                        }
                      </div>
                      {ps.shared_subset && (
                        <div className="border border-indigo-200 rounded-xl p-4 bg-indigo-50/30 space-y-3">
                          <div>
                            <label className="label text-xs">Όνομα</label>
                            <input className="input text-sm" placeholder="π.χ. Είδος ζάχαρης" value={ps.shared_subset.name || ''} onChange={e => setSharedSubsetName(si, e.target.value)} />
                          </div>
                          <div className="space-y-2">
                            {(ps.shared_subset.choices || []).map((sc, sci) => (
                              <div key={sci} className="flex items-center gap-2">
                                <ReorderBtns onUp={() => moveSharedSubsetChoice(si, sci, -1)} onDown={() => moveSharedSubsetChoice(si, sci, 1)}
                                  disableUp={sci === 0} disableDown={sci === ps.shared_subset.choices.length - 1} />
                                <DefaultBtn isDefault={sc.is_default} onClick={() => setSharedSubsetChoice(si, sci, 'is_default', !sc.is_default)} />
                                <input className="input flex-1 text-sm" placeholder="π.χ. Λευκή" value={sc.name} onChange={e => setSharedSubsetChoice(si, sci, 'name', e.target.value)} />
                                <PriceInput value={sc.extra_cost} onChange={v => setSharedSubsetChoice(si, sci, 'extra_cost', v)} allowNegative className="w-32 text-sm" />
                                <button onClick={() => removeSharedSubsetChoice(si, sci)} className="btn btn-danger px-2 min-h-0 h-9 text-sm shrink-0">✕</button>
                              </div>
                            ))}
                          </div>
                          <button onClick={() => addSharedSubsetChoice(si)} className="btn btn-secondary text-xs px-3 py-1 min-h-0 h-7">+ Επιλογή</button>
                        </div>
                      )}
                    </div>
                  </div>
                )
              })()}
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between px-6 py-4 border-t border-gray-100 bg-gray-50/50 shrink-0 gap-3">
          <button onClick={onClose} className="btn btn-secondary px-6">Ακύρωση</button>
          <div className="flex gap-3">
            {!isNew && (
              <button onClick={() => onCopy({ ...form })} className="btn btn-secondary px-6 text-indigo-600 border-indigo-200 hover:bg-indigo-50">
                📋 Αντιγραφή
              </button>
            )}
            <button onClick={submit} disabled={!canSave || uploading} className="btn btn-primary px-8">
              {uploading ? 'Ανέβασμα…' : isNew ? 'Δημιουργία' : 'Αποθήκευση'}
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}
