'use client';

import { useState, useEffect } from 'react';
import { X, Save, Plus, Trash2, ChevronDown, ChevronRight, Flame, Leaf, Check, Pencil, Upload, Package, Clock, MapPin } from 'lucide-react';
import { toast } from 'sonner';
import { createMenuItem, updateMenuItem, createModifierGroup, updateModifierGroup, deleteModifierGroup, createModifierOption, updateModifierOption, deleteModifierOption } from '@client/api/menu';
import { useAuth } from '@client/contexts/AuthContext';
import DemoDisabled from '@client/components/demo/DemoDisabled';
import { useLanguage } from '@client/contexts/LanguageContext';
import type { Category, MenuItem, ModGroup, ModOption } from './page';
import SchedulePicker, { type ScheduleWindow } from './SchedulePicker';
import BranchAvailability from './BranchAvailability';

interface Props {
  item?: MenuItem | null;
  categories: Category[];
  onClose: () => void;
  onSaved: (item: MenuItem, isNew: boolean) => void;
}

const SPICE_LABELS = ['No Spice', 'Mild', 'Medium', 'Hot'];

export default function ItemDrawer({ item, categories, onClose, onSaved }: Props) {
  const { t } = useLanguage();
  const { restaurantId, userRecord } = useAuth();
  // Owners (role=owner) see and can mutate every branch's availability;
  // every other role is pinned to their assigned branch and the server-side
  // assertBranchAccess will reject any cross-branch mutation.
  const pinnedBranchId = userRecord?.role === 'owner' ? null : (userRecord?.branch_id ?? null);
  const isEditing = !!item?.id;

  const [form, setForm] = useState({
    name: item?.name ?? '', description: item?.description ?? '',
    price: item?.price?.toString() ?? '', categoryId: item?.categoryId ?? '',
    imageUrl: item?.imageUrl ?? '', isVeg: item?.isVeg ?? false,
    spiceLevel: item?.spiceLevel ?? 0, prepTime: item?.prepTime?.toString() ?? '',
    calories: item?.calories?.toString() ?? '',
    isInStock: (item as MenuItem & { isInStock?: boolean })?.isInStock ?? true,
    stockCount: (item as MenuItem & { stockCount?: number | null })?.stockCount ?? null as number | null,
    // Task #295: alert + daily-reset thresholds. null = disabled.
    lowStockThreshold: (item as MenuItem & { lowStockThreshold?: number | null })?.lowStockThreshold ?? null as number | null,
    dailyResetCount: (item as MenuItem & { dailyResetCount?: number | null })?.dailyResetCount ?? null as number | null,
  });
  const [schedule, setSchedule] = useState<ScheduleWindow[] | null>(
    ((item as MenuItem & { schedule?: ScheduleWindow[] | null })?.schedule) ?? null
  );
  const [saving, setSaving] = useState(false);
  const [savedId, setSavedId] = useState<string | null>(item?.id ?? null);
  const [groups, setGroups] = useState<ModGroup[]>(item?.modifierGroups ?? []);
  const [expanded, setExpanded] = useState<Set<string>>(new Set());
  const [addingGroup, setAddingGroup] = useState(false);
  const [newGroup, setNewGroup] = useState({ name: '', type: 'checkbox' as 'radio' | 'checkbox', isRequired: false, minSelections: '0', maxSelections: '' });
  const [editingGroup, setEditingGroup] = useState<string | null>(null);
  const [editGroupForm, setEditGroupForm] = useState({ name: '', type: 'checkbox' as 'radio' | 'checkbox', isRequired: false, minSelections: '0', maxSelections: '' });
  const [addingOption, setAddingOption] = useState<string | null>(null);
  const [newOption, setNewOption] = useState({ name: '', priceDelta: '', isDefault: false });
  const [editingOption, setEditingOption] = useState<{ groupId: string; optId: string } | null>(null);
  const [editOptionForm, setEditOptionForm] = useState({ name: '', priceDelta: '', isDefault: false });
  const [imgError, setImgError] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);

  useEffect(() => { setImgError(false); }, [form.imageUrl]);

  // Free the object URL whenever it changes or the drawer unmounts so we
  // don't leak blobs each time the user picks a different image.
  useEffect(() => {
    if (!previewUrl) return;
    return () => { URL.revokeObjectURL(previewUrl); };
  }, [previewUrl]);

  const setField = (field: string, val: unknown) => setForm(f => ({ ...f, [field]: val }));

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setSelectedFile(file);
      const url = URL.createObjectURL(file);
      setPreviewUrl(url);
    }
  };

  const handleSaveItem = async () => {
    if (!form.name.trim()) { toast.error(t('menuManagement.itemNameRequired', 'Item name is required')); return; }
    if (!restaurantId) return;
    setSaving(true);
    try {
      const formData = new FormData();
      formData.append('name', form.name);
      formData.append('description', form.description || '');
      formData.append('price', form.price || '0');
      formData.append('category_id', form.categoryId || '');
      formData.append('is_veg', String(form.isVeg));
      formData.append('spice_level', String(form.spiceLevel));
      formData.append('prep_time_minutes', form.prepTime || '0');
      formData.append('calories', form.calories || '0');
      formData.append('is_available', String(item?.available ?? true));
      formData.append('is_in_stock', String(form.isInStock));
      // stock_count: empty string → null on server (unlimited); numeric otherwise.
      formData.append('stock_count', form.stockCount == null ? '' : String(form.stockCount));
      // Task #295: empty string → null on server (alert / reset disabled).
      formData.append('low_stock_threshold', form.lowStockThreshold == null ? '' : String(form.lowStockThreshold));
      formData.append('daily_reset_count', form.dailyResetCount == null ? '' : String(form.dailyResetCount));
      // Schedule travels as a JSON string; the PATCH route's
      // formDataToObject will leave it as a plain string, so we send via the
      // dedicated schedule field name only when a non-empty array is present
      // and the server's updateMenuItemSchema parses it back into an array.
      if (schedule && schedule.length > 0) {
        formData.append('schedule', JSON.stringify(schedule));
      } else {
        formData.append('schedule', 'null');
      }

      if (selectedFile) {
        formData.append('image', selectedFile);
      } else {
        formData.append('image_url', form.imageUrl || '');
      }

      if (!savedId) {
        formData.append('restaurant_id', restaurantId);
      }

      const result = (savedId
        ? await updateMenuItem(savedId, formData)
        : await createMenuItem(formData)) as { item: Record<string, unknown> };

      const d = result.item;
      const newId = d.id as string;
      const wasNew = !savedId;
      setSavedId(newId);
      const saved: MenuItem = {
        id: newId, name: d.name as string, description: (d.description as string) || '',
        price: Number(d.price), categoryId: (d.category_id as string) || '',
        imageUrl: (d.image_url as string) || '', isVeg: (d.is_veg as boolean) ?? false,
        spiceLevel: (d.spice_level as number) ?? 0, prepTime: (d.prep_time_minutes as number) ?? 0,
        calories: (d.calories as number) ?? 0, available: (d.is_available as boolean) ?? true,
        dietary: Array.isArray(d.dietary_tags) ? d.dietary_tags as string[] : [],
        category: item?.category ?? '', modifierGroups: groups,
        isInStock: (d.is_in_stock as boolean) ?? true,
        stockCount: (d.stock_count as number | null) ?? null,
        schedule: Array.isArray(d.schedule) ? (d.schedule as ScheduleWindow[]) : null,
        // Task #295: propagate the new threshold/reset fields back so the
        // table row's read-only inventory summary updates without a refetch.
        lowStockThreshold: (d.low_stock_threshold as number | null) ?? null,
        dailyResetCount: (d.daily_reset_count as number | null) ?? null,
        lastResetAt: (d.last_reset_at as string | null) ?? null,
      };
      onSaved(saved, wasNew);
      toast.success(wasNew ? t('menuManagement.itemCreated', 'Item created') : t('menuManagement.itemUpdated', 'Item updated'));
      setSelectedFile(null); // Clear file after successful save
    } catch (e: unknown) { toast.error(e instanceof Error ? e.message : t('menuManagement.saveFailed', 'Save failed')); }
    finally { setSaving(false); }
  };

  const handleAddGroup = async () => {
    if (!newGroup.name.trim() || !savedId || !restaurantId) return;
    try {
      const res = await createModifierGroup({
        menu_item_id: savedId, name: newGroup.name, type: newGroup.type,
        is_required: newGroup.isRequired,
        min_selections: parseInt(newGroup.minSelections, 10) || 0,
        max_selections: newGroup.maxSelections ? parseInt(newGroup.maxSelections, 10) : null,
      });
      const g = (res as { group: Record<string, unknown> }).group as Record<string, unknown>;
      setGroups(prev => [...prev, { id: g.id as string, name: g.name as string, type: g.type as 'radio' | 'checkbox', is_required: g.is_required as boolean, options: [], display_order: (g.display_order as number) ?? 0, min_selections: (g.min_selections as number) ?? 0, max_selections: (g.max_selections as number | null) ?? null }]);
      setNewGroup({ name: '', type: 'checkbox', isRequired: false, minSelections: '0', maxSelections: '' });
      setAddingGroup(false);
      setExpanded(prev => new Set([...prev, g.id as string]));
    } catch (e: unknown) { toast.error(e instanceof Error ? e.message : 'Failed to add group'); }
  };

  const startEditGroup = (g: ModGroup) => {
    setEditingGroup(g.id);
    setEditGroupForm({ name: g.name, type: g.type, isRequired: g.is_required, minSelections: g.min_selections?.toString() ?? '0', maxSelections: g.max_selections?.toString() ?? '' });
  };

  const handleUpdateGroup = async (groupId: string) => {
    try {
      const res = await updateModifierGroup(groupId, {
        name: editGroupForm.name, type: editGroupForm.type,
        is_required: editGroupForm.isRequired,
        min_selections: parseInt(editGroupForm.minSelections, 10) || 0,
        max_selections: editGroupForm.maxSelections ? parseInt(editGroupForm.maxSelections, 10) : null,
      });
      const g = (res as { group: Record<string, unknown> }).group as Record<string, unknown>;
      setGroups(prev => prev.map(grp => grp.id === groupId ? { ...grp, name: g.name as string, type: g.type as 'radio' | 'checkbox', is_required: g.is_required as boolean, min_selections: (g.min_selections as number) ?? 0, max_selections: (g.max_selections as number | null) ?? null } : grp));
      setEditingGroup(null);
    } catch (e: unknown) { toast.error(e instanceof Error ? e.message : 'Failed to update group'); }
  };

  const handleDeleteGroup = async (groupId: string) => {
    try { await deleteModifierGroup(groupId); setGroups(prev => prev.filter(g => g.id !== groupId)); }
    catch (e: unknown) { toast.error(e instanceof Error ? e.message : 'Failed to delete group'); }
  };

  const handleAddOption = async (groupId: string) => {
    if (!newOption.name.trim()) return;
    try {
      const res = await createModifierOption(groupId, { name: newOption.name, price_delta: parseFloat(newOption.priceDelta) || 0, is_default: newOption.isDefault });
      const o = (res as { option: Record<string, unknown> }).option as Record<string, unknown>;
      setGroups(prev => prev.map(g => g.id === groupId ? { ...g, options: [...g.options, { id: o.id as string, name: o.name as string, price_delta: Number(o.price_delta), is_default: o.is_default as boolean, is_available: true, display_order: (o.display_order as number) ?? 0 }] } : g));
      setNewOption({ name: '', priceDelta: '', isDefault: false }); setAddingOption(null);
    } catch (e: unknown) { toast.error(e instanceof Error ? e.message : 'Failed to add option'); }
  };

  const startEditOption = (groupId: string, opt: ModOption) => {
    setEditingOption({ groupId, optId: opt.id });
    setEditOptionForm({ name: opt.name, priceDelta: opt.price_delta !== 0 ? opt.price_delta.toString() : '', isDefault: opt.is_default });
  };

  const handleUpdateOption = async () => {
    if (!editingOption) return;
    try {
      const res = await updateModifierOption(editingOption.groupId, editingOption.optId, { name: editOptionForm.name, price_delta: parseFloat(editOptionForm.priceDelta) || 0, is_default: editOptionForm.isDefault });
      const o = (res as { option: Record<string, unknown> }).option as Record<string, unknown>;
      setGroups(prev => prev.map(g => g.id === editingOption.groupId ? { ...g, options: g.options.map(opt => opt.id === editingOption.optId ? { ...opt, name: o.name as string, price_delta: Number(o.price_delta), is_default: o.is_default as boolean } : opt) } : g));
      setEditingOption(null);
    } catch (e: unknown) { toast.error(e instanceof Error ? e.message : 'Failed to update option'); }
  };

  const handleDeleteOption = async (groupId: string, optId: string) => {
    try { await deleteModifierOption(groupId, optId); setGroups(prev => prev.map(g => g.id === groupId ? { ...g, options: g.options.filter(o => o.id !== optId) } : g)); }
    catch (e: unknown) { toast.error(e instanceof Error ? e.message : 'Failed to delete option'); }
  };

  return (
    <div className="fixed inset-0 z-50 flex">
      <div className="flex-1 bg-black/40 backdrop-blur-sm" onClick={onClose} />
      <div className="w-full max-w-xl bg-white shadow-2xl flex flex-col h-full overflow-hidden">
        <div className="flex items-center justify-between px-5 py-4 border-b" style={{ borderColor: 'hsl(var(--border))' }}>
          <h2 className="font-bold text-lg" style={{ color: 'hsl(var(--foreground))' }}>{isEditing ? t('menuManagement.editItem', 'Edit Item') : t('menuManagement.addItem', 'Add Menu Item')}</h2>
          <button className="btn-ghost p-1.5" onClick={onClose}><X size={18} /></button>
        </div>

        <div className="flex-1 overflow-y-auto px-5 py-4 space-y-5">
          {(previewUrl || (form.imageUrl && !imgError)) && (
            <div className="relative w-full h-40 rounded-xl overflow-hidden" style={{ backgroundColor: 'hsl(var(--muted))' }}>
              <img src={previewUrl || form.imageUrl} alt="Preview" className="w-full h-full object-cover" onError={() => setImgError(true)} />
              {previewUrl && (
                <button
                  className="absolute top-2 right-2 p-1.5 bg-black/50 text-white rounded-full hover:bg-black/70 transition-colors"
                  onClick={(e) => { e.stopPropagation(); setSelectedFile(null); setPreviewUrl(null); }}
                >
                  <X size={14} />
                </button>
              )}
            </div>
          )}

          <div className="space-y-3">
            <div className="grid grid-cols-2 gap-3">
              <div className="col-span-2">
                <label className="label-base">{t('menuManagement.itemNameStar', 'Item Name *')}</label>
                <input className="input-base" placeholder={t('menuManagement.itemNamePlaceholder', 'e.g. Butter Chicken')} value={form.name} onChange={e => setField('name', e.target.value)} />
              </div>
              <div>
                <label className="label-base">{t('menuManagement.priceLabel', 'Price (₹)')}</label>
                <input type="number" className="input-base" placeholder="0.00" value={form.price} onChange={e => setField('price', e.target.value)} />
              </div>
              <div>
                <label className="label-base">{t('menuManagement.category', 'Category')}</label>
                <select className="input-base" value={form.categoryId} onChange={e => setField('categoryId', e.target.value)}>
                  <option value="">{t('menuManagement.uncategorized', 'Uncategorized')}</option>
                  {categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
              </div>
              <div className="col-span-2">
                <label className="label-base">{t('menuManagement.description', 'Description')}</label>
                <textarea className="input-base resize-none" rows={2} placeholder={t('menuManagement.descriptionPlaceholder', 'Describe the dish…')} value={form.description} onChange={e => setField('description', e.target.value)} />
              </div>
              <div className="col-span-2">
                <label className="label-base">{t('menuManagement.itemImage', 'Item Image')}</label>
                <div className="flex gap-3">
                  <div className="flex-1">
                    <input type="file" accept="image/*" className="hidden" id="item-image-upload" onChange={handleFileChange} />
                    <label htmlFor="item-image-upload" className="flex items-center justify-center gap-2 px-4 py-2 border-2 border-dashed rounded-xl cursor-pointer hover:border-primary transition-colors h-[42px]" style={{ borderColor: 'hsl(var(--border))', color: 'hsl(var(--muted-foreground))' }}>
                      <Upload size={16} />
                      <span className="text-sm truncate max-w-[150px]">{selectedFile ? selectedFile.name : t('menuManagement.upload', 'Upload')}</span>
                    </label>
                  </div>
                  <div className="flex-[1.5]">
                    <input className="input-base" placeholder={t('menuItem.imageUrlPlaceholder', 'Or paste URL…')} value={form.imageUrl} onChange={e => { setField('imageUrl', e.target.value); setSelectedFile(null); setPreviewUrl(null); }} />
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className="space-y-3">
            <p className="text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('menuManagement.properties', 'Properties')}</p>
            <div className="grid grid-cols-2 gap-3">
              <div className="flex items-center gap-3 p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                <Leaf size={16} style={{ color: 'hsl(var(--success))' }} />
                <span className="text-sm font-medium flex-1" style={{ color: 'hsl(var(--foreground))' }}>{t('menuManagement.vegetarian', 'Vegetarian')}</span>
                <button onClick={() => setField('isVeg', !form.isVeg)} className="w-10 h-6 rounded-full transition-colors flex items-center px-0.5" style={{ backgroundColor: form.isVeg ? 'hsl(var(--success))' : 'hsl(var(--muted-foreground))' }}>
                  <span className="w-5 h-5 bg-white rounded-full shadow transition-transform" style={{ transform: form.isVeg ? 'translateX(16px)' : 'translateX(0)' }} />
                </button>
              </div>
              <div className="p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                <div className="flex items-center gap-2 mb-2">
                  <Flame size={14} style={{ color: 'hsl(var(--warning))' }} />
                  <span className="text-xs font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('menuManagement.spice', 'Spice')}: {[t('menuManagement.spiceNo', 'No Spice'), t('menuManagement.spiceMild', 'Mild'), t('menuManagement.spiceMedium', 'Medium'), t('menuManagement.spiceHot', 'Hot')][form.spiceLevel]}</span>
                </div>
                <div className="flex gap-1">
                  {[0, 1, 2, 3].map(lvl => (
                    <button key={lvl} onClick={() => setField('spiceLevel', lvl)} className="flex-1 h-2 rounded-full transition-colors"
                      style={{ backgroundColor: form.spiceLevel >= lvl ? 'hsl(var(--warning))' : 'hsl(var(--border))' }} />
                  ))}
                </div>
              </div>
              <div>
                <label className="label-base">{t('menuManagement.prepTime', 'Prep Time (min)')}</label>
                <input type="number" className="input-base" placeholder="15" value={form.prepTime} onChange={e => setField('prepTime', e.target.value)} />
              </div>
              <div>
                <label className="label-base">{t('menuManagement.calories', 'Calories (kcal)')}</label>
                <input type="number" className="input-base" placeholder="350" value={form.calories} onChange={e => setField('calories', e.target.value)} />
              </div>
            </div>
          </div>

          {/* Stock & availability — Task #291. Inline so it's editable both
              for new items (saved on first create) and existing ones. */}
          <div className="space-y-3">
            <p className="text-xs font-semibold uppercase tracking-wider flex items-center gap-1.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
              <Package size={12} /> {t('menuManagement.stock', 'Stock')}
            </p>
            <div className="grid grid-cols-2 gap-3">
              <div className="flex items-center gap-3 p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                <span className="text-sm font-medium flex-1" style={{ color: 'hsl(var(--foreground))' }}>{t('menuManagement.inStock', 'In stock')}</span>
                <button type="button" onClick={() => setField('isInStock', !form.isInStock)} className="w-10 h-6 rounded-full transition-colors flex items-center px-0.5" style={{ backgroundColor: form.isInStock ? 'hsl(var(--success))' : 'hsl(var(--muted-foreground))' }}>
                  <span className="w-5 h-5 bg-white rounded-full shadow transition-transform" style={{ transform: form.isInStock ? 'translateX(16px)' : 'translateX(0)' }} />
                </button>
              </div>
              <div>
                <label className="label-base">{t('menuManagement.stockCount', 'Stock count')}</label>
                <input
                  type="number"
                  min="0"
                  className="input-base"
                  placeholder={t('menuManagement.unlimited', 'Unlimited')}
                  value={form.stockCount ?? ''}
                  onChange={e => setField('stockCount', e.target.value === '' ? null : Math.max(0, parseInt(e.target.value, 10) || 0))}
                />
                <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {t('menuManagement.stockCountHelp', 'Leave blank for unlimited. Auto-decrements per order.')}
                </p>
              </div>
              {/* Task #295: low-stock threshold + daily reset target. Both
                  optional — blank disables the corresponding behaviour. */}
              <div>
                <label className="label-base">{t('menuManagement.lowStockThreshold', 'Low-stock threshold')}</label>
                <input
                  type="number"
                  min="0"
                  className="input-base"
                  placeholder={t('menuManagement.disabled', 'Disabled')}
                  value={form.lowStockThreshold ?? ''}
                  onChange={e => setField('lowStockThreshold', e.target.value === '' ? null : Math.max(0, parseInt(e.target.value, 10) || 0))}
                />
                <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {t('menuManagement.lowStockThresholdHelp', 'Email + dashboard alert when stock drops to this value. Leave blank to disable.')}
                </p>
              </div>
              <div>
                <label className="label-base">{t('menuManagement.dailyResetCount', 'Daily reset target')}</label>
                <input
                  type="number"
                  min="0"
                  className="input-base"
                  placeholder={t('menuManagement.disabled', 'Disabled')}
                  value={form.dailyResetCount ?? ''}
                  onChange={e => setField('dailyResetCount', e.target.value === '' ? null : Math.max(0, parseInt(e.target.value, 10) || 0))}
                />
                <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {t('menuManagement.dailyResetCountHelp', 'At local midnight, stock resets to this number. Leave blank to disable.')}
                </p>
              </div>
            </div>
            {form.lowStockThreshold != null && form.dailyResetCount != null
              && form.lowStockThreshold > form.dailyResetCount && (
              <p className="text-xs" style={{ color: 'hsl(var(--danger))' }}>
                {t('menuManagement.thresholdAboveReset', 'Low-stock threshold must be at most the daily reset target.')}
              </p>
            )}
          </div>

          {/* Schedule — Task #291. Empty schedule == always available. */}
          <div className="space-y-3">
            <p className="text-xs font-semibold uppercase tracking-wider flex items-center gap-1.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
              <Clock size={12} /> {t('menuManagement.schedule', 'Schedule')}
            </p>
            <SchedulePicker
              value={schedule}
              onChange={setSchedule}
              helpText={t('menuManagement.scheduleHelp', 'Limit when this item is orderable. Times are in the branch timezone.')}
            />
          </div>

          {/* Branch availability — only shown after the item has been saved
              so the override endpoints have a real menu_items.id. */}
          {savedId && (
            <div className="space-y-3">
              <p className="text-xs font-semibold uppercase tracking-wider flex items-center gap-1.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                <MapPin size={12} /> {t('menuManagement.branchAvailability', 'Branch availability')}
              </p>
              <BranchAvailability itemId={savedId} pinnedBranchId={pinnedBranchId} />
            </div>
          )}

          {/* Modifier Groups */}
          {savedId ? (
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <p className="text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('menuManagement.modifierGroups', 'Modifier Groups')}</p>
                <button className="btn-ghost text-xs px-2 py-1 flex items-center gap-1" style={{ color: 'hsl(var(--primary))' }} onClick={() => setAddingGroup(true)}>
                  <Plus size={13} /> {t('menuManagement.addGroup', 'Add Group')}
                </button>
              </div>

              {addingGroup && (
                <div className="border rounded-xl p-3 space-y-2" style={{ borderColor: 'hsl(var(--primary))' }}>
                  <input className="input-base text-sm" placeholder={t('menuManagement.groupNamePlaceholder', 'Group name (e.g. Choose Size, Add-ons)')} value={newGroup.name} onChange={e => setNewGroup(g => ({ ...g, name: e.target.value }))} autoFocus />
                  <div className="flex gap-2">
                    {(['radio', 'checkbox'] as const).map(t_grp => (
                      <button key={t_grp} onClick={() => setNewGroup(g => ({ ...g, type: t_grp }))} className="flex-1 py-1.5 rounded-lg text-xs font-medium border transition-all"
                        style={{ borderColor: newGroup.type === t_grp ? 'hsl(var(--primary))' : 'hsl(var(--border))', backgroundColor: newGroup.type === t_grp ? 'hsl(var(--primary-light))' : 'transparent', color: newGroup.type === t_grp ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))' }}>
                        {t_grp === 'radio' ? t('menuManagement.radioPickOne', 'Radio (Pick one)') : t('menuManagement.checkboxPickMany', 'Checkbox (Pick many)')}
                      </button>
                    ))}
                  </div>
                  <div className="grid grid-cols-2 gap-2">
                    <div>
                      <label className="label-base text-xs">{t('menuManagement.minSelections', 'Min selections')}</label>
                      <input type="number" min="0" className="input-base text-xs py-1.5" value={newGroup.minSelections} onChange={e => setNewGroup(g => ({ ...g, minSelections: e.target.value }))} />
                    </div>
                    <div>
                      <label className="label-base text-xs">{t('menuManagement.maxSelections', 'Max selections')}</label>
                      <input type="number" min="1" className="input-base text-xs py-1.5" placeholder={t('menuManagement.noLimit', 'No limit')} value={newGroup.maxSelections} onChange={e => setNewGroup(g => ({ ...g, maxSelections: e.target.value }))} />
                    </div>
                  </div>
                  <label className="flex items-center gap-2 text-xs cursor-pointer" style={{ color: 'hsl(var(--foreground))' }}>
                    <input type="checkbox" checked={newGroup.isRequired} onChange={e => setNewGroup(g => ({ ...g, isRequired: e.target.checked }))} /> {t('menuManagement.requiredSelection', 'Required selection')}
                  </label>
                  <div className="flex gap-2">
                    <button className="btn-primary text-xs py-1.5 flex-1" onClick={handleAddGroup}><Check size={12} /> {t('menuManagement.create', 'Create')}</button>
                    <button className="btn-secondary text-xs py-1.5" onClick={() => setAddingGroup(false)}><X size={12} /></button>
                  </div>
                </div>
              )}

              {groups.length === 0 && !addingGroup && (
                <p className="text-xs text-center py-4" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('menuManagement.noModifierGroups', 'No modifier groups yet. Add sizes, add-ons, or sides.')}</p>
              )}

              {groups.map(group => (
                <div key={group.id} className="border rounded-xl overflow-hidden" style={{ borderColor: 'hsl(var(--border))' }}>
                  {editingGroup === group.id ? (
                    <div className="p-3 space-y-2" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                      <input className="input-base text-sm" value={editGroupForm.name} onChange={e => setEditGroupForm(f => ({ ...f, name: e.target.value }))} autoFocus />
                      <div className="flex gap-2">
                        {(['radio', 'checkbox'] as const).map(gtype => (
                          <button key={gtype} onClick={() => setEditGroupForm(f => ({ ...f, type: gtype }))} className="flex-1 py-1.5 rounded-lg text-xs font-medium border transition-all"
                            style={{ borderColor: editGroupForm.type === gtype ? 'hsl(var(--primary))' : 'hsl(var(--border))', backgroundColor: editGroupForm.type === gtype ? 'hsl(var(--primary-light))' : 'transparent', color: editGroupForm.type === gtype ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))' }}>
                            {gtype === 'radio' ? t('menuManagement.radio', 'Radio') : t('menuManagement.checkbox', 'Checkbox')}
                          </button>
                        ))}
                      </div>
                      <div className="grid grid-cols-2 gap-2">
                        <div><label className="label-base text-xs">{t('menuManagement.min', 'Min')}</label><input type="number" min="0" className="input-base text-xs py-1.5" value={editGroupForm.minSelections} onChange={e => setEditGroupForm(f => ({ ...f, minSelections: e.target.value }))} /></div>
                        <div><label className="label-base text-xs">{t('menuManagement.max', 'Max')}</label><input type="number" min="1" className="input-base text-xs py-1.5" placeholder={t('menuManagement.noLimit', 'No limit')} value={editGroupForm.maxSelections} onChange={e => setEditGroupForm(f => ({ ...f, maxSelections: e.target.value }))} /></div>
                      </div>
                      <label className="flex items-center gap-2 text-xs cursor-pointer"><input type="checkbox" checked={editGroupForm.isRequired} onChange={e => setEditGroupForm(f => ({ ...f, isRequired: e.target.checked }))} /> {t('menuManagement.required', 'Required')}</label>
                      <div className="flex gap-2">
                        <button className="btn-primary text-xs py-1.5 flex-1" onClick={() => handleUpdateGroup(group.id)}><Check size={12} /> {t('common.save', 'Save')}</button>
                        <button className="btn-secondary text-xs py-1.5" onClick={() => setEditingGroup(null)}><X size={12} /></button>
                      </div>
                    </div>
                  ) : (
                    <div className="flex items-center gap-2 px-3 py-2.5 cursor-pointer" style={{ backgroundColor: 'hsl(var(--muted))' }}
                      onClick={() => setExpanded(prev => { const n = new Set(prev); n.has(group.id) ? n.delete(group.id) : n.add(group.id); return n; })}>
                      {expanded.has(group.id) ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
                      <span className="font-medium text-sm flex-1 truncate" style={{ color: 'hsl(var(--foreground))' }}>{group.name}</span>
                      <span className="badge badge-neutral text-xs">{group.type}</span>
                      {group.is_required && <span className="badge badge-danger text-xs">Req</span>}
                      <span className="text-xs hidden sm:block" style={{ color: 'hsl(var(--muted-foreground))' }}>{group.options.length} opts</span>
                      <button className="btn-ghost p-1" onClick={e => { e.stopPropagation(); startEditGroup(group); }} style={{ color: 'hsl(var(--primary))' }}><Pencil size={12} /></button>
                      <button className="btn-ghost p-1" onClick={e => { e.stopPropagation(); handleDeleteGroup(group.id); }} style={{ color: 'hsl(var(--danger))' }}><Trash2 size={13} /></button>
                    </div>
                  )}
                  {expanded.has(group.id) && (
                    <div className="px-3 py-2 space-y-1.5">
                      {group.options.map(opt => (
                        editingOption?.groupId === group.id && editingOption.optId === opt.id ? (
                          <div key={opt.id} className="flex gap-2 py-1">
                            <input className="input-base text-xs flex-1 py-1.5" value={editOptionForm.name} onChange={e => setEditOptionForm(f => ({ ...f, name: e.target.value }))} autoFocus />
                            <input type="number" className="input-base text-xs w-20 py-1.5" placeholder={t('menuManagement.priceDeltaPlaceholder', '₹ delta')} value={editOptionForm.priceDelta} onChange={e => setEditOptionForm(f => ({ ...f, priceDelta: e.target.value }))} />
                            <label className="flex items-center gap-1 text-xs cursor-pointer shrink-0"><input type="checkbox" checked={editOptionForm.isDefault} onChange={e => setEditOptionForm(f => ({ ...f, isDefault: e.target.checked }))} /> {t('menuManagement.def', 'Def')}</label>
                            <button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--success))' }} onClick={handleUpdateOption}><Check size={13} /></button>
                            <button className="btn-ghost p-1.5" onClick={() => setEditingOption(null)}><X size={13} /></button>
                          </div>
                        ) : (
                          <div key={opt.id} className="flex items-center gap-2 py-1.5 px-2 rounded-lg" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                            <span className="flex-1 text-sm" style={{ color: 'hsl(var(--foreground))' }}>{opt.name}</span>
                            {opt.is_default && <span className="badge badge-success text-xs">{t('menuManagement.defBadge', 'Def')}</span>}
                            <span className="text-xs tabular-nums font-medium" style={{ color: opt.price_delta > 0 ? 'hsl(var(--success))' : opt.price_delta < 0 ? 'hsl(var(--danger))' : 'hsl(var(--muted-foreground))' }}>
                              {opt.price_delta === 0 ? t('menuManagement.free', 'Free') : (opt.price_delta > 0 ? '+' : '') + `₹${Math.abs(opt.price_delta).toFixed(0)}`}
                            </span>
                            <button className="btn-ghost p-1" onClick={() => startEditOption(group.id, opt)} style={{ color: 'hsl(var(--primary))' }}><Pencil size={11} /></button>
                            <button className="btn-ghost p-1" onClick={() => handleDeleteOption(group.id, opt.id)} style={{ color: 'hsl(var(--danger))' }}><Trash2 size={11} /></button>
                          </div>
                        )
                      ))}
                      {addingOption === group.id ? (
                        <div className="flex gap-2 pt-1">
                          <input className="input-base text-xs flex-1 py-1.5" placeholder={t('menuManagement.optionName', 'Option name')} value={newOption.name} onChange={e => setNewOption(o => ({ ...o, name: e.target.value }))} onKeyDown={e => e.key === 'Enter' && handleAddOption(group.id)} autoFocus />
                          <input type="number" className="input-base text-xs w-20 py-1.5" placeholder={t('menuManagement.extraPrice', '₹ extra')} value={newOption.priceDelta} onChange={e => setNewOption(o => ({ ...o, priceDelta: e.target.value }))} />
                          <label className="flex items-center gap-1 text-xs cursor-pointer shrink-0"><input type="checkbox" checked={newOption.isDefault} onChange={e => setNewOption(o => ({ ...o, isDefault: e.target.checked }))} /> {t('menuManagement.def', 'Def')}</label>
                          <button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--success))' }} onClick={() => handleAddOption(group.id)}><Check size={14} /></button>
                          <button className="btn-ghost p-1.5" onClick={() => { setAddingOption(null); setNewOption({ name: '', priceDelta: '', isDefault: false }); }}><X size={14} /></button>
                        </div>
                      ) : (
                        <button className="text-xs flex items-center gap-1 py-1 px-2" style={{ color: 'hsl(var(--primary))' }} onClick={() => { setAddingOption(group.id); setNewOption({ name: '', priceDelta: '', isDefault: false }); }}>
                          <Plus size={12} /> Add Option
                        </button>
                      )}
                    </div>
                  )}
                </div>
              ))}
            </div>
          ) : (
            <div className="rounded-xl px-4 py-3 text-xs" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--muted-foreground))' }}>
              {t('menuManagement.saveItemFirstToAddModifierGroups', 'Save item first to add modifier groups (sizes, add-ons, sides).')}
            </div>
          )}
        </div>

        <div className="px-5 py-4 border-t flex gap-3" style={{ borderColor: 'hsl(var(--border))' }}>
          <DemoDisabled className="flex-1"><button className="btn-primary w-full" onClick={handleSaveItem} disabled={saving}>
            <Save size={15} /> {saving ? t('common.savingDots', 'Saving…') : savedId ? t('menuManagement.updateItem', 'Update Item') : t('menuManagement.createItem', 'Create Item')}
          </button></DemoDisabled>
          <button className="btn-secondary" onClick={onClose}><X size={15} /></button>
        </div>
      </div>
    </div>
  );
}
