'use client';

import { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ShoppingCart, Plus, Minus, X, DollarSign, CreditCard, Banknote,
  Receipt, ArrowLeftRight, Trash2, Search, User, Clock, Hash,
  AlertTriangle, CheckCircle, Ban, Percent, MessageSquare,
  ChevronLeft, Printer, Split, RotateCcw, UtensilsCrossed
} from 'lucide-react';

interface Category {
  id: string;
  name: string;
  displayName: string;
  color: string;
  icon?: string;
  items: MenuItem[];
}

interface MenuItem {
  id: string;
  name: string;
  shortName?: string;
  price: number;
  taxRate: number;
  color: string;
  modifierGroups: ModifierGroup[];
  isActive: boolean;
}

interface ModifierGroup {
  name: string;
  required: boolean;
  maxSelect: number;
  options: { name: string; price: number }[];
}

interface CartItem {
  id: string;
  menuItemId: string;
  name: string;
  quantity: number;
  unitPrice: number;
  modifiers: { name: string; price: number }[];
  modifierTotal: number;
  taxRate: number;
  notes: string;
  status: string;
}

interface Order {
  id: string;
  orderNumber: string;
  status: string;
  orderType: string;
  tableNumber?: string;
  subtotal: number;
  taxAmount: number;
  discountAmount: number;
  tipAmount: number;
  total: number;
  items: CartItem[];
  payments: Payment[];
}

interface Payment {
  id: string;
  method: string;
  amount: number;
  tipAmount: number;
  status: string;
  changeDue: number;
}

type Screen = 'menu' | 'payment' | 'receipt' | 'transfer' | 'void_confirm';

