'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  Search, X, Phone, Mail, Plus, RefreshCw, ShoppingBag,
  Calendar, ChevronRight, Star, Tag, Loader2, Users, ChevronLeft,
} from 'lucide-react';
import { listCustomers, createCustomer, type Customer } from '@client/api/customers';
import { setCustomerOptOut } from '@client/api/marketing';
import { listOrders, type Order, type OrderListResponse } from '@client/api/orders';
import { listBookings, type Booking, type BookingListResponse } from '@client/api/bookings';
import { formatOid } from '@client/utils/formatOid';
import { useAuth } from '@client/contexts/AuthContext';
import { usePlanFeatures } from '@client/contexts/PlanFeaturesContext';
import { toast } from 'sonner';
import { InlineTableSkeleton } from '@client/components/skeletons/PageSkeletons';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import CustomerLoyaltyCard from '@client/components/loyalty/CustomerLoyaltyCard';

type TFn = (key: string, fallback: string) => string;

const STATUS_BADGE: Record<string, string> = {
  confirmed: 'badge-success', pending: 'badge-warning', completed: 'badge-success',
  cancelled: 'badge-danger', seated: 'badge-info', noshow: 'badge-danger',
  kitchen: 'badge-info', ready: 'badge-success', delivered: 'badge-success',
  processing: 'badge-info', rider: 'badge-info', failed: 'badge-danger', escalated: 'badge-danger',
};

const PANEL_PAGE_SIZE = 10;

function fmtDate(s: string | undefined, lang: string) {
  if (!s) return '—';
  try { return new Date(s).toLocaleDateString(lang, { month: 'short', day: 'numeric', year: 'numeric' }); } catch { return '—'; }
}

function fmtDateShort(s: string | undefined, lang: string) {
  if (!s) return '—';
  try { return new Date(s).toLocaleDateString(lang, { month: 'short', day: 'numeric' }); } catch { return '—'; }
}

function Avatar({ name, size = 32 }: { name: string; size?: number }) {
  const initials = name.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase();
  return (
    <div
      className="rounded-full flex items-center justify-center text-white font-bold shrink-0"
      style={{ width: size, height: size, fontSize: size * 0.35, background: 'linear-gradient(135deg, hsl(var(--primary)), hsl(22, 89%, 36%))' }}
    >
      {initials}
    </div>
  );
}

function Paginator({ page, pages, total, onPrev, onNext, loading, t }: {
  page: number; pages: number; total: number; onPrev: () => void; onNext: () => void; loading: boolean;
  t: TFn;
}) {
  if (pages <= 1) return null;
  return (
    <div className="flex items-center justify-between px-4 py-2.5" style={{ borderTop: '1px solid hsl(var(--border))' }}>
      <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
        {t('common.page', 'Page')} {page} {t('common.of', 'of')} {pages} ({total} {t('common.total', 'total')})
      </span>
      <div className="flex gap-1">
        <button className="btn-ghost p-1" disabled={page <= 1 || loading} onClick={onPrev}><ChevronLeft size={14} /></button>
        <button className="btn-ghost p-1" disabled={page >= pages || loading} onClick={onNext}><ChevronRight size={14} /></button>
      </div>
    </div>
  );
}

interface PanelState {
  orders: Order[];
  ordersLoading: boolean;
  ordersPage: number;
  ordersTotal: number;
  ordersPages: number;
  bookings: Booking[];
  bookingsLoading: boolean;
  bookingsPage: number;
  bookingsTotal: number;
  bookingsPages: number;
}

const EMPTY_PANEL: PanelState = {
  orders: [], ordersLoading: false, ordersPage: 1, ordersTotal: 0, ordersPages: 0,
  bookings: [], bookingsLoading: false, bookingsPage: 1, bookingsTotal: 0, bookingsPages: 0,
};

