'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import { Search, Download, RefreshCw, Phone, MessageSquare, ChevronUp, ChevronDown, Eye, Trash2, CheckSquare, Square, ChevronLeft, ChevronRight, ShoppingBag, FileSpreadsheet, ChevronDown as ChevronDownIcon, Bell, X, Calendar, Star, Globe, Monitor, Zap, UtensilsCrossed, MessageCircle, Mail } from 'lucide-react';
import StatusBadge from '@client/components/ui/StatusBadge';
import DemoDisabled from '@client/components/demo/DemoDisabled';
import ConfirmModal from '@client/components/ui/ConfirmModal';
import SuccessModal from '@client/components/ui/SuccessModal';
import OrderDetailModal, { type Order } from './OrderDetailModal';
import OrderEditPanel from './OrderEditPanel';
import { toast } from 'sonner';
import { listOrders, updateOrder, deleteOrder } from '@client/api/orders';
import { useAuth } from '@client/contexts/AuthContext';
import { InlineTableSkeleton } from '@client/components/skeletons/PageSkeletons';
import { usePolling, formatLastUpdated } from '@client/hooks/usePolling';
import { formatOid } from '@client/utils/formatOid';
import { useCurrency } from '@client/hooks/useCurrency';
import { useLanguage } from '@client/contexts/LanguageContext';

function playNewOrderChime() {
  try {
    const AudioCtx = window.AudioContext || (window as any).webkitAudioContext;
    if (!AudioCtx) return;
    const ctx = new AudioCtx();
    const notes = [523.25, 659.25, 783.99];
    notes.forEach((freq, i) => {
      const osc = ctx.createOscillator();
      const gain = ctx.createGain();
      osc.connect(gain);
      gain.connect(ctx.destination);
      osc.type = 'sine';
      osc.frequency.value = freq;
      const start = ctx.currentTime + i * 0.18;
      gain.gain.setValueAtTime(0, start);
      gain.gain.linearRampToValueAtTime(0.25, start + 0.04);
      gain.gain.exponentialRampToValueAtTime(0.001, start + 0.55);
      osc.start(start);
      osc.stop(start + 0.6);
    });
  } catch {
    // audio not available
  }
}

const STATUS_TABS = [
  { label: 'All Orders', value: 'all' },
  { label: 'Pending', value: 'pending' },
  { label: 'AI Processing', value: 'processing' },
  { label: 'Confirmed', value: 'confirmed' },
  { label: 'In Kitchen', value: 'kitchen' },
  { label: 'Ready', value: 'ready' },
  { label: 'With Rider', value: 'rider' },
  { label: 'Delivered', value: 'delivered' },
  { label: 'Completed', value: 'completed' },
  { label: 'Escalated', value: 'escalated' },
  { label: 'Cancelled', value: 'cancelled' },
];

const BULK_STATUS_OPTIONS = [
  { value: 'confirmed', label: 'Confirmed' },
  { value: 'kitchen', label: 'In Kitchen' },
  { value: 'ready', label: 'Ready' },
  { value: 'delivered', label: 'Delivered' },
  { value: 'completed', label: 'Completed' },
  { value: 'cancelled', label: 'Cancelled' },
];

const CHANNEL_CONFIG: Record<string, { icon: React.ReactNode; label: string; bg: string; color: string }> = {
  voice:     { icon: <Phone size={11} />,           label: 'Voice',     bg: 'hsl(142 60% 90%)', color: 'hsl(142 65% 28%)' },
  chat:      { icon: <MessageSquare size={11} />,   label: 'Chat',      bg: 'hsl(215 80% 92%)', color: 'hsl(215 75% 38%)' },
  whatsapp:  { icon: <MessageCircle size={11} />,   label: 'WhatsApp',  bg: 'hsl(145 70% 88%)', color: 'hsl(145 60% 26%)' },
  online:    { icon: <Globe size={11} />,           label: 'Online',    bg: 'hsl(197 90% 90%)', color: 'hsl(197 80% 32%)' },
  pos:       { icon: <Monitor size={11} />,         label: 'POS',       bg: 'hsl(270 60% 92%)', color: 'hsl(270 60% 38%)' },
  zomato:    { icon: <UtensilsCrossed size={11} />, label: 'Zomato',    bg: 'hsl(0 90% 92%)',   color: 'hsl(0 75% 38%)' },
  swiggy:    { icon: <Zap size={11} />,             label: 'Swiggy',    bg: 'hsl(25 100% 90%)', color: 'hsl(20 80% 36%)' },
  email:     { icon: <Mail size={11} />,            label: 'Email',     bg: 'hsl(240 50% 92%)', color: 'hsl(240 55% 40%)' },
  sms:       { icon: <MessageSquare size={11} />,   label: 'SMS',       bg: 'hsl(180 50% 90%)', color: 'hsl(180 55% 28%)' },
};

