'use client';

import React, { useState, useEffect, useCallback } from 'react';
import {
  X,
  LayoutDashboard,
  ClipboardList,
  UtensilsCrossed,
  FolderOpen,
  Settings,
  Search,
  Plus,
  Pencil,
  Trash2,
  Eye,
  ShoppingCart,
  DollarSign,
  Package,
  Clock,
  Loader2,
  ChevronLeft,
  ChevronRight,
  Menu,
  Check,
  BarChart3,
  TrendingUp,
  Users,
  Eye as EyeIcon,
  Calendar,
} from 'lucide-react';
import { toast } from '@/hooks/use-toast';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Switch } from '@/components/ui/switch';
import { Separator } from '@/components/ui/separator';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';

// ─── Types ───────────────────────────────────────────────────────────────────

interface AdminDashboardProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

type TabId = 'dashboard' | 'orders' | 'menu' | 'categories' | 'settings' | 'analytics';

interface OrderItem {
  id: string;
  name: string;
  price: number;
  quantity: number;
  variant?: string;
  note?: string;
  thumbnail?: string;
}

interface Invoice {
  id: string;
  invoiceNumber: string;
  buyerName: string;
  buyerPhone: string;
  buyerAddress: string;
  buyerNotes: string;
  paymentMethod: string;
  items: string;
  subtotal: number;
  shipping: number;
  total: number;
  status: string;
  createdAt: string;
  updatedAt: string;
}

interface Category {
  id: string;
  name: string;
  slug: string;
  icon: string;
  order: number;
  foodCount: number;
}

interface FoodItem {
  id: string;
  name: string;
  description: string;
  price: number;
  discountPrice: number | null;
  discountPercent: number | null;
  rating: number;
  reviews: number;
  badge: string;
  isBestseller: boolean;
  isHalal: boolean;
  isAvailable: boolean;
  categoryId: string;
  thumbnail: string;
  largeImage: string;
  order: number;
  createdAt: string;
  updatedAt: string;
  category?: { id: string; name: string; slug: string; icon: string };
}

interface StoreSettingsData {
  id: string;
  storeName: string;
  storeDesc: string;
  whatsapp: string;
  address: string;
  phone: string;
  email: string;
  instagram: string;
  facebook: string;
  twitter: string;
  tiktok: string;
  freeShippingThreshold: number;
  shippingRate: number;
  codAvailable: boolean;
  qrisImage: string;
  gofoodUrl: string;
  grabfoodUrl: string;
  shopeefoodUrl: string;
  googleMapsEmbed: string;
  heroType: string;
  heroPromoLabel: string;
  heroPromoTitle1: string;
  heroPromoTitle2: string;
  heroPromoDesc: string;
  heroPromoCode: string;
  heroImage: string;
  heroProductTitle: string;
  heroProductLink: string;
  themeMode: string;
  accentColor: string;
  logoUrl: string;
  autoMessage: string;
}

interface FoodFormData {
  name: string;
  description: string;
  price: string;
  discountPrice: string;
  discountPercent: string;
  categoryId: string;
  thumbnail: string;
  largeImage: string;
  isAvailable: boolean;
  isBestseller: boolean;
  isHalal: boolean;
  badge: string;
  order: string;
}

interface CategoryFormData {
  name: string;
  slug: string;
  icon: string;
  order: string;
}

interface SettingsFormData {
  storeName: string;
  storeDesc: string;
  address: string;
  phone: string;
  email: string;
  whatsapp: string;
  instagram: string;
  facebook: string;
  twitter: string;
  tiktok: string;
  freeShippingThreshold: string;
  shippingRate: string;
  codAvailable: boolean;
  qrisImage: string;
  heroPromoLabel: string;
  heroPromoTitle1: string;
  heroPromoTitle2: string;
  heroPromoDesc: string;
  heroPromoCode: string;
  googleMapsEmbed: string;
  heroType: string;
  themeMode: string;
  accentColor: string;
  logoUrl: string;
  autoMessage: string;
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

function formatPrice(price: number): string {
  return new Intl.NumberFormat('id-ID').format(price);
}

function formatDate(dateStr: string): string {
  return new Intl.DateTimeFormat('id-ID', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  }).format(new Date(dateStr));
}

function formatDateShort(dateStr: string): string {
  return new Intl.DateTimeFormat('id-ID', {
    day: '2-digit',
    month: 'short',
    hour: '2-digit',
    minute: '2-digit',
  }).format(new Date(dateStr));
}

function isToday(dateStr: string): boolean {
  const d = new Date(dateStr);
  const now = new Date();
  return (
    d.getDate() === now.getDate() &&
    d.getMonth() === now.getMonth() &&
    d.getFullYear() === now.getFullYear()
  );
}

const STATUS_MAP: Record<string, { label: string; color: string; bg: string }> = {
  pending: { label: 'Baru', color: 'text-amber-400', bg: 'bg-amber-500/15 border-amber-500/30' },
  confirmed: { label: 'Dikonfirmasi', color: 'text-blue-400', bg: 'bg-blue-500/15 border-blue-500/30' },
  preparing: { label: 'Diproses', color: 'text-purple-400', bg: 'bg-purple-500/15 border-purple-500/30' },
  on_the_way: { label: 'Dikirim', color: 'text-cyan-400', bg: 'bg-cyan-500/15 border-cyan-500/30' },
  delivered: { label: 'Selesai', color: 'text-emerald-400', bg: 'bg-emerald-500/15 border-emerald-500/30' },
  cancelled: { label: 'Dibatalkan', color: 'text-red-400', bg: 'bg-red-500/15 border-red-500/30' },
};

const ORDER_STATUS_OPTIONS = [
  { value: 'pending', label: 'Baru' },
  { value: 'confirmed', label: 'Dikonfirmasi' },
  { value: 'preparing', label: 'Diproses' },
  { value: 'on_the_way', label: 'Dikirim' },
  { value: 'delivered', label: 'Selesai' },
  { value: 'cancelled', label: 'Dibatalkan' },
];

const ORDER_FILTER_TABS = [
  { value: '', label: 'Semua' },
  { value: 'pending', label: 'Baru' },
  { value: 'confirmed', label: 'Dikonfirmasi' },
  { value: 'preparing', label: 'Diproses' },
  { value: 'on_the_way', label: 'Dikirim' },
  { value: 'delivered', label: 'Selesai' },
  { value: 'cancelled', label: 'Dibatalkan' },
];

const EMPTY_FOOD_FORM: FoodFormData = {
  name: '',
  description: '',
  price: '',
  discountPrice: '',
  discountPercent: '',
  categoryId: '',
  thumbnail: '',
  largeImage: '',
  isAvailable: true,
  isBestseller: false,
  isHalal: true,
  badge: '',
  order: '0',
};

const EMPTY_CATEGORY_FORM: CategoryFormData = {
  name: '',
  slug: '',
  icon: '🍽️',
  order: '0',
};

const EMPTY_SETTINGS_FORM: SettingsFormData = {
  storeName: '',
  storeDesc: '',
  address: '',
  phone: '',
  email: '',
  whatsapp: '',
  instagram: '',
  facebook: '',
  twitter: '',
  tiktok: '',
  freeShippingThreshold: '',
  shippingRate: '',
  codAvailable: true,
  qrisImage: '',
  heroPromoLabel: '',
  heroPromoTitle1: '',
  heroPromoTitle2: '',
  heroPromoDesc: '',
  heroPromoCode: '',
  googleMapsEmbed: '',
  heroType: 'promo',
  themeMode: 'dark',
  accentColor: 'orange',
  logoUrl: '',
  autoMessage: 'Halo! Saya ingin memesan:',
};

// ─── API Helper ──────────────────────────────────────────────────────────────

async function apiFetch(url: string, options?: RequestInit) {
  const res = await fetch(url, {
    headers: { 'Content-Type': 'application/json' },
    ...options,
  });
  return res.json();
}

// ─── Sidebar Navigation ──────────────────────────────────────────────────────

const NAV_ITEMS: { id: TabId; label: string; icon: React.ReactNode }[] = [
  { id: 'dashboard', label: 'Dashboard', icon: <LayoutDashboard className="h-5 w-5" /> },
  { id: 'orders', label: 'Pesanan', icon: <ClipboardList className="h-5 w-5" /> },
  { id: 'menu', label: 'Menu', icon: <UtensilsCrossed className="h-5 w-5" /> },
  { id: 'categories', label: 'Kategori', icon: <FolderOpen className="h-5 w-5" /> },
  { id: 'settings', label: 'Pengaturan', icon: <Settings className="h-5 w-5" /> },
  { id: 'analytics', label: 'Analitik', icon: <BarChart3 className="h-5 w-5" /> },
];

// ─── Main Component ──────────────────────────────────────────────────────────

