'use client';

import { useState, useEffect, useCallback } from 'react';
import { Plus, Search, Trash2, Tag, Package, Sliders, ToggleLeft, ToggleRight, Upload, Pencil, Leaf, Clock, Check, X } from 'lucide-react';
import { useAuth } from '@client/contexts/AuthContext';
import { toast } from 'sonner';
import { InlineTableSkeleton } from '@client/components/skeletons/PageSkeletons';
import DemoDisabled from '@client/components/demo/DemoDisabled';
import { listMenuItems, listMenuCategories, deleteMenuItem, updateMenuItem, createMenuCategory, deleteMenuCategory, updateMenuCategory } from '@client/api/menu';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import BulkUploadTab from './BulkUploadTab';
import ItemDrawer from './ItemDrawer';
import ModifiersTab from './ModifiersTab';
import SchedulePicker, { type ScheduleWindow } from './SchedulePicker';
import { usePlanFeatures } from '@client/contexts/PlanFeaturesContext';

type Tab = 'items' | 'categories' | 'modifiers' | 'bulk-upload';

export interface ModOption { id: string; name: string; price_delta: number; is_default: boolean; is_available: boolean; display_order: number; }
export interface ModGroup { id: string; name: string; type: 'radio' | 'checkbox'; is_required: boolean; min_selections: number; max_selections: number | null; display_order: number; options: ModOption[]; }

export interface MenuItem {
  id: string; name: string; category: string; categoryId: string;
  price: number; description: string; available: boolean; dietary: string[];
  imageUrl: string; isVeg: boolean; spiceLevel: number; prepTime: number; calories: number;
  modifierGroups: ModGroup[];
  // Task #291: real-time stock + per-item schedule.
  isInStock?: boolean;
  stockCount?: number | null;
  schedule?: ScheduleWindow[] | null;
  // Task #295: low-stock alert + daily-reset config.
  lowStockThreshold?: number | null;
  dailyResetCount?: number | null;
  lastResetAt?: string | null;
}

export interface Category {
  id: string; name: string; itemCount: number; available: boolean; sortOrder: number;
  // Task #291: per-category schedule (overrides nothing, just gates orderability).
  schedule?: ScheduleWindow[] | null;
}

const SPICE_DOTS = ['', '🌶', '🌶🌶', '🌶🌶🌶'];