const CHANNEL_FILTERS = [
  { label: 'All',      value: 'all' },
  { label: 'POS',      value: 'pos' },
  { label: 'Zomato',   value: 'zomato' },
  { label: 'Swiggy',   value: 'swiggy' },
  { label: 'Online',   value: 'online' },
  { label: 'Chat',     value: 'chat' },
  { label: 'Voice',    value: 'voice' },
  { label: 'WhatsApp', value: 'whatsapp' },
];

function dbRowToOrder(row: any): Order {
  const rawItems = Array.isArray(row.items) ? row.items : [];
  return {
    id: row.id,
    orderNumber: row.orderNumber !== undefined ? Number(row.orderNumber) : (row.order_number !== undefined ? Number(row.order_number) : undefined),
    restaurantId: row.restaurantId || row.restaurant_id || undefined,
    customerName: row.customerName || row.customer_name || 'Unknown',
    customerPhone: row.customerPhone || row.customer_phone || '',
    channel: row.channel || 'chat',
    status: row.status || 'pending',
    items: rawItems.map((item: any) => ({
      name: item.name || '',
      qty: Number(item.qty ?? item.quantity ?? 1),
      price: Number(item.price ?? 0),
      modifiers: item.modifiers,
      // Real per-item customer notes only — never fall back to `item.notes`,
      // which `normalizeOrderItem` may synthesize from joined modifier strings.
      note: item.note ?? undefined,
    })),
    subtotal: Number(row.subtotal) || 0,
    tax: Number(row.tax) || 0,
    total: Number(row.total) || 0,
    aiConfidence: row.aiConfidence !== undefined ? row.aiConfidence : (row.ai_confidence !== undefined ? row.ai_confidence : null),
    placedAt: (() => {
      const raw = row.placedAt || row.created_at || row.createdAt || '';
      if (!raw) return '';
      const d = new Date(raw);
      if (isNaN(d.getTime())) return String(raw);
      return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) + ' ' +
        (d.toDateString() === new Date().toDateString() ? 'today' : d.toLocaleDateString());
    })(),
    agentId: row.agentId || row.agent_id || '',
    conversationId: row.conversationId || row.conversation_id || '',
    isModified: row.isModified || row.is_modified || false,
    modificationNote: row.modificationNote || row.modification_note || '',
    deliveryType: row.deliveryType || row.delivery_type || 'dine-in',
    tableNumber: row.tableNumber || row.table_number || '',
    deliveryAddress: row.deliveryAddress || row.delivery_address || '',
    specialInstructions: row.specialInstructions || row.special_instructions || '',
    transcriptSummary: row.transcriptSummary || row.transcript_summary || '',
    couponCode: row.couponCode != null ? String(row.couponCode) : (row.coupon_code != null ? String(row.coupon_code) : null),
    discountAmount: row.discountAmount != null ? Number(row.discountAmount) : (row.discount_amount != null ? Number(row.discount_amount) : 0),
    loyaltyPointsRedeemed: row.loyaltyPointsRedeemed != null ? Number(row.loyaltyPointsRedeemed) : (row.loyalty_points_redeemed != null ? Number(row.loyalty_points_redeemed) : 0),
    loyaltyPointsEarned: row.loyaltyPointsEarned != null ? Number(row.loyaltyPointsEarned) : (row.loyalty_points_earned != null ? Number(row.loyalty_points_earned) : 0),
    loyaltyDiscount: row.loyaltyDiscount != null ? Number(row.loyaltyDiscount) : (row.loyalty_discount != null ? Number(row.loyalty_discount) : 0),
    giftCardApplied: row.giftCardApplied != null ? Number(row.giftCardApplied) : (row.gift_card_applied != null ? Number(row.gift_card_applied) : 0),
    giftCardId: row.giftCardId != null ? String(row.giftCardId) : (row.gift_card_id != null ? String(row.gift_card_id) : null),
  };
}