export default function POSTerminalPage() {
  const [categories, setCategories] = useState<Category[]>([]);
  const [activeCategory, setActiveCategory] = useState<string>('');
  const [currentOrder, setCurrentOrder] = useState<Order | null>(null);
  const [screen, setScreen] = useState<Screen>('menu');
  const [searchQuery, setSearchQuery] = useState('');
  const [loading, setLoading] = useState(false);
  const [paymentMethod, setPaymentMethod] = useState<'cash' | 'card'>('cash');
  const [tenderedAmount, setTenderedAmount] = useState('');
  const [tipAmount, setTipAmount] = useState('');
  const [splitCount, setSplitCount] = useState(1);
  const [voidReason, setVoidReason] = useState('');
  const [voidTarget, setVoidTarget] = useState<{ type: string; id: string; name: string } | null>(null);
  const [discountAmount, setDiscountAmount] = useState('');
  const [discountReason, setDiscountReason] = useState('');
  const [showDiscount, setShowDiscount] = useState(false);
  const [orderType, setOrderType] = useState<'dine-in' | 'takeout' | 'delivery'>('dine-in');
  const [tableNumber, setTableNumber] = useState('');
  const [notification, setNotification] = useState<{ type: 'success' | 'error' | 'warning'; message: string } | null>(null);

  // Load menu
  useEffect(() => {
    fetch('/api/pos/menu')
      .then(r => r.json())
      .then(data => {
        setCategories(data.categories || []);
        if (data.categories?.length > 0) setActiveCategory(data.categories[0].id);
      })
      .catch(console.error);
  }, []);

  const notify = useCallback((type: 'success' | 'error' | 'warning', message: string) => {
    setNotification({ type, message });
    setTimeout(() => setNotification(null), 4000);
  }, []);

  // Create new order
  const createOrder = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/pos/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'create', orderType, tableNumber: tableNumber || undefined }),
      });
      const data = await res.json();
      setCurrentOrder(data.order);
      notify('success', `Order ${data.order.orderNumber} created`);
    } catch (e) { notify('error', 'Failed to create order'); }
    setLoading(false);
  };

  // Add item to order
  const addItem = async (item: MenuItem) => {
    if (!currentOrder) {
      // Auto-create order
      setLoading(true);
      try {
        const res = await fetch('/api/pos/orders', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ action: 'create', orderType, tableNumber: tableNumber || undefined }),
        });
        const data = await res.json();
        setCurrentOrder(data.order);
        // Now add item to this order
        await addItemToOrder(data.order.id, item);
      } catch (e) { notify('error', 'Failed to create order'); }
      setLoading(false);
      return;
    }
    await addItemToOrder(currentOrder.id, item);
  };

  const addItemToOrder = async (orderId: string, item: MenuItem) => {
    try {
      const res = await fetch('/api/pos/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'add_items',
          orderId,
          items: [{
            menuItemId: item.id,
            name: item.name,
            unitPrice: item.price,
            quantity: 1,
            taxRate: item.taxRate,
            modifiers: [],
            modifierTotal: 0,
          }],
        }),
      });
      const data = await res.json();
      if (data.order) setCurrentOrder(data.order);
    } catch (e) { notify('error', 'Failed to add item'); }
  };

  // Void item
  const voidItem = async () => {
    if (!voidTarget || !voidReason || !currentOrder) return;
    try {
      const res = await fetch('/api/pos/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'void_item',
          orderId: currentOrder.id,
          itemId: voidTarget.id,
          reason: voidReason,
        }),
      });
      const data = await res.json();
      if (data.error) { notify('error', data.error); return; }
      setCurrentOrder(data.order);
      setScreen('menu');
      setVoidTarget(null);
      setVoidReason('');
      notify('success', `Item voided: ${voidTarget.name}`);
    } catch (e) { notify('error', 'Void failed'); }
  };

  // Process payment
  const processPayment = async () => {
    if (!currentOrder) return;
    setLoading(true);
    try {
      const payAmt = splitCount > 1 ? currentOrder.total / splitCount : currentOrder.total;
      const res = await fetch('/api/pos/payments', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'pay',
          orderId: currentOrder.id,
          method: paymentMethod,
          amount: payAmt,
          tipAmount: Number(tipAmount || 0),
          tendered: paymentMethod === 'cash' ? Number(tenderedAmount || payAmt) : payAmt,
        }),
      });
      const data = await res.json();
      if (data.error) { notify('error', data.error); setLoading(false); return; }
      setCurrentOrder(data.order);
      if (data.order.status === 'closed') {
        setScreen('receipt');
        notify('success', `Payment received! ${data.changeDue > 0 ? `Change: $${data.changeDue.toFixed(2)}` : ''}`);
      } else {
        notify('success', `Split payment processed ($${payAmt.toFixed(2)}). ${splitCount - 1} remaining.`);
        setSplitCount(s => Math.max(1, s - 1));
      }
    } catch (e) { notify('error', 'Payment failed'); }
    setLoading(false);
  };

  // Apply discount
  const applyDiscount = async () => {
    if (!currentOrder || !discountAmount || !discountReason) return;
    try {
      const res = await fetch('/api/pos/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'discount',
          orderId: currentOrder.id,
          discountAmount: Number(discountAmount),
          discountReason,
        }),
      });
      const data = await res.json();
      if (data.error) { notify(data.guardrail ? 'warning' : 'error', data.error); return; }
      setCurrentOrder(data.order);
      setShowDiscount(false);
      setDiscountAmount('');
      setDiscountReason('');
      notify('success', `Discount applied: $${Number(discountAmount).toFixed(2)}`);
    } catch (e) { notify('error', 'Discount failed'); }
  };

  // New order (reset)
  const newOrder = () => {
    setCurrentOrder(null);
    setScreen('menu');
    setTenderedAmount('');
    setTipAmount('');
    setSplitCount(1);
    setTableNumber('');
  };

  // Filtered items
  const activeCat = categories.find(c => c.id === activeCategory);
  const filteredItems = searchQuery
    ? categories.flatMap(c => c.items).filter(i => i.name.toLowerCase().includes(searchQuery.toLowerCase()))
    : activeCat?.items || [];

  const activeItems = currentOrder?.items?.filter(i => i.status !== 'voided') || [];
  const totalPaid = currentOrder?.payments?.filter(p => p.status === 'completed')?.reduce((s, p) => s + p.amount, 0) || 0;
  const remaining = (currentOrder?.total || 0) - totalPaid;

  return (
    <div className="flex h-[calc(100vh-4rem)] bg-gray-950 text-white overflow-hidden">
      {/* Notification Toast */}
      <AnimatePresence>
        {notification && (
          <motion.div
            initial={{ opacity: 0, y: -50 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -50 }}
            className={`fixed top-20 left-1/2 -translate-x-1/2 z-50 px-6 py-3 rounded-xl shadow-2xl flex items-center gap-3 ${
              notification.type === 'success' ? 'bg-green-600' :
              notification.type === 'warning' ? 'bg-amber-600' : 'bg-red-600'
            }`}
          >
            {notification.type === 'success' ? <CheckCircle className="w-5 h-5" /> :
             notification.type === 'warning' ? <AlertTriangle className="w-5 h-5" /> :
             <X className="w-5 h-5" />}
            <span className="font-medium">{notification.message}</span>
          </motion.div>
        )}
      </AnimatePresence>

      {/* LEFT: Menu Grid */}
      <div className="flex-1 flex flex-col">
        {/* Top Bar */}
        <div className="flex items-center gap-3 p-3 border-b border-gray-800 bg-gray-900">
          <ChevronLeft
            className="w-8 h-8 p-1.5 rounded-lg bg-gray-800 hover:bg-gray-700 cursor-pointer"
            onClick={() => window.history.back()}
          />
          <UtensilsCrossed className="w-5 h-5 text-emerald-400" />
          <span className="font-bold text-lg">POS Terminal</span>
          <div className="flex items-center gap-2 ml-4">
            {(['dine-in', 'takeout', 'delivery'] as const).map(t => (
              <button
                key={t}
                onClick={() => setOrderType(t)}
                className={`px-3 py-1.5 rounded-lg text-xs font-semibold uppercase tracking-wide transition-all ${
                  orderType === t ? 'bg-emerald-600 text-white' : 'bg-gray-800 text-gray-400 hover:bg-gray-700'
                }`}
              >
                {t}
              </button>
            ))}
          </div>
          {orderType === 'dine-in' && (
            <div className="flex items-center gap-2 ml-2">
              <Hash className="w-4 h-4 text-gray-500" />
              <input
                type="text"
                value={tableNumber}
                onChange={e => setTableNumber(e.target.value)}
                placeholder="Table"
                className="w-16 px-2 py-1 bg-gray-800 border border-gray-700 rounded text-sm text-center"
              />
            </div>
          )}
          <div className="flex-1" />
          <div className="relative">
            <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
            <input
              type="text"
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              placeholder="Search items..."
              className="pl-8 pr-3 py-1.5 w-48 bg-gray-800 border border-gray-700 rounded-lg text-sm"
            />
          </div>
        </div>

        {/* Category Tabs */}
        <div className="flex gap-1 p-2 overflow-x-auto bg-gray-900/50 border-b border-gray-800 scrollbar-hide">
          {categories.map(cat => (
            <button
              key={cat.id}
              onClick={() => { setActiveCategory(cat.id); setSearchQuery(''); }}
              className={`px-4 py-2.5 rounded-xl text-sm font-semibold whitespace-nowrap transition-all min-w-[100px] ${
                activeCategory === cat.id
                  ? 'text-white shadow-lg scale-105'
                  : 'bg-gray-800/50 text-gray-400 hover:bg-gray-700'
              }`}
              style={activeCategory === cat.id ? { backgroundColor: cat.color } : undefined}
            >
              {cat.displayName}
            </button>
          ))}
        </div>

        {/* Menu Items Grid */}
        <div className="flex-1 overflow-y-auto p-3">
          {filteredItems.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-full text-gray-500">
              <UtensilsCrossed className="w-16 h-16 mb-4 opacity-30" />
              <p className="text-lg">No menu items found</p>
              <p className="text-sm mt-1">Add items in POS Admin → Menu Editor</p>
            </div>
          ) : (
            <div className="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-2">
              {filteredItems.map(item => (
                <button
                  key={item.id}
                  onClick={() => addItem(item)}
                  className="flex flex-col items-center justify-center p-4 rounded-xl border-2 border-transparent hover:border-white/20 transition-all active:scale-95 min-h-[100px] text-center"
                  style={{ backgroundColor: item.color + '33', borderColor: item.color + '44' }}
                >
                  <span className="font-bold text-sm leading-tight">{item.shortName || item.name}</span>
                  <span className="text-lg font-bold mt-1" style={{ color: item.color }}>
                    ${item.price.toFixed(2)}
                  </span>
                </button>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* RIGHT: Order Panel */}
      <div className="w-[380px] flex flex-col border-l border-gray-800 bg-gray-900">
        {/* Order Header */}
        <div className="p-3 border-b border-gray-800 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <ShoppingCart className="w-5 h-5 text-emerald-400" />
            <span className="font-bold">
              {currentOrder ? `#${currentOrder.orderNumber}` : 'New Order'}
            </span>
            {currentOrder?.status && (
              <span className={`text-xs px-2 py-0.5 rounded-full ${
                currentOrder.status === 'open' ? 'bg-emerald-500/20 text-emerald-400' :
                currentOrder.status === 'closed' ? 'bg-blue-500/20 text-blue-400' :
                currentOrder.status === 'voided' ? 'bg-red-500/20 text-red-400' :
                'bg-amber-500/20 text-amber-400'
              }`}>
                {currentOrder.status.toUpperCase()}
              </span>
            )}
          </div>
          <button onClick={newOrder} className="text-xs text-gray-400 hover:text-white flex items-center gap-1">
            <Plus className="w-3 h-3" /> New
          </button>
        </div>

        {/* Cart Items */}
        <div className="flex-1 overflow-y-auto">
          {activeItems.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-full text-gray-600">
              <ShoppingCart className="w-12 h-12 mb-3 opacity-30" />
              <p className="text-sm">Tap menu items to add</p>
            </div>
          ) : (
            <div className="divide-y divide-gray-800">
              {activeItems.map((item, idx) => (
                <div key={item.id || idx} className="p-3 flex items-start gap-3 hover:bg-gray-800/50">
                  <div className="flex-1">
                    <div className="font-medium text-sm">{item.name}</div>
                    {item.modifiers?.length > 0 && (
                      <div className="text-xs text-gray-500 mt-0.5">
                        {(item.modifiers as { name: string }[]).map(m => m.name).join(', ')}
                      </div>
                    )}
                    {item.notes && <div className="text-xs text-amber-400 mt-0.5">{item.notes}</div>}
                  </div>
                  <div className="text-right">
                    <div className="text-sm font-semibold">
                      ${((item.unitPrice + (item.modifierTotal || 0)) * item.quantity).toFixed(2)}
                    </div>
                    <div className="text-xs text-gray-500">×{item.quantity}</div>
                  </div>
                  <button
                    onClick={() => {
                      setVoidTarget({ type: 'item', id: item.id, name: item.name });
                      setScreen('void_confirm');
                    }}
                    className="p-1 text-gray-600 hover:text-red-400 transition-colors"
                    title="Void item"
                  >
                    <Ban className="w-4 h-4" />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Order Totals */}
        {currentOrder && (
          <div className="border-t border-gray-800 p-3 space-y-1 bg-gray-900">
            <div className="flex justify-between text-sm text-gray-400">
              <span>Subtotal</span><span>${currentOrder.subtotal.toFixed(2)}</span>
            </div>
            <div className="flex justify-between text-sm text-gray-400">
              <span>Tax</span><span>${currentOrder.taxAmount.toFixed(2)}</span>
            </div>
            {currentOrder.discountAmount > 0 && (
              <div className="flex justify-between text-sm text-green-400">
                <span>Discount</span><span>-${currentOrder.discountAmount.toFixed(2)}</span>
              </div>
            )}
            {currentOrder.tipAmount > 0 && (
              <div className="flex justify-between text-sm text-blue-400">
                <span>Tip</span><span>${currentOrder.tipAmount.toFixed(2)}</span>
              </div>
            )}
            <div className="flex justify-between text-xl font-bold pt-2 border-t border-gray-700">
              <span>Total</span><span className="text-emerald-400">${currentOrder.total.toFixed(2)}</span>
            </div>
            {totalPaid > 0 && remaining > 0 && (
              <div className="flex justify-between text-sm text-amber-400 pt-1">
                <span>Remaining</span><span>${remaining.toFixed(2)}</span>
              </div>
            )}
          </div>
        )}

        {/* Action Buttons */}
        <div className="border-t border-gray-800 p-3 space-y-2 bg-gray-900">
          {screen === 'menu' && currentOrder && currentOrder.status !== 'closed' && currentOrder.status !== 'voided' && (
            <>
              <div className="grid grid-cols-3 gap-2">
                <button onClick={() => setShowDiscount(!showDiscount)} className="flex flex-col items-center gap-1 p-2 rounded-lg bg-gray-800 hover:bg-gray-700 text-xs text-gray-300">
                  <Percent className="w-4 h-4" /> Discount
                </button>
                <button
                  onClick={() => {
                    setVoidTarget({ type: 'order', id: currentOrder.id, name: currentOrder.orderNumber });
                    setScreen('void_confirm');
                  }}
                  className="flex flex-col items-center gap-1 p-2 rounded-lg bg-gray-800 hover:bg-gray-700 text-xs text-red-400"
                >
                  <Ban className="w-4 h-4" /> Void Order
                </button>
                <button onClick={() => setScreen('transfer')} className="flex flex-col items-center gap-1 p-2 rounded-lg bg-gray-800 hover:bg-gray-700 text-xs text-blue-400">
                  <ArrowLeftRight className="w-4 h-4" /> Transfer
                </button>
              </div>

              {showDiscount && (
                <div className="p-3 bg-gray-800/80 rounded-lg space-y-2">
                  <input type="number" value={discountAmount} onChange={e => setDiscountAmount(e.target.value)}
                    placeholder="$ amount" className="w-full px-3 py-2 bg-gray-700 rounded text-sm" />
                  <input type="text" value={discountReason} onChange={e => setDiscountReason(e.target.value)}
                    placeholder="Reason (required)" className="w-full px-3 py-2 bg-gray-700 rounded text-sm" />
                  <button onClick={applyDiscount}
                    disabled={!discountAmount || !discountReason}
                    className="w-full py-2 bg-green-600 hover:bg-green-500 disabled:opacity-40 rounded-lg text-sm font-semibold">Apply Discount</button>
                </div>
              )}

              {activeItems.length > 0 && (
                <button
                  onClick={() => setScreen('payment')}
                  className="w-full py-4 bg-emerald-600 hover:bg-emerald-500 rounded-xl text-lg font-bold flex items-center justify-center gap-3 transition-all active:scale-[0.98]"
                >
                  <DollarSign className="w-6 h-6" />
                  Pay ${(remaining > 0 ? remaining : currentOrder.total).toFixed(2)}
                </button>
              )}
            </>
          )}

          {screen === 'receipt' && (
            <div className="space-y-3 text-center">
              <CheckCircle className="w-16 h-16 text-emerald-400 mx-auto" />
              <p className="text-lg font-bold text-emerald-400">Payment Complete!</p>
              <p className="text-sm text-gray-400">Order {currentOrder?.orderNumber}</p>
              <button onClick={newOrder}
                className="w-full py-4 bg-emerald-600 hover:bg-emerald-500 rounded-xl text-lg font-bold">
                New Order
              </button>
            </div>
          )}
        </div>

        {/* Payment Screen Overlay */}
        <AnimatePresence>
          {screen === 'payment' && currentOrder && (
            <motion.div
              initial={{ x: 400 }} animate={{ x: 0 }} exit={{ x: 400 }}
              className="absolute right-0 top-0 w-[380px] h-full bg-gray-900 z-20 flex flex-col border-l border-gray-800"
            >
              <div className="p-4 border-b border-gray-800 flex items-center gap-3">
                <button onClick={() => setScreen('menu')} className="p-2 rounded-lg bg-gray-800 hover:bg-gray-700">
                  <ChevronLeft className="w-5 h-5" />
                </button>
                <DollarSign className="w-5 h-5 text-emerald-400" />
                <span className="font-bold text-lg">Payment</span>
              </div>

              <div className="flex-1 overflow-y-auto p-4 space-y-4">
                {/* Amount */}
                <div className="text-center py-4">
                  <p className="text-sm text-gray-400">Amount Due</p>
                  <p className="text-4xl font-bold text-emerald-400">
                    ${(remaining > 0 ? remaining : currentOrder.total).toFixed(2)}
                  </p>
                </div>

                {/* Payment Method */}
                <div className="grid grid-cols-2 gap-2">
                  <button
                    onClick={() => setPaymentMethod('cash')}
                    className={`flex items-center justify-center gap-2 p-4 rounded-xl border-2 text-lg font-bold transition-all ${
                      paymentMethod === 'cash' ? 'border-emerald-500 bg-emerald-500/10 text-emerald-400' : 'border-gray-700 text-gray-400'
                    }`}
                  >
                    <Banknote className="w-6 h-6" /> Cash
                  </button>
                  <button
                    onClick={() => setPaymentMethod('card')}
                    className={`flex items-center justify-center gap-2 p-4 rounded-xl border-2 text-lg font-bold transition-all ${
                      paymentMethod === 'card' ? 'border-blue-500 bg-blue-500/10 text-blue-400' : 'border-gray-700 text-gray-400'
                    }`}
                  >
                    <CreditCard className="w-6 h-6" /> Card
                  </button>
                </div>

                {/* Split Payment */}
                <div className="flex items-center justify-between p-3 bg-gray-800 rounded-lg">
                  <div className="flex items-center gap-2 text-sm text-gray-300">
                    <Split className="w-4 h-4" /> Split
                  </div>
                  <div className="flex items-center gap-2">
                    <button onClick={() => setSplitCount(Math.max(1, splitCount - 1))} className="w-8 h-8 rounded-lg bg-gray-700 flex items-center justify-center">
                      <Minus className="w-4 h-4" />
                    </button>
                    <span className="w-8 text-center font-bold">{splitCount}</span>
                    <button onClick={() => setSplitCount(splitCount + 1)} className="w-8 h-8 rounded-lg bg-gray-700 flex items-center justify-center">
                      <Plus className="w-4 h-4" />
                    </button>
                  </div>
                </div>
                {splitCount > 1 && (
                  <p className="text-center text-sm text-amber-400">
                    Each pays: ${(currentOrder.total / splitCount).toFixed(2)}
                  </p>
                )}

                {/* Cash: Tendered Amount */}
                {paymentMethod === 'cash' && (
                  <div>
                    <label className="text-sm text-gray-400 mb-1 block">Amount Tendered</label>
                    <input
                      type="number"
                      value={tenderedAmount}
                      onChange={e => setTenderedAmount(e.target.value)}
                      placeholder={`$${(splitCount > 1 ? currentOrder.total / splitCount : currentOrder.total).toFixed(2)}`}
                      className="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded-xl text-xl text-center font-bold"
                    />
                    {/* Quick Cash Buttons */}
                    <div className="grid grid-cols-4 gap-2 mt-2">
                      {[5, 10, 20, 50].map(amt => (
                        <button key={amt} onClick={() => setTenderedAmount(String(amt))}
                          className="py-2 bg-gray-800 hover:bg-gray-700 rounded-lg text-sm font-semibold">
                          ${amt}
                        </button>
                      ))}
                    </div>
                  </div>
                )}

                {/* Tip */}
                <div>
                  <label className="text-sm text-gray-400 mb-1 block">Tip</label>
                  <div className="grid grid-cols-5 gap-2">
                    {['0', '15', '18', '20', '25'].map(pct => {
                      const due = splitCount > 1 ? currentOrder.total / splitCount : currentOrder.total;
                      const tipVal = pct === '0' ? '0' : (due * Number(pct) / 100).toFixed(2);
                      return (
                        <button key={pct}
                          onClick={() => setTipAmount(tipVal)}
                          className={`py-2 rounded-lg text-xs font-semibold ${
                            tipAmount === tipVal ? 'bg-blue-600 text-white' : 'bg-gray-800 text-gray-400 hover:bg-gray-700'
                          }`}>
                          {pct === '0' ? 'None' : `${pct}%`}
                        </button>
                      );
                    })}
                  </div>
                  <input type="number" value={tipAmount} onChange={e => setTipAmount(e.target.value)}
                    placeholder="Custom tip" className="w-full mt-2 px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm text-center" />
                </div>
              </div>

              {/* Process Button */}
              <div className="p-4 border-t border-gray-800">
                <button
                  onClick={processPayment}
                  disabled={loading}
                  className="w-full py-4 bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 rounded-xl text-xl font-bold flex items-center justify-center gap-3 transition-all active:scale-[0.98]"
                >
                  {loading ? <RotateCcw className="w-6 h-6 animate-spin" /> : <CheckCircle className="w-6 h-6" />}
                  {paymentMethod === 'cash' ? 'Accept Cash' : 'Process Card'}
                </button>
              </div>
            </motion.div>
          )}
        </AnimatePresence>

        {/* Void Confirmation Overlay */}
        <AnimatePresence>
          {screen === 'void_confirm' && voidTarget && (
            <motion.div
              initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
              className="absolute inset-0 bg-black/70 z-30 flex items-center justify-center p-6"
            >
              <div className="bg-gray-900 rounded-2xl p-6 w-full max-w-md border border-red-500/30 space-y-4">
                <div className="flex items-center gap-3 text-red-400">
                  <AlertTriangle className="w-6 h-6" />
                  <h3 className="text-lg font-bold">Void {voidTarget.type === 'order' ? 'Order' : 'Item'}</h3>
                </div>
                <p className="text-sm text-gray-300">
                  {voidTarget.type === 'order'
                    ? `Void entire order ${voidTarget.name}? This action is logged in the audit trail.`
                    : `Void "${voidTarget.name}"? This action cannot be undone.`}
                </p>
                <div className="space-y-2">
                  <label className="text-sm text-gray-400">Reason (required — Standing Orders §13.3)</label>
                  <select
                    value={voidReason}
                    onChange={e => setVoidReason(e.target.value)}
                    className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm"
                  >
                    <option value="">Select reason...</option>
                    <option value="DUPLICATE">Duplicate Entry</option>
                    <option value="ERROR">Data Entry Error</option>
                    <option value="CUSTOMER_REQUEST">Customer Request</option>
                    <option value="WRONG_ITEM">Wrong Item</option>
                    <option value="QUALITY">Quality Issue</option>
                    <option value="OTHER">Other</option>
                  </select>
                </div>
                <div className="flex gap-3">
                  <button onClick={() => { setScreen('menu'); setVoidTarget(null); setVoidReason(''); }}
                    className="flex-1 py-3 bg-gray-800 hover:bg-gray-700 rounded-xl font-semibold">Cancel</button>
                  <button
                    onClick={async () => {
                      if (voidTarget.type === 'order') {
                        const res = await fetch('/api/pos/orders', {
                          method: 'POST',
                          headers: { 'Content-Type': 'application/json' },
                          body: JSON.stringify({ action: 'void_order', orderId: voidTarget.id, reason: voidReason }),
                        });
                        const data = await res.json();
                        if (data.error) { notify(data.guardrail ? 'warning' : 'error', data.error); return; }
                        newOrder();
                        notify('success', 'Order voided');
                      } else {
                        await voidItem();
                      }
                    }}
                    disabled={!voidReason}
                    className="flex-1 py-3 bg-red-600 hover:bg-red-500 disabled:opacity-40 rounded-xl font-semibold">Confirm Void</button>
                </div>
              </div>
            </motion.div>
          )}
        </AnimatePresence>

        {/* Transfer Overlay */}
        <AnimatePresence>
          {screen === 'transfer' && currentOrder && (
            <motion.div
              initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
              className="absolute inset-0 bg-black/70 z-30 flex items-center justify-center p-6"
            >
              <div className="bg-gray-900 rounded-2xl p-6 w-full max-w-md border border-blue-500/30 space-y-4">
                <div className="flex items-center gap-3 text-blue-400">
                  <ArrowLeftRight className="w-6 h-6" />
                  <h3 className="text-lg font-bold">Transfer Order {currentOrder.orderNumber}</h3>
                </div>
                <div>
                  <label className="text-sm text-gray-400 mb-1 block">To Table #</label>
                  <input type="text" placeholder="Table number"
                    className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm"
                    id="transfer-table" />
                </div>
                <div className="flex gap-3">
                  <button onClick={() => setScreen('menu')}
                    className="flex-1 py-3 bg-gray-800 hover:bg-gray-700 rounded-xl font-semibold">Cancel</button>
                  <button onClick={async () => {
                    const el = document.getElementById('transfer-table') as HTMLInputElement;
                    const res = await fetch('/api/pos/orders', {
                      method: 'POST',
                      headers: { 'Content-Type': 'application/json' },
                      body: JSON.stringify({
                        action: 'transfer',
                        orderId: currentOrder.id,
                        toTableNumber: el?.value || '',
                      }),
                    });
                    const data = await res.json();
                    if (data.order) setCurrentOrder(data.order);
                    setScreen('menu');
                    notify('success', `Transferred to Table ${el?.value}`);
                  }} className="flex-1 py-3 bg-blue-600 hover:bg-blue-500 rounded-xl font-semibold">Transfer</button>
                </div>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </div>
  );
}