export default function AdminDashboard({ open, onOpenChange }: AdminDashboardProps) {
  const [activeTab, setActiveTab] = useState<TabId>('dashboard');
  const [sidebarOpen, setSidebarOpen] = useState(false);

  // Data states
  const [orders, setOrders] = useState<Invoice[]>([]);
  const [ordersTotal, setOrdersTotal] = useState(0);
  const [ordersPage, setOrdersPage] = useState(1);
  const [ordersStatus, setOrdersStatus] = useState('');
  const [ordersSearch, setOrdersSearch] = useState('');
  const [ordersLoading, setOrdersLoading] = useState(false);

  const [foods, setFoods] = useState<FoodItem[]>([]);
  const [foodsTotal, setFoodsTotal] = useState(0);
  const [foodsPage, setFoodsPage] = useState(1);
  const [foodsSearch, setFoodsSearch] = useState('');
  const [foodsCategoryFilter, setFoodsCategoryFilter] = useState('');
  const [foodsLoading, setFoodsLoading] = useState(false);

  const [categories, setCategories] = useState<Category[]>([]);
  const [categoriesLoading, setCategoriesLoading] = useState(false);

  const [settings, setSettings] = useState<StoreSettingsData | null>(null);
  const [settingsLoading, setSettingsLoading] = useState(false);

  const [dashStats, setDashStats] = useState({
    todayOrders: 0,
    todayRevenue: 0,
    activeFoods: 0,
    pendingOrders: 0,
  });
  const [recentOrders, setRecentOrders] = useState<Invoice[]>([]);
  const [dashLoading, setDashLoading] = useState(false);

  // Form states
  const [foodDialogOpen, setFoodDialogOpen] = useState(false);
  const [editingFood, setEditingFood] = useState<FoodItem | null>(null);
  const [foodForm, setFoodForm] = useState<FoodFormData>(EMPTY_FOOD_FORM);
  const [foodSaving, setFoodSaving] = useState(false);

  const [categoryDialogOpen, setCategoryDialogOpen] = useState(false);
  const [editingCategory, setEditingCategory] = useState<Category | null>(null);
  const [categoryForm, setCategoryForm] = useState<CategoryFormData>(EMPTY_CATEGORY_FORM);
  const [categorySaving, setCategorySaving] = useState(false);

  const [settingsForm, setSettingsForm] = useState<SettingsFormData>(EMPTY_SETTINGS_FORM);
  const [settingsSaving, setSettingsSaving] = useState(false);

  // Detail / delete states
  const [orderDetail, setOrderDetail] = useState<Invoice | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<{ type: 'food' | 'category' | 'invoice'; id: string; name: string } | null>(null);
  const [deleting, setDeleting] = useState(false);
  const [deletingInvoice, setDeletingInvoice] = useState(false);

  const [analytics, setAnalytics] = useState({ totalViews: 0, totalVisitors: 0, todayViews: 0, todayVisitors: 0, last7Days: [] as { date: string; views: number; visitors: number }[] });
  const [analyticsLoading, setAnalyticsLoading] = useState(false);

  const [statusUpdating, setStatusUpdating] = useState<string | null>(null);

  // ─── Data Fetchers ───────────────────────────────────────────────────────

  const fetchDashboard = useCallback(async () => {
    setDashLoading(true);
    try {
      const [ordersRes, foodsRes] = await Promise.all([
        apiFetch('/api/admin/orders?limit=100'),
        apiFetch('/api/admin/foods?limit=100'),
      ]);

      if (ordersRes.success) {
        const allOrders = ordersRes.data.orders as Invoice[];
        const todayOrders = allOrders.filter((o) => isToday(o.createdAt));
        const todayRevenue = todayOrders
          .filter((o) => o.status !== 'cancelled')
          .reduce((sum, o) => sum + o.total, 0);
        const pending = allOrders.filter((o) => o.status === 'pending').length;
        setDashStats({
          todayOrders: todayOrders.length,
          todayRevenue,
          activeFoods: 0,
          pendingOrders: pending,
        });
        setRecentOrders(allOrders.slice(0, 5));
      }
      if (foodsRes.success) {
        const allFoods = foodsRes.data.foods as FoodItem[];
        setDashStats((prev) => ({
          ...prev,
          activeFoods: allFoods.filter((f) => f.isAvailable).length,
        }));
      }
    } catch {
      toast({ title: 'Error', description: 'Gagal memuat data dashboard', variant: 'destructive' });
    } finally {
      setDashLoading(false);
    }
  }, []);

  const fetchOrders = useCallback(async (page = 1, status = '', search = '') => {
    setOrdersLoading(true);
    try {
      const params = new URLSearchParams({ page: String(page), limit: '20' });
      if (status) params.set('status', status);
      if (search) params.set('search', search);
      const res = await apiFetch(`/api/admin/orders?${params}`);
      if (res.success) {
        setOrders(res.data.orders);
        setOrdersTotal(res.data.total);
        setOrdersPage(page);
      }
    } catch {
      toast({ title: 'Error', description: 'Gagal memuat pesanan', variant: 'destructive' });
    } finally {
      setOrdersLoading(false);
    }
  }, []);

  const fetchFoods = useCallback(async (page = 1, search = '', category = '') => {
    setFoodsLoading(true);
    try {
      const params = new URLSearchParams({ page: String(page), limit: '50', includeUnavailable: 'true' });
      if (search) params.set('search', search);
      if (category) params.set('category', category);
      const res = await apiFetch(`/api/admin/foods?${params}`);
      if (res.success) {
        setFoods(res.data.foods);
        setFoodsTotal(res.data.total);
        setFoodsPage(page);
      }
    } catch {
      toast({ title: 'Error', description: 'Gagal memuat menu', variant: 'destructive' });
    } finally {
      setFoodsLoading(false);
    }
  }, []);

  const fetchCategories = useCallback(async () => {
    setCategoriesLoading(true);
    try {
      const res = await apiFetch('/api/admin/categories');
      if (res.success) {
        setCategories(res.data);
      }
    } catch {
      toast({ title: 'Error', description: 'Gagal memuat kategori', variant: 'destructive' });
    } finally {
      setCategoriesLoading(false);
    }
  }, []);

  const fetchSettings = useCallback(async () => {
    setSettingsLoading(true);
    try {
      const res = await apiFetch('/api/admin/settings');
      if (res.success) {
        const s = res.data as StoreSettingsData;
        setSettings(s);
        setSettingsForm({
          storeName: s.storeName || '',
          storeDesc: s.storeDesc || '',
          address: s.address || '',
          phone: s.phone || '',
          email: s.email || '',
          whatsapp: s.whatsapp || '',
          instagram: s.instagram || '',
          facebook: s.facebook || '',
          twitter: s.twitter || '',
          tiktok: s.tiktok || '',
          freeShippingThreshold: String(s.freeShippingThreshold || ''),
          shippingRate: String(s.shippingRate || ''),
          codAvailable: s.codAvailable ?? true,
          qrisImage: s.qrisImage || '',
          heroPromoLabel: s.heroPromoLabel || '',
          heroPromoTitle1: s.heroPromoTitle1 || '',
          heroPromoTitle2: s.heroPromoTitle2 || '',
          heroPromoDesc: s.heroPromoDesc || '',
          heroPromoCode: s.heroPromoCode || '',
          googleMapsEmbed: s.googleMapsEmbed || '',
          heroType: s.heroType || 'promo',
          themeMode: s.themeMode || 'dark',
          accentColor: s.accentColor || 'orange',
          logoUrl: s.logoUrl || '',
          autoMessage: s.autoMessage || 'Halo! Saya ingin memesan:',
        });
      }
    } catch {
      toast({ title: 'Error', description: 'Gagal memuat pengaturan', variant: 'destructive' });
    } finally {
      setSettingsLoading(false);
    }
  }, []);

  const fetchAnalytics = useCallback(async () => {
    setAnalyticsLoading(true);
    try {
      const res = await apiFetch('/api/admin/analytics');
      if (res.success) setAnalytics(res.data);
    } catch {
      toast({ title: 'Error', description: 'Gagal memuat analitik', variant: 'destructive' });
    } finally {
      setAnalyticsLoading(false);
    }
  }, []);

  // Load data on tab switch
  useEffect(() => {
    if (!open) return;
    switch (activeTab) {
      case 'dashboard':
        fetchDashboard();
        break;
      case 'orders':
        fetchOrders(ordersPage, ordersStatus, ordersSearch);
        break;
      case 'menu':
        fetchFoods(foodsPage, foodsSearch, foodsCategoryFilter);
        fetchCategories();
        break;
      case 'categories':
        fetchCategories();
        break;
      case 'settings':
        fetchSettings();
        break;
      case 'analytics':
        fetchAnalytics();
        break;
    }
    setSidebarOpen(false);
  }, [open, activeTab, fetchDashboard, fetchOrders, ordersPage, ordersStatus, ordersSearch, fetchFoods, foodsPage, foodsSearch, foodsCategoryFilter, fetchCategories, fetchSettings, fetchAnalytics]);

  // ─── Actions ─────────────────────────────────────────────────────────────

  const handleUpdateOrderStatus = async (orderId: string, newStatus: string) => {
    setStatusUpdating(orderId);
    try {
      const res = await apiFetch('/api/admin/orders', {
        method: 'PATCH',
        body: JSON.stringify({ id: orderId, status: newStatus }),
      });
      if (res.success) {
        toast({ title: 'Berhasil!', description: 'Status pesanan berhasil diubah' });
        setOrders((prev) => prev.map((o) => (o.id === orderId ? { ...o, status: newStatus } : o)));
        if (orderDetail?.id === orderId) {
          setOrderDetail((prev) => (prev ? { ...prev, status: newStatus } : null));
        }
      } else {
        toast({ title: 'Gagal', description: res.error || 'Gagal mengubah status', variant: 'destructive' });
      }
    } catch {
      toast({ title: 'Error', description: 'Terjadi kesalahan', variant: 'destructive' });
    } finally {
      setStatusUpdating(null);
    }
  };

  const openFoodDialog = (food?: FoodItem) => {
    if (food) {
      setEditingFood(food);
      setFoodForm({
        name: food.name,
        description: food.description || '',
        price: String(food.price),
        discountPrice: food.discountPrice ? String(food.discountPrice) : '',
        discountPercent: food.discountPercent ? String(food.discountPercent) : '',
        categoryId: food.categoryId,
        thumbnail: food.thumbnail || '',
        largeImage: food.largeImage || '',
        isAvailable: food.isAvailable,
        isBestseller: food.isBestseller,
        isHalal: food.isHalal,
        badge: food.badge || '',
        order: String(food.order || 0),
      });
    } else {
      setEditingFood(null);
      setFoodForm(EMPTY_FOOD_FORM);
    }
    setFoodDialogOpen(true);
  };

  const saveFood = async () => {
    if (!foodForm.name.trim()) {
      toast({ title: 'Perhatian', description: 'Nama menu wajib diisi', variant: 'destructive' });
      return;
    }
    if (!foodForm.price || isNaN(Number(foodForm.price)) || Number(foodForm.price) < 0) {
      toast({ title: 'Perhatian', description: 'Harga wajib diisi dan harus angka', variant: 'destructive' });
      return;
    }
    if (!foodForm.categoryId) {
      toast({ title: 'Perhatian', description: 'Kategori wajib dipilih', variant: 'destructive' });
      return;
    }

    setFoodSaving(true);
    try {
      const body: Record<string, unknown> = {
        name: foodForm.name.trim(),
        description: foodForm.description,
        price: Number(foodForm.price),
        discountPrice: foodForm.discountPrice ? Number(foodForm.discountPrice) : null,
        discountPercent: foodForm.discountPercent ? Number(foodForm.discountPercent) : null,
        categoryId: foodForm.categoryId,
        thumbnail: foodForm.thumbnail,
        largeImage: foodForm.largeImage,
        isAvailable: foodForm.isAvailable,
        isBestseller: foodForm.isBestseller,
        isHalal: foodForm.isHalal,
        badge: foodForm.badge,
        order: Number(foodForm.order) || 0,
      };

      let res;
      if (editingFood) {
        res = await apiFetch(`/api/admin/foods/${editingFood.id}`, { method: 'PATCH', body: JSON.stringify(body) });
      } else {
        res = await apiFetch('/api/admin/foods', { method: 'POST', body: JSON.stringify(body) });
      }

      if (res.success) {
        toast({
          title: editingFood ? 'Berhasil Diperbarui!' : 'Berhasil Ditambahkan!',
          description: editingFood ? 'Menu berhasil diperbarui' : 'Menu baru berhasil ditambahkan',
        });
        setFoodDialogOpen(false);
        fetchFoods(foodsPage, foodsSearch, foodsCategoryFilter);
      } else {
        toast({ title: 'Gagal', description: res.error || 'Terjadi kesalahan', variant: 'destructive' });
      }
    } catch {
      toast({ title: 'Error', description: 'Terjadi kesalahan jaringan', variant: 'destructive' });
    } finally {
      setFoodSaving(false);
    }
  };

  const handleDeleteFood = async () => {
    if (!deleteTarget || deleteTarget.type !== 'food') return;
    setDeleting(true);
    try {
      const res = await apiFetch(`/api/admin/foods/${deleteTarget.id}`, { method: 'DELETE' });
      if (res.success) {
        toast({ title: 'Berhasil!', description: 'Menu berhasil dinonaktifkan' });
        fetchFoods(foodsPage, foodsSearch, foodsCategoryFilter);
      } else {
        toast({ title: 'Gagal', description: res.error || 'Gagal menghapus menu', variant: 'destructive' });
      }
    } catch {
      toast({ title: 'Error', description: 'Terjadi kesalahan', variant: 'destructive' });
    } finally {
      setDeleting(false);
      setDeleteTarget(null);
    }
  };

  const openCategoryDialog = (cat?: Category) => {
    if (cat) {
      setEditingCategory(cat);
      setCategoryForm({ name: cat.name, slug: cat.slug, icon: cat.icon || '🍽️', order: String(cat.order || 0) });
    } else {
      setEditingCategory(null);
      setCategoryForm(EMPTY_CATEGORY_FORM);
    }
    setCategoryDialogOpen(true);
  };

  const saveCategory = async () => {
    if (!categoryForm.name.trim()) {
      toast({ title: 'Perhatian', description: 'Nama kategori wajib diisi', variant: 'destructive' });
      return;
    }
    setCategorySaving(true);
    try {
      const body: Record<string, unknown> = {
        name: categoryForm.name.trim(),
        slug: categoryForm.slug.trim() || categoryForm.name.trim().toLowerCase().replace(/\s+/g, '-'),
        icon: categoryForm.icon,
        order: Number(categoryForm.order) || 0,
      };

      let res;
      if (editingCategory) {
        res = await apiFetch(`/api/admin/categories/${editingCategory.id}`, { method: 'PATCH', body: JSON.stringify(body) });
      } else {
        res = await apiFetch('/api/admin/categories', { method: 'POST', body: JSON.stringify(body) });
      }

      if (res.success) {
        toast({
          title: editingCategory ? 'Berhasil Diperbarui!' : 'Berhasil Ditambahkan!',
          description: editingCategory ? 'Kategori berhasil diperbarui' : 'Kategori baru berhasil ditambahkan',
        });
        setCategoryDialogOpen(false);
        fetchCategories();
      } else {
        toast({ title: 'Gagal', description: res.error || 'Terjadi kesalahan', variant: 'destructive' });
      }
    } catch {
      toast({ title: 'Error', description: 'Terjadi kesalahan jaringan', variant: 'destructive' });
    } finally {
      setCategorySaving(false);
    }
  };

  const handleDeleteCategory = async () => {
    if (!deleteTarget || deleteTarget.type !== 'category') return;
    setDeleting(true);
    try {
      const res = await apiFetch(`/api/admin/categories/${deleteTarget.id}`, { method: 'DELETE' });
      if (res.success) {
        toast({ title: 'Berhasil!', description: 'Kategori berhasil dihapus' });
        fetchCategories();
      } else {
        toast({ title: 'Gagal', description: res.error || 'Gagal menghapus kategori', variant: 'destructive' });
      }
    } catch {
      toast({ title: 'Error', description: 'Terjadi kesalahan', variant: 'destructive' });
    } finally {
      setDeleting(false);
      setDeleteTarget(null);
    }
  };

  const handleDeleteInvoice = async () => {
    if (!deleteTarget || deleteTarget.type !== 'invoice') return;
    setDeleting(true);
    try {
      const res = await apiFetch(`/api/admin/orders/${deleteTarget.id}`, { method: 'DELETE' });
      if (res.success) {
        toast({ title: 'Berhasil!', description: 'Invoice berhasil dihapus' });
        fetchOrders(ordersPage, ordersStatus, ordersSearch);
        fetchDashboard();
      } else {
        toast({ title: 'Gagal', description: res.error || 'Gagal menghapus invoice', variant: 'destructive' });
      }
    } catch {
      toast({ title: 'Error', description: 'Terjadi kesalahan', variant: 'destructive' });
    } finally {
      setDeleting(false);
      setDeleteTarget(null);
    }
  };

  const saveSettings = async () => {
    setSettingsSaving(true);
    try {
      const body: Record<string, unknown> = {
        storeName: settingsForm.storeName,
        storeDesc: settingsForm.storeDesc,
        address: settingsForm.address,
        phone: settingsForm.phone,
        email: settingsForm.email,
        whatsapp: settingsForm.whatsapp,
        instagram: settingsForm.instagram,
        facebook: settingsForm.facebook,
        twitter: settingsForm.twitter,
        tiktok: settingsForm.tiktok,
        freeShippingThreshold: Number(settingsForm.freeShippingThreshold) || 0,
        shippingRate: Number(settingsForm.shippingRate) || 0,
        codAvailable: settingsForm.codAvailable,
        qrisImage: settingsForm.qrisImage,
        heroPromoLabel: settingsForm.heroPromoLabel,
        heroPromoTitle1: settingsForm.heroPromoTitle1,
        heroPromoTitle2: settingsForm.heroPromoTitle2,
        heroPromoDesc: settingsForm.heroPromoDesc,
        heroPromoCode: settingsForm.heroPromoCode,
        googleMapsEmbed: settingsForm.googleMapsEmbed,
        heroType: settingsForm.heroType,
        themeMode: settingsForm.themeMode,
        accentColor: settingsForm.accentColor,
        logoUrl: settingsForm.logoUrl,
        autoMessage: settingsForm.autoMessage,
      };

      const res = await apiFetch('/api/admin/settings', { method: 'PATCH', body: JSON.stringify(body) });
      if (res.success) {
        toast({ title: 'Berhasil!', description: 'Pengaturan berhasil disimpan' });
      } else {
        toast({ title: 'Gagal', description: res.error || 'Gagal menyimpan pengaturan', variant: 'destructive' });
      }
    } catch {
      toast({ title: 'Error', description: 'Terjadi kesalahan', variant: 'destructive' });
    } finally {
      setSettingsSaving(false);
    }
  };

  // Auto-calculate discount percent
  useEffect(() => {
    if (foodForm.price && foodForm.discountPrice && Number(foodForm.discountPrice) < Number(foodForm.price)) {
      const percent = Math.round(((Number(foodForm.price) - Number(foodForm.discountPrice)) / Number(foodForm.price)) * 100);
      setFoodForm((prev) => ({ ...prev, discountPercent: String(percent) }));
    } else {
      setFoodForm((prev) => ({ ...prev, discountPercent: '' }));
    }
  }, [foodForm.price, foodForm.discountPrice]);

  // Auto-generate slug from category name
  useEffect(() => {
    if (!editingCategory && categoryForm.name) {
      setCategoryForm((prev) => ({
        ...prev,
        slug: prev.name.trim().toLowerCase().replace(/\s+/g, '-'),
      }));
    }
  }, [categoryForm.name, editingCategory]);

  // ─── Render Helpers ─────────────────────────────────────────────────────

  const StatusBadge = ({ status }: { status: string }) => {
    const s = STATUS_MAP[status] || { label: status, color: 'text-white', bg: 'bg-zinc-700' };
    return (
      <span className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium ${s.color} ${s.bg}`}>
        {s.label}
      </span>
    );
  };

  // ─── Dashboard Tab ──────────────────────────────────────────────────────

  const renderDashboard = () => (
    <div className="space-y-6">
      <h2 className="text-xl font-bold text-white sm:text-2xl">Dashboard</h2>

      {dashLoading ? (
        <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
          {[...Array(4)].map((_, i) => (
            <Skeleton key={i} className="h-28 rounded-xl bg-[#18181b]" />
          ))}
        </div>
      ) : (
        <>
          {/* Stats Cards */}
          <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
            <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-5">
              <div className="mb-3 flex items-center gap-2">
                <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-500/15">
                  <ShoppingCart className="h-5 w-5 text-blue-400" />
                </div>
              </div>
              <p className="text-2xl font-bold text-white sm:text-3xl">{dashStats.todayOrders}</p>
              <p className="mt-1 text-xs text-white/50 sm:text-sm">Pesanan Hari Ini</p>
            </div>

            <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-5">
              <div className="mb-3 flex items-center gap-2">
                <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-emerald-500/15">
                  <DollarSign className="h-5 w-5 text-emerald-400" />
                </div>
              </div>
              <p className="text-2xl font-bold text-emerald-400 sm:text-3xl">Rp {formatPrice(dashStats.todayRevenue)}</p>
              <p className="mt-1 text-xs text-white/50 sm:text-sm">Pendapatan Hari Ini</p>
            </div>

            <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-5">
              <div className="mb-3 flex items-center gap-2">
                <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-orange-500/15">
                  <Package className="h-5 w-5 text-orange-400" />
                </div>
              </div>
              <p className="text-2xl font-bold text-white sm:text-3xl">{dashStats.activeFoods}</p>
              <p className="mt-1 text-xs text-white/50 sm:text-sm">Menu Aktif</p>
            </div>

            <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-5">
              <div className="mb-3 flex items-center gap-2">
                <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-amber-500/15">
                  <Clock className="h-5 w-5 text-amber-400" />
                </div>
              </div>
              <p className="text-2xl font-bold text-amber-400 sm:text-3xl">{dashStats.pendingOrders}</p>
              <p className="mt-1 text-xs text-white/50 sm:text-sm">Pesanan Baru</p>
            </div>
          </div>
        </>
      )}

      {/* Recent Orders */}
      <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-5">
        <h3 className="mb-4 text-lg font-semibold text-white">Pesanan Terbaru</h3>
        {dashLoading ? (
          <div className="space-y-3">
            {[...Array(3)].map((_, i) => (
              <Skeleton key={i} className="h-12 rounded-lg bg-[#111113]" />
            ))}
          </div>
        ) : recentOrders.length === 0 ? (
          <div className="py-8 text-center text-white/40">
            <ClipboardList className="mx-auto mb-2 h-8 w-8" />
            <p>Belum ada pesanan</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow className="border-white/5 hover:bg-transparent">
                  <TableHead className="text-white/50">Invoice</TableHead>
                  <TableHead className="text-white/50">Nama</TableHead>
                  <TableHead className="text-white/50 hidden sm:table-cell">Total</TableHead>
                  <TableHead className="text-white/50">Status</TableHead>
                  <TableHead className="text-white/50 hidden md:table-cell">Tanggal</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {recentOrders.map((order) => (
                  <TableRow
                    key={order.id}
                    className="cursor-pointer border-white/5 transition-colors hover:bg-white/5"
                    onClick={() => setOrderDetail(order)}
                  >
                    <TableCell className="font-mono text-xs text-white/70">{order.invoiceNumber}</TableCell>
                    <TableCell className="text-sm text-white">{order.buyerName}</TableCell>
                    <TableCell className="hidden text-sm text-orange-400 sm:table-cell">
                      Rp {formatPrice(order.total)}
                    </TableCell>
                    <TableCell>
                      <StatusBadge status={order.status} />
                    </TableCell>
                    <TableCell className="hidden text-xs text-white/50 md:table-cell">
                      {formatDateShort(order.createdAt)}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        )}
      </div>
    </div>
  );

  // ─── Orders Tab ─────────────────────────────────────────────────────────

  const renderOrders = () => (
    <div className="space-y-4">
      <h2 className="text-xl font-bold text-white sm:text-2xl">Kelola Pesanan</h2>

      {/* Search */}
      <div className="flex gap-2">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-white/40" />
          <Input
            placeholder="Cari nama, telepon, atau nomor invoice..."
            className="border-white/10 bg-[#111113] pl-9 text-white placeholder:text-white/30"
            value={ordersSearch}
            onChange={(e) => setOrdersSearch(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && fetchOrders(1, ordersStatus, ordersSearch)}
          />
        </div>
        <Button
          onClick={() => fetchOrders(1, ordersStatus, ordersSearch)}
          className="min-h-[44px] min-w-[44px] bg-orange-500 hover:bg-orange-600"
        >
          <Search className="h-4 w-4" />
        </Button>
      </div>

      {/* Filter Tabs */}
      <div className="flex gap-1.5 overflow-x-auto pb-2 no-scrollbar">
        {ORDER_FILTER_TABS.map((tab) => (
          <button
            key={tab.value}
            onClick={() => {
              setOrdersStatus(tab.value);
              fetchOrders(1, tab.value, ordersSearch);
            }}
            className={`shrink-0 rounded-lg px-3 py-2 text-xs font-medium transition-colors sm:text-sm min-h-[44px] ${
              ordersStatus === tab.value
                ? 'bg-orange-500 text-white'
                : 'bg-[#18181b] text-white/60 hover:bg-white/10 hover:text-white'
            }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* Orders Table */}
      <div className="rounded-xl border border-white/5 bg-[#18181b] overflow-hidden">
        {ordersLoading ? (
          <div className="p-4 space-y-3">
            {[...Array(5)].map((_, i) => (
              <Skeleton key={i} className="h-14 rounded-lg bg-[#111113]" />
            ))}
          </div>
        ) : orders.length === 0 ? (
          <div className="py-12 text-center text-white/40">
            <ClipboardList className="mx-auto mb-2 h-8 w-8" />
            <p>Tidak ada pesanan ditemukan</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow className="border-white/5 hover:bg-transparent">
                  <TableHead className="text-white/50 text-xs">Invoice</TableHead>
                  <TableHead className="text-white/50 text-xs">Nama</TableHead>
                  <TableHead className="text-white/50 text-xs hidden sm:table-cell">Total</TableHead>
                  <TableHead className="text-white/50 text-xs">Status</TableHead>
                  <TableHead className="text-white/50 text-xs hidden md:table-cell">Tanggal</TableHead>
                  <TableHead className="text-white/50 text-xs text-right">Aksi</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {orders.map((order) => (
                  <TableRow key={order.id} className="border-white/5 hover:bg-white/5">
                    <TableCell className="font-mono text-xs text-white/70">{order.invoiceNumber}</TableCell>
                    <TableCell>
                      <div>
                        <p className="text-sm font-medium text-white">{order.buyerName}</p>
                        <p className="text-xs text-white/40">{order.buyerPhone}</p>
                      </div>
                    </TableCell>
                    <TableCell className="hidden text-sm font-semibold text-orange-400 sm:table-cell">
                      Rp {formatPrice(order.total)}
                    </TableCell>
                    <TableCell>
                      <StatusBadge status={order.status} />
                    </TableCell>
                    <TableCell className="hidden text-xs text-white/50 md:table-cell">
                      {formatDateShort(order.createdAt)}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-1">
                        <Select
                          value={order.status}
                          onValueChange={(val) => handleUpdateOrderStatus(order.id, val)}
                        >
                          <SelectTrigger
                            size="sm"
                            className="w-auto min-w-[100px] border-white/10 bg-[#111113] text-xs"
                          >
                            {statusUpdating === order.id ? (
                              <Loader2 className="h-3 w-3 animate-spin" />
                            ) : (
                              <SelectValue />
                            )}
                          </SelectTrigger>
                          <SelectContent className="border-white/10 bg-[#18181b]">
                            {ORDER_STATUS_OPTIONS.map((opt) => (
                              <SelectItem key={opt.value} value={opt.value} className="text-white/80 focus:bg-white/10 focus:text-white">
                                {opt.label}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <Button
                          variant="ghost"
                          size="sm"
                          className="min-h-[44px] min-w-[44px] text-white/60 hover:text-white hover:bg-white/10"
                          onClick={() => setOrderDetail(order)}
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          className="min-h-[44px] min-w-[44px] text-white/60 hover:text-red-400 hover:bg-red-500/10"
                          onClick={(e) => { e.stopPropagation(); setDeleteTarget({ type: 'invoice', id: order.id, name: order.invoiceNumber }); }}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        )}

        {/* Pagination */}
        {ordersTotal > 20 && (
          <div className="flex items-center justify-between border-t border-white/5 px-4 py-3">
            <p className="text-xs text-white/40">
              Menampilkan {((ordersPage - 1) * 20) + 1}-{Math.min(ordersPage * 20, ordersTotal)} dari {ordersTotal}
            </p>
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                className="min-h-[44px] border-white/10 bg-[#111113] text-white/60 hover:text-white"
                disabled={ordersPage <= 1}
                onClick={() => fetchOrders(ordersPage - 1, ordersStatus, ordersSearch)}
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <Button
                variant="outline"
                size="sm"
                className="min-h-[44px] border-white/10 bg-[#111113] text-white/60 hover:text-white"
                disabled={ordersPage * 20 >= ordersTotal}
                onClick={() => fetchOrders(ordersPage + 1, ordersStatus, ordersSearch)}
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        )}
      </div>

      {/* Order Detail Dialog */}
      <Dialog open={!!orderDetail} onOpenChange={() => setOrderDetail(null)}>
        <DialogContent className="max-h-[85vh] overflow-y-auto border-white/10 bg-[#111113] sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle className="text-white">Detail Pesanan</DialogTitle>
            <DialogDescription className="text-white/50">
              {orderDetail?.invoiceNumber}
            </DialogDescription>
          </DialogHeader>

          {orderDetail && (
            <div className="space-y-4">
              {/* Status & Date */}
              <div className="flex flex-wrap items-center gap-3">
                <StatusBadge status={orderDetail.status} />
                <span className="text-xs text-white/40">{formatDate(orderDetail.createdAt)}</span>
              </div>

              <Separator className="bg-white/10" />

              {/* Buyer Info */}
              <div className="space-y-2">
                <h4 className="text-sm font-semibold text-white">Info Pembeli</h4>
                <div className="rounded-lg bg-[#18181b] p-3 space-y-1.5">
                  <p className="text-sm text-white"><span className="text-white/50">Nama:</span> {orderDetail.buyerName}</p>
                  <p className="text-sm text-white"><span className="text-white/50">Telepon:</span> {orderDetail.buyerPhone}</p>
                  <p className="text-sm text-white"><span className="text-white/50">Alamat:</span> {orderDetail.buyerAddress}</p>
                  {orderDetail.buyerNotes && (
                    <p className="text-sm text-white"><span className="text-white/50">Catatan:</span> {orderDetail.buyerNotes}</p>
                  )}
                </div>
              </div>

              {/* Items */}
              <div className="space-y-2">
                <h4 className="text-sm font-semibold text-white">Item Pesanan</h4>
                <div className="rounded-lg bg-[#18181b] p-3 space-y-3">
                  {(() => {
                    try {
                      const items: OrderItem[] = JSON.parse(orderDetail.items);
                      return items.map((item, idx) => (
                        <div key={idx} className="flex items-center gap-3">
                          {item.thumbnail ? (
                            <img src={item.thumbnail} alt={item.name} className="h-10 w-10 rounded-lg object-cover" />
                          ) : (
                            <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-white/5 text-lg">🍽️</div>
                          )}
                          <div className="flex-1 min-w-0">
                            <p className="text-sm font-medium text-white truncate">{item.name}</p>
                            {item.variant && <p className="text-xs text-white/40">{item.variant}</p>}
                            {item.note && <p className="text-xs text-white/40 italic">Catatan: {item.note}</p>}
                          </div>
                          <div className="text-right shrink-0">
                            <p className="text-sm text-white">{item.quantity}x</p>
                            <p className="text-xs text-orange-400">Rp {formatPrice(item.price * item.quantity)}</p>
                          </div>
                        </div>
                      ));
                    } catch {
                      return <p className="text-sm text-white/40">Gagal memuat item</p>;
                    }
                  })()}
                </div>
              </div>

              {/* Totals */}
              <div className="rounded-lg bg-[#18181b] p-3 space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-white/50">Subtotal</span>
                  <span className="text-white">Rp {formatPrice(orderDetail.subtotal)}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-white/50">Ongkir</span>
                  <span className="text-white">Rp {formatPrice(orderDetail.shipping)}</span>
                </div>
                <Separator className="bg-white/10" />
                <div className="flex justify-between text-base font-bold">
                  <span className="text-white">Total</span>
                  <span className="text-orange-400">Rp {formatPrice(orderDetail.total)}</span>
                </div>
              </div>

              {/* Change Status */}
              <div className="space-y-2">
                <Label className="text-sm font-semibold text-white">Ubah Status</Label>
                <Select
                  value={orderDetail.status}
                  onValueChange={(val) => handleUpdateOrderStatus(orderDetail.id, val)}
                >
                  <SelectTrigger className="w-full border-white/10 bg-[#18181b] text-white">
                    {statusUpdating === orderDetail.id ? (
                      <Loader2 className="h-4 w-4 animate-spin" />
                    ) : (
                      <SelectValue />
                    )}
                  </SelectTrigger>
                  <SelectContent className="border-white/10 bg-[#18181b]">
                    {ORDER_STATUS_OPTIONS.map((opt) => (
                      <SelectItem key={opt.value} value={opt.value} className="text-white/80 focus:bg-white/10 focus:text-white">
                        {opt.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );

  // ─── Menu Tab ───────────────────────────────────────────────────────────

  const renderMenu = () => (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <h2 className="text-xl font-bold text-white sm:text-2xl">Kelola Menu</h2>
        <Button
          onClick={() => openFoodDialog()}
          className="min-h-[44px] bg-orange-500 hover:bg-orange-600"
        >
          <Plus className="mr-2 h-4 w-4" />
          Tambah Menu
        </Button>
      </div>

      {/* Search & Filter */}
      <div className="flex flex-col gap-2 sm:flex-row">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-white/40" />
          <Input
            placeholder="Cari menu..."
            className="border-white/10 bg-[#111113] pl-9 text-white placeholder:text-white/30"
            value={foodsSearch}
            onChange={(e) => setFoodsSearch(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && fetchFoods(1, foodsSearch, foodsCategoryFilter)}
          />
        </div>
        <Select value={foodsCategoryFilter} onValueChange={(val) => {
          setFoodsCategoryFilter(val);
          fetchFoods(1, foodsSearch, val);
        }}>
          <SelectTrigger className="w-full border-white/10 bg-[#111113] text-white sm:w-48">
            <SelectValue placeholder="Semua Kategori" />
          </SelectTrigger>
          <SelectContent className="border-white/10 bg-[#18181b]">
            <SelectItem value="" className="text-white/80 focus:bg-white/10 focus:text-white">Semua Kategori</SelectItem>
            {categories.map((cat) => (
              <SelectItem key={cat.id} value={cat.slug} className="text-white/80 focus:bg-white/10 focus:text-white">
                {cat.icon} {cat.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* Food Cards Grid */}
      {foodsLoading ? (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {[...Array(6)].map((_, i) => (
            <Skeleton key={i} className="h-64 rounded-xl bg-[#18181b]" />
          ))}
        </div>
      ) : foods.length === 0 ? (
        <div className="py-12 text-center text-white/40">
          <UtensilsCrossed className="mx-auto mb-2 h-8 w-8" />
          <p>Tidak ada menu ditemukan</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {foods.map((food) => (
            <div
              key={food.id}
              className="group rounded-xl border border-white/5 bg-[#18181b] overflow-hidden transition-all hover:border-white/10"
            >
              <div className="relative h-40 bg-[#111113]">
                {food.thumbnail ? (
                  <img src={food.thumbnail} alt={food.name} className="h-full w-full object-cover" />
                ) : (
                  <div className="flex h-full w-full items-center justify-center text-4xl text-white/10">🍽️</div>
                )}
                {!food.isAvailable && (
                  <div className="absolute inset-0 flex items-center justify-center bg-black/60">
                    <Badge className="bg-red-500/90 text-white border-0">Tidak Aktif</Badge>
                  </div>
                )}
                {food.isAvailable && (
                  <div className="absolute top-2 right-2">
                    <Badge className="bg-emerald-500/90 text-white border-0">Aktif</Badge>
                  </div>
                )}
                {food.discountPercent && food.isAvailable && (
                  <div className="absolute bottom-2 right-2">
                    <Badge className="bg-red-500 text-white border-0">-{food.discountPercent}%</Badge>
                  </div>
                )}
              </div>
              <div className="p-4">
                <div className="mb-1 flex items-start justify-between gap-2">
                  <h3 className="text-sm font-semibold text-white line-clamp-1">{food.name}</h3>
                  <div className="flex gap-1 shrink-0">
                    <Button
                      variant="ghost"
                      size="sm"
                      className="min-h-[44px] min-w-[44px] text-white/40 hover:text-orange-400 hover:bg-orange-500/10"
                      onClick={() => openFoodDialog(food)}
                    >
                      <Pencil className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      className="min-h-[44px] min-w-[44px] text-white/40 hover:text-red-400 hover:bg-red-500/10"
                      onClick={() => setDeleteTarget({ type: 'food', id: food.id, name: food.name })}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
                {food.category && (
                  <p className="mb-1 text-xs text-white/40">{food.category.icon} {food.category.name}</p>
                )}
                <div className="flex items-baseline gap-2">
                  <span className="text-base font-bold text-orange-400">
                    Rp {formatPrice(food.discountPrice || food.price)}
                  </span>
                  {food.discountPrice && food.discountPrice < food.price && (
                    <span className="text-xs text-white/30 line-through">Rp {formatPrice(food.price)}</span>
                  )}
                </div>
                <div className="mt-2 flex flex-wrap gap-1">
                  {food.isBestseller && (
                    <span className="rounded-full bg-orange-500/15 px-2 py-0.5 text-[10px] font-medium text-orange-400">Bestseller</span>
                  )}
                  {food.isHalal && (
                    <span className="rounded-full bg-emerald-500/15 px-2 py-0.5 text-[10px] font-medium text-emerald-400">Halal</span>
                  )}
                  {food.badge && (
                    <span className="rounded-full bg-blue-500/15 px-2 py-0.5 text-[10px] font-medium text-blue-400">{food.badge}</span>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Pagination */}
      {foodsTotal > 50 && (
        <div className="flex items-center justify-between pt-2">
          <p className="text-xs text-white/40">
            Menampilkan {((foodsPage - 1) * 50) + 1}-{Math.min(foodsPage * 50, foodsTotal)} dari {foodsTotal}
          </p>
          <div className="flex gap-2">
            <Button
              variant="outline"
              size="sm"
              className="min-h-[44px] border-white/10 bg-[#111113] text-white/60 hover:text-white"
              disabled={foodsPage <= 1}
              onClick={() => fetchFoods(foodsPage - 1, foodsSearch, foodsCategoryFilter)}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              size="sm"
              className="min-h-[44px] border-white/10 bg-[#111113] text-white/60 hover:text-white"
              disabled={foodsPage * 50 >= foodsTotal}
              onClick={() => fetchFoods(foodsPage + 1, foodsSearch, foodsCategoryFilter)}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      {/* Food Form Dialog */}
      <Dialog open={foodDialogOpen} onOpenChange={setFoodDialogOpen}>
        <DialogContent className="max-h-[85vh] overflow-y-auto border-white/10 bg-[#111113] sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle className="text-white">
              {editingFood ? 'Edit Menu' : 'Tambah Menu Baru'}
            </DialogTitle>
            <DialogDescription className="text-white/50">
              {editingFood ? 'Ubah informasi menu' : 'Isi data menu baru'}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-2">
            {/* Nama Menu */}
            <div className="space-y-2">
              <Label htmlFor="food-name" className="text-white/80">Nama Menu <span className="text-red-400">*</span></Label>
              <Input
                id="food-name"
                placeholder="Contoh: Nasi Goreng Spesial"
                className="border-white/10 bg-[#18181b] text-white placeholder:text-white/30"
                value={foodForm.name}
                onChange={(e) => setFoodForm((p) => ({ ...p, name: e.target.value }))}
              />
            </div>

            {/* Deskripsi */}
            <div className="space-y-2">
              <Label htmlFor="food-desc" className="text-white/80">Deskripsi</Label>
              <Textarea
                id="food-desc"
                placeholder="Deskripsi singkat menu..."
                className="border-white/10 bg-[#18181b] text-white placeholder:text-white/30 min-h-[80px]"
                value={foodForm.description}
                onChange={(e) => setFoodForm((p) => ({ ...p, description: e.target.value }))}
              />
            </div>

            {/* Harga & Promo */}
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
              <div className="space-y-2">
                <Label htmlFor="food-price" className="text-white/80">Harga <span className="text-red-400">*</span></Label>
                <Input
                  id="food-price"
                  type="number"
                  placeholder="25000"
                  className="border-white/10 bg-[#18181b] text-white placeholder:text-white/30"
                  value={foodForm.price}
                  onChange={(e) => setFoodForm((p) => ({ ...p, price: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="food-disc-price" className="text-white/80">Harga Promo</Label>
                <Input
                  id="food-disc-price"
                  type="number"
                  placeholder="20000"
                  className="border-white/10 bg-[#18181b] text-white placeholder:text-white/30"
                  value={foodForm.discountPrice}
                  onChange={(e) => setFoodForm((p) => ({ ...p, discountPrice: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <Label className="text-white/80">% Diskon</Label>
                <Input
                  type="text"
                  disabled
                  placeholder="Otomatis"
                  className="border-white/10 bg-[#18181b]/50 text-white/60 placeholder:text-white/20"
                  value={foodForm.discountPercent ? `${foodForm.discountPercent}%` : ''}
                />
              </div>
            </div>

            {/* Kategori */}
            <div className="space-y-2">
              <Label className="text-white/80">Kategori <span className="text-red-400">*</span></Label>
              <Select
                value={foodForm.categoryId}
                onValueChange={(val) => setFoodForm((p) => ({ ...p, categoryId: val }))}
              >
                <SelectTrigger className="w-full border-white/10 bg-[#18181b] text-white">
                  <SelectValue placeholder="Pilih kategori..." />
                </SelectTrigger>
                <SelectContent className="border-white/10 bg-[#18181b]">
                  {categories.map((cat) => (
                    <SelectItem key={cat.id} value={cat.id} className="text-white/80 focus:bg-white/10 focus:text-white">
                      {cat.icon} {cat.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* Thumbnail URL */}
            <div className="space-y-2">
              <Label htmlFor="food-thumb" className="text-white/80">URL Gambar</Label>
              <Input
                id="food-thumb"
                placeholder="https://contoh.com/gambar.jpg"
                className="border-white/10 bg-[#18181b] text-white placeholder:text-white/30"
                value={foodForm.thumbnail}
                onChange={(e) => setFoodForm((p) => ({ ...p, thumbnail: e.target.value }))}
              />
            </div>

            {/* Switches */}
            <div className="space-y-4">
              <div className="flex items-center justify-between rounded-lg bg-[#18181b] p-3">
                <div>
                  <p className="text-sm font-medium text-white">Status Aktif</p>
                  <p className="text-xs text-white/40">Menu akan tampil di toko</p>
                </div>
                <Switch
                  checked={foodForm.isAvailable}
                  onCheckedChange={(v) => setFoodForm((p) => ({ ...p, isAvailable: v }))}
                  className="data-[state=checked]:bg-orange-500"
                />
              </div>
              <div className="flex items-center justify-between rounded-lg bg-[#18181b] p-3">
                <div>
                  <p className="text-sm font-medium text-white">Bestseller</p>
                  <p className="text-xs text-white/40">Tandai sebagai menu terlaris</p>
                </div>
                <Switch
                  checked={foodForm.isBestseller}
                  onCheckedChange={(v) => setFoodForm((p) => ({ ...p, isBestseller: v }))}
                  className="data-[state=checked]:bg-orange-500"
                />
              </div>
              <div className="flex items-center justify-between rounded-lg bg-[#18181b] p-3">
                <div>
                  <p className="text-sm font-medium text-white">Halal</p>
                  <p className="text-xs text-white/40">Tandai sebagai menu halal</p>
                </div>
                <Switch
                  checked={foodForm.isHalal}
                  onCheckedChange={(v) => setFoodForm((p) => ({ ...p, isHalal: v }))}
                  className="data-[state=checked]:bg-emerald-500"
                />
              </div>
            </div>

            {/* Badge text */}
            <div className="space-y-2">
              <Label htmlFor="food-badge" className="text-white/80">Badge</Label>
              <Input
                id="food-badge"
                placeholder="contoh: Promo, Baru, Bestseller"
                className="border-white/10 bg-[#18181b] text-white placeholder:text-white/30"
                value={foodForm.badge}
                onChange={(e) => setFoodForm((p) => ({ ...p, badge: e.target.value }))}
              />
            </div>
          </div>

          <DialogFooter className="gap-2">
            <Button
              variant="outline"
              onClick={() => setFoodDialogOpen(false)}
              className="min-h-[44px] border-white/10 bg-[#18181b] text-white/60 hover:text-white"
            >
              Batal
            </Button>
            <Button
              onClick={saveFood}
              disabled={foodSaving}
              className="min-h-[44px] bg-orange-500 hover:bg-orange-600"
            >
              {foodSaving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
              {editingFood ? 'Simpan Perubahan' : 'Tambah Menu'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );

  // ─── Categories Tab ─────────────────────────────────────────────────────

  const renderCategories = () => (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <h2 className="text-xl font-bold text-white sm:text-2xl">Kelola Kategori</h2>
        <Button
          onClick={() => openCategoryDialog()}
          className="min-h-[44px] bg-orange-500 hover:bg-orange-600"
        >
          <Plus className="mr-2 h-4 w-4" />
          Tambah Kategori
        </Button>
      </div>

      {categoriesLoading ? (
        <div className="space-y-3">
          {[...Array(4)].map((_, i) => (
            <Skeleton key={i} className="h-16 rounded-xl bg-[#18181b]" />
          ))}
        </div>
      ) : categories.length === 0 ? (
        <div className="py-12 text-center text-white/40">
          <FolderOpen className="mx-auto mb-2 h-8 w-8" />
          <p>Belum ada kategori</p>
        </div>
      ) : (
        <div className="space-y-2">
          {categories.map((cat) => (
            <div
              key={cat.id}
              className="flex items-center gap-4 rounded-xl border border-white/5 bg-[#18181b] p-4 transition-all hover:border-white/10"
            >
              <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg bg-orange-500/10 text-2xl">
                {cat.icon || '🍽️'}
              </div>
              <div className="flex-1 min-w-0">
                <h3 className="text-sm font-semibold text-white">{cat.name}</h3>
                <div className="flex flex-wrap items-center gap-2 text-xs text-white/40">
                  <span className="font-mono">{cat.slug}</span>
                  <span>•</span>
                  <span>{cat.foodCount} menu</span>
                </div>
              </div>
              <div className="flex gap-1 shrink-0">
                <Button
                  variant="ghost"
                  size="sm"
                  className="min-h-[44px] min-w-[44px] text-white/40 hover:text-orange-400 hover:bg-orange-500/10"
                  onClick={() => openCategoryDialog(cat)}
                >
                  <Pencil className="h-4 w-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  className="min-h-[44px] min-w-[44px] text-white/40 hover:text-red-400 hover:bg-red-500/10"
                  onClick={() => setDeleteTarget({ type: 'category', id: cat.id, name: cat.name })}
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Category Form Dialog */}
      <Dialog open={categoryDialogOpen} onOpenChange={setCategoryDialogOpen}>
        <DialogContent className="border-white/10 bg-[#111113] sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="text-white">
              {editingCategory ? 'Edit Kategori' : 'Tambah Kategori Baru'}
            </DialogTitle>
            <DialogDescription className="text-white/50">
              {editingCategory ? 'Ubah informasi kategori' : 'Isi data kategori baru'}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-2">
            <div className="space-y-2">
              <Label htmlFor="cat-icon" className="text-white/80">Icon (Emoji)</Label>
              <Input
                id="cat-icon"
                placeholder="🍽️"
                className="border-white/10 bg-[#18181b] text-white placeholder:text-white/30 text-xl text-center h-14"
                value={categoryForm.icon}
                onChange={(e) => setCategoryForm((p) => ({ ...p, icon: e.target.value }))}
                maxLength={4}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="cat-name" className="text-white/80">Nama Kategori <span className="text-red-400">*</span></Label>
              <Input
                id="cat-name"
                placeholder="Contoh: Makanan Berat"
                className="border-white/10 bg-[#18181b] text-white placeholder:text-white/30"
                value={categoryForm.name}
                onChange={(e) => setCategoryForm((p) => ({ ...p, name: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="cat-slug" className="text-white/80">Slug (URL)</Label>
              <Input
                id="cat-slug"
                placeholder="makanan-berat"
                className="border-white/10 bg-[#18181b] text-white placeholder:text-white/30 font-mono text-sm"
                value={categoryForm.slug}
                onChange={(e) => setCategoryForm((p) => ({ ...p, slug: e.target.value }))}
              />
              <p className="text-xs text-white/30">Otomatis dibuat dari nama. Gunakan huruf kecil dan tanda -</p>
            </div>
          </div>

          <DialogFooter className="gap-2">
            <Button
              variant="outline"
              onClick={() => setCategoryDialogOpen(false)}
              className="min-h-[44px] border-white/10 bg-[#18181b] text-white/60 hover:text-white"
            >
              Batal
            </Button>
            <Button
              onClick={saveCategory}
              disabled={categorySaving}
              className="min-h-[44px] bg-orange-500 hover:bg-orange-600"
            >
              {categorySaving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
              {editingCategory ? 'Simpan Perubahan' : 'Tambah Kategori'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );

  // ─── Settings Tab ───────────────────────────────────────────────────────

  const renderSettings = () => (
    <div className="space-y-6">
      <h2 className="text-xl font-bold text-white sm:text-2xl">Pengaturan Toko</h2>

      {settingsLoading ? (
        <div className="space-y-4">
          {[...Array(6)].map((_, i) => (
            <Skeleton key={i} className="h-16 rounded-xl bg-[#18181b]" />
          ))}
        </div>
      ) : (
        <>
          {/* Tema & Tampilan */}
          <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-5">
            <h3 className="mb-4 text-base font-semibold text-white">🎨 Tema & Tampilan</h3>
            <div className="grid gap-4 sm:grid-cols-2">
              {/* Hero Type */}
              <div className="space-y-2">
                <Label className="text-white/60 text-xs">Tipe Hero</Label>
                <Select value={settingsForm.heroType} onValueChange={(v) => setSettingsForm((p) => ({ ...p, heroType: v }))}>
                  <SelectTrigger className="border-white/10 bg-[#111113] text-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="border-white/10 bg-[#18181b]">
                    <SelectItem value="promo" className="text-white/80">Banner Promo</SelectItem>
                    <SelectItem value="products" className="text-white/80">Produk Unggulan</SelectItem>
                  </SelectContent>
                </Select>
                <p className="text-[10px] text-white/30">Pilih tampilan hero section di beranda</p>
              </div>

              {/* Theme Mode */}
              <div className="space-y-2">
                <Label className="text-white/60 text-xs">Mode Tema</Label>
                <Select value={settingsForm.themeMode} onValueChange={(v) => setSettingsForm((p) => ({ ...p, themeMode: v }))}>
                  <SelectTrigger className="border-white/10 bg-[#111113] text-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="border-white/10 bg-[#18181b]">
                    <SelectItem value="light" className="text-white/80">☀️ Terang (Putih)</SelectItem>
                    <SelectItem value="dark" className="text-white/80">🌙 Gelap (Hitam)</SelectItem>
                  </SelectContent>
                </Select>
                <p className="text-[10px] text-white/30">Tema terang atau gelap untuk website</p>
              </div>

              {/* Accent Color */}
              <div className="space-y-2 sm:col-span-2">
                <Label className="text-white/60 text-xs">Warna Aksen</Label>
                <div className="flex flex-wrap gap-2">
                  {[
                    { value: 'orange', label: 'Jingga', color: '#f97316' },
                    { value: 'red', label: 'Merah', color: '#ef4444' },
                    { value: 'purple', label: 'Ungu', color: '#a855f7' },
                    { value: 'blue', label: 'Biru', color: '#3b82f6' },
                  ].map((c) => (
                    <button
                      key={c.value}
                      onClick={() => setSettingsForm((p) => ({ ...p, accentColor: c.value }))}
                      className={`flex items-center gap-2 rounded-lg border px-3 py-2 text-xs font-medium transition-all ${
                        settingsForm.accentColor === c.value
                          ? 'border-white/30 bg-white/10 text-white'
                          : 'border-white/5 bg-[#111113] text-white/50 hover:bg-white/5 hover:text-white/80'
                      }`}
                    >
                      <span className="h-4 w-4 rounded-full" style={{ backgroundColor: c.color }} />
                      {c.label}
                      {settingsForm.accentColor === c.value && <Check className="h-3 w-3" />}
                    </button>
                  ))}
                </div>
                <p className="text-[10px] text-white/30">Warna utama untuk tombol, badge, dan aksen</p>
              </div>
            </div>
          </div>

          {/* Informasi Toko */}
          <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-6 space-y-4">
            <h3 className="text-lg font-semibold text-white">Informasi Toko</h3>
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label className="text-white/80">Nama Toko</Label>
                <Input
                  className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                  value={settingsForm.storeName}
                  onChange={(e) => setSettingsForm((p) => ({ ...p, storeName: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <Label className="text-white/80">Email</Label>
                <Input
                  className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                  value={settingsForm.email}
                  onChange={(e) => setSettingsForm((p) => ({ ...p, email: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <Label className="text-white/80">URL Logo Toko</Label>
                <Input
                  placeholder="https://contoh.com/logo.png"
                  className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                  value={settingsForm.logoUrl}
                  onChange={(e) => setSettingsForm((p) => ({ ...p, logoUrl: e.target.value }))}
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label className="text-white/80">Deskripsi Toko</Label>
              <Textarea
                className="border-white/10 bg-[#111113] text-white placeholder:text-white/30 min-h-[80px]"
                value={settingsForm.storeDesc}
                onChange={(e) => setSettingsForm((p) => ({ ...p, storeDesc: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label className="text-white/80">Alamat</Label>
              <Textarea
                className="border-white/10 bg-[#111113] text-white placeholder:text-white/30 min-h-[60px]"
                value={settingsForm.address}
                onChange={(e) => setSettingsForm((p) => ({ ...p, address: e.target.value }))}
              />
            </div>
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label className="text-white/80">Telepon</Label>
                <Input
                  className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                  value={settingsForm.phone}
                  onChange={(e) => setSettingsForm((p) => ({ ...p, phone: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <Label className="text-white/80">WhatsApp</Label>
                <Input
                  className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                  value={settingsForm.whatsapp}
                  onChange={(e) => setSettingsForm((p) => ({ ...p, whatsapp: e.target.value }))}
                />
              </div>
            </div>
            <div className="space-y-2 sm:col-span-2">
              <Label className="text-white/80">Pesan Otomatis WhatsApp</Label>
              <Textarea
                placeholder="Pesan awal yang dikirim saat pelanggan klik tombol WhatsApp..."
                className="border-white/10 bg-[#111113] text-white placeholder:text-white/30 min-h-[80px]"
                value={settingsForm.autoMessage}
                onChange={(e) => setSettingsForm((p) => ({ ...p, autoMessage: e.target.value }))}
              />
              <p className="text-[10px] text-white/30">Pesan ini akan dikirim otomatis saat pelanggan klik tombol WhatsApp</p>
            </div>
          </div>

          {/* WhatsApp & Social Media */}
          <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-6 space-y-4">
            <h3 className="text-lg font-semibold text-white">WhatsApp & Media Sosial</h3>
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label className="text-white/80">Instagram</Label>
                <Input
                  placeholder="username"
                  className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                  value={settingsForm.instagram}
                  onChange={(e) => setSettingsForm((p) => ({ ...p, instagram: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <Label className="text-white/80">Facebook</Label>
                <Input
                  placeholder="username"
                  className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                  value={settingsForm.facebook}
                  onChange={(e) => setSettingsForm((p) => ({ ...p, facebook: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <Label className="text-white/80">Twitter / X</Label>
                <Input
                  placeholder="username"
                  className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                  value={settingsForm.twitter}
                  onChange={(e) => setSettingsForm((p) => ({ ...p, twitter: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <Label className="text-white/80">TikTok</Label>
                <Input
                  placeholder="username"
                  className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                  value={settingsForm.tiktok}
                  onChange={(e) => setSettingsForm((p) => ({ ...p, tiktok: e.target.value }))}
                />
              </div>
            </div>
          </div>

          {/* Pengiriman */}
          <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-6 space-y-4">
            <h3 className="text-lg font-semibold text-white">Pengiriman</h3>
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label className="text-white/80">Gratis Ongkir (Minimal Belanja, Rp)</Label>
                <Input
                  type="number"
                  className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                  value={settingsForm.freeShippingThreshold}
                  onChange={(e) => setSettingsForm((p) => ({ ...p, freeShippingThreshold: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <Label className="text-white/80">Biaya Ongkir (Rp)</Label>
                <Input
                  type="number"
                  className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                  value={settingsForm.shippingRate}
                  onChange={(e) => setSettingsForm((p) => ({ ...p, shippingRate: e.target.value }))}
                />
              </div>
            </div>
            <div className="flex items-center justify-between rounded-lg bg-[#111113] p-3">
              <div>
                <p className="text-sm font-medium text-white">Bayar di Tempat (COD)</p>
                <p className="text-xs text-white/40">Izinkan pembayaran COD</p>
              </div>
              <Switch
                checked={settingsForm.codAvailable}
                onCheckedChange={(v) => setSettingsForm((p) => ({ ...p, codAvailable: v }))}
                className="data-[state=checked]:bg-emerald-500"
              />
            </div>
          </div>

          {/* QRIS */}
          <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-6 space-y-4">
            <h3 className="text-lg font-semibold text-white">QRIS</h3>
            <div className="space-y-2">
              <Label className="text-white/80">URL Gambar QRIS</Label>
              <Input
                placeholder="https://contoh.com/qris.png"
                className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                value={settingsForm.qrisImage}
                onChange={(e) => setSettingsForm((p) => ({ ...p, qrisImage: e.target.value }))}
              />
            </div>
          </div>

          {/* Hero Banner */}
          <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-6 space-y-4">
            <h3 className="text-lg font-semibold text-white">Hero Banner</h3>
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label className="text-white/80">Label Promo</Label>
                <Input
                  placeholder="🎉 Special Offer"
                  className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                  value={settingsForm.heroPromoLabel}
                  onChange={(e) => setSettingsForm((p) => ({ ...p, heroPromoLabel: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <Label className="text-white/80">Judul Utama</Label>
                <Input
                  placeholder="20% OFF"
                  className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                  value={settingsForm.heroPromoTitle1}
                  onChange={(e) => setSettingsForm((p) => ({ ...p, heroPromoTitle1: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <Label className="text-white/80">Judul Kedua</Label>
                <Input
                  placeholder="Your First Order!"
                  className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                  value={settingsForm.heroPromoTitle2}
                  onChange={(e) => setSettingsForm((p) => ({ ...p, heroPromoTitle2: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <Label className="text-white/80">Kode Promo</Label>
                <Input
                  placeholder="WELCOME20"
                  className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                  value={settingsForm.heroPromoCode}
                  onChange={(e) => setSettingsForm((p) => ({ ...p, heroPromoCode: e.target.value }))}
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label className="text-white/80">Deskripsi Promo</Label>
              <Input
                placeholder="Gunakan kode di checkout"
                className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                value={settingsForm.heroPromoDesc}
                onChange={(e) => setSettingsForm((p) => ({ ...p, heroPromoDesc: e.target.value }))}
              />
            </div>
          </div>

          {/* Google Maps */}
          <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-6 space-y-4">
            <h3 className="text-lg font-semibold text-white">Google Maps</h3>
            <div className="space-y-2">
              <Label className="text-white/80">URL Embed Google Maps</Label>
              <Input
                placeholder="https://www.google.com/maps/embed?..."
                className="border-white/10 bg-[#111113] text-white placeholder:text-white/30"
                value={settingsForm.googleMapsEmbed}
                onChange={(e) => setSettingsForm((p) => ({ ...p, googleMapsEmbed: e.target.value }))}
              />
            </div>
          </div>

          {/* Save Button */}
          <div className="flex justify-end pt-2">
            <Button
              onClick={saveSettings}
              disabled={settingsSaving}
              className="min-h-[48px] min-w-[160px] bg-orange-500 hover:bg-orange-600 text-base font-semibold"
            >
              {settingsSaving ? <Loader2 className="mr-2 h-5 w-5 animate-spin" /> : null}
              Simpan Pengaturan
            </Button>
          </div>
        </>
      )}
    </div>
  );

  // ─── Analytics Tab ──────────────────────────────────────────────────────

  const renderAnalytics = () => {
    const maxViews = Math.max(...analytics.last7Days.map((d) => d.views), 1);
    const maxVisitors = Math.max(...analytics.last7Days.map((d) => d.visitors), 1);

    return (
      <div className="space-y-6">
        <h2 className="text-xl font-bold text-white sm:text-2xl">Analitik Pengunjung</h2>

        {analyticsLoading ? (
          <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
            {[...Array(4)].map((_, i) => (
              <Skeleton key={i} className="h-28 rounded-xl bg-[#18181b]" />
            ))}
          </div>
        ) : (
          <>
            {/* Stat Cards */}
            <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
              <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-5">
                <div className="mb-3 flex items-center gap-2">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-500/15">
                    <EyeIcon className="h-5 w-5 text-blue-400" />
                  </div>
                </div>
                <p className="text-2xl font-bold text-white sm:text-3xl">{analytics.totalViews.toLocaleString('id-ID')}</p>
                <p className="mt-1 text-xs text-white/50 sm:text-sm">Total Kunjungan</p>
              </div>

              <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-5">
                <div className="mb-3 flex items-center gap-2">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-emerald-500/15">
                    <Users className="h-5 w-5 text-emerald-400" />
                  </div>
                </div>
                <p className="text-2xl font-bold text-white sm:text-3xl">{analytics.totalVisitors.toLocaleString('id-ID')}</p>
                <p className="mt-1 text-xs text-white/50 sm:text-sm">Total Pengunjung Unik</p>
              </div>

              <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-5">
                <div className="mb-3 flex items-center gap-2">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-orange-500/15">
                    <EyeIcon className="h-5 w-5 text-orange-400" />
                  </div>
                </div>
                <p className="text-2xl font-bold text-white sm:text-3xl">{analytics.todayViews.toLocaleString('id-ID')}</p>
                <p className="mt-1 text-xs text-white/50 sm:text-sm">Kunjungan Hari Ini</p>
              </div>

              <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-5">
                <div className="mb-3 flex items-center gap-2">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-purple-500/15">
                    <Users className="h-5 w-5 text-purple-400" />
                  </div>
                </div>
                <p className="text-2xl font-bold text-white sm:text-3xl">{analytics.todayVisitors.toLocaleString('id-ID')}</p>
                <p className="mt-1 text-xs text-white/50 sm:text-sm">Pengunjung Hari Ini</p>
              </div>
            </div>

            {/* 7-Day Chart */}
            <div className="rounded-xl border border-white/5 bg-[#18181b] p-4 sm:p-6">
              <div className="mb-6 flex items-center gap-2">
                <Calendar className="h-5 w-5 text-white/50" />
                <h3 className="text-lg font-semibold text-white">7 Hari Terakhir</h3>
              </div>

              <div className="space-y-3">
                {analytics.last7Days.map((day) => {
                  const d = new Date(day.date + 'T00:00:00');
                  const dayName = new Intl.DateTimeFormat('id-ID', { weekday: 'short', day: 'numeric', month: 'short' }).format(d);
                  const isCurrentDay = day.date === new Date().toISOString().split('T')[0];

                  return (
                    <div key={day.date} className="space-y-1.5">
                      <div className="flex items-center justify-between">
                        <span className={`text-xs font-medium ${isCurrentDay ? 'text-orange-400' : 'text-white/60'}`}>
                          {dayName} {isCurrentDay ? '(Hari ini)' : ''}
                        </span>
                        <div className="flex items-center gap-3 text-xs text-white/40">
                          <span className="flex items-center gap-1">
                            <EyeIcon className="h-3 w-3" /> {day.views}
                          </span>
                          <span className="flex items-center gap-1">
                            <Users className="h-3 w-3" /> {day.visitors}
                          </span>
                        </div>
                      </div>
                      <div className="flex gap-2">
                        <div className="flex-1">
                          <div className="h-3 w-full rounded-full bg-white/5">
                            <div
                              className="h-full rounded-full bg-blue-500/70 transition-all duration-500"
                              style={{ width: `${Math.max((day.views / maxViews) * 100, day.views > 0 ? 4 : 0)}%` }}
                            />
                          </div>
                        </div>
                        <div className="flex-1">
                          <div className="h-3 w-full rounded-full bg-white/5">
                            <div
                              className="h-full rounded-full bg-emerald-500/70 transition-all duration-500"
                              style={{ width: `${Math.max((day.visitors / maxVisitors) * 100, day.visitors > 0 ? 4 : 0)}%` }}
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>

              {/* Legend */}
              <div className="mt-4 flex items-center justify-center gap-6">
                <div className="flex items-center gap-2">
                  <div className="h-3 w-6 rounded-full bg-blue-500/70" />
                  <span className="text-xs text-white/40">Kunjungan</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="h-3 w-6 rounded-full bg-emerald-500/70" />
                  <span className="text-xs text-white/40">Pengunjung Unik</span>
                </div>
              </div>
            </div>
          </>
        )}
      </div>
    );
  };

  // ─── Delete Confirmation Dialog ─────────────────────────────────────────

  const renderDeleteDialog = () => (
    <AlertDialog open={!!deleteTarget} onOpenChange={() => setDeleteTarget(null)}>
      <AlertDialogContent className="border-white/10 bg-[#111113]">
        <AlertDialogHeader>
          <AlertDialogTitle className="text-white">Hapus {deleteTarget?.type === 'food' ? 'Menu' : deleteTarget?.type === 'invoice' ? 'Invoice' : 'Kategori'}?</AlertDialogTitle>
          <AlertDialogDescription className="text-white/50">
            {deleteTarget?.type === 'invoice'
              ? `Invoice "${deleteTarget?.name}" akan dihapus secara permanen.`
              : deleteTarget?.type === 'food'
              ? `Menu "${deleteTarget?.name}" akan dinonaktifkan (tidak ditampilkan di toko).`
              : `Kategori "${deleteTarget?.name}" akan dihapus secara permanen. Pastikan kategori ini tidak memiliki menu.`}
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter className="gap-2">
          <AlertDialogCancel className="min-h-[44px] border-white/10 bg-[#18181b] text-white/60 hover:text-white">
            Batal
          </AlertDialogCancel>
          <AlertDialogAction
            onClick={deleteTarget?.type === 'food' ? handleDeleteFood : deleteTarget?.type === 'invoice' ? handleDeleteInvoice : handleDeleteCategory}
            disabled={deleting}
            className="min-h-[44px] bg-red-500 hover:bg-red-600 text-white"
          >
            {deleting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
            Ya, {deleteTarget?.type === 'food' ? 'Nonaktifkan' : 'Hapus'}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );

  // ─── Main Render ────────────────────────────────────────────────────────

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex bg-[#0a0a0b]">
      {/* Mobile sidebar overlay */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 z-40 bg-black/60 md:hidden"
          onClick={() => setSidebarOpen(false)}
        />
      )}

      {/* Sidebar */}
      <aside
        className={`fixed left-0 top-0 z-50 flex h-full w-72 flex-col border-r border-white/5 bg-[#111113] transition-transform duration-300 md:relative md:z-0 md:translate-x-0 ${
          sidebarOpen ? 'translate-x-0' : '-translate-x-full'
        }`}
      >
        {/* Logo & Close */}
        <div className="flex items-center justify-between px-4 py-5 border-b border-white/5">
          <div className="flex items-center gap-2">
            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-orange-500">
              <span className="text-lg">🏪</span>
            </div>
            <span className="text-base font-bold text-white">FoodMart Admin</span>
          </div>
          <Button
            variant="ghost"
            size="sm"
            className="min-h-[44px] min-w-[44px] text-white/40 hover:text-white hover:bg-white/10 md:hidden"
            onClick={() => setSidebarOpen(false)}
          >
            <X className="h-5 w-5" />
          </Button>
        </div>

        {/* Navigation */}
        <nav className="flex-1 space-y-1 p-3">
          {NAV_ITEMS.map((item) => (
            <button
              key={item.id}
              onClick={() => setActiveTab(item.id)}
              className={`flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium transition-all min-h-[44px] ${
                activeTab === item.id
                  ? 'bg-orange-500/15 text-orange-400 border border-orange-500/30'
                  : 'text-white/50 hover:bg-white/5 hover:text-white border border-transparent'
              }`}
            >
              {item.icon}
              {item.label}
            </button>
          ))}
        </nav>

        {/* Close Admin */}
        <div className="border-t border-white/5 p-3">
          <Button
            variant="ghost"
            className="w-full min-h-[44px] justify-start gap-3 text-white/40 hover:text-red-400 hover:bg-red-500/10"
            onClick={() => onOpenChange(false)}
          >
            <X className="h-5 w-5" />
            Tutup Admin Panel
          </Button>
        </div>
      </aside>

      {/* Main Content */}
      <main className="flex-1 overflow-y-auto">
        {/* Top Bar */}
        <div className="sticky top-0 z-30 flex items-center gap-3 border-b border-white/5 bg-[#0a0a0b]/95 px-4 py-3 backdrop-blur-md">
          <Button
            variant="ghost"
            size="sm"
            className="min-h-[44px] min-w-[44px] text-white/60 hover:text-white hover:bg-white/10 md:hidden"
            onClick={() => setSidebarOpen(true)}
          >
            <Menu className="h-5 w-5" />
          </Button>
          <h1 className="text-base font-semibold text-white sm:text-lg">
            {NAV_ITEMS.find((n) => n.id === activeTab)?.label || 'Dashboard'}
          </h1>
        </div>

        {/* Content Area */}
        <div className="p-4 sm:p-6 lg:p-8">
          {activeTab === 'dashboard' && renderDashboard()}
          {activeTab === 'orders' && renderOrders()}
          {activeTab === 'menu' && renderMenu()}
          {activeTab === 'categories' && renderCategories()}
          {activeTab === 'settings' && renderSettings()}
          {activeTab === 'analytics' && renderAnalytics()}
        </div>
      </main>

      {/* Delete Dialog */}
      {renderDeleteDialog()}
    </div>
  );
}
