import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
  ShoppingCart, Search, Plus, Minus, Trash2, X, CheckCircle,
  Printer, User, Phone, Package,
  Banknote, CreditCard, Smartphone, RefreshCw,
  ShoppingBag, TrendingUp, Percent, Scan, ZapOff, Zap
} from 'lucide-react';

interface Product {
  id: string;
  name: string;
  nameBangla?: string;
  price: number;
  image?: string;
  category?: string;
  stock?: number;
  sizes?: string[];
  priceConfigs?: Record<string, { salePrice: number; originalPrice: number }>;
}

interface CartItem {
  productId: string;
  name: string;
  nameBangla?: string;
  image?: string;
  price: number;
  originalPrice: number;
  quantity: number;
  size?: string;
}

interface POSOrder {
  items: CartItem[];
  customerName: string;
  customerPhone: string;
  paymentMethod: 'cash' | 'bkash' | 'nagad' | 'card';
  subtotal: number;
  discount: number;
  total: number;
  paid: number;
  change: number;
  note: string;
}

interface POSSystemProps {
  products: Product[];
  settings?: { siteName?: string; logo?: string; phone?: string; address?: string };
  showToast?: (msg: string, type?: 'success' | 'error') => void;
}

const API_BASE = '/api';

const tenantHeaders = (extra: Record<string, string> = {}) => {
  const h: Record<string, string> = { 'Content-Type': 'application/json', ...extra };
  const token = localStorage.getItem('tenant_token');
  if (token) h['X-Tenant-Token'] = token;
  return h;
};

const getBanglaName = (nameBangla?: string, name?: string) =>
  nameBangla && /[\u0980-\u09FF]/.test(nameBangla) ? nameBangla : (name || '');

const PAYMENT_METHODS = [
  { id: 'cash', label: 'Cash', icon: Banknote, color: 'green' },
  { id: 'bkash', label: 'bKash', icon: Smartphone, color: 'pink' },
  { id: 'nagad', label: 'Nagad', icon: Smartphone, color: 'orange' },
  { id: 'card', label: 'Card', icon: CreditCard, color: 'blue' },
] as const;