export default function CustomersPage() {
  const { t, currentLang } = useLanguage();
  usePageHeader(t('nav.customers', 'Customer Management'), t('customers.subtitle', 'Profiles, order history, and reservations'));
  const { restaurantId } = useAuth();
  const { hasFeature } = usePlanFeatures();

  const [customers, setCustomers] = useState<Customer[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [selected, setSelected] = useState<Customer | null>(null);
  const [showAddForm, setShowAddForm] = useState(false);
  const [newCustomer, setNewCustomer] = useState({ name: '', email: '', phone: '' });
  const [saving, setSaving] = useState(false);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(20);
  const [panel, setPanel] = useState<PanelState>(EMPTY_PANEL);
  const [loyaltyEnabled, setLoyaltyEnabled] = useState(false);

  const showLoyaltyCol = loyaltyEnabled && hasFeature('loyalty');

  const fetchCustomers = useCallback(async () => {
    if (!restaurantId) { setLoading(false); return; }
    setLoading(true);
    try {
      const params: Record<string, string> = { page: String(page), limit: String(pageSize) };
      if (search) params.search = search;
      const result = await listCustomers(params);
      setCustomers(result.customers ?? []);
      setTotal(result.total ?? 0);
      setLoyaltyEnabled(result.loyaltyEnabled === true);
    } catch (err: unknown) {
      toast.error(t('customers.loadError', 'Failed to load customers') + ': ' + (err instanceof Error ? err.message : String(err)));
    } finally {
      setLoading(false);
    }
  }, [restaurantId, search, page, pageSize, t]);

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

  const loadPanelOrders = useCallback(async (customerId: string, pg: number) => {
    setPanel(p => ({ ...p, ordersLoading: true }));
    let result: OrderListResponse;
    try {
      result = await listOrders({ customer_id: customerId, page: String(pg), limit: String(PANEL_PAGE_SIZE), sort_field: 'created_at', sort_dir: 'desc' });
    } catch {
      toast.error(t('customers.ordersLoadError', 'Failed to load orders'));
      result = { orders: [], total: 0, page: pg, limit: PANEL_PAGE_SIZE, pages: 0 };
    }
    setPanel(p => ({ ...p, orders: result.orders, ordersLoading: false, ordersPage: result.page, ordersTotal: result.total, ordersPages: result.pages }));
  }, [t]);

  const loadPanelBookings = useCallback(async (customerId: string, pg: number) => {
    setPanel(p => ({ ...p, bookingsLoading: true }));
    let result: BookingListResponse;
    try {
      result = await listBookings({ customer_id: customerId, page: String(pg), limit: String(PANEL_PAGE_SIZE), sort_dir: 'desc' });
    } catch {
      toast.error(t('customers.bookingsLoadError', 'Failed to load reservations'));
      result = { bookings: [], total: 0, page: pg, limit: PANEL_PAGE_SIZE, pages: 0 };
    }
    setPanel(p => ({ ...p, bookings: result.bookings, bookingsLoading: false, bookingsPage: result.page, bookingsTotal: result.total, bookingsPages: result.pages }));
  }, [t]);

  const handleSelectCustomer = (c: Customer) => {
    if (selected?.id === c.id) { setSelected(null); return; }
    setSelected(c);
    setPanel(EMPTY_PANEL);
    loadPanelOrders(c.id, 1);
    loadPanelBookings(c.id, 1);
  };

  const handleAddCustomer = async () => {
    if (!restaurantId || !newCustomer.name.trim()) return;
    setSaving(true);
    try {
      const result = await createCustomer({ name: newCustomer.name, email: newCustomer.email, phone: newCustomer.phone });
      setCustomers(prev => [result.customer, ...prev]);
      setTotal(tot => tot + 1);
      setShowAddForm(false);
      setNewCustomer({ name: '', email: '', phone: '' });
      toast.success(t('customers.added', 'Customer added'));
    } catch (err: unknown) {
      toast.error(t('customers.addError', 'Failed to add customer') + ': ' + (err instanceof Error ? err.message : String(err)));
    } finally {
      setSaving(false);
    }
  };

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

  const tableHeaders = [
    t('customers.colCustomer', 'Customer'),
    t('common.email', 'Email'),
    t('common.phone', 'Phone'),
    t('customers.colOrders', 'Orders'),
    t('customers.colTotalSpent', 'Total Spent'),
    ...(showLoyaltyCol ? [t('customers.colLoyalty', 'Loyalty')] : []),
    t('customers.colReservations', 'Reservations'),
    t('customers.colLastVisit', 'Last Visit'),
    t('customers.colMemberSince', 'Member Since'),
    '',
  ];

  return (
    <>
      {/* Toolbar */}
      <div className="flex flex-col sm:flex-row gap-3 mb-5">
        <div className="relative flex-1 max-w-sm">
          <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
          <input
            className="input-base pl-9"
            placeholder={t('customers.searchPlaceholder', 'Search by name, email, or phone…')}
            value={search}
            onChange={e => { setSearch(e.target.value); setPage(1); }}
          />
        </div>
        <button className="btn-primary" onClick={() => setShowAddForm(v => !v)}>
          <Plus size={15} /> {t('customers.addCustomer', 'Add Customer')}
        </button>
        <button className="btn-secondary" onClick={fetchCustomers} title={t('common.refresh', 'Refresh')}>
          <RefreshCw size={15} className={loading ? 'animate-spin' : ''} />
        </button>
      </div>

      {/* Add Form */}
      {showAddForm && (
        <div className="card p-5 mb-5">
          <h3 className="font-semibold mb-3" style={{ color: 'hsl(var(--foreground))' }}>{t('customers.addNewCustomer', 'Add New Customer')}</h3>
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 mb-3">
            <input className="input-base" placeholder={t('customers.fullNamePlaceholder', 'Full name *')} value={newCustomer.name} onChange={e => setNewCustomer(p => ({ ...p, name: e.target.value }))} />
            <input className="input-base" placeholder={t('common.email', 'Email')} value={newCustomer.email} onChange={e => setNewCustomer(p => ({ ...p, email: e.target.value }))} />
            <input className="input-base" placeholder={t('common.phone', 'Phone')} value={newCustomer.phone} onChange={e => setNewCustomer(p => ({ ...p, phone: e.target.value }))} />
          </div>
          <div className="flex gap-2">
            <button className="btn-primary" onClick={handleAddCustomer} disabled={saving || !newCustomer.name.trim()}>
              {saving ? <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : t('common.save', 'Save')}
            </button>
            <button className="btn-secondary" onClick={() => setShowAddForm(false)}>{t('common.cancel', 'Cancel')}</button>
          </div>
        </div>
      )}

      <div className="flex gap-5">
        {/* Table */}
        <div className={`card overflow-hidden transition-all min-w-0 ${selected ? 'flex-1' : 'w-full'}`}>
          {loading ? (
            <InlineTableSkeleton columns={7} rows={8} />
          ) : customers.length === 0 ? (
            <div className="text-center py-16" style={{ color: 'hsl(var(--muted-foreground))' }}>
              <Users size={40} className="mx-auto mb-3 opacity-30" />
              <p className="font-medium">{t('customers.noCustomers', 'No customers found')}</p>
              <p className="text-xs mt-1">{t('customers.noCustomersSub', 'Customers appear when they interact with your AI agent or when you add them manually')}</p>
            </div>
          ) : (
            <>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                      {tableHeaders.map((h, i) => (
                        <th key={i} className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider whitespace-nowrap" style={{ color: 'hsl(var(--muted-foreground))' }}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {customers.map((c, idx) => (
                      <tr
                        key={c.id}
                        className="table-row-hover cursor-pointer"
                        style={{
                          borderBottom: idx < customers.length - 1 ? '1px solid hsl(var(--border))' : 'none',
                          backgroundColor: selected?.id === c.id ? 'hsl(var(--primary-light))' : '',
                        }}
                        onClick={() => handleSelectCustomer(c)}
                      >
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-3">
                            <Avatar name={c.name} size={32} />
                            <p className="font-medium text-sm truncate" style={{ color: 'hsl(var(--foreground))' }}>{c.name}</p>
                          </div>
                        </td>
                        <td className="px-4 py-3 text-sm truncate max-w-[160px]" style={{ color: 'hsl(var(--muted-foreground))' }}>{c.email || '—'}</td>
                        <td className="px-4 py-3 text-sm whitespace-nowrap" style={{ color: 'hsl(var(--muted-foreground))' }}>{c.phone || '—'}</td>
                        <td className="px-4 py-3 tabular-nums text-sm font-semibold text-center" style={{ color: 'hsl(var(--foreground))' }}>{c.totalOrders}</td>
                        <td className="px-4 py-3 tabular-nums text-sm font-semibold" style={{ color: 'hsl(var(--primary))' }}>
                          ${Number(c.totalSpend).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                        </td>
                        {showLoyaltyCol && (
                          <td className="px-4 py-3 text-sm whitespace-nowrap">
                            {c.loyalty ? (
                              <div className="flex items-center gap-2">
                                {c.loyalty.tierName ? (
                                  <span
                                    className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium"
                                    style={{
                                      backgroundColor: c.loyalty.tierColor ? `${c.loyalty.tierColor}22` : 'hsl(var(--muted))',
                                      color: c.loyalty.tierColor || 'hsl(var(--foreground))',
                                      border: `1px solid ${c.loyalty.tierColor || 'hsl(var(--border))'}`,
                                    }}
                                  >
                                    <span className="w-1.5 h-1.5 rounded-full" style={{ background: c.loyalty.tierColor || 'hsl(var(--muted-foreground))' }} />
                                    {c.loyalty.tierName}
                                  </span>
                                ) : null}
                                <span className="tabular-nums font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
                                  {c.loyalty.balance.toLocaleString()}
                                </span>
                                <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                                  {t('customers.pts', 'pts')}
                                </span>
                              </div>
                            ) : (
                              <span style={{ color: 'hsl(var(--muted-foreground))' }}>—</span>
                            )}
                          </td>
                        )}
                        <td className="px-4 py-3 tabular-nums text-sm text-center" style={{ color: 'hsl(var(--foreground))' }}>{c.totalReservations}</td>
                        <td className="px-4 py-3 text-sm whitespace-nowrap" style={{ color: 'hsl(var(--muted-foreground))' }}>{fmtDate(c.lastVisit, currentLang)}</td>
                        <td className="px-4 py-3 text-sm whitespace-nowrap" style={{ color: 'hsl(var(--muted-foreground))' }}>{fmtDate(c.createdAt, currentLang)}</td>
                        <td className="px-4 py-3">
                          <ChevronRight size={16} style={{ color: 'hsl(var(--muted-foreground))', transform: selected?.id === c.id ? 'rotate(90deg)' : 'none' }} />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Pagination */}
              {totalPages > 1 && (
                <div className="flex items-center justify-between px-4 py-3" style={{ borderTop: '1px solid hsl(var(--border))' }}>
                  <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    {(page - 1) * pageSize + 1}–{Math.min(page * pageSize, total)} {t('common.of', 'of')} {total} {t('customers.customers', 'customers')}
                  </p>
                  <div className="flex gap-1">
                    <button className="btn-secondary px-2 py-1 text-xs" disabled={page <= 1} onClick={() => setPage(p => p - 1)}>{t('common.prev', 'Prev')}</button>
                    <button className="btn-secondary px-2 py-1 text-xs" disabled={page >= totalPages} onClick={() => setPage(p => p + 1)}>{t('common.next', 'Next')}</button>
                  </div>
                </div>
              )}
            </>
          )}
        </div>

        {/* Detail Panel */}
        {selected && (
          <div className="w-[560px] shrink-0 animate-slide-in-right flex flex-col gap-4" style={{ maxHeight: 'calc(100vh - 200px)', overflowY: 'auto' }}>
            {/* Header Card */}
            <div className="card p-5">
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center gap-4">
                  <Avatar name={selected.name} size={52} />
                  <div>
                    <h3 className="text-lg font-bold" style={{ color: 'hsl(var(--foreground))' }}>{selected.name}</h3>
                    <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {t('customers.memberSince', 'Member since')} {fmtDate(selected.createdAt, currentLang)}
                    </p>
                  </div>
                </div>
                <button className="btn-ghost p-1.5" onClick={() => setSelected(null)}>
                  <X size={16} />
                </button>
              </div>

              {/* Contact Info */}
              <div className="space-y-2">
                {selected.email && (
                  <div className="flex items-center gap-2 text-sm" style={{ color: 'hsl(var(--foreground))' }}>
                    <Mail size={14} style={{ color: 'hsl(var(--muted-foreground))' }} />
                    <span>{selected.email}</span>
                  </div>
                )}
                {selected.phone && (
                  <div className="flex items-center gap-2 text-sm" style={{ color: 'hsl(var(--foreground))' }}>
                    <Phone size={14} style={{ color: 'hsl(var(--muted-foreground))' }} />
                    <span>{selected.phone}</span>
                  </div>
                )}
                {!selected.email && !selected.phone && (
                  <p className="text-xs italic" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('customers.noContactDetails', 'No contact details on record')}</p>
                )}
              </div>

              {/* Marketing opt-out toggle */}
              <div className="mt-3 pt-3 flex items-center justify-between" style={{ borderTop: '1px solid hsl(var(--border))' }}>
                <div className="text-sm">
                  <span className="font-medium">{t('customers.marketingPrefs', 'Marketing messages')}</span>
                  <span className={`ml-2 badge text-xs ${selected.marketingOptOut ? 'badge-warning' : 'badge-success'}`}>
                    {selected.marketingOptOut
                      ? t('customers.optedOut', 'Opted out')
                      : t('customers.optedIn', 'Opted in')}
                  </span>
                </div>
                <button
                  type="button"
                  className="btn-ghost text-xs px-2 py-1"
                  onClick={async () => {
                    const next = !selected.marketingOptOut;
                    try {
                      await setCustomerOptOut(selected.id, next, next ? 'manual' : undefined);
                      setSelected({ ...selected, marketingOptOut: next, optOutAt: next ? new Date().toISOString() : undefined });
                      toast.success(next
                        ? t('customers.markedOptOut', 'Customer opted out of marketing')
                        : t('customers.markedOptIn', 'Customer re-subscribed to marketing'));
                    } catch (err) {
                      toast.error(err instanceof Error ? err.message : 'Failed to update preference');
                    }
                  }}
                >
                  {selected.marketingOptOut
                    ? t('customers.reSubscribe', 'Re-subscribe')
                    : t('customers.optOut', 'Opt out')}
                </button>
              </div>

              {/* Stat Cards */}
              <div className="grid grid-cols-3 gap-3 mt-4">
                {[
                  { label: t('customers.statTotalOrders', 'Total Orders'), value: String(selected.totalOrders) },
                  { label: t('customers.statTotalSpent', 'Total Spent'), value: `$${Number(selected.totalSpend).toFixed(2)}` },
                  {
                    label: t('customers.statAvgOrder', 'Avg Order'),
                    value: selected.totalOrders > 0 ? `$${(selected.totalSpend / selected.totalOrders).toFixed(2)}` : '—',
                  },
                  { label: t('customers.statReservations', 'Reservations'), value: String(selected.totalReservations) },
                  { label: t('customers.statLastVisit', 'Last Visit'), value: fmtDateShort(selected.lastVisit, currentLang) },
                  { label: t('customers.statTotalVisits', 'Total Visits'), value: selected.totalVisits ? String(selected.totalVisits) : '—' },
                  { label: t('customers.colMemberSince', 'Member Since'), value: fmtDateShort(selected.createdAt, currentLang) },
                ].map(stat => (
                  <div key={stat.label} className="p-3 rounded-lg text-center" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                    <p className="text-base font-bold tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>{stat.value}</p>
                    <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{stat.label}</p>
                  </div>
                ))}
              </div>

              {/* Loyalty — gated by both plan feature and restaurant setting */}
              {showLoyaltyCol && (
                <div className="mt-4">
                  <CustomerLoyaltyCard customerId={selected.id} />
                </div>
              )}

              {/* Preferences */}
              {selected.preferences && selected.preferences.length > 0 && (
                <div className="mt-4">
                  <p className="text-xs font-semibold uppercase tracking-wider mb-2 flex items-center gap-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    <Star size={11} /> {t('customers.preferences', 'Preferences')}
                  </p>
                  <div className="flex flex-wrap gap-1.5">
                    {selected.preferences.map(p => <span key={p} className="badge badge-info text-xs">{p}</span>)}
                  </div>
                </div>
              )}

              {/* Tags */}
              {selected.tags && selected.tags.length > 0 && (
                <div className="mt-3">
                  <p className="text-xs font-semibold uppercase tracking-wider mb-2 flex items-center gap-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    <Tag size={11} /> {t('customers.tags', 'Tags')}
                  </p>
                  <div className="flex flex-wrap gap-1.5">
                    {selected.tags.map(tag => <span key={tag} className="badge badge-neutral text-xs">{tag}</span>)}
                  </div>
                </div>
              )}

              {/* Notes */}
              {selected.notes && (
                <div className="mt-4 p-3 rounded-lg text-sm" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground))' }}>
                  <p className="text-xs font-semibold uppercase tracking-wider mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('common.notes', 'Notes')}</p>
                  <p>{selected.notes}</p>
                </div>
              )}
            </div>

            {/* Orders Table */}
            <div className="card overflow-hidden">
              <div className="px-4 py-3 flex items-center justify-between" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                <h4 className="font-semibold text-sm flex items-center gap-2" style={{ color: 'hsl(var(--foreground))' }}>
                  <ShoppingBag size={14} /> {t('nav.orders', 'Orders')}
                  {!panel.ordersLoading && <span className="badge badge-neutral text-xs">{panel.ordersTotal}</span>}
                </h4>
                <a href={`/order-management?customer_id=${selected.id}`} className="text-xs font-semibold" style={{ color: 'hsl(var(--primary))' }}>
                  {t('common.viewAll', 'View All')}
                </a>
              </div>
              {panel.ordersLoading ? (
                <div className="flex items-center justify-center py-8">
                  <Loader2 size={18} className="animate-spin" style={{ color: 'hsl(var(--primary))' }} />
                </div>
              ) : panel.orders.length === 0 ? (
                <p className="text-center py-8 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('customers.noOrders', 'No orders found')}</p>
              ) : (
                <>
                  <table className="w-full">
                    <thead>
                      <tr style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                        {[
                          t('customers.orderNum', 'Order #'),
                          t('common.date', 'Date'),
                          t('customers.items', 'Items'),
                          t('common.total', 'Total'),
                          t('common.status', 'Status'),
                        ].map(h => (
                          <th key={h} className="text-left px-4 py-2 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{h}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {panel.orders.map((o, idx) => (
                        <tr key={o.id} style={{ borderBottom: idx < panel.orders.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                          <td className="px-4 py-2.5 text-xs font-mono font-bold" style={{ color: 'hsl(var(--foreground))' }}>
                            {formatOid(o.orderNumber, o.id, o.restaurantId)}
                          </td>
                          <td className="px-4 py-2.5 text-xs whitespace-nowrap" style={{ color: 'hsl(var(--muted-foreground))' }}>
                            {fmtDateShort(o.createdAt, currentLang)}
                          </td>
                          <td className="px-4 py-2.5 text-xs max-w-[140px] truncate" style={{ color: 'hsl(var(--foreground))' }}>
                            {o.items.map(i => i.name).join(', ') || '—'}
                          </td>
                          <td className="px-4 py-2.5 text-xs font-semibold whitespace-nowrap" style={{ color: 'hsl(var(--primary))' }}>
                            ${Number(o.total).toFixed(2)}
                          </td>
                          <td className="px-4 py-2.5">
                            <span className={`badge ${STATUS_BADGE[o.status] ?? 'badge-neutral'} text-xs capitalize`}>{o.status}</span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                  <Paginator
                    page={panel.ordersPage}
                    pages={panel.ordersPages}
                    total={panel.ordersTotal}
                    loading={panel.ordersLoading}
                    onPrev={() => loadPanelOrders(selected.id, panel.ordersPage - 1)}
                    onNext={() => loadPanelOrders(selected.id, panel.ordersPage + 1)}
                    t={t}
                  />
                </>
              )}
            </div>

            {/* Bookings Table */}
            <div className="card overflow-hidden">
              <div className="px-4 py-3 flex items-center justify-between" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                <h4 className="font-semibold text-sm flex items-center gap-2" style={{ color: 'hsl(var(--foreground))' }}>
                  <Calendar size={14} /> {t('nav.reservations', 'Reservations')}
                  {!panel.bookingsLoading && <span className="badge badge-neutral text-xs">{panel.bookingsTotal}</span>}
                </h4>
                <a href="/table-booking-management" className="text-xs font-semibold" style={{ color: 'hsl(var(--primary))' }}>
                  {t('common.viewAll', 'View All')}
                </a>
              </div>
              {panel.bookingsLoading ? (
                <div className="flex items-center justify-center py-8">
                  <Loader2 size={18} className="animate-spin" style={{ color: 'hsl(var(--primary))' }} />
                </div>
              ) : panel.bookings.length === 0 ? (
                <p className="text-center py-8 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('customers.noReservations', 'No reservations found')}</p>
              ) : (
                <>
                  <table className="w-full">
                    <thead>
                      <tr style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                        {[
                          t('common.date', 'Date'),
                          t('common.time', 'Time'),
                          t('customers.party', 'Party'),
                          t('common.status', 'Status'),
                          t('customers.specialRequests', 'Special Requests'),
                        ].map(h => (
                          <th key={h} className="text-left px-4 py-2 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{h}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {panel.bookings.map((b, idx) => (
                        <tr key={b.id} style={{ borderBottom: idx < panel.bookings.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                          <td className="px-4 py-2.5 text-xs whitespace-nowrap" style={{ color: 'hsl(var(--foreground))' }}>
                            {b.date ? fmtDate(b.date, currentLang) : '—'}
                          </td>
                          <td className="px-4 py-2.5 text-xs whitespace-nowrap" style={{ color: 'hsl(var(--foreground))' }}>
                            {b.time || '—'}
                          </td>
                          <td className="px-4 py-2.5 text-xs text-center" style={{ color: 'hsl(var(--foreground))' }}>
                            {b.partySize}
                          </td>
                          <td className="px-4 py-2.5">
                            <span className={`badge ${STATUS_BADGE[b.status] ?? 'badge-neutral'} text-xs capitalize`}>{b.status}</span>
                          </td>
                          <td className="px-4 py-2.5 text-xs max-w-[160px] truncate" style={{ color: 'hsl(var(--muted-foreground))' }}>
                            {b.specialRequests || '—'}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                  <Paginator
                    page={panel.bookingsPage}
                    pages={panel.bookingsPages}
                    total={panel.bookingsTotal}
                    loading={panel.bookingsLoading}
                    onPrev={() => loadPanelBookings(selected.id, panel.bookingsPage - 1)}
                    onNext={() => loadPanelBookings(selected.id, panel.bookingsPage + 1)}
                    t={t}
                  />
                </>
              )}
            </div>
          </div>
        )}
      </div>
    </>
  );
}