export default function OrdersTable() {
  const { restaurantId } = useAuth();
  const { format: fc } = useCurrency();
  const { t } = useLanguage();

  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('all');
  const [activeChannel, setActiveChannel] = useState('all');
  const [search, setSearch] = useState('');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [sortField, setSortField] = useState<string>('created_at');
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc');
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [totalCount, setTotalCount] = useState(0);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [detailOrder, setDetailOrder] = useState<Order | null>(null);
  const [confirmDelete, setConfirmDelete] = useState(false);
  const [successModal, setSuccessModal] = useState<{ open: boolean; title: string; description?: string }>({ open: false, title: '' });
  const [exportMenuOpen, setExportMenuOpen] = useState(false);
  const [bulkStatusOpen, setBulkStatusOpen] = useState(false);
  const [nowTick, setNowTick] = useState(0);
  const [newOrderAlert, setNewOrderAlert] = useState<Order[]>([]);
  const [editOrder, setEditOrder] = useState<Order | null>(null);
  const knownOrderIdsRef = useRef<Set<string> | null>(null);
  const hasActiveFiltersRef = useRef(false);

  // tick every 15s to keep "last updated X ago" text fresh
  useEffect(() => {
    const t = setInterval(() => setNowTick(n => n + 1), 15000);
    return () => clearInterval(t);
  }, []);

  const [foregroundLastUpdated, setForegroundLastUpdated] = useState<Date | null>(null);

  const fetchOrders = useCallback(async () => {
    if (!restaurantId) { setLoading(false); return; }
    setLoading(true);
    try {
      const params: Record<string, string> = {
        page: String(page),
        limit: String(pageSize),
        sort_field: sortField,
        sort_dir: sortDir,
      };
      if (activeTab !== 'all') params.status = activeTab;
      if (activeChannel !== 'all') params.channel = activeChannel;
      if (search) params.search = search;
      if (dateFrom) params.start_date = dateFrom;
      if (dateTo) params.end_date = dateTo + 'T23:59:59';
      const result = await listOrders(params);
      const mapped = (result.orders || []).map(dbRowToOrder);
      setOrders(mapped);
      setTotalCount(result.total || 0);
      setForegroundLastUpdated(new Date());
      if (knownOrderIdsRef.current === null) {
        knownOrderIdsRef.current = new Set(mapped.map(o => o.id));
      } else {
        mapped.forEach(o => knownOrderIdsRef.current!.add(o.id));
      }
    } catch (err: any) {
      toast.error(t('orderManagement.loadFailed', 'Failed to load orders: ') + err.message);
    } finally {
      setLoading(false);
    }
  }, [restaurantId, activeTab, activeChannel, search, dateFrom, dateTo, sortField, sortDir, page, pageSize, t]);

  // Track whether user has active filters (for polling logic)
  useEffect(() => {
    hasActiveFiltersRef.current = activeTab !== 'all' || activeChannel !== 'all' || !!search || !!dateFrom || !!dateTo || page > 1 || sortField !== 'created_at' || sortDir !== 'desc';
  }, [activeTab, activeChannel, search, dateFrom, dateTo, page, sortField, sortDir]);

  // show skeleton when filters/sort/page change (includes initial mount)
  useEffect(() => {
    fetchOrders();
  }, [fetchOrders]);

  // silent background polling — no skeleton, no error toast
  const silentFetch = useCallback(async () => {
    if (!restaurantId) return;
    try {
      const params: Record<string, string> = {
        page: '1',
        limit: String(pageSize),
        sort_field: 'created_at',
        sort_dir: 'desc',
      };
      const result = await listOrders(params);
      const incoming = (result.orders || []).map(dbRowToOrder);

      if (knownOrderIdsRef.current === null) {
        knownOrderIdsRef.current = new Set(incoming.map(o => o.id));
      } else {
        const freshOnes = incoming.filter(o => !knownOrderIdsRef.current!.has(o.id));
        if (freshOnes.length > 0) {
          freshOnes.forEach(o => knownOrderIdsRef.current!.add(o.id));
          playNewOrderChime();
          setNewOrderAlert(prev => [...freshOnes, ...prev]);
        }
      }

      // Only update displayed orders if user is on the default unfiltered view
      if (!hasActiveFiltersRef.current) {
        setOrders(incoming);
        setTotalCount(result.total || 0);
      }
    } catch {
      // silently ignore polling errors
    }
  }, [restaurantId, pageSize]);

  const { lastUpdated, trigger: manualRefresh } = usePolling(silentFetch, {
    intervalMs: 30000,
    enabled: !!restaurantId,
    runOnMount: false,
  });

  const handleUpdateStatus = async (orderId: string, newStatus: string) => {
    try {
      await updateOrder(orderId, { status: newStatus });
      setOrders(prev => prev.map(o => o.id === orderId ? { ...o, status: newStatus } : o));
      toast.success(t('orderManagement.statusUpdated', 'Order status updated'));
    } catch (err: any) {
      toast.error(t('orderManagement.updateFailed', 'Failed to update order: ') + err.message);
    }
  };

  const handleBulkStatus = async (newStatus: string) => {
    setBulkStatusOpen(false);
    try {
      await Promise.all(selectedIds.map(id => updateOrder(id, { status: newStatus })));
      setOrders(prev => prev.map(o => selectedIds.includes(o.id) ? { ...o, status: newStatus } : o));
      const label = BULK_STATUS_OPTIONS.find(s => s.value === newStatus)?.label ?? newStatus;
      toast.success(t('orderManagement.bulkStatusUpdated', `${selectedIds.length} order${selectedIds.length > 1 ? 's' : ''} marked as ${label}`, { count: selectedIds.length, label }));
      setSelectedIds([]);
    } catch (err: any) {
      toast.error(t('orderManagement.bulkUpdateFailed', 'Failed to update orders: ') + err.message);
    }
  };

  const handleDelete = async (orderIds: string[]) => {
    try {
      await Promise.all(orderIds.map(id => deleteOrder(id)));
      setOrders(prev => prev.filter(o => !orderIds.includes(o.id)));
      setSelectedIds([]);
      setConfirmDelete(false);
      setSuccessModal({ open: true, title: t('orderManagement.deletedTitle', `${orderIds.length} order${orderIds.length > 1 ? 's' : ''} deleted`, { count: orderIds.length }) });
    } catch (err: any) {
      toast.error(t('orderManagement.deleteFailed', 'Failed to delete orders: ') + err.message);
    }
  };

  const handleSort = (field: string) => {
    if (sortField === field) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortField(field); setSortDir('desc'); }
  };

  const toggleRow = (id: string) => setSelectedIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  const toggleAll = () => setSelectedIds(selectedIds.length === orders.length ? [] : orders.map(o => o.id));

  const exportCSV = () => {
    const data = selectedIds.length > 0 ? orders.filter(o => selectedIds.includes(o.id)) : orders;
    const headers = [
      'Order #', 'Order ID', 'Customer Name', 'Customer Phone', 'Channel',
      'Delivery Type', 'Delivery Address', 'Table Number',
      'Items', 'Subtotal', 'Tax', 'Total',
      'Status', 'Placed At', 'Special Instructions', 'Modified',
    ];
    const rows = data.map(o => [
      formatOid(o.orderNumber, o.id, o.restaurantId),
      o.id,
      o.customerName,
      o.customerPhone || '',
      o.channel,
      o.deliveryType || '',
      o.deliveryAddress || '',
      o.tableNumber || '',
      Array.isArray(o.items) ? o.items.map(i => `${i.qty}x ${i.name} (${fc(Number(i.price))})`).join('; ') : '',
      fc(Number(o.subtotal || 0)),
      fc(Number(o.tax || 0)),
      fc(Number(o.total)),
      o.status,
      o.createdAt ? new Date(o.createdAt).toISOString() : (o.placedAt || ''),
      o.specialInstructions || '',
      o.isModified ? 'Yes' : 'No',
    ]);
    const csv = [headers, ...rows].map(r => r.map(v => `"${String(v).replace(/"/g, '""')}"`).join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = `orders-${new Date().toISOString().slice(0, 10)}.csv`; a.click();
    URL.revokeObjectURL(url);
    setExportMenuOpen(false);
    toast.success(t('orderManagement.exported', 'Orders exported'));
  };

  const totalPages = Math.ceil(totalCount / pageSize);

  const SortIcon = ({ field }: { field: string }) => (
    sortField === field
      ? sortDir === 'asc' ? <ChevronUp size={12} /> : <ChevronDown size={12} />
      : <ChevronDown size={12} style={{ opacity: 0.3 }} />
  );

  // show whichever timestamp is most recent: background poll or foreground load
  const displayLastUpdated = lastUpdated && foregroundLastUpdated
    ? (lastUpdated > foregroundLastUpdated ? lastUpdated : foregroundLastUpdated)
    : (lastUpdated ?? foregroundLastUpdated);

  void nowTick; // trigger re-render for "ago" text

  return (
    <div className="card overflow-hidden">
      <div className="flex overflow-x-auto" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
        {STATUS_TABS.map(tab => (
          <button
            key={tab.value}
            onClick={() => { setActiveTab(tab.value); setPage(1); }}
            className="px-4 py-3 text-xs font-semibold whitespace-nowrap transition-colors"
            style={{ color: activeTab === tab.value ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))', borderBottom: activeTab === tab.value ? '2px solid hsl(var(--primary))' : '2px solid transparent' }}
          >
            {t(`orderManagement.tabs.${tab.value}`, tab.label)}
          </button>
        ))}
      </div>

      {/* Channel filter chips */}
      <div className="flex items-center gap-2 px-4 py-2.5 overflow-x-auto" style={{ borderBottom: '1px solid hsl(var(--border))', backgroundColor: 'hsl(var(--muted) / 0.35)' }}>
        <span className="text-xs font-medium shrink-0" style={{ color: 'hsl(var(--muted-foreground))' }}>
          {t('orderManagement.channelFilter', 'Channel:')}
        </span>
        {CHANNEL_FILTERS.map(ch => {
          const cfg = CHANNEL_CONFIG[ch.value];
          const isActive = activeChannel === ch.value;
          return (
            <button
              key={ch.value}
              onClick={() => { setActiveChannel(ch.value); setPage(1); }}
              className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold whitespace-nowrap transition-all shrink-0"
              style={isActive
                ? { backgroundColor: cfg ? cfg.bg : 'hsl(var(--primary-light))', color: cfg ? cfg.color : 'hsl(var(--primary))', boxShadow: `0 0 0 1.5px ${cfg ? cfg.color : 'hsl(var(--primary))'}` }
                : { backgroundColor: 'hsl(var(--surface))', color: 'hsl(var(--muted-foreground))', border: '1px solid hsl(var(--border))' }
              }
            >
              {cfg && <span className="opacity-80">{cfg.icon}</span>}
              {t(`orderManagement.channel.${ch.value}`, ch.label)}
            </button>
          );
        })}
      </div>

      {/* Toolbar */}
      <div className="flex flex-col gap-3 p-4" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
        {/* Row 1: Search + date filters */}
        <div className="flex flex-col sm:flex-row items-start sm:items-center gap-3">
          <div className="relative max-w-xs flex-1">
            <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
            <input className="input-base pl-9 text-sm" placeholder={t('orderManagement.searchPlaceholder', 'Search by customer name...')} value={search} onChange={e => { setSearch(e.target.value); setPage(1); }} />
          </div>
          <div className="flex items-center gap-2">
            <Calendar size={13} style={{ color: 'hsl(var(--muted-foreground))' }} />
            <input
              type="date"
              className="input-base text-xs px-2 py-1.5"
              value={dateFrom}
              onChange={e => { setDateFrom(e.target.value); setPage(1); }}
              title={t('common.fromDate', 'From date')}
            />
            <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>–</span>
            <input
              type="date"
              className="input-base text-xs px-2 py-1.5"
              value={dateTo}
              onChange={e => { setDateTo(e.target.value); setPage(1); }}
              title={t('common.toDate', 'To date')}
            />
            {(dateFrom || dateTo) && (
              <button
                className="text-xs px-2 py-1.5 rounded-lg"
                style={{ color: 'hsl(var(--danger))' }}
                onClick={() => { setDateFrom(''); setDateTo(''); setPage(1); }}
                title={t('common.clearDates', 'Clear dates')}
              >
                <X size={12} />
              </button>
            )}
          </div>
          {selectedIds.length > 0 && (
            <span className="text-xs font-medium px-2 py-1 rounded-lg" style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}>
              {t('orderManagement.selectedCount', `${selectedIds.length} selected`, { count: selectedIds.length })}
            </span>
          )}
        </div>

        {/* Row 2: Action buttons */}
        <div className="flex items-center justify-between gap-2 flex-wrap">
          <div className="flex items-center gap-2">
            {displayLastUpdated && (
              <div className="flex items-center gap-1.5">
                <span
                  className="w-1.5 h-1.5 rounded-full shrink-0"
                  style={{ backgroundColor: 'hsl(var(--success))', boxShadow: '0 0 0 2px hsl(var(--success) / 0.25)', animation: 'pulse 2s cubic-bezier(0.4,0,0.6,1) infinite' }}
                />
                <span className="text-xs whitespace-nowrap" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {formatLastUpdated(displayLastUpdated)}
                </span>
              </div>
            )}
          </div>
          <div className="flex items-center gap-2 flex-wrap">
            {selectedIds.length > 0 && (
              <>
                <div className="relative">
                  <button
                    className="btn-secondary text-xs py-1.5"
                    onClick={() => setBulkStatusOpen(o => !o)}
                  >
                    {t('orderManagement.changeStatus', 'Change Status')} <ChevronDownIcon size={12} />
                  </button>
                  {bulkStatusOpen && (
                    <div className="absolute left-0 top-full mt-1 w-44 rounded-xl shadow-lg z-20 overflow-hidden" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                      {BULK_STATUS_OPTIONS.map(s => (
                        <button
                          key={s.value}
                          className="flex items-center w-full px-3 py-2.5 text-xs hover:bg-black/5 text-left"
                          onClick={() => handleBulkStatus(s.value)}
                        >
                          {t(`orderManagement.statusLabel.${s.value}`, s.label)}
                        </button>
                      ))}
                    </div>
                  )}
                </div>
                <DemoDisabled>
                  <button className="btn-secondary text-xs py-1.5" style={{ color: 'hsl(var(--danger))' }} onClick={() => setConfirmDelete(true)}>
                    <Trash2 size={13} /> {t('common.delete', 'Delete')}
                  </button>
                </DemoDisabled>
              </>
            )}
            <div className="relative">
              <button className="btn-secondary text-xs py-1.5" onClick={() => setExportMenuOpen(!exportMenuOpen)}>
                <Download size={13} /> {t('common.export', 'Export')} <ChevronDownIcon size={12} />
              </button>
              {exportMenuOpen && (
                <div className="absolute right-0 top-full mt-1 w-40 rounded-xl shadow-lg z-20 overflow-hidden" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                  <button className="flex items-center gap-2 w-full px-3 py-2.5 text-xs hover:bg-black/5" onClick={exportCSV}>
                    <FileSpreadsheet size={13} /> {t('common.exportCSV', 'Export CSV')}
                  </button>
                </div>
              )}
            </div>
            <button className="btn-secondary text-xs py-1.5" onClick={manualRefresh} title={t('common.refreshNow', 'Refresh now')}>
              <RefreshCw size={13} className={loading ? 'animate-spin' : ''} />
            </button>
          </div>
        </div>
      </div>

      {loading ? (
        <InlineTableSkeleton columns={7} rows={8} />
      ) : orders.length === 0 ? (
        <div className="text-center py-16" style={{ color: 'hsl(var(--muted-foreground))' }}>
          <ShoppingBag size={32} className="mx-auto mb-3 opacity-30" />
          <p className="font-medium">{t('orderManagement.noOrdersFound', 'No orders found')}</p>
          <p className="text-xs mt-1">{t('orderManagement.noOrdersDescription', 'Orders will appear here when customers place them')}</p>
        </div>
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                <th className="px-4 py-3 w-10">
                  <button onClick={toggleAll}>
                    {selectedIds.length === orders.length && orders.length > 0 ? <CheckSquare size={15} style={{ color: 'hsl(var(--primary))' }} /> : <Square size={15} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                  </button>
                </th>
                {[
                  { label: t('orderManagement.orderNum', 'Order #'), field: null },
                  { label: t('orderManagement.customer', 'Customer'), field: 'customer_name' },
                  { label: t('orderManagement.channel', 'Channel'), field: 'channel' },
                  { label: t('orderManagement.type', 'Type'), field: null },
                  { label: t('orderManagement.items', 'Items'), field: null },
                  { label: t('orderManagement.total', 'Total'), field: 'total' },
                  { label: t('orderManagement.status', 'Status'), field: 'status' },
                  { label: t('orderManagement.placedAt', 'Placed At'), field: 'created_at' },
                  { label: '', field: null },
                ].map(col => (
                  <th
                    key={col.label}
                    className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider"
                    style={{ color: 'hsl(var(--muted-foreground))', cursor: col.field ? 'pointer' : 'default' }}
                    onClick={() => col.field && handleSort(col.field)}
                  >
                    <span className="flex items-center gap-1">
                      {col.label}
                      {col.field && <SortIcon field={col.field} />}
                    </span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {orders.map((order, idx) => (
                <tr key={order.id} className="table-row-hover" style={{ borderBottom: idx < orders.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                  <td className="px-4 py-3">
                    <button onClick={() => toggleRow(order.id)}>
                      {selectedIds.includes(order.id) ? <CheckSquare size={15} style={{ color: 'hsl(var(--primary))' }} /> : <Square size={15} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                    </button>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1.5">
                      <span className="text-xs font-mono font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{formatOid(order.orderNumber, order.id, order.restaurantId)}</span>
                      {((order.loyaltyPointsEarned ?? 0) > 0 || (order.loyaltyPointsRedeemed ?? 0) > 0) && (
                        <span
                          className="inline-flex items-center gap-0.5 text-[10px] font-bold px-1.5 py-0.5 rounded-full"
                          style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}
                          title={
                            (order.loyaltyPointsEarned ?? 0) > 0 && (order.loyaltyPointsRedeemed ?? 0) > 0
                              ? t('orderManagement.pointsBadgeBoth', `${order.loyaltyPointsEarned} earned · ${order.loyaltyPointsRedeemed} redeemed`, { earned: order.loyaltyPointsEarned ?? 0, redeemed: order.loyaltyPointsRedeemed ?? 0 })
                              : (order.loyaltyPointsEarned ?? 0) > 0
                                ? t('orderManagement.pointsBadgeEarned', `${order.loyaltyPointsEarned} pts earned`, { points: order.loyaltyPointsEarned ?? 0 })
                                : t('orderManagement.pointsBadgeRedeemed', `${order.loyaltyPointsRedeemed} pts redeemed`, { points: order.loyaltyPointsRedeemed ?? 0 })
                          }
                        >
                          <Star size={9} fill="currentColor" />
                          {(order.loyaltyPointsEarned ?? 0) > 0 ? (order.loyaltyPointsEarned ?? 0) : (order.loyaltyPointsRedeemed ?? 0)}
                        </span>
                      )}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div>
                      <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{order.customerName}</p>
                      <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{order.customerPhone}</p>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    {(() => {
                      const cfg = CHANNEL_CONFIG[order.channel];
                      if (cfg) {
                        return (
                          <span
                            className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold whitespace-nowrap"
                            style={{ backgroundColor: cfg.bg, color: cfg.color }}
                          >
                            {cfg.icon}
                            {cfg.label}
                          </span>
                        );
                      }
                      return (
                        <span className="text-xs font-medium capitalize" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                          {order.channel}
                        </span>
                      );
                    })()}
                  </td>
                  <td className="px-4 py-3">
                    {(() => {
                      const dt = (order.deliveryType || '').toLowerCase();
                      const label = dt === 'dine-in' ? t('orderManagement.deliveryType.dineIn', '🍽️ Dine-In') : dt === 'takeaway' ? t('orderManagement.deliveryType.takeaway', '🛍️ Takeaway') : dt === 'delivery' ? t('orderManagement.deliveryType.delivery', '🚚 Delivery') : order.deliveryType || '—';
                      const bg = dt === 'dine-in' ? 'hsl(142 76% 92%)' : dt === 'takeaway' ? 'hsl(215 100% 92%)' : dt === 'delivery' ? 'hsl(30 100% 92%)' : 'hsl(var(--muted))';
                      const color = dt === 'dine-in' ? 'hsl(142 70% 28%)' : dt === 'takeaway' ? 'hsl(215 80% 35%)' : dt === 'delivery' ? 'hsl(20 80% 35%)' : 'hsl(var(--muted-foreground))';
                      return (
                        <span className="inline-flex items-center text-xs font-semibold px-2 py-1 rounded-full whitespace-nowrap" style={{ backgroundColor: bg, color }}>
                          {label}
                        </span>
                      );
                    })()}
                  </td>
                  <td className="px-4 py-3 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    {(() => { const c = Array.isArray(order.items) ? order.items.length : 0; return t('orderManagement.itemCount', `${c} item${c !== 1 ? 's' : ''}`, { count: c, plural: c !== 1 ? 's' : '' }); })()}
                  </td>
                  <td className="px-4 py-3 font-semibold tabular-nums text-sm" style={{ color: 'hsl(var(--foreground))' }}>
                    {fc(Number(order.total))}
                  </td>
                  <td className="px-4 py-3"><StatusBadge status={order.status} /></td>
                  <td className="px-4 py-3 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{order.placedAt}</td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1">
                      <button className="btn-ghost p-1.5" onClick={() => setDetailOrder(order)} title={t('common.viewDetails', 'View details')}><Eye size={14} /></button>
                      <DemoDisabled><button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--danger))' }} onClick={() => { setSelectedIds([order.id]); setConfirmDelete(true); }} title={t('common.delete', 'Delete')}><Trash2 size={14} /></button></DemoDisabled>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Pagination — always visible */}
      <div className="flex items-center justify-between px-4 py-3 flex-wrap gap-2" style={{ borderTop: '1px solid hsl(var(--border))' }}>
        <div className="flex items-center gap-3">
          <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {totalCount === 0
              ? t('common.noItems', 'No items')
              : t('common.paginationShowing', `Showing ${Math.min((page - 1) * pageSize + 1, totalCount)}–${Math.min(page * pageSize, totalCount)} of ${totalCount}`, { from: Math.min((page - 1) * pageSize + 1, totalCount), to: Math.min(page * pageSize, totalCount), total: totalCount })}
          </span>
          <div className="flex items-center gap-1.5">
            <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('common.perPage', 'Per page:')}</span>
            <select
              className="input-base text-xs px-2 py-1"
              value={pageSize}
              onChange={e => { setPageSize(Number(e.target.value)); setPage(1); }}
            >
              <option value={10}>10</option>
              <option value={20}>20</option>
              <option value={50}>50</option>
            </select>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <button className="btn-ghost p-1.5" disabled={page === 1 || totalPages === 0} onClick={() => setPage(p => p - 1)}><ChevronLeft size={15} /></button>
          <span className="text-xs font-medium" style={{ color: 'hsl(var(--foreground))' }}>{totalPages === 0 ? '0 / 0' : `${page} / ${totalPages}`}</span>
          <button className="btn-ghost p-1.5" disabled={page >= totalPages || totalPages === 0} onClick={() => setPage(p => p + 1)}><ChevronRight size={15} /></button>
        </div>
      </div>

      <OrderDetailModal order={detailOrder} isOpen={detailOrder !== null} onClose={() => setDetailOrder(null)} onStatusChange={(id, status) => handleUpdateStatus(id, status)} onEdit={(o) => { setDetailOrder(null); setEditOrder(o); }} />
      <OrderEditPanel order={editOrder} isOpen={editOrder !== null} onClose={() => setEditOrder(null)} onSaved={fetchOrders} />
      <ConfirmModal isOpen={confirmDelete} onClose={() => setConfirmDelete(false)} onConfirm={() => handleDelete(selectedIds)} title={t('orderManagement.deleteConfirmTitle', 'Delete Orders')} description={t('orderManagement.deleteConfirmDescription', `Are you sure you want to delete ${selectedIds.length} order${selectedIds.length > 1 ? 's' : ''}? This cannot be undone.`, { count: selectedIds.length })} confirmLabel={t('common.delete', 'Delete')} variant="danger" />
      <SuccessModal isOpen={successModal.open} title={successModal.title} description={successModal.description} onClose={() => setSuccessModal({ open: false, title: '' })} />

      {newOrderAlert.length > 0 && (
        <div className="fixed inset-0 z-[60] flex items-center justify-center" style={{ backgroundColor: 'rgba(0,0,0,0.45)' }}>
          <div
            className="w-full max-w-sm mx-4 rounded-2xl overflow-hidden shadow-2xl"
            style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}
          >
            <div className="flex items-center justify-between px-5 py-4" style={{ backgroundColor: 'hsl(var(--success-bg))', borderBottom: '1px solid hsl(var(--success-border))' }}>
              <div className="flex items-center gap-3">
                <span className="w-9 h-9 rounded-full flex items-center justify-center" style={{ backgroundColor: 'hsl(var(--success))', color: '#fff' }}>
                  <Bell size={18} />
                </span>
                <div>
                  <p className="text-sm font-bold" style={{ color: 'hsl(var(--success))' }}>
                    {newOrderAlert.length === 1 ? t('orderManagement.newOrderReceived', 'New Order Received!') : t('orderManagement.newOrdersReceived', `${newOrderAlert.length} New Orders!`, { count: newOrderAlert.length })}
                  </p>
                  <p className="text-xs" style={{ color: 'hsl(var(--success))' }}>{t('orderManagement.newOrdersAttention', `New incoming ${newOrderAlert.length === 1 ? 'order' : 'orders'} need attention`, { count: newOrderAlert.length })}</p>
                </div>
              </div>
              <button className="btn-ghost p-1.5" onClick={() => setNewOrderAlert([])}><X size={16} /></button>
            </div>
            <div className="px-5 py-3 max-h-60 overflow-y-auto space-y-2">
              {newOrderAlert.map(o => (
                <div
                  key={o.id}
                  className="flex items-start justify-between p-3 rounded-xl cursor-pointer hover:opacity-80 transition-opacity"
                  style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}
                  onClick={() => { setDetailOrder(o); setNewOrderAlert([]); }}
                >
                  <div>
                    <p className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{o.customerName}</p>
                    <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {(() => { const c = o.items.length; return t('orderManagement.itemCount', `${c} item${c !== 1 ? 's' : ''}`, { count: c, plural: c !== 1 ? 's' : '' }); })()} · {t(`orderManagement.deliveryType.${o.deliveryType}`, o.deliveryType)} · {o.placedAt}
                    </p>
                    <p className="text-xs mt-0.5 font-mono" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                      {o.items.map(i => `${i.qty}× ${i.name}`).join(', ')}
                    </p>
                  </div>
                  <span className="text-sm font-bold font-mono shrink-0 ml-3" style={{ color: 'hsl(var(--foreground))' }}>
                    {fc(Number(o.total))}
                  </span>
                </div>
              ))}
            </div>
            <div className="flex gap-2 px-5 py-4" style={{ borderTop: '1px solid hsl(var(--border))' }}>
              <button
                className="flex-1 btn-primary text-sm py-2"
                onClick={() => {
                  if (newOrderAlert.length === 1) setDetailOrder(newOrderAlert[0]);
                  setNewOrderAlert([]);
                }}
              >
                {t('common.view', 'View')} {newOrderAlert.length === 1 ? t('orderManagement.order', 'Order') : t('orderManagement.orders', 'Orders')}
              </button>
              <button className="flex-1 btn-secondary text-sm py-2" onClick={() => setNewOrderAlert([])}>
                {t('common.dismiss', 'Dismiss')}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