// ─── Receipt Component ────────────────────────────────────────────────
const POSReceipt: React.FC<{
  order: POSOrder;
  settings?: { siteName?: string; logo?: string; phone?: string; address?: string };
  orderId?: string;
  onClose: () => void;
}> = ({ order, settings, orderId, onClose }) => {
  const printRef = useRef<HTMLDivElement>(null);

  const handlePrint = () => {
    const content = printRef.current?.innerHTML;
    const win = window.open('', '_blank', 'width=380,height=600');
    if (win && content) {
      win.document.write(`
        <html><head><title>Receipt</title>
        <style>
          * { margin:0; padding:0; box-sizing:border-box; }
          body { font-family: 'Courier New', monospace; font-size: 12px; padding: 10px; width: 72mm; }
          .center { text-align: center; }
          .bold { font-weight: bold; }
          .divider { border-top: 1px dashed #000; margin: 6px 0; }
          .row { display: flex; justify-content: space-between; margin: 2px 0; }
          .logo { max-width: 60px; max-height: 40px; display: block; margin: 0 auto 4px; }
          .total-row { border-top: 2px solid #000; margin-top: 4px; padding-top: 4px; font-size: 14px; font-weight: bold; }
          img { max-width: 100%; }
        </style></head>
        <body>${content}</body></html>
      `);
      win.document.close();
      win.focus();
      setTimeout(() => { win.print(); win.close(); }, 300);
    }
  };

  const now = new Date();
  const dateStr = now.toLocaleDateString('en-BD') + ' ' + now.toLocaleTimeString('en-BD', { hour: '2-digit', minute: '2-digit' });

  return (
    <div className="fixed inset-0 z-[9999] bg-black/60 backdrop-blur-sm flex items-center justify-center p-4" onClick={onClose}>
      <div className="bg-white rounded-3xl shadow-2xl w-full max-w-sm overflow-hidden" onClick={e => e.stopPropagation()}>
        {/* Actions */}
        <div className="flex items-center justify-between p-4 border-b">
          <h3 className="font-black text-lg">Receipt Preview</h3>
          <div className="flex gap-2">
            <button onClick={handlePrint} className="flex items-center gap-2 px-4 py-2 bg-slate-900 text-white rounded-xl font-bold text-sm hover:bg-slate-800 transition-all text-black placeholder-black">
              <Printer size={16} /> Print
            </button>
            <button onClick={onClose} className="p-2 hover:bg-slate-100 rounded-xl text-black placeholder-black"><X size={20} /></button>
          </div>
        </div>

        {/* Receipt Paper */}
        <div className="p-6 overflow-y-auto max-h-[70vh]">
          <div ref={printRef} style={{ fontFamily: "'Courier New', monospace", fontSize: 12, color: '#000' }}>
            <div className="center" style={{ textAlign: 'center', marginBottom: 8 }}>
              {settings?.logo && <img src={settings.logo} alt="logo" className="logo" style={{ maxWidth: 60, maxHeight: 40, display: 'block', margin: '0 auto 4px' }} />}
              <div className="bold" style={{ fontWeight: 'bold', fontSize: 16 }}>{settings?.siteName || 'Store'}</div>
              {settings?.phone && <div>{settings.phone}</div>}
              {settings?.address && <div>{settings.address}</div>}
            </div>

            <div className="divider" style={{ borderTop: '1px dashed #000', margin: '6px 0' }} />
            <div className="row" style={{ display: 'flex', justifyContent: 'space-between', margin: '2px 0' }}>
              <span>Receipt #: {orderId || 'POS-' + Date.now().toString().slice(-6)}</span>
            </div>
            <div className="row" style={{ display: 'flex', justifyContent: 'space-between', margin: '2px 0' }}>
              <span>{dateStr}</span>
            </div>
            {order.customerName && (
              <div className="row" style={{ display: 'flex', justifyContent: 'space-between', margin: '2px 0' }}>
                <span>Customer: {order.customerName}</span>
              </div>
            )}
            {order.customerPhone && (
              <div className="row" style={{ display: 'flex', justifyContent: 'space-between', margin: '2px 0' }}>
                <span>Phone: {order.customerPhone}</span>
              </div>
            )}
            <div className="divider" style={{ borderTop: '1px dashed #000', margin: '6px 0' }} />

            {/* Items */}
            {order.items.map((item, i) => (
              <div key={i} style={{ marginBottom: 4 }}>
                <div className="bold" style={{ fontWeight: 'bold' }}>
                  {item.nameBangla && /[\u0980-\u09FF]/.test(item.nameBangla) ? item.nameBangla : item.name}
                  {item.size ? ` (${item.size})` : ''}
                </div>
                <div className="row" style={{ display: 'flex', justifyContent: 'space-between', margin: '2px 0' }}>
                  <span>{item.quantity} x ৳{item.price}</span>
                  <span>৳{(item.quantity * item.price).toLocaleString()}</span>
                </div>
              </div>
            ))}

            <div className="divider" style={{ borderTop: '1px dashed #000', margin: '6px 0' }} />
            <div className="row" style={{ display: 'flex', justifyContent: 'space-between', margin: '2px 0' }}>
              <span>Subtotal</span><span>৳{order.subtotal.toLocaleString()}</span>
            </div>
            {order.discount > 0 && (
              <div className="row" style={{ display: 'flex', justifyContent: 'space-between', margin: '2px 0', color: '#e31e24' }}>
                <span>Discount</span><span>-৳{order.discount.toLocaleString()}</span>
              </div>
            )}
            <div className="total-row row" style={{ display: 'flex', justifyContent: 'space-between', borderTop: '2px solid #000', marginTop: 4, paddingTop: 4, fontSize: 14, fontWeight: 'bold' }}>
              <span>TOTAL</span><span>৳{order.total.toLocaleString()}</span>
            </div>
            <div className="row" style={{ display: 'flex', justifyContent: 'space-between', margin: '2px 0' }}>
              <span>Paid ({order.paymentMethod.toUpperCase()})</span><span>৳{order.paid.toLocaleString()}</span>
            </div>
            {order.change > 0 && (
              <div className="row" style={{ display: 'flex', justifyContent: 'space-between', margin: '2px 0' }}>
                <span>Change</span><span>৳{order.change.toLocaleString()}</span>
              </div>
            )}

            <div className="divider" style={{ borderTop: '1px dashed #000', margin: '6px 0' }} />
            <div className="center" style={{ textAlign: 'center', marginTop: 8, fontSize: 11 }}>
              Thank you for shopping!<br />
              {settings?.siteName || 'Store'}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ─── Size Picker Modal ─────────────────────────────────────────────────────
const SizePicker: React.FC<{
  product: Product;
  onSelect: (size: string, price: number) => void;
  onClose: () => void;
}> = ({ product, onSelect, onClose }) => {
  const configs = typeof product.priceConfigs === 'string'
    ? (() => { try { return JSON.parse(product.priceConfigs as any); } catch { return {}; } })()
    : (product.priceConfigs || {});

  const sizes = Object.keys(configs).length > 0 ? Object.keys(configs) : (product.sizes || []);

  return (
    <div className="fixed inset-0 z-[9990] bg-black/50 backdrop-blur-sm flex items-end sm:items-center justify-center p-4" onClick={onClose}>
      <div className="bg-white rounded-3xl shadow-2xl w-full max-w-sm" onClick={e => e.stopPropagation()}>
        <div className="p-5 border-b flex items-center justify-between">
          <div>
            <p className="text-xs text-black font-bold uppercase tracking-widest">Select Size</p>
            <h3 className="font-black text-lg font-bangla">{getBanglaName(product.nameBangla, product.name)}</h3>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-slate-100 rounded-xl text-black placeholder-black"><X size={20} /></button>
        </div>
        <div className="p-5 grid grid-cols-2 gap-3">
          {sizes.map(size => {
            const price = configs[size]?.salePrice || product.price;
            const original = configs[size]?.originalPrice || price;
            const hasDiscount = original > price;
            return (
              <button
                key={size}
                onClick={() => { onSelect(size, price); onClose(); }}
                className="flex flex-col items-center p-4 rounded-2xl border-2 border-slate-200 hover:border-red-500 hover:bg-red-50 transition-all group text-black placeholder-black"
              >
                <span className="font-black text-lg group-hover:text-red-600">{size}</span>
                <span className="font-black text-red-600 text-xl">৳{price.toLocaleString()}</span>
                {hasDiscount && <span className="text-xs text-black line-through">৳{original.toLocaleString()}</span>}
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
};

// ─── Main POS System ───────────────────────────────────────────────────────
const POSSystem: React.FC<POSSystemProps> = ({ products, settings, showToast }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [cart, setCart] = useState<CartItem[]>([]);
  const [customerName, setCustomerName] = useState('');
  const [customerPhone, setCustomerPhone] = useState('');
  const [paymentMethod, setPaymentMethod] = useState<'cash' | 'bkash' | 'nagad' | 'card'>('cash');
  const [paidAmount, setPaidAmount] = useState('');
  const [discount, setDiscount] = useState('');
  const [note, setNote] = useState('');
  const [isSaving, setIsSaving] = useState(false);
  const [showReceipt, setShowReceipt] = useState(false);
  const [lastOrder, setLastOrder] = useState<POSOrder | null>(null);
  const [lastOrderId, setLastOrderId] = useState('');
  const [sizePicker, setSizePicker] = useState<Product | null>(null);
  const [todaySales, setTodaySales] = useState({ count: 0, total: 0 });
  const searchRef = useRef<HTMLInputElement>(null);

  // ── Barcode scanner state ──────────────────────────────────────────
  const [scanMode, setScanMode] = useState(false);
  const [scanFeedback, setScanFeedback] = useState<{ type: 'success' | 'error'; msg: string } | null>(null);
  const scanBufferRef = useRef('');
  const scanLastTimeRef = useRef(0);
  const barcodeInputRef = useRef<HTMLInputElement>(null);

  // Global keyboard listener for barcode scanner
  // Barcode scanners type each character < 50ms apart, then send Enter
  useEffect(() => {
    if (!scanMode) return;
    const handleKeyDown = (e: KeyboardEvent) => {
      const target = e.target as HTMLElement;
      // Ignore if user is typing in customer/discount/note inputs
      if (
        target.tagName === 'INPUT' &&
        target !== barcodeInputRef.current &&
        (target as HTMLInputElement).type !== 'hidden'
      ) return;

      const now = Date.now();
      if (e.key === 'Enter') {
        const code = scanBufferRef.current.trim();
        if (code.length >= 2) processScan(code);
        scanBufferRef.current = '';
        e.preventDefault();
        return;
      }
      // If gap > 100ms, it's manual typing — reset buffer
      if (now - scanLastTimeRef.current > 100 && scanBufferRef.current.length > 0) {
        scanBufferRef.current = '';
      }
      if (e.key.length === 1) {
        scanBufferRef.current += e.key;
        scanLastTimeRef.current = now;
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [scanMode, products]);

  // Auto-focus barcode input when scan mode enabled
  useEffect(() => {
    if (scanMode) setTimeout(() => barcodeInputRef.current?.focus(), 100);
  }, [scanMode]);

  // Clear scan feedback after 2 seconds
  useEffect(() => {
    if (!scanFeedback) return;
    const t = setTimeout(() => setScanFeedback(null), 2200);
    return () => clearTimeout(t);
  }, [scanFeedback]);

  const categories = ['all', ...Array.from(new Set(products.map(p => p.category).filter(Boolean) as string[]))];

  const filteredProducts = products.filter(p => {
    const matchCat = selectedCategory === 'all' || p.category === selectedCategory;
    const q = searchQuery.toLowerCase();
    const matchSearch = !q || p.name.toLowerCase().includes(q) ||
      (p.nameBangla || '').includes(q) ||
      (p.category || '').toLowerCase().includes(q);
    return matchCat && matchSearch;
  });

  const subtotal = cart.reduce((s, i) => s + i.price * i.quantity, 0);
  const discountAmt = Math.min(parseFloat(discount) || 0, subtotal);
  const total = subtotal - discountAmt;
  const paid = parseFloat(paidAmount) || 0;
  const change = Math.max(0, paid - total);

  // Load today's POS stats
  useEffect(() => {
    fetch(`${API_BASE}/orders.php?pos_stats=1`, { headers: tenantHeaders() })
      .then(r => r.json())
      .then(d => {
        if (d.pos_today) setTodaySales(d.pos_today);
      }).catch(() => {});
  }, []);

  const addToCart = useCallback((product: Product, size?: string, price?: number) => {
    const configs = typeof product.priceConfigs === 'string'
      ? (() => { try { return JSON.parse(product.priceConfigs as any); } catch { return {}; } })()
      : (product.priceConfigs || {});
    const sizes = Object.keys(configs).length > 0 ? Object.keys(configs) : (product.sizes || []);

    if (sizes.length > 0 && !size) {
      setSizePicker(product);
      return;
    }

    const finalPrice = price || (size && configs[size]?.salePrice) || product.price;
    const originalPrice = (size && configs[size]?.originalPrice) || product.price;

    setCart(prev => {
      const key = product.id + (size || '');
      const existing = prev.find(i => i.productId + (i.size || '') === key);
      if (existing) {
        return prev.map(i => i.productId + (i.size || '') === key ? { ...i, quantity: i.quantity + 1 } : i);
      }
      return [...prev, {
        productId: product.id,
        name: product.name,
        nameBangla: product.nameBangla,
        image: product.image,
        price: finalPrice,
        originalPrice,
        quantity: 1,
        size
      }];
    });
  }, []);

  // ✅ processScan declared AFTER addToCart to avoid block-scope usage error
  const processScan = useCallback((code: string) => {
    const q = code.toLowerCase().trim();
    let found = products.find(p => String(p.id).toLowerCase() === q);
    if (!found) found = products.find(p => p.name.toLowerCase() === q || (p.nameBangla || '').toLowerCase() === q);
    if (!found) found = products.find(p => p.name.toLowerCase().includes(q) || (p.nameBangla || '').includes(q));

    if (found) {
      addToCart(found);
      setScanFeedback({ type: 'success', msg: `✅ Added: ${getBanglaName(found.nameBangla, found.name)}` });
      try {
        const ctx = new (window.AudioContext || (window as any).webkitAudioContext)();
        const osc = ctx.createOscillator();
        const gain = ctx.createGain();
        osc.connect(gain); gain.connect(ctx.destination);
        osc.frequency.value = 880; gain.gain.value = 0.3;
        osc.start(); osc.stop(ctx.currentTime + 0.08);
      } catch {}
    } else {
      setScanFeedback({ type: 'error', msg: `❌ Not found: "${code}"` });
    }
    if (barcodeInputRef.current) barcodeInputRef.current.value = '';
  }, [products, addToCart]);

  const updateQty = (idx: number, delta: number) => {
    setCart(prev => {
      const updated = prev.map((item, i) => i === idx ? { ...item, quantity: Math.max(0, item.quantity + delta) } : item);
      return updated.filter(i => i.quantity > 0);
    });
  };

  const removeItem = (idx: number) => setCart(prev => prev.filter((_, i) => i !== idx));

  const clearCart = () => {
    setCart([]);
    setCustomerName('');
    setCustomerPhone('');
    setDiscount('');
    setPaidAmount('');
    setNote('');
    setPaymentMethod('cash');
  };

  const handleCheckout = async () => {
    if (cart.length === 0) {
      showToast?.('Cart is empty!', 'error');
      return;
    }
    if (paid < total) {
      showToast?.('Paid amount is less than total!', 'error');
      return;
    }

    setIsSaving(true);
    const orderId = 'POS-' + Date.now().toString().slice(-8);
    const orderData = {
      customer_name: customerName || 'Walk-in Customer',
      customer_phone: customerPhone || '00000000000',
      customer_address: 'POS Sale',
      items: cart.map(i => ({
        product_id: i.productId,
        name: i.name,
        qty: i.quantity,
        price: i.price,
        size: i.size,
      })),
      total,
      payment_method: paymentMethod,
      source: 'POS System',
      status: 'completed',
      note: `POS Sale | ${paymentMethod.toUpperCase()} | Paid: ৳${paid} | Change: ৳${change}${note ? ' | ' + note : ''}`,
    };

    try {
      const res = await fetch(`${API_BASE}/admin/orders`, {
        method: 'POST',
        headers: tenantHeaders(),
        body: JSON.stringify(orderData),
      });
      const data = await res.json();

      const finalOrder: POSOrder = {
        items: cart,
        customerName: customerName || 'Walk-in Customer',
        customerPhone,
        paymentMethod,
        subtotal,
        discount: discountAmt,
        total,
        paid,
        change,
        note,
      };

      setLastOrder(finalOrder);
      setLastOrderId(orderId);
      setShowReceipt(true);
      setTodaySales(prev => ({ count: prev.count + 1, total: prev.total + total }));
      showToast?.(`✅ Sale complete! Change: ৳${change}`, 'success');
      clearCart();
    } catch (err) {
      showToast?.('Failed to save order. Please try again.', 'error');
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <div className="flex flex-col h-full min-h-screen bg-slate-100  -m-6 md:-m-10">
      {/* ── Scan Feedback Toast ── */}
      {scanFeedback && (
        <div className={`fixed top-20 left-1/2 -translate-x-1/2 z-[9995] px-6 py-3 rounded-2xl shadow-2xl font-black text-sm flex items-center gap-2 animate-bounce-in ${
          scanFeedback.type === 'success' ? 'bg-emerald-600 text-white' : 'bg-red-600 text-white'
        }`}>
          <Scan size={18} />{scanFeedback.msg}
        </div>
      )}

      {/* ── Top Bar ── */}
      <div className="bg-white  border-b px-6 py-3 flex items-center justify-between shrink-0">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 bg-gradient-to-br from-emerald-500 to-teal-600 rounded-2xl flex items-center justify-center shadow-lg shadow-emerald-500/20 text-black placeholder-black">
            <ShoppingCart size={20} className="text-white" />
          </div>
          <div>
            <h1 className="text-black font-black text-lg leading-tight">Point of Sale</h1>
            <p className="text-xs text-black">{settings?.siteName || 'Store'}</p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          {/* ✅ Scan Mode Toggle */}
          <button
            onClick={() => setScanMode(v => !v)}
            title={scanMode ? 'Disable barcode scanner mode' : 'Enable barcode scanner mode (F2)'}
            className={`flex items-center gap-2 px-4 py-2 rounded-2xl font-black text-sm transition-all ${
              scanMode
                ? 'bg-amber-500 text-white shadow-lg shadow-amber-500/30 animate-pulse-slow'
                : 'bg-slate-100 text-black hover:bg-slate-200'
            }`}
          >
            {scanMode ? <Zap size={16} /> : <Scan size={16} />}
            <span className="hidden sm:inline">{scanMode ? 'Scanning ON' : 'Scan'}</span>
          </button>

          <div className="hidden md:flex items-center gap-2 bg-emerald-50 text-emerald-700 px-4 py-2 rounded-2xl text-sm text-black placeholder-black">
            <TrendingUp size={14} />
            <span className="font-black">Today: ৳{todaySales.total.toLocaleString()}</span>
            <span className="text-emerald-500 font-bold">({todaySales.count} sales)</span>
          </div>
        </div>
      </div>

      {/* ── Split Layout ── */}
      <div className="flex flex-1 overflow-hidden">

        {/* ── LEFT: Products ── */}
        <div className="flex-1 flex flex-col overflow-hidden">
          {/* Search + Categories */}
          <div className="bg-white  border-b px-4 py-3 space-y-3">
            {/* ✅ Barcode Scan Input (visible when scan mode is ON) */}
            {scanMode && (
              <div className="relative">
                <Scan className="absolute left-4 top-1/2 -translate-y-1/2 text-amber-500" size={18} />
                <input
                  ref={barcodeInputRef}
                  type="text"
                  placeholder="🔍 Scan barcode or type product ID / name..."
                  className="w-full pl-11 pr-4 py-3 bg-amber-50 border-2 border-amber-400 rounded-2xl font-bold text-sm outline-none focus:ring-2 focus:ring-amber-500 transition-all text-black placeholder-black"
                  onKeyDown={e => {
                    if (e.key === 'Enter') {
                      const val = (e.target as HTMLInputElement).value.trim();
                      if (val) { processScan(val); (e.target as HTMLInputElement).value = ''; }
                      e.preventDefault();
                    }
                  }}
                  autoComplete="off"
                />
                <span className="absolute right-4 top-1/2 -translate-y-1/2 text-[10px] font-black text-amber-500 uppercase tracking-wider">Scanner Mode ON</span>
              </div>
            )}
            <div className="relative">
              <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-black" size={18} />
              <input
                ref={searchRef}
                type="text"
                placeholder="Search products..."
                value={searchQuery}
                onChange={e => setSearchQuery(e.target.value)}
                className="w-full pl-11 pr-4 py-3 bg-slate-50  rounded-2xl font-bold text-sm outline-none focus:ring-2 focus:ring-emerald-500 transition-all text-black placeholder-black"
              />
              {searchQuery && (
                <button onClick={() => setSearchQuery('')} className="absolute right-3 top-1/2 -translate-y-1/2 text-black hover:text-black">
                  <X size={16} />
                </button>
              )}
            </div>
            {/* Category Tabs */}
            <div className="flex gap-2 overflow-x-auto pb-1 scrollbar-none">
              {categories.map(cat => (
                <button
                  key={cat}
                  onClick={() => setSelectedCategory(cat)}
                  className={`shrink-0 px-4 py-2 rounded-xl font-bold text-xs transition-all ${
                    selectedCategory === cat
                      ? 'bg-emerald-600 text-white shadow-lg shadow-emerald-600/20'
                      : 'bg-slate-100  text-black hover:bg-slate-200'
                  }`}
                >
                  {cat === 'all' ? '🛍️ All' : cat}
                </button>
              ))}
            </div>
          </div>

          {/* Product Grid */}
          <div className="flex-1 overflow-y-auto p-4">
            {filteredProducts.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-full text-black">
                <Package size={48} className="mb-3 opacity-30" />
                <p className="text-black font-extrabold">No products found</p>
              </div>
            ) : (
              <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3">
                {filteredProducts.map(product => {
                  const configs = typeof product.priceConfigs === 'string'
                    ? (() => { try { return JSON.parse(product.priceConfigs as any); } catch { return {}; } })()
                    : (product.priceConfigs || {});
                  const hasSizes = Object.keys(configs).length > 0 || (product.sizes || []).length > 0;
                  const displayPrice = Object.values(configs)[0] ? (Object.values(configs)[0] as any).salePrice : product.price;

                  return (
                    <button
                      key={product.id}
                      onClick={() => addToCart(product)}
                      className="group bg-white  rounded-2xl overflow-hidden border border-slate-200 hover:border-emerald-400 hover:shadow-lg hover:shadow-emerald-500/10 transition-all active:scale-95 text-left text-black placeholder-black"
                    >
                      {/* Image */}
                      <div className="relative aspect-square bg-slate-100 overflow-hidden">
                        {product.image ? (
                          <img src={product.image} alt={product.name} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300" />
                        ) : (
                          <div className="w-full h-full flex items-center justify-center">
                            <ShoppingBag size={32} className="text-black" />
                          </div>
                        )}
                        {hasSizes && (
                          <div className="absolute top-1.5 right-1.5 bg-emerald-500 text-white text-[9px] font-black px-1.5 py-0.5 rounded-full">
                            {Object.keys(configs).length || product.sizes?.length} sizes
                          </div>
                        )}
                        <div className="absolute inset-0 bg-emerald-600/0 group-hover:bg-emerald-600/10 transition-colors flex items-center justify-center">
                          <Plus size={24} className="text-white opacity-0 group-hover:opacity-100 scale-75 group-hover:scale-100 transition-all bg-emerald-600 rounded-full p-1" />
                        </div>
                      </div>
                      {/* Info */}
                      <div className="p-2.5">
                        <p className="font-black text-xs leading-tight line-clamp-2 font-bangla">
                          {getBanglaName(product.nameBangla, product.name)}
                        </p>
                        <p className="text-emerald-600 font-black text-sm mt-1">৳{displayPrice.toLocaleString()}</p>
                      </div>
                    </button>
                  );
                })}
              </div>
            )}
          </div>
        </div>

        {/* ── RIGHT: Cart ── */}
        <div className="w-80 xl:w-96 bg-white  border-l flex flex-col shrink-0 shadow-2xl">
          {/* Cart Header */}
          <div className="p-4 border-b flex items-center justify-between">
            <div className="flex items-center gap-2">
              <ShoppingCart size={18} className="text-emerald-600" />
              <span className="text-black font-black">Cart</span>
              {cart.length > 0 && (
                <span className="bg-emerald-100 text-emerald-700 text-xs font-black px-2 py-0.5 rounded-full">
                  {cart.reduce((s, i) => s + i.quantity, 0)} items
                </span>
              )}
            </div>
            {cart.length > 0 && (
              <button onClick={clearCart} className="flex items-center gap-1 text-xs text-red-500 hover:text-red-700 font-bold px-2 py-1 hover:bg-red-50 rounded-lg transition-all">
                <Trash2 size={13} /> Clear
              </button>
            )}
          </div>

          {/* Customer */}
          <div className="p-4 border-b space-y-2">
            <div className="relative">
              <User className="absolute left-3 top-1/2 -translate-y-1/2 text-black" size={15} />
              <input
                type="text"
                placeholder="Customer name (optional)"
                value={customerName}
                onChange={e => setCustomerName(e.target.value)}
                className="w-full pl-9 pr-3 py-2.5 bg-slate-50  rounded-xl text-sm font-black outline-none focus:ring-2 focus:ring-emerald-500 text-black placeholder-black"
              />
            </div>
            <div className="relative">
              <Phone className="absolute left-3 top-1/2 -translate-y-1/2 text-black" size={15} />
              <input
                type="tel"
                placeholder="Phone (optional)"
                value={customerPhone}
                onChange={e => setCustomerPhone(e.target.value)}
                className="w-full pl-9 pr-3 py-2.5 bg-slate-50  rounded-xl text-sm font-black outline-none focus:ring-2 focus:ring-emerald-500 text-black placeholder-black"
              />
            </div>
          </div>

          {/* Cart Items */}
          <div className="flex-1 overflow-y-auto">
            {cart.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-full text-black p-8">
                <ShoppingCart size={40} className="mb-3" />
                <p className="text-black font-extrabold text-sm">Cart is empty</p>
                <p className="text-black font-bold text-xs mt-1">Click products to add</p>
              </div>
            ) : (
              <div className="divide-y">
                {cart.map((item, idx) => (
                  <div key={idx} className="p-3 flex items-center gap-3">
                    {item.image && (
                      <img src={item.image} alt={item.name} className="w-10 h-10 rounded-lg object-cover shrink-0" />
                    )}
                    <div className="flex-1 min-w-0">
                      <p className="font-bold text-xs leading-tight truncate font-bangla">
                        {getBanglaName(item.nameBangla, item.name)}
                        {item.size && <span className="text-black font-normal"> · {item.size}</span>}
                      </p>
                      <p className="text-emerald-600 font-black text-sm">৳{(item.price * item.quantity).toLocaleString()}</p>
                      <p className="text-[10px] text-black">৳{item.price} each</p>
                    </div>
                    <div className="flex items-center gap-1 shrink-0">
                      <button onClick={() => updateQty(idx, -1)} className="w-7 h-7 rounded-lg bg-slate-100 hover:bg-red-50 hover:text-red-600 flex items-center justify-center font-black transition-all">
                        <Minus size={12} />
                      </button>
                      <span className="w-7 text-center font-black text-sm">{item.quantity}</span>
                      <button onClick={() => updateQty(idx, 1)} className="w-7 h-7 rounded-lg bg-slate-100 hover:bg-emerald-50 hover:text-emerald-600 flex items-center justify-center font-black transition-all">
                        <Plus size={12} />
                      </button>
                      <button onClick={() => removeItem(idx)} className="w-7 h-7 rounded-lg bg-slate-100 hover:bg-red-50 hover:text-red-600 flex items-center justify-center transition-all ml-1">
                        <X size={12} />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Totals & Checkout */}
          <div className="border-t p-4 space-y-3 bg-slate-50 ">
            {/* Discount */}
            <div className="flex items-center gap-2">
              <Percent size={15} className="text-black shrink-0" />
              <input
                type="number"
                placeholder="Discount (৳)"
                value={discount}
                onChange={e => setDiscount(e.target.value)}
                min="0"
                max={subtotal}
                className="flex-1 px-3 py-2 bg-white  rounded-xl text-sm font-black outline-none focus:ring-2 focus:ring-emerald-500 border text-black placeholder-black"
              />
            </div>

            {/* Summary */}
            <div className="space-y-1 text-sm">
              <div className="flex justify-between text-black font-bold">
                <span>Subtotal</span><span className="font-bold">৳{subtotal.toLocaleString()}</span>
              </div>
              {discountAmt > 0 && (
                <div className="flex justify-between text-red-500">
                  <span>Discount</span><span className="font-bold">-৳{discountAmt.toLocaleString()}</span>
                </div>
              )}
              <div className="flex justify-between text-black font-black text-base border-t pt-2 mt-2">
                <span>Total</span><span className="text-emerald-600 text-lg">৳{total.toLocaleString()}</span>
              </div>
            </div>

            {/* Payment Method */}
            <div className="grid grid-cols-4 gap-1.5">
              {PAYMENT_METHODS.map(pm => (
                <button
                  key={pm.id}
                  onClick={() => setPaymentMethod(pm.id)}
                  className={`flex flex-col items-center py-2 px-1 rounded-xl font-bold text-[10px] transition-all ${
                    paymentMethod === pm.id
                      ? 'bg-emerald-600 text-white shadow-lg shadow-emerald-600/20'
                      : 'bg-white  text-black font-extrabold hover:bg-slate-100 border'
                  }`}
                >
                  <pm.icon size={14} className="mb-0.5" />
                  {pm.label}
                </button>
              ))}
            </div>

            {/* Paid Amount */}
            <div className="relative">
              <Banknote className="absolute left-3 top-1/2 -translate-y-1/2 text-black" size={15} />
              <input
                type="number"
                placeholder={`Paid amount (min ৳${total})`}
                value={paidAmount}
                onChange={e => setPaidAmount(e.target.value)}
                className="w-full pl-9 pr-3 py-3 bg-white  rounded-xl text-sm font-black outline-none focus:ring-2 focus:ring-emerald-500 border text-black placeholder-black"
              />
            </div>

            {/* Quick amount buttons */}
            <div className="grid grid-cols-4 gap-1.5">
              {[total, Math.ceil(total / 100) * 100, Math.ceil(total / 500) * 500, Math.ceil(total / 1000) * 1000]
                .filter((v, i, arr) => arr.indexOf(v) === i)
                .slice(0, 4)
                .map(amt => (
                  <button
                    key={amt}
                    onClick={() => setPaidAmount(String(amt))}
                    className="py-2 bg-white  border rounded-xl text-xs font-black hover:bg-emerald-50 hover:border-emerald-400 hover:text-emerald-700 transition-all text-black placeholder-black"
                  >
                    ৳{amt >= 1000 ? (amt / 1000 + 'k') : amt}
                  </button>
                ))}
            </div>

            {/* Change */}
            {paid > 0 && (
              <div className={`flex justify-between rounded-xl px-4 py-2.5 text-sm font-black ${change >= 0 ? 'bg-emerald-50 text-emerald-700' : 'bg-red-50 text-red-700'}`}>
                <span>{change >= 0 ? '💵 Change' : '⚠️ Short'}</span>
                <span>৳{Math.abs(change).toLocaleString()}</span>
              </div>
            )}

            {/* Note */}
            <input
              type="text"
              placeholder="Note (optional)"
              value={note}
              onChange={e => setNote(e.target.value)}
              className="w-full px-3 py-2 bg-white  rounded-xl text-xs font-black outline-none focus:ring-2 focus:ring-emerald-500 border text-black placeholder-black"
            />

            {/* Checkout Button */}
            <button
              onClick={handleCheckout}
              disabled={isSaving || cart.length === 0 || paid < total}
              className="w-full py-4 bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-700 hover:to-teal-700 disabled:from-slate-300 disabled:to-slate-400 disabled:cursor-not-allowed text-white rounded-2xl font-black text-base shadow-xl shadow-emerald-600/20 transition-all active:scale-95 flex items-center justify-center gap-2 text-black placeholder-black"
            >
              {isSaving ? (
                <><RefreshCw size={18} className="animate-spin" /> Processing...</>
              ) : (
                <><CheckCircle size={18} /> Complete Sale</>
              )}
            </button>
          </div>
        </div>
      </div>

      {/* Size Picker Modal */}
      {sizePicker && (
        <SizePicker
          product={sizePicker}
          onSelect={(size, price) => addToCart(sizePicker, size, price)}
          onClose={() => setSizePicker(null)}
        />
      )}

      {/* Receipt Modal */}
      {showReceipt && lastOrder && (
        <POSReceipt
          order={lastOrder}
          settings={settings}
          orderId={lastOrderId}
          onClose={() => setShowReceipt(false)}
        />
      )}
    </div>
  );
};

export default POSSystem;