export default function MenuManagementPage() {
  const { t } = useLanguage();
  usePageHeader(t('nav.menuManagement', 'Menu Management'), t('nav.menuManagementSubtitle', 'Manage items, categories, modifiers and bulk uploads'));
  const { restaurantId, branchId } = useAuth();
  const { hasFeature } = usePlanFeatures();
  const canBulkUpload = hasFeature('bulk_upload');

  const [activeTab, setActiveTab] = useState<Tab>('items');
  const [search, setSearch] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('');
  const [items, setItems] = useState<MenuItem[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [drawerItem, setDrawerItem] = useState<MenuItem | null | undefined>(undefined);
  const [showAddCategory, setShowAddCategory] = useState(false);
  const [newCategory, setNewCategory] = useState('');
  const [saving, setSaving] = useState(false);

  const fetchData = useCallback(async () => {
    if (!restaurantId) { setLoading(false); return; }
    setLoading(true);
    try {
      const [catResult, itemResult] = (await Promise.all([
        listMenuCategories(),
        listMenuItems(),
      ])) as [
        { categories?: Record<string, unknown>[] },
        { data?: Record<string, unknown>[]; items?: Record<string, unknown>[] },
      ];
      const rawCats = catResult.categories || [];
      const rawItems = itemResult.data || itemResult.items || [];

      const cats: Category[] = rawCats.map((c: Record<string, unknown>) => ({
        id: c.id as string, name: c.name as string,
        itemCount: rawItems.filter(i => i.category_id === c.id).length,
        available: (c.is_active as boolean) ?? true,
        sortOrder: (c.display_order as number) || 0,
        schedule: Array.isArray(c.schedule) ? (c.schedule as ScheduleWindow[]) : null,
      }));
      setCategories(cats);

      const catMap: Record<string, string> = {};
      rawCats.forEach((c: Record<string, unknown>) => { catMap[c.id as string] = c.name as string; });

      setItems(rawItems.map(i => ({
        id: i.id as string, name: i.name as string,
        category: catMap[i.category_id as string] || 'Uncategorized',
        categoryId: (i.category_id as string) || '',
        price: Number(i.price) || 0,
        description: (i.description as string) || '',
        available: (i.is_available as boolean) ?? true,
        dietary: Array.isArray(i.dietary_tags) ? i.dietary_tags as string[] : [],
        imageUrl: (i.image_url as string) || '',
        isVeg: (i.is_veg as boolean) ?? false,
        spiceLevel: (i.spice_level as number) ?? 0,
        prepTime: (i.prep_time_minutes as number) ?? 0,
        calories: (i.calories as number) ?? 0,
        modifierGroups: Array.isArray(i.modifier_groups) ? (i.modifier_groups as ModGroup[]) : [],
        isInStock: (i.is_in_stock as boolean) ?? true,
        stockCount: (i.stock_count as number | null) ?? null,
        schedule: Array.isArray(i.schedule) ? (i.schedule as ScheduleWindow[]) : null,
        lowStockThreshold: (i.low_stock_threshold as number | null) ?? null,
        dailyResetCount: (i.daily_reset_count as number | null) ?? null,
        lastResetAt: (i.last_reset_at as string | null) ?? null,
      })));
    } catch (err: unknown) {
      toast.error(t('menuManagement.failedToLoad', 'Failed to load menu') + ': ' + (err instanceof Error ? err.message : ''));
    } finally { setLoading(false); }
  }, [restaurantId]);

  useEffect(() => { fetchData(); }, [fetchData]);

  const toggleItem = async (id: string, current: boolean) => {
    try {
      await updateMenuItem(id, { is_available: !current });
      setItems(prev => prev.map(i => i.id === id ? { ...i, available: !current } : i));
    } catch (err: unknown) { toast.error(t('common.failedToUpdate', 'Failed to update') + ': ' + (err instanceof Error ? err.message : '')); }
  };

  // Task #291: real-time stock controls. Inline toggle uses JSON PATCH so we
  // bypass the multipart/form-data path used by the drawer.
  const toggleStock = async (id: string, current: boolean) => {
    try {
      await updateMenuItem(id, { is_in_stock: !current });
      setItems(prev => prev.map(i => i.id === id ? { ...i, isInStock: !current } : i));
    } catch (err: unknown) { toast.error(t('common.failedToUpdate', 'Failed to update') + ': ' + (err instanceof Error ? err.message : '')); }
  };

  const saveStockCount = async (id: string, value: number | null) => {
    try {
      await updateMenuItem(id, { stock_count: value });
      setItems(prev => prev.map(i => i.id === id ? { ...i, stockCount: value } : i));
    } catch (err: unknown) { toast.error(t('common.failedToUpdate', 'Failed to update') + ': ' + (err instanceof Error ? err.message : '')); }
  };

  const saveCategorySchedule = async (id: string, value: ScheduleWindow[] | null) => {
    try {
      await updateMenuCategory(id, { schedule: value });
      setCategories(prev => prev.map(c => c.id === id ? { ...c, schedule: value } : c));
      toast.success(t('menuManagement.scheduleUpdated', 'Schedule updated'));
    } catch (err: unknown) { toast.error(t('common.failedToUpdate', 'Failed to update') + ': ' + (err instanceof Error ? err.message : '')); }
  };

  const toggleCategory = async (id: string, current: boolean) => {
    try {
      await updateMenuCategory(id, { is_active: !current });
      setCategories(prev => prev.map(c => c.id === id ? { ...c, available: !current } : c));
    } catch (err: unknown) { toast.error(t('common.failedToUpdate', 'Failed to update') + ': ' + (err instanceof Error ? err.message : '')); }
  };

  const handleAddCategory = async () => {
    if (!restaurantId || !newCategory.trim()) return;
    setSaving(true);
    try {
      const result = (await createMenuCategory({
        restaurant_id: restaurantId,
        branch_id: branchId,
        name: newCategory,
        display_order: categories.length + 1,
      })) as { category?: { id: string; name: string; display_order?: number | null } };
      const data = result.category;
      if (data) setCategories(prev => [...prev, { id: data.id, name: data.name, itemCount: 0, available: true, sortOrder: data.display_order || prev.length + 1 }]);
      setNewCategory(''); setShowAddCategory(false);
      toast.success(t('menuManagement.categoryAdded', 'Category added'));
    } catch (err: unknown) { toast.error(t('common.failed', 'Failed') + ': ' + (err instanceof Error ? err.message : '')); }
    finally { setSaving(false); }
  };

  const handleDeleteItem = async (id: string) => {
    try {
      await deleteMenuItem(id);
      setItems(prev => prev.filter(i => i.id !== id));
      toast.success(t('menuManagement.itemDeleted', 'Item deleted'));
    } catch (err: unknown) { toast.error(t('common.failed', 'Failed') + ': ' + (err instanceof Error ? err.message : '')); }
  };

  const handleDeleteCategory = async (id: string) => {
    try {
      await deleteMenuCategory(id);
      setCategories(prev => prev.filter(c => c.id !== id));
      toast.success(t('menuManagement.categoryDeleted', 'Category deleted'));
    } catch (err: unknown) { toast.error(t('common.failed', 'Failed') + ': ' + (err instanceof Error ? err.message : '')); }
  };

  const handleItemSaved = (saved: MenuItem, isNew: boolean) => {
    const catName = categories.find(c => c.id === saved.categoryId)?.name || 'Uncategorized';
    const mapped = { ...saved, category: catName };
    if (isNew) { setItems(prev => [mapped, ...prev]); }
    else { setItems(prev => prev.map(i => i.id === saved.id ? mapped : i)); }
  };

  const filteredItems = items.filter(i => {
    const matchSearch = i.name.toLowerCase().includes(search.toLowerCase()) || i.category.toLowerCase().includes(search.toLowerCase());
    const matchCat = !categoryFilter || i.categoryId === categoryFilter;
    return matchSearch && matchCat;
  });

  const tabs: { key: Tab; label: string; icon: React.ReactNode }[] = [
    { key: 'items', label: 'Menu Items', icon: <Package size={15} /> },
    { key: 'categories', label: 'Categories', icon: <Tag size={15} /> },
    { key: 'modifiers', label: 'Modifiers', icon: <Sliders size={15} /> },
    ...(canBulkUpload ? [{ key: 'bulk-upload' as Tab, label: 'Bulk Upload', icon: <Upload size={15} /> }] : []),
  ];

  return (
    <>
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-6">
        <div className="flex gap-1 p-1 rounded-xl overflow-x-auto" style={{ backgroundColor: 'hsl(var(--muted))' }}>
          {tabs.map(t => (
            <button key={t.key} onClick={() => setActiveTab(t.key)}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all whitespace-nowrap ${activeTab === t.key ? 'bg-white shadow-sm' : ''}`}
              style={{ color: activeTab === t.key ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}>
              {t.icon} {t.label}
            </button>
          ))}
        </div>
        {(activeTab === 'items' || activeTab === 'categories') && (
          <DemoDisabled><button className="btn-primary" onClick={() => activeTab === 'items' ? setDrawerItem(null) : setShowAddCategory(true)}>
            <Plus size={16} /> Add {activeTab === 'items' ? 'Item' : 'Category'}
          </button></DemoDisabled>
        )}
      </div>

      {activeTab === 'bulk-upload' ? (
        <BulkUploadTab />
      ) : loading ? (
        <InlineTableSkeleton columns={5} rows={6} />
      ) : (
        <>
          {activeTab === 'items' && (
            <div>
              <div className="flex flex-wrap gap-3 mb-4">
                <div className="relative flex-1 min-w-[200px] max-w-sm">
                  <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                  <input className="input-base pl-9" placeholder={t('menu.searchItemsPlaceholder', 'Search items…')} value={search} onChange={e => setSearch(e.target.value)} />
                </div>
                <select className="input-base max-w-xs" value={categoryFilter} onChange={e => setCategoryFilter(e.target.value)}>
                  <option value="">{t('menu.allCategories', 'All categories')}</option>
                  {categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
                <span className="text-sm self-center" style={{ color: 'hsl(var(--muted-foreground))' }}>{filteredItems.length} {t('menu.items', 'items')}</span>
              </div>

              {filteredItems.length === 0 ? (
                <div className="text-center py-16 card" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  <Package size={32} className="mx-auto mb-3 opacity-30" />
                  <p className="font-medium">{t('menu.noMenuItemsFound', 'No menu items found')}</p>
                  <p className="text-xs mt-1">{t('menu.addFirstMenuItemOrAdjustSearch', 'Add your first menu item or adjust your search')}</p>
                </div>
              ) : (
                <div className="card overflow-hidden">
                  <table className="w-full">
                    <thead>
                      <tr style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                        {[t('menu.colItem', 'Item'), t('menu.colCategory', 'Category'), t('menu.colPrice', 'Price'), t('menu.colDetails', 'Details'), t('menu.colStock', 'Stock'), t('menu.colAvailable', 'Available'), ''].map(h => (
                          <th key={h} className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{h}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {filteredItems.map((item, idx) => (
                        <tr key={item.id} className="table-row-hover" style={{ borderBottom: idx < filteredItems.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-3">
                              <div className="w-12 h-12 rounded-xl overflow-hidden shrink-0 flex items-center justify-center" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                                {item.imageUrl ? (
                                  <img src={item.imageUrl} alt={item.name} className="w-full h-full object-cover" onError={e => { (e.target as HTMLImageElement).style.display = 'none'; }} />
                                ) : (
                                  <span className="text-xl">🍽️</span>
                                )}
                              </div>
                              <div>
                                <div className="flex items-center gap-1.5 flex-wrap">
                                  <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{item.name}</p>
                                  {item.isVeg ? (
                                    <span title={t('menu.vegetarian', 'Vegetarian')}><Leaf size={12} style={{ color: 'hsl(var(--success))' }} /></span>
                                  ) : (
                                    <span className="w-3 h-3 rounded-full bg-red-500 inline-block shrink-0" title={t('menu.nonVeg', 'Non-Veg')} />
                                  )}
                                  {item.modifierGroups.length > 0 && (
                                    <span className="badge badge-neutral text-xs" title={`${item.modifierGroups.length} modifier group${item.modifierGroups.length > 1 ? 's' : ''}`}>
                                      <Sliders size={9} className="inline mr-0.5" />{item.modifierGroups.length}
                                    </span>
                                  )}
                                </div>
                                <p className="text-xs truncate max-w-[200px]" style={{ color: 'hsl(var(--muted-foreground))' }}>{item.description}</p>
                              </div>
                            </div>
                          </td>
                          <td className="px-4 py-3"><span className="badge badge-neutral">{item.category}</span></td>
                          <td className="px-4 py-3 font-semibold tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>₹{item.price.toFixed(0)}</td>
                          <td className="px-4 py-3">
                            <div className="flex flex-col gap-0.5">
                              {item.spiceLevel > 0 && <span className="text-xs">{SPICE_DOTS[item.spiceLevel] || ''}</span>}
                              {item.prepTime > 0 && <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>⏱ {item.prepTime}m</span>}
                              {item.calories > 0 && <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>🔥 {item.calories} kcal</span>}
                            </div>
                          </td>
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-2">
                              <DemoDisabled><button onClick={() => toggleStock(item.id, item.isInStock ?? true)} className="flex items-center gap-1 transition-colors" title={t('menu.stockToggle', 'Toggle in-stock')}>
                                {(item.isInStock ?? true)
                                  ? <ToggleRight size={20} style={{ color: 'hsl(var(--success))' }} />
                                  : <ToggleLeft size={20} style={{ color: 'hsl(var(--danger))' }} />}
                              </button></DemoDisabled>
                              <DemoDisabled><input
                                type="number"
                                min="0"
                                className="input-base w-20 py-1 text-xs"
                                placeholder="∞"
                                defaultValue={item.stockCount ?? ''}
                                title={t('menu.stockCountHelp', 'Blank = unlimited')}
                                onBlur={(e) => {
                                  const raw = e.target.value;
                                  const next = raw === '' ? null : Math.max(0, parseInt(raw, 10) || 0);
                                  if (next !== (item.stockCount ?? null)) saveStockCount(item.id, next);
                                }}
                              /></DemoDisabled>
                            </div>
                            {/* Task #295: read-only inventory summary. Empty
                                fields render nothing — keeps the row tight
                                for items with no thresholds configured.
                                Edits happen in the drawer. */}
                            {(item.lowStockThreshold != null || item.dailyResetCount != null) && (
                              <div className="mt-1.5 text-[10px] leading-tight" style={{ color: 'hsl(var(--muted-foreground))' }}>
                                {item.lowStockThreshold != null && (
                                  <div>{t('menuManagement.thresholdShort', 'Alert ≤')} <span className="font-medium tabular-nums">{item.lowStockThreshold}</span></div>
                                )}
                                {item.dailyResetCount != null && (
                                  <div>
                                    {t('menuManagement.dailyResetShort', 'Daily reset')}: <span className="font-medium tabular-nums">{item.dailyResetCount}</span>
                                    {item.lastResetAt && (
                                      <span className="ml-1 opacity-70">({new Date(item.lastResetAt).toLocaleDateString()})</span>
                                    )}
                                  </div>
                                )}
                              </div>
                            )}
                          </td>
                          <td className="px-4 py-3">
                            <DemoDisabled><button onClick={() => toggleItem(item.id, item.available)} className="flex items-center gap-2 transition-colors">
                              {item.available
                                ? <ToggleRight size={22} style={{ color: 'hsl(var(--success))' }} />
                                : <ToggleLeft size={22} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                              <span className="text-xs font-medium" style={{ color: item.available ? 'hsl(var(--success))' : 'hsl(var(--muted-foreground))' }}>
                                {item.available ? t('menu.available', 'Available') : t('menu.hidden', 'Hidden')}
                              </span>
                            </button></DemoDisabled>
                          </td>
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-1">
                              <DemoDisabled><button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--primary))' }} onClick={() => setDrawerItem(item)} title={t('common.edit', 'Edit')}><Pencil size={14} /></button></DemoDisabled>
                              <DemoDisabled><button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--danger))' }} onClick={() => handleDeleteItem(item.id)} title={t('common.delete', 'Delete')}><Trash2 size={14} /></button></DemoDisabled>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          )}

          {activeTab === 'categories' && (
            <div className="space-y-3">
              {showAddCategory && (
                <div className="card p-5">
                  <h3 className="font-semibold mb-3" style={{ color: 'hsl(var(--foreground))' }}>{t('menu.addCategory', 'Add Category')}</h3>
                  <div className="flex gap-3">
                    <input className="input-base flex-1" placeholder={t('menu.categoryNamePlaceholder', 'Category name *')} value={newCategory} onChange={e => setNewCategory(e.target.value)} onKeyDown={e => e.key === 'Enter' && handleAddCategory()} autoFocus />
                    <DemoDisabled><button className="btn-primary" onClick={handleAddCategory} disabled={saving}>{t('common.save', 'Save')}</button></DemoDisabled>
                    <button className="btn-secondary" onClick={() => setShowAddCategory(false)}>{t('common.cancel', 'Cancel')}</button>
                  </div>
                </div>
              )}
              {categories.length === 0 ? (
                <div className="text-center py-16 card" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  <Tag size={32} className="mx-auto mb-3 opacity-30" />
                  <p className="font-medium">{t('menu.noCategoriesYet', 'No categories yet')}</p>
                </div>
              ) : (
                categories.map(cat => (
                  <CategoryRow
                    key={cat.id}
                    cat={cat}
                    onToggle={toggleCategory}
                    onDelete={handleDeleteCategory}
                    onSaveSchedule={saveCategorySchedule}
                    t={t}
                  />
                ))
              )}
            </div>
          )}

          {activeTab === 'modifiers' && (
            <ModifiersTab items={items.map(i => ({ id: i.id, name: i.name }))} categories={categories} />
          )}
        </>
      )}

      {drawerItem !== undefined && (
        <ItemDrawer
          item={drawerItem}
          categories={categories}
          onClose={() => setDrawerItem(undefined)}
          onSaved={(saved, isNew) => { handleItemSaved(saved, isNew); }}
        />
      )}
    </>
  );
}

// Inline row for the categories tab. Hosts the per-category schedule editor —
// expanding the row reveals a SchedulePicker and Save/Cancel actions so that
// edits are explicit rather than implicit on every keystroke.
interface CategoryRowProps {
  cat: Category;
  onToggle: (id: string, current: boolean) => void;
  onDelete: (id: string) => void;
  onSaveSchedule: (id: string, value: ScheduleWindow[] | null) => Promise<void> | void;
  t: (key: string, fallback: string) => string;
}

function CategoryRow({ cat, onToggle, onDelete, onSaveSchedule, t }: CategoryRowProps) {
  const [open, setOpen] = useState(false);
  const [draft, setDraft] = useState<ScheduleWindow[] | null>(cat.schedule ?? null);
  const hasSchedule = (cat.schedule ?? []).length > 0;

  useEffect(() => { setDraft(cat.schedule ?? null); }, [cat.schedule]);

  const handleSave = async () => {
    await onSaveSchedule(cat.id, draft && draft.length > 0 ? draft : null);
    setOpen(false);
  };

  return (
    <div className="card p-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <div className="w-8 h-8 rounded-lg flex items-center justify-center font-bold text-sm" style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}>
            {cat.sortOrder}
          </div>
          <div>
            <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{cat.name}</p>
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{cat.itemCount} {t('menu.items', 'items')}</p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <DemoDisabled><button
            onClick={() => setOpen(o => !o)}
            className="flex items-center gap-1.5 text-xs font-medium px-2 py-1 rounded-md transition-colors"
            style={{
              backgroundColor: hasSchedule ? 'hsl(var(--primary-light))' : 'hsl(var(--muted))',
              color: hasSchedule ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))',
            }}
            title={t('menu.editSchedule', 'Edit schedule')}
          >
            <Clock size={14} />
            {hasSchedule ? t('menu.scheduled', 'Scheduled') : t('menu.alwaysAvailable', 'Always')}
          </button></DemoDisabled>
          <DemoDisabled><button onClick={() => onToggle(cat.id, cat.available)} className="flex items-center gap-2">
            {cat.available ? <ToggleRight size={22} style={{ color: 'hsl(var(--success))' }} /> : <ToggleLeft size={22} style={{ color: 'hsl(var(--muted-foreground))' }} />}
            <span className="text-xs font-medium" style={{ color: cat.available ? 'hsl(var(--success))' : 'hsl(var(--muted-foreground))' }}>
              {cat.available ? t('menu.visible', 'Visible') : t('menu.hidden', 'Hidden')}
            </span>
          </button></DemoDisabled>
          <DemoDisabled><button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--danger))' }} onClick={() => onDelete(cat.id)}><Trash2 size={14} /></button></DemoDisabled>
        </div>
      </div>
      {open && (
        <div className="mt-4 pt-4 space-y-3" style={{ borderTop: '1px solid hsl(var(--border))' }}>
          <SchedulePicker
            value={draft}
            onChange={setDraft}
            helpText={t('menu.categoryScheduleHelp', 'Limit when items in this category are orderable. Times are in the branch timezone.')}
          />
          <div className="flex justify-end gap-2">
            <button
              type="button"
              className="btn-ghost text-xs px-3 py-1.5 flex items-center gap-1"
              onClick={() => { setDraft(cat.schedule ?? null); setOpen(false); }}
            >
              <X size={14} /> {t('common.cancel', 'Cancel')}
            </button>
            <DemoDisabled><button
              type="button"
              className="btn-primary text-xs px-3 py-1.5 flex items-center gap-1"
              onClick={handleSave}
            >
              <Check size={14} /> {t('common.save', 'Save')}
            </button></DemoDisabled>
          </div>
        </div>
      )}
    </div>
  );
}
