'use client';

import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import {
  Plus,
  Minus,
  Trash2,
  ShoppingCart,
  CheckCircle,
  User,
  CreditCard,
  Smartphone,
  Banknote,
  Search,
  X,
  Package,
  Receipt,
  Sparkles,
  Pause,
  Play,
  Clock,
  Pencil,
  Delete,
  Users,
  Phone,
  AlertTriangle,
  Keyboard,
} from 'lucide-react';
import LoadingSpinner from '@/components/LoadingSpinner';
import { formatCurrency, cn } from '@/lib/utils';
import { categoryApi, productApi, orderApi, heldOrderApi, discountApi, customerApi, settingsApi, transaksiApi } from '@/lib/api';
import ReceiptPrintButtons, { useReceiptPrinter } from '@/components/ReceiptPrinter';
import {
  cartLineKey,
  findProductUnit,
  getDefaultSaleUnit,
  initialSaleQty,
  isBaseQtyAllowed,
  nextSaleQty,
  qtyRuleMessage,
  toBaseQty,
  unitLabel,
  unitMultiplier,
} from '@/lib/productUnits';
import {
  clearCartStorage,
  clearFailedCheckout,
  loadCart,
  loadCartMeta,
  loadFailedCheckout,
  loadPrefs,
  saveCart,
  saveCartMeta,
  saveFailedCheckout,
  savePrefs,
} from '@/lib/cartStorage';
import type { Category, Product, OrderItem, HeldOrder, Order, AvailableDiscount, Customer, ReceiptData, ProductUnit } from '@/types';
import { useAuth } from '@/components/AuthContext';
import { canOverridePrice } from '@/lib/roles';

type PaymentMethod = 'cash' | 'transfer' | 'qris';
type ModalView = 'none' | 'item-note' | 'payment' | 'receipt' | 'held-orders' | 'customer-picker' | 'add-customer' | 'unit-picker';

interface CartItem extends OrderItem {
  _key: string;
  is_edited?: boolean;
  product_unit_id?: number | null;
  unit_name?: string | null;
  /** Base stock quantity for stock checks & tier pricing */
  base_qty: number;
  multiplier: number;
}

export default function TransaksiPage() {
  const { user } = useAuth();
  const allowPriceOverride = canOverridePrice(user);
  const [categories, setCategories] = useState<Category[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeCategory, setActiveCategory] = useState<number | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const searchInputRef = useRef<HTMLInputElement>(null);
  const cartHydrated = useRef(false);

  // Cart state (hydrated from localStorage after mount)
  const [cart, setCart] = useState<CartItem[]>([]);
  const [customerName, setCustomerName] = useState('');
  const [selectedCustomer, setSelectedCustomer] = useState<Customer | null>(null);
  const [discount, setDiscount] = useState(0);
  const [paymentMethod, setPaymentMethod] = useState<PaymentMethod>('cash');

  // Customer search state
  const [customerSearch, setCustomerSearch] = useState('');
  const [customerResults, setCustomerResults] = useState<Customer[]>([]);
  const [customerLoading, setCustomerLoading] = useState(false);

  // Add Customer form state
  const [newCustomerName, setNewCustomerName] = useState('');
  const [newCustomerPhone, setNewCustomerPhone] = useState('');
  const [newCustomerAddress, setNewCustomerAddress] = useState('');
  const [newCustomerNotes, setNewCustomerNotes] = useState('');
  const [creatingCustomer, setCreatingCustomer] = useState(false);

  // Autocomplete Customer dropdown state
  const [showCustomerDropdown, setShowCustomerDropdown] = useState(false);
  const [inlineCustomerResults, setInlineCustomerResults] = useState<Customer[]>([]);
  const [inlineCustomerLoading, setInlineCustomerLoading] = useState(false);

  // Payment status (piutang/tempo)
  const [paymentStatus, setPaymentStatus] = useState<'paid' | 'unpaid' | 'partial'>('paid');
  const [dueDate, setDueDate] = useState('');
  const [paidAmount, setPaidAmount] = useState('');
  /** Transfer / QRIS payment reference (required when marking paid) */
  const [paymentReference, setPaymentReference] = useState('');

  // Discount/Promo state
  const [availableDiscounts, setAvailableDiscounts] = useState<AvailableDiscount[]>([]);
  const [selectedDiscountId, setSelectedDiscountId] = useState<number | null>(null);
  const [showDiscountPicker, setShowDiscountPicker] = useState(false);

  // Modal state
  const [modalView, setModalView] = useState<ModalView>('none');
  const [editingItem, setEditingItem] = useState<CartItem | null>(null);
  const [itemNote, setItemNote] = useState('');
  const [editItemPrice, setEditItemPrice] = useState<string>('');
  const [editItemDiscount, setEditItemDiscount] = useState<string>('');
  // Unit picker when product has multiple sale units
  const [unitPickerProduct, setUnitPickerProduct] = useState<Product | null>(null);

  // Payment state
  const [cashReceived, setCashReceived] = useState('');
  const [submitting, setSubmitting] = useState(false);

  // Held orders
  const [heldOrders, setHeldOrders] = useState<HeldOrder[]>([]);

  // Success state
  const [completedOrder, setCompletedOrder] = useState<Order | null>(null);
  const [receiptData, setReceiptData] = useState<ReceiptData | null>(null);

  // Modern Toast State
  const [toast, setToast] = useState<{ message: string; type: 'error' | 'success' | 'warning' | 'info' } | null>(null);

  const showToast = useCallback((message: string, type: 'error' | 'success' | 'warning' | 'info' = 'error') => {
    setToast({ message, type });
  }, []);

  useEffect(() => {
    if (!toast) return;
    const timer = setTimeout(() => {
      setToast(null);
    }, 4000);
    return () => clearTimeout(timer);
  }, [toast]);

  // Prefs + printer
  const [autoPrintEnabled, setAutoPrintEnabled] = useState(false);
  const [showShortcuts, setShowShortcuts] = useState(false);
  const [failedCheckoutAt, setFailedCheckoutAt] = useState<string | null>(null);
  const [isOnline, setIsOnline] = useState(true);
  const { printReceipt } = useReceiptPrinter();

  // Restore cart + prefs from localStorage (once)
  useEffect(() => {
    const prefs = loadPrefs();
    setAutoPrintEnabled(prefs.autoPrint);

    const saved = loadCart<CartItem>();
    if (saved.length > 0) {
      setCart(saved);
    }
    const meta = loadCartMeta();
    if (meta.customerName) setCustomerName(meta.customerName);
    if (meta.paymentMethod) setPaymentMethod(meta.paymentMethod as PaymentMethod);
    if (meta.paymentStatus) setPaymentStatus(meta.paymentStatus as 'paid' | 'unpaid' | 'partial');
    if (typeof meta.discount === 'number') setDiscount(meta.discount);
    if (meta.selectedDiscountId) setSelectedDiscountId(meta.selectedDiscountId);
    if (meta.dueDate) setDueDate(meta.dueDate);
    if (meta.paidAmount) setPaidAmount(meta.paidAmount);
    if (meta.customerId) {
      customerApi.getById(meta.customerId).then(setSelectedCustomer).catch(() => {});
    }
    const failed = loadFailedCheckout();
    if (failed?.at) setFailedCheckoutAt(failed.at);
    cartHydrated.current = true;
  }, []);

  // Online / offline indicator
  useEffect(() => {
    if (typeof window === 'undefined') return;
    const sync = () => setIsOnline(navigator.onLine);
    sync();
    window.addEventListener('online', sync);
    window.addEventListener('offline', sync);
    return () => {
      window.removeEventListener('online', sync);
      window.removeEventListener('offline', sync);
    };
  }, []);

  // Persist cart whenever it changes (after hydrate)
  useEffect(() => {
    if (!cartHydrated.current) return;
    saveCart(cart);
    saveCartMeta({
      customerName,
      customerId: selectedCustomer?.id ?? null,
      paymentMethod,
      paymentStatus,
      discount,
      selectedDiscountId,
      dueDate,
      paidAmount,
    });
  }, [cart, customerName, selectedCustomer, paymentMethod, paymentStatus, discount, selectedDiscountId, dueDate, paidAmount]);

  // Click outside to close customer autocomplete dropdown
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (!target.closest('.customer-select-container')) {
        setShowCustomerDropdown(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Tax settings
  const [taxEnabled, setTaxEnabled] = useState(true);
  const [taxRate, setTaxRate] = useState(11); // percentage, default 11%

  // Animation
  const [addedProductId, setAddedProductId] = useState<number | null>(null);

  // Mobile cart
  const [showMobileCart, setShowMobileCart] = useState(false);

  useEffect(() => {
    const loadData = async () => {
      try {
        const initData = await transaksiApi.getInitData();
        setCategories(initData.categories);
        setProducts(initData.products.map((p) => ({ ...p, price: Number(p.price) })));
        setAvailableDiscounts(initData.discounts);
        if (initData.settings) {
          setTaxEnabled(initData.settings.tax_enabled ?? true);
          setTaxRate(Number(initData.settings.tax_rate) || 11);
        }
        setLoading(false);
      } catch (error: any) {
        console.warn('Failed to load data:', error?.message || error);
        setLoading(false);
      }
    };
    loadData();
  }, []);

  // Cart calculations (memoized)
  const filteredProducts = useMemo(() => products.filter((p) => {
    const matchCategory = activeCategory ? p.category_id === activeCategory : true;
    const matchSearch = searchQuery
      ? p.name.toLowerCase().includes(searchQuery.toLowerCase())
      : true;
    return matchCategory && matchSearch && p.is_available;
  }), [products, activeCategory, searchQuery]);

  const subtotal = useMemo(() => cart.reduce((sum, item) => sum + item.subtotal, 0), [cart]);
  const tax = useMemo(() => taxEnabled ? Math.round(subtotal * (taxRate / 100)) : 0, [subtotal, taxEnabled, taxRate]);

  // Calculate discount from selected promo
  const selectedDiscount = useMemo(() => availableDiscounts.find((d) => d.id === selectedDiscountId), [availableDiscounts, selectedDiscountId]);
  const promoDiscountAmount = useMemo(() => selectedDiscount
    ? selectedDiscount.type === 'percentage'
      ? Math.min(
          Math.round(subtotal * (selectedDiscount.value / 100)),
          selectedDiscount.max_discount ?? Infinity
        )
      : Math.min(selectedDiscount.value, subtotal)
    : 0, [selectedDiscount, subtotal]);
  const effectiveDiscount = useMemo(() => {
    if (selectedDiscountId) return promoDiscountAmount;
    // Manual % only for admin/manager — kasir totals must match server (promo only)
    if (allowPriceOverride && discount > 0) return Math.round(subtotal * (discount / 100));
    return 0;
  }, [selectedDiscountId, promoDiscountAmount, discount, subtotal, allowPriceOverride]);
  const total = Math.max(0, subtotal + tax - effectiveDiscount);
  const totalItems = useMemo(() => cart.reduce((sum, item) => sum + item.quantity, 0), [cart]);
  /** Total base stock reserved in cart (for stock display) */
  const cartBaseByProduct = useMemo(() => {
    const map = new Map<number, number>();
    for (const item of cart) {
      map.set(item.product_id, (map.get(item.product_id) || 0) + (item.base_qty || item.quantity));
    }
    return map;
  }, [cart]);
  const cashReceivedNum = Number(cashReceived) || 0;
  const cashChange = cashReceivedNum > total ? cashReceivedNum - total : 0;

  // ==========================================
  // CART ACTIONS
  // ==========================================

  // Get unit price based on tiered pricing
  const getUnitPrice = useCallback((product: Product, qty: number): number => {
    if (!product.prices || product.prices.length === 0) return product.price;
    const sortedTiers = [...product.prices].sort((a, b) => b.min_qty - a.min_qty);
    const matchedTier = sortedTiers.find((tier) => qty >= tier.min_qty);
    return matchedTier ? Number(matchedTier.price) : product.price;
  }, []);

  const getProductDiscountPercent = useCallback((product: Product): number => {
    const price = product.price;
    if (price <= 0) return 0;

    // 1. Look for product-scoped percentage discount
    const prodDiscountPct = availableDiscounts.find(
      (d) => d.scope === 'product' && d.product_id === product.id && d.type === 'percentage'
    );
    if (prodDiscountPct) return Number(prodDiscountPct.value);

    // 2. Look for product-scoped fixed discount → convert to effective %
    const prodDiscountFixed = availableDiscounts.find(
      (d) => d.scope === 'product' && d.product_id === product.id && d.type === 'fixed'
    );
    if (prodDiscountFixed) {
      const fixedAmt = Math.min(Number(prodDiscountFixed.value), price);
      return Math.round((fixedAmt / price) * 10000) / 100; // round to 2 decimal places
    }

    // 3. Look for category-scoped percentage discount
    const catDiscountPct = availableDiscounts.find(
      (d) => d.scope === 'category' && d.category_id === product.category_id && d.type === 'percentage'
    );
    if (catDiscountPct) return Number(catDiscountPct.value);

    // 4. Look for category-scoped fixed discount → convert to effective %
    const catDiscountFixed = availableDiscounts.find(
      (d) => d.scope === 'category' && d.category_id === product.category_id && d.type === 'fixed'
    );
    if (catDiscountFixed) {
      const fixedAmt = Math.min(Number(catDiscountFixed.value), price);
      return Math.round((fixedAmt / price) * 10000) / 100;
    }

    return 0;
  }, [availableDiscounts]);

  const getProductDiscountedPrice = useCallback((product: Product): { original: number; current: number; percent: number } => {
    const original = product.price;
    const percent = getProductDiscountPercent(product);
    const current = percent > 0 ? original * (1 - percent / 100) : original;
    return { original, current, percent };
  }, [getProductDiscountPercent]);

  /** Add product with optional sale unit (opens unit picker if multiple units) */
  const addToCartWithUnit = useCallback((product: Product, unit: ProductUnit | null = null) => {
    const unitId = unit?.id ?? null;
    const cartKey = cartLineKey(product.id, unitId);
    const mult = unitMultiplier(unit);
    const existing = cart.find((item) => item._key === cartKey);

    let newSaleQty: number;
    if (existing) {
      const next = nextSaleQty(product, existing.quantity, 1, unit);
      if (next === null || next <= 0) {
        showToast(qtyRuleMessage(product) || 'Qty tidak sesuai aturan min/kelipatan', 'warning');
        return;
      }
      newSaleQty = next;
    } else {
      newSaleQty = initialSaleQty(product, unit);
    }

    const newBase = toBaseQty(newSaleQty, unit);
    if (!isBaseQtyAllowed(product, newBase)) {
      showToast(qtyRuleMessage(product) || 'Qty tidak sesuai aturan min/kelipatan', 'warning');
      return;
    }

    // Stock check: other cart lines for same product + this line
    const otherBase = cart
      .filter((i) => i.product_id === product.id && i._key !== cartKey)
      .reduce((s, i) => s + (i.base_qty || 0), 0);
    if (otherBase + newBase > Number(product.stock)) {
      showToast(
        `Stok tidak mencukupi! Tersedia ${Number(product.stock)} ${product.unit}, butuh ${otherBase + newBase} ${product.unit}.`,
        'warning'
      );
      return;
    }

    setAddedProductId(product.id);
    setTimeout(() => setAddedProductId(null), 300);

    const label = unitLabel(product, unit);
    const discountPercent = getProductDiscountPercent(product);

    setCart((prev) => {
      if (existing) {
        if (existing.is_edited) {
          const gross = newBase * existing.unit_price;
          const discountAmount = gross * ((existing.discount || 0) / 100);
          return prev.map((item) =>
            item._key === cartKey
              ? {
                  ...item,
                  quantity: newSaleQty,
                  base_qty: newBase,
                  multiplier: mult,
                  subtotal: Math.round(gross - discountAmount),
                }
              : item
          );
        }
        const newUnitPrice = getUnitPrice(product, newBase);
        const gross = newBase * newUnitPrice;
        const discAmt = gross * (discountPercent / 100);
        return prev.map((item) =>
          item._key === cartKey
            ? {
                ...item,
                quantity: newSaleQty,
                base_qty: newBase,
                multiplier: mult,
                unit_price: newUnitPrice,
                product_price: product.price,
                discount: discountPercent,
                subtotal: Math.round(gross - discAmt),
              }
            : item
        );
      }

      const unitPrice = getUnitPrice(product, newBase);
      const gross = newBase * unitPrice;
      const discAmt = gross * (discountPercent / 100);
      return [
        ...prev,
        {
          _key: cartKey,
          product_id: product.id,
          product_unit_id: unitId,
          product_name: product.name,
          product_price: product.price,
          unit_price: unitPrice,
          quantity: newSaleQty,
          base_qty: newBase,
          multiplier: mult,
          unit_name: label,
          unit: label,
          discount: discountPercent,
          subtotal: Math.round(gross - discAmt),
        },
      ];
    });
  }, [cart, getUnitPrice, getProductDiscountPercent, showToast]);

  const addToCart = useCallback((product: Product) => {
    const units = product.units || [];
    if (units.length > 1) {
      // Let cashier pick unit when product has multiple sale units
      setUnitPickerProduct(product);
      setModalView('unit-picker');
      return;
    }
    const unit = units.length === 1 ? units[0] : getDefaultSaleUnit(product);
    addToCartWithUnit(product, unit);
  }, [addToCartWithUnit]);

  /** Barcode / SKU exact match → add to cart (scanner sends Enter) */
  const tryAddByCode = useCallback(
    (code: string): boolean => {
      const q = code.trim();
      if (!q) return false;
      const product = products.find(
        (p) =>
          p.is_available &&
          ((p.barcode && p.barcode.toLowerCase() === q.toLowerCase()) ||
            (p.sku && p.sku.toLowerCase() === q.toLowerCase()))
      );
      if (!product) return false;
      // Prefer default sale unit on scan (skip picker for speed)
      const unit = getDefaultSaleUnit(product) || (product.units?.length === 1 ? product.units[0] : null);
      if (product.units && product.units.length > 1 && !getDefaultSaleUnit(product)) {
        setUnitPickerProduct(product);
        setModalView('unit-picker');
      } else {
        addToCartWithUnit(product, unit);
      }
      showToast(`${product.name} ditambahkan`, 'success');
      return true;
    },
    [products, addToCartWithUnit, showToast]
  );

  const handleSearchKeyDown = useCallback(
    (e: React.KeyboardEvent<HTMLInputElement>) => {
      if (e.key !== 'Enter') return;
      e.preventDefault();
      const q = searchQuery.trim();
      if (!q) return;
      if (tryAddByCode(q)) {
        setSearchQuery('');
        return;
      }
      // Single filtered product → add it
      if (filteredProducts.length === 1) {
        addToCart(filteredProducts[0]);
        setSearchQuery('');
      }
    },
    [searchQuery, tryAddByCode, filteredProducts, addToCart]
  );

  const updateQuantity = useCallback((key: string, delta: number) => {
    const item = cart.find((i) => i._key === key);
    if (!item) return;

    const product = products.find((p) => p.id === item.product_id);
    if (!product) return;

    const unit = findProductUnit(product, item.product_unit_id);
    const newSaleQty = nextSaleQty(product, item.quantity, delta, unit);

    if (newSaleQty === null) {
      showToast(qtyRuleMessage(product) || 'Qty tidak sesuai aturan', 'warning');
      return;
    }
    if (newSaleQty <= 0) {
      setCart((prev) => prev.filter((i) => i._key !== key));
      return;
    }

    const newBase = toBaseQty(newSaleQty, unit);
    const otherBase = cart
      .filter((i) => i.product_id === product.id && i._key !== key)
      .reduce((s, i) => s + (i.base_qty || 0), 0);
    if (otherBase + newBase > Number(product.stock)) {
      showToast(
        `Stok tidak mencukupi! Tersedia ${Number(product.stock)} ${product.unit}.`,
        'warning'
      );
      return;
    }

    setCart((prev) =>
      prev.map((i) => {
        if (i._key !== key) return i;
        if (i.is_edited) {
          const gross = newBase * i.unit_price;
          const discountAmount = gross * ((i.discount || 0) / 100);
          return {
            ...i,
            quantity: newSaleQty,
            base_qty: newBase,
            subtotal: Math.round(gross - discountAmount),
          };
        }
        const newUnitPrice = getUnitPrice(product, newBase);
        const discountPercent = getProductDiscountPercent(product);
        const gross = newBase * newUnitPrice;
        const discountAmount = gross * (discountPercent / 100);
        return {
          ...i,
          quantity: newSaleQty,
          base_qty: newBase,
          unit_price: newUnitPrice,
          discount: discountPercent,
          subtotal: Math.round(gross - discountAmount),
        };
      })
    );
  }, [cart, products, getUnitPrice, getProductDiscountPercent, showToast]);

  const changeCartUnit = useCallback((key: string, unitId: number | null) => {
    const item = cart.find((i) => i._key === key);
    if (!item) return;
    const product = products.find((p) => p.id === item.product_id);
    if (!product) return;

    const unit = findProductUnit(product, unitId);
    const newKey = cartLineKey(product.id, unitId);
    // Merge into existing line if same unit already in cart
    if (newKey !== key && cart.some((i) => i._key === newKey)) {
      showToast('Satuan itu sudah ada di keranjang — ubah qty di baris tersebut.', 'warning');
      return;
    }

    const saleQty = item.quantity;
    const newBase = toBaseQty(saleQty, unit);
    if (!isBaseQtyAllowed(product, newBase)) {
      showToast(qtyRuleMessage(product) || 'Qty tidak valid untuk satuan ini', 'warning');
      return;
    }

    const otherBase = cart
      .filter((i) => i.product_id === product.id && i._key !== key)
      .reduce((s, i) => s + (i.base_qty || 0), 0);
    if (otherBase + newBase > Number(product.stock)) {
      showToast(`Stok tidak mencukupi untuk satuan ini.`, 'warning');
      return;
    }

    const label = unitLabel(product, unit);
    const mult = unitMultiplier(unit);
    const newUnitPrice = item.is_edited ? item.unit_price : getUnitPrice(product, newBase);
    const discountPercent = item.is_edited ? (item.discount || 0) : getProductDiscountPercent(product);
    const gross = newBase * newUnitPrice;
    const discAmt = gross * (discountPercent / 100);

    setCart((prev) =>
      prev.map((i) =>
        i._key === key
          ? {
              ...i,
              _key: newKey,
              product_unit_id: unitId,
              unit_name: label,
              unit: label,
              quantity: saleQty,
              base_qty: newBase,
              multiplier: mult,
              unit_price: newUnitPrice,
              discount: discountPercent,
              subtotal: Math.round(gross - discAmt),
            }
          : i
      )
    );
  }, [cart, products, getUnitPrice, getProductDiscountPercent, showToast]);

  const removeFromCart = useCallback((key: string) => {
    setCart((prev) => prev.filter((item) => item._key !== key));
  }, []);

  const clearCart = () => {
    setCart([]);
    setCustomerName('');
    setSelectedCustomer(null);
    setDiscount(0);
    setSelectedDiscountId(null);
    setPaymentMethod('cash');
    setPaymentStatus('paid');
    setDueDate('');
    setPaidAmount('');
    setPaymentReference('');
    setCashReceived('');
    clearCartStorage();
  };



  // ==========================================
  // EDIT ITEM
  // ==========================================

  /** Format raw digit string → "1.000.000" (no decimals) */
  const formatPriceInput = (raw: string): string => {
    const digits = raw.replace(/\D/g, '');
    if (!digits) return '';
    return parseInt(digits, 10).toLocaleString('id-ID');
  };

  /** Strip separators back to raw number string */
  const parsePriceInput = (formatted: string): number => {
    return parseInt(formatted.replace(/\./g, '').replace(/,/g, ''), 10) || 0;
  };

  const openEditItem = (item: CartItem) => {
    setEditingItem(item);
    setEditItemPrice(formatPriceInput(String(Math.floor(item.unit_price))));
    setEditItemDiscount(String(item.discount || 0));
    setItemNote(item.notes || '');
    setModalView('item-note');
  };

  const saveEditItem = () => {
    if (!editingItem) return;
    // Kasir may only edit notes — price/discount locked to catalog + server promos
    if (!allowPriceOverride) {
      setCart((prev) =>
        prev.map((item) =>
          item._key === editingItem._key
            ? { ...item, notes: itemNote || undefined }
            : item
        )
      );
      setModalView('none');
      setEditingItem(null);
      return;
    }

    const priceNum = Math.max(0, parsePriceInput(editItemPrice));
    const discountNum = Math.max(0, Math.min(100, Number(editItemDiscount) || 0));
    // Price is per base unit; subtotal = base_qty × price
    const baseQty = editingItem.base_qty || editingItem.quantity;
    const gross = baseQty * priceNum;
    const discountAmount = gross * (discountNum / 100);

    setCart((prev) =>
      prev.map((item) =>
        item._key === editingItem._key
          ? {
              ...item,
              unit_price: priceNum,
              discount: discountNum,
              subtotal: Math.round(gross - discountAmount),
              notes: itemNote || undefined,
              is_edited: true,
            }
          : item
      )
    );
    setModalView('none');
    setEditingItem(null);
  };

  // ==========================================
  // HOLD / OPEN BILL
  // ==========================================
  const holdOrder = async () => {
    if (cart.length === 0) return;
    try {
      await heldOrderApi.create({
        label: customerName || `Pesanan ${new Date().toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' })}`,
        cart_data: cart.map((item, idx) => ({
          product_id: item.product_id,
          product_unit_id: item.product_unit_id ?? null,
          product_name: item.product_name,
          product_price: item.product_price,
          unit: item.unit_name || item.unit || 'pcs',
          unit_name: item.unit_name || item.unit || 'pcs',
          quantity: item.quantity,
          base_qty: item.base_qty,
          multiplier: item.multiplier,
          unit_price: item.unit_price,
          discount: item.discount || 0,
          subtotal: item.subtotal,
          notes: item.notes,
          is_edited: item.is_edited,
          ...(idx === 0 && selectedDiscountId ? { selected_discount_id: selectedDiscountId } : {}),
        })),
        customer_id: selectedCustomer?.id || undefined,
        customer_name: customerName || undefined,
        payment_method: paymentMethod,
        discount: discount > 0 ? discount : undefined,
      });
      clearCart();
      showToast('Pesanan berhasil disimpan di Open Bill!', 'success');
    } catch (error: any) {
      if (error.response?.status === 422) {
        console.warn('Failed to hold order (validation):', error.response.data);
      } else {
        console.warn('Failed to hold order:', error?.message || error);
      }
      let errMsg = 'Gagal menyimpan pesanan.';
      if (error.response?.data?.message) {
        errMsg = error.response.data.message;
        if (error.response.data.errors) {
          const detailedErrors = Object.values(error.response.data.errors).flat().join(', ');
          if (detailedErrors) {
            errMsg += `: ${detailedErrors}`;
          }
        }
      }
      showToast(errMsg, 'error');
    }
  };

  const loadHeldOrders = async () => {
    try {
      const data = await heldOrderApi.getAll();
      setHeldOrders(data);
      setModalView('held-orders');
    } catch (error: any) {
      console.warn('Failed to load held orders:', error?.message || error);
    }
  };

  const resumeHeldOrder = async (held: HeldOrder) => {
    setCart(held.cart_data.map((item, i) => {
      const uPrice = Number(item.unit_price) || Number(item.product_price) || 0;
      const prodPrice = Number(item.product_price) || uPrice || 0;
      const disc = Number(item.discount) || 0;
      const qty = Number(item.quantity) || 1;
      const mult = Number(item.multiplier) > 0 ? Number(item.multiplier) : 1;
      const baseQty = Number(item.base_qty) > 0 ? Number(item.base_qty) : qty * mult;
      const unitId = item.product_unit_id ?? null;
      const label = item.unit_name || item.unit || 'pcs';
      const sub = Number(item.subtotal) || Math.round(baseQty * uPrice * (1 - disc / 100));

      return {
        product_id: item.product_id,
        product_unit_id: unitId,
        product_name: item.product_name,
        product_price: prodPrice,
        unit_price: uPrice,
        quantity: qty,
        base_qty: baseQty,
        multiplier: mult,
        unit_name: label,
        unit: label,
        discount: disc,
        subtotal: sub,
        notes: item.notes,
        is_edited: item.is_edited,
        _key: cartLineKey(item.product_id, unitId) + `-${i}`,
      } as CartItem;
    }));
    setCustomerName(held.customer_name || '');
    if (held.customer_id) {
      try {
        const cust = await customerApi.getById(held.customer_id);
        setSelectedCustomer(cust);
      } catch { /* ignore */ }
    }
    setPaymentMethod((held.payment_method as PaymentMethod) || 'cash');

    const promoId = held.cart_data[0]?.selected_discount_id || null;
    setSelectedDiscountId(promoId);
    setDiscount(promoId ? 0 : (Number(held.discount) || 0));

    try {
      await heldOrderApi.delete(held.id);
    } catch (e) { /* ignore */ }
    setModalView('none');
  };

  const deleteHeldOrder = async (id: number) => {
    try {
      await heldOrderApi.delete(id);
      setHeldOrders((prev) => prev.filter((h) => h.id !== id));
    } catch (error: any) {
      console.warn('Failed to delete held order:', error?.message || error);
    }
  };

  // ==========================================
  // PAYMENT FLOW
  // ==========================================
  const openPayment = () => {
    if (cart.length === 0) return;
    setCashReceived('');
    setModalView('payment');
  };

  const handleNumpad = (val: string) => {
    if (val === 'clear') {
      setCashReceived('');
    } else if (val === 'backspace') {
      setCashReceived((prev) => prev.slice(0, -1));
    } else if (val === '000') {
      setCashReceived((prev) => prev + '000');
    } else {
      setCashReceived((prev) => prev + val);
    }
  };

  const quickCash = (amount: number) => {
    setCashReceived(String(amount));
  };

  const handleCreateOrder = async () => {
    if (cart.length === 0 || submitting) return;

    // Transfer/QRIS paid requires reference for audit trail
    if (
      paymentStatus === 'paid' &&
      (paymentMethod === 'transfer' || paymentMethod === 'qris') &&
      !paymentReference.trim()
    ) {
      showToast('Isi nomor referensi / bukti transfer atau QRIS.', 'error');
      return;
    }

    setSubmitting(true);
    // Snapshot cart before clear (stock optimistic update + payload)
    const cartSnapshot = cart;
    try {
      const paidAmountNum = Number(paidAmount) || 0;
      const order = await orderApi.create({
        customer_id: selectedCustomer?.id || undefined,
        customer_name: customerName || undefined,
        order_type: 'retail',
        payment_method: paymentMethod,
        payment_status: paymentStatus,
        due_date: paymentStatus !== 'paid' && dueDate ? dueDate : undefined,
        paid_amount: paymentStatus === 'partial' && paidAmountNum > 0 ? paidAmountNum : undefined,
        payment_reference:
          paymentStatus === 'paid' &&
          (paymentMethod === 'transfer' || paymentMethod === 'qris') &&
          paymentReference.trim()
            ? paymentReference.trim()
            : undefined,
        notes:
          paymentStatus === 'paid' &&
          (paymentMethod === 'transfer' || paymentMethod === 'qris') &&
          paymentReference.trim()
            ? paymentReference.trim()
            : undefined,
        discount_id: selectedDiscountId || undefined,
        // Manual nominal discount only for admin/manager; kasir uses discount_id promo only
        discount:
          allowPriceOverride && !selectedDiscountId && effectiveDiscount > 0
            ? effectiveDiscount
            : undefined,
        cash_received: paymentMethod === 'cash' && paymentStatus === 'paid' && cashReceivedNum > 0 ? cashReceivedNum : undefined,
        items: cartSnapshot.map((item) => {
          const line: {
            product_id: number;
            quantity: number;
            product_unit_id?: number;
            unit_price?: number;
            discount?: number;
            notes?: string;
          } = {
            product_id: item.product_id,
            quantity: item.quantity,
            product_unit_id: item.product_unit_id ?? undefined,
            notes: item.notes || undefined,
          };
          // Server ignores client price/discount for kasir; only send override when allowed
          if (allowPriceOverride && item.is_edited) {
            line.unit_price = item.unit_price;
            line.discount = item.discount || 0;
          }
          return line;
        }),
      });
      setCompletedOrder({
        ...order,
        total: Number(order.total),
        subtotal: Number(order.subtotal),
        tax: Number(order.tax),
        discount: Number(order.discount),
        cash_received: order.cash_received ? Number(order.cash_received) : undefined,
        cash_change: order.cash_change ? Number(order.cash_change) : undefined,
      });
      setModalView('receipt');
      setShowMobileCart(false);

      // Optimistic stock update by base qty (from snapshot, before cart clear)
      setProducts((prevProducts) =>
        prevProducts.map((prod) => {
          const usedBase = cartSnapshot
            .filter((item) => item.product_id === prod.id)
            .reduce((s, item) => s + (item.base_qty || item.quantity), 0);
          return usedBase > 0 ? { ...prod, stock: Math.max(0, prod.stock - usedBase) } : prod;
        })
      );

      // Clear cart + persisted draft immediately (receipt stays open)
      clearCart();
      clearFailedCheckout();
      setFailedCheckoutAt(null);

      // Fetch receipt data for print
      try {
        const receipt = await orderApi.getReceipt(order.id);
        setReceiptData(receipt);

        const prefs = loadPrefs();
        if (prefs.autoPrint || autoPrintEnabled) {
          printReceipt(receipt, 'customer');
        }
      } catch {
        // Non-critical
      }
    } catch (error: any) {
      // Keep draft for retry after network/server failure
      try {
        saveFailedCheckout({
          customer_id: selectedCustomer?.id,
          customer_name: customerName,
          order_type: 'retail',
          payment_method: paymentMethod,
          payment_status: paymentStatus,
          // Mirror checkout rules: never persist price override for kasir
          items: cartSnapshot.map((item) => {
            const line: {
              product_id: number;
              quantity: number;
              product_unit_id?: number | null;
              unit_price?: number;
              discount?: number;
            } = {
              product_id: item.product_id,
              quantity: item.quantity,
              product_unit_id: item.product_unit_id,
            };
            if (allowPriceOverride && item.is_edited) {
              line.unit_price = item.unit_price;
              line.discount = item.discount || 0;
            }
            return line;
          }),
        });
        setFailedCheckoutAt(new Date().toISOString());
      } catch {
        /* ignore */
      }
      if (error.response?.status === 422) {
        console.warn('Failed to create order (validation/stock):', error.response.data);
      } else {
        console.warn('Failed to create order:', error?.message || error);
      }
      let errMsg = 'Gagal membuat pesanan. Silakan coba lagi.';
      const data = error.response?.data;
      if (data?.message) {
        errMsg = data.message;
      }
      // Surface stock / qty_rules validation clearly
      if (data?.errors) {
        const stock = data.errors.stock;
        const qtyRules = data.errors.qty_rules;
        if (Array.isArray(stock) && stock.length) {
          errMsg = stock.join(' · ');
        } else if (Array.isArray(qtyRules) && qtyRules.length) {
          errMsg = qtyRules.join(' · ');
        } else {
          const detailedErrors = Object.values(data.errors).flat().join(', ');
          if (detailedErrors) errMsg += `: ${detailedErrors}`;
        }
      }
      if (Array.isArray(data?.insufficient_stock) && data.insufficient_stock.length) {
        errMsg = data.insufficient_stock
          .map(
            (s: { product?: string; needed?: number; available?: number; unit?: string }) =>
              `${s.product}: butuh ${s.needed} ${s.unit || ''}, sisa ${s.available}`
          )
          .join(' · ');
      }
      showToast(errMsg, 'error');
      // Stay on payment modal so cashier can fix cart
      if (modalView !== 'payment') {
        setModalView('none');
      }
    } finally {
      setSubmitting(false);
    }
  };

  const handleNewOrder = () => {
    clearCart();
    setCompletedOrder(null);
    setReceiptData(null);
    setModalView('none');
    setShowMobileCart(false);

    // Silent background refresh of products to sync 100% with database server
    transaksiApi.getInitData().then((initData) => {
      setProducts(initData.products.map((p) => ({ ...p, price: Number(p.price) })));
      setAvailableDiscounts(initData.discounts);
    }).catch((err) => console.warn('Failed to sync background products:', err?.message || err));
  };

  const retryFailedCheckout = async () => {
    const failed = loadFailedCheckout();
    if (!failed?.payload || submitting) return;
    setSubmitting(true);
    try {
      const order = await orderApi.create(failed.payload as Parameters<typeof orderApi.create>[0]);
      setCompletedOrder({
        ...order,
        total: Number(order.total),
        subtotal: Number(order.subtotal),
        tax: Number(order.tax),
        discount: Number(order.discount),
      });
      setModalView('receipt');
      clearCart();
      clearFailedCheckout();
      setFailedCheckoutAt(null);
      showToast('Checkout ulang berhasil', 'success');
      try {
        const receipt = await orderApi.getReceipt(order.id);
        setReceiptData(receipt);
      } catch {
        /* ignore */
      }
    } catch (error: unknown) {
      const msg =
        error && typeof error === 'object' && 'response' in error
          ? (error as { response?: { data?: { message?: string } } }).response?.data?.message
          : undefined;
      showToast(msg || 'Retry gagal — periksa stok/jaringan', 'error');
    } finally {
      setSubmitting(false);
    }
  };

  // Keyboard shortcuts (F2 pay, Esc close, / focus search, Ctrl+S hold)
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      const tag = (e.target as HTMLElement)?.tagName;
      const inField =
        tag === 'INPUT' ||
        tag === 'TEXTAREA' ||
        tag === 'SELECT' ||
        (e.target as HTMLElement)?.isContentEditable;

      if (e.key === 'Escape') {
        if (modalView !== 'none') {
          e.preventDefault();
          if (modalView === 'receipt') {
            handleNewOrder();
          } else {
            setModalView('none');
            setUnitPickerProduct(null);
          }
        } else if (showMobileCart) {
          setShowMobileCart(false);
        }
        return;
      }

      if (e.key === 'F2') {
        e.preventDefault();
        if (cart.length > 0 && modalView === 'none' && !submitting) {
          openPayment();
        }
        return;
      }

      if (e.key === '/' && !inField) {
        e.preventDefault();
        searchInputRef.current?.focus();
        return;
      }

      if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
        e.preventDefault();
        if (cart.length > 0) {
          void holdOrder();
        }
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
    // eslint-disable-next-line react-hooks/exhaustive-deps -- stable handlers recreated each render
  }, [modalView, cart.length, submitting, showMobileCart]);

  const handleCreateCustomer = async () => {
    if (!newCustomerName.trim() || creatingCustomer) return;
    setCreatingCustomer(true);
    try {
      const customer = await customerApi.create({
        name: newCustomerName,
        phone: newCustomerPhone || undefined,
        address: newCustomerAddress || undefined,
        notes: newCustomerNotes || undefined,
      });
      setSelectedCustomer(customer);
      setCustomerName(customer.name);
      setNewCustomerName('');
      setNewCustomerPhone('');
      setNewCustomerAddress('');
      setNewCustomerNotes('');
      setModalView('none');
      showToast('Pelanggan baru berhasil ditambahkan!', 'success');
    } catch (error: any) {
      if (error.response?.status === 422) {
        console.warn('Failed to create customer (validation):', error.response.data);
      } else {
        console.warn('Failed to create customer:', error?.message || error);
      }
      let errMsg = 'Gagal menambahkan pelanggan baru.';
      if (error.response?.data?.message) {
        errMsg = error.response.data.message;
      }
      showToast(errMsg, 'error');
    } finally {
      setCreatingCustomer(false);
    }
  };

  // ==========================================
  // LOADING
  // ==========================================
  if (loading) {
    return (
      <div className="flex h-full items-center justify-center py-32 bg-gradient-to-br from-blue-50 to-white">
        <div className="text-center animate-fade-in">
          <Package className="h-12 w-12 text-blue-400 mx-auto animate-pulse-soft" />
          <p className="mt-4 text-sm text-gray-400">Memuat produk...</p>
        </div>
      </div>
    );
  }

  // ==========================================
  // RENDER
  // ==========================================
  return (
    <div className="flex h-full flex-col lg:flex-row relative bg-gradient-to-br from-blue-50 to-white">
      {/* Toast Notification overlay */}
      {toast && (
        <div className="fixed top-6 right-6 left-6 sm:left-auto sm:w-[400px] z-[100] animate-slide-in-right pointer-events-none">
          <div className={cn(
            "pointer-events-auto flex items-center gap-3.5 rounded-2xl border p-4 shadow-2xl backdrop-blur-md transition-all duration-350",
            toast.type === 'error' && "bg-red-50/95 border-red-200/50 text-red-900 shadow-red-500/10",
            toast.type === 'warning' && "bg-amber-50/95 border-amber-200/50 text-amber-900 shadow-amber-500/10",
            toast.type === 'success' && "bg-emerald-50/95 border-emerald-200/50 text-emerald-900 shadow-emerald-500/10",
            toast.type === 'info' && "bg-blue-50/95 border-blue-200/50 text-blue-900 shadow-blue-500/10"
          )}>
            <div className={cn(
              "flex h-10 w-10 shrink-0 items-center justify-center rounded-xl shadow-inner animate-scale-in",
              toast.type === 'error' && "bg-red-100 text-red-600",
              toast.type === 'warning' && "bg-amber-100 text-amber-600",
              toast.type === 'success' && "bg-emerald-100 text-emerald-600",
              toast.type === 'info' && "bg-blue-100 text-blue-600"
            )}>
              {toast.type === 'error' && <AlertTriangle className="h-5 w-5 animate-pulse-soft" />}
              {toast.type === 'warning' && <AlertTriangle className="h-5 w-5 animate-pulse-soft" />}
              {toast.type === 'success' && <CheckCircle className="h-5 w-5" />}
              {toast.type === 'info' && <Sparkles className="h-5 w-5" />}
            </div>
            
            <div className="flex-1 min-w-0">
              <p className="text-[10px] font-bold uppercase tracking-wider opacity-60 leading-none">
                {toast.type === 'error' ? 'Gagal' : toast.type === 'warning' ? 'Perhatian' : toast.type === 'success' ? 'Sukses' : 'Info'}
              </p>
              <p className="text-xs sm:text-sm font-bold mt-1.5 leading-tight">{toast.message}</p>
            </div>

            <button 
              onClick={() => setToast(null)} 
              className="shrink-0 text-gray-400 hover:text-gray-600 p-1.5 rounded-lg hover:bg-black/5 transition-colors cursor-pointer"
              aria-label="Tutup"
            >
              <X className="h-4 w-4" />
            </button>
          </div>
        </div>
      )}

      {/* ============================================================
          LEFT PANEL - Product Catalog
          ============================================================ */}
      <div className="flex-1 min-h-0 flex flex-col">

        {/* Offline / failed checkout banners */}
        {!isOnline && (
          <div className="shrink-0 bg-amber-500 text-white text-center text-xs font-bold py-1.5 px-3">
            Offline — cart tersimpan lokal. Checkout butuh koneksi.
          </div>
        )}
        {failedCheckoutAt && (
          <div className="shrink-0 bg-red-50 border-b border-red-200 px-3 py-2 flex flex-wrap items-center justify-between gap-2 text-xs">
            <span className="text-red-700 font-semibold">
              Ada checkout gagal ({new Date(failedCheckoutAt).toLocaleString('id-ID')})
            </span>
            <div className="flex gap-2">
              <button
                type="button"
                onClick={() => void retryFailedCheckout()}
                disabled={submitting}
                className="rounded-lg bg-red-600 text-white px-3 py-1 font-bold hover:bg-red-700 cursor-pointer disabled:opacity-50"
              >
                {submitting ? 'Mengirim…' : 'Retry checkout'}
              </button>
              <button
                type="button"
                onClick={() => {
                  clearFailedCheckout();
                  setFailedCheckoutAt(null);
                }}
                className="rounded-lg border border-red-200 text-red-600 px-3 py-1 font-semibold cursor-pointer"
              >
                Abaikan
              </button>
            </div>
          </div>
        )}

        {/* ── Sticky Navbar: Header + Search + Categories ── */}
        <div className="shrink-0 bg-white/95 backdrop-blur-sm z-10 border-b border-blue-100 px-4 xl:px-6 pt-3 xl:pt-4 pb-2 xl:pb-3 space-y-2 xl:space-y-3">

          {/* Top Bar: Title + Hold/Resume buttons */}
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-lg xl:text-xl font-bold text-gray-900 font-heading">Kasir Ecer</h1>
              <p className="text-[11px] text-gray-400 hidden xl:block">Pilih produk untuk menambahkan ke pesanan</p>
            </div>
            <div className="flex items-center gap-1.5">
              {/* Hold Order */}
              <button
                onClick={holdOrder}
                disabled={cart.length === 0}
                className={cn(
                  'flex items-center gap-1 rounded-lg xl:rounded-xl px-2.5 xl:px-3.5 py-1.5 xl:py-2 text-[11px] xl:text-xs font-semibold transition-all cursor-pointer',
                  cart.length > 0
                    ? 'bg-blue-50 text-blue-900 border border-blue-200 hover:bg-blue-100 active:scale-95 shadow-sm'
                    : 'bg-white text-gray-400 cursor-not-allowed'
                )}
              >
                <Pause className="h-3 w-3 xl:h-3.5 xl:w-3.5" />
                <span className="hidden sm:inline">Simpan</span>
              </button>
              {/* Resume / Open Bill */}
              <button
                onClick={loadHeldOrders}
                className="flex items-center gap-1 rounded-lg xl:rounded-xl bg-white border border-blue-200 px-2.5 xl:px-3.5 py-1.5 xl:py-2 text-[11px] xl:text-xs font-semibold text-blue-900 hover:bg-blue-50 active:scale-95 transition-all cursor-pointer shadow-sm"
              >
                <Play className="h-3 w-3 xl:h-3.5 xl:w-3.5" />
                <span className="hidden sm:inline">Open Bill</span>
              </button>
            </div>
          </div>

          {/* Search + barcode (Enter = scan) */}
          <div className="relative">
            <Search className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-blue-400" />
            <input
              ref={searchInputRef}
              type="text"
              placeholder="Cari / scan barcode / SKU… Enter"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              onKeyDown={handleSearchKeyDown}
              className="w-full rounded-lg xl:rounded-xl border border-blue-200 bg-white py-1.5 xl:py-2.5 pl-9 xl:pl-10 pr-16 text-xs xl:text-sm text-gray-700 placeholder:text-gray-400 focus:border-blue-800 focus:ring-2 focus:ring-blue-800/20 outline-none transition-shadow"
              style={{ boxShadow: 'var(--shadow-card)' }}
              autoComplete="off"
            />
            <div className="absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1">
              {searchQuery && (
                <button onClick={() => setSearchQuery('')} className="text-gray-400 hover:text-gray-600 cursor-pointer p-0.5" aria-label="Hapus pencarian">
                  <X className="h-4 w-4" />
                </button>
              )}
              <button
                type="button"
                onClick={() => setShowShortcuts((v) => !v)}
                className="text-blue-400 hover:text-blue-700 cursor-pointer p-0.5"
                title="Shortcut keyboard"
                aria-label="Shortcut"
              >
                <Keyboard className="h-3.5 w-3.5" />
              </button>
            </div>
            {showShortcuts && (
              <div className="absolute z-20 top-full mt-1 right-0 left-0 sm:left-auto sm:w-64 rounded-xl border border-blue-100 bg-white shadow-lg p-3 text-[11px] text-gray-600 space-y-1">
                <p className="font-bold text-gray-800 text-xs mb-1">Shortcut kasir</p>
                <p><kbd className="font-mono bg-blue-50 px-1 rounded">F2</kbd> Bayar</p>
                <p><kbd className="font-mono bg-blue-50 px-1 rounded">Esc</kbd> Tutup modal</p>
                <p><kbd className="font-mono bg-blue-50 px-1 rounded">/</kbd> Fokus cari/scan</p>
                <p><kbd className="font-mono bg-blue-50 px-1 rounded">Ctrl+S</kbd> Simpan open bill</p>
                <p><kbd className="font-mono bg-blue-50 px-1 rounded">Enter</kbd> di search = scan barcode</p>
              </div>
            )}
          </div>

          {/* Category Tabs */}
          <div className="flex gap-1 xl:gap-1.5 overflow-x-auto scrollbar-hide -mx-4 xl:-mx-6 px-4 xl:px-6">
            <button
              onClick={() => setActiveCategory(null)}
              className={cn(
                'shrink-0 rounded-lg px-2.5 xl:px-3.5 py-1 xl:py-1.5 text-[11px] xl:text-xs font-semibold transition-all cursor-pointer',
                activeCategory === null
                  ? 'bg-blue-900 text-white shadow-sm'
                  : 'bg-white text-blue-900 border border-blue-200 hover:bg-blue-50 active:scale-95'
              )}
            >
              Semua
            </button>
            {categories.map((cat) => (
              <button
                key={cat.id}
                onClick={() => setActiveCategory(cat.id)}
                className={cn(
                  'shrink-0 rounded-lg px-2.5 xl:px-3.5 py-1 xl:py-1.5 text-[11px] xl:text-xs font-semibold transition-all cursor-pointer',
                  activeCategory === cat.id
                    ? 'bg-blue-900 text-white shadow-sm'
                    : 'bg-white text-blue-900 border border-blue-200 hover:bg-blue-50 active:scale-95'
                )}
              >
                {cat.name}
              </button>
            ))}
          </div>
        </div>

        {/* ── Scrollable Product Grid ── */}
        <div className="flex-1 min-h-0 overflow-y-auto pb-24 lg:pb-2">
          <div className="p-2.5 lg:p-3 xl:px-5 xl:pt-3">
          <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5">
            {filteredProducts.map((product) => {
              const inCartBase = cartBaseByProduct.get(product.id) || 0;
              const inCart = inCartBase > 0;
              const isJustAdded = addedProductId === product.id;
              const { original, current, percent } = getProductDiscountedPrice(product);
              const ruleHint = qtyRuleMessage(product);
              return (
                  <button
                  key={product.id}
                  onClick={() => addToCart(product)}
                  className={cn(
                    'group relative flex flex-col rounded-xl border bg-white p-2 xl:p-2.5 text-left transition-all duration-200 cursor-pointer',
                    'active:scale-[0.97]',
                    inCart
                      ? 'border-blue-400/50 ring-1 ring-blue-400/20 bg-blue-50/50'
                      : 'border-blue-200 hover:border-blue-300',
                    isJustAdded && 'animate-cart-add',
                  )}
                  style={{ boxShadow: 'var(--shadow-card)' }}
                >
                  {/* Product Image / Image placeholder */}
                  <div className="relative mb-1.5 flex aspect-[3/2] w-full items-center justify-center rounded-lg bg-gradient-to-br from-blue-100 via-blue-50 to-white overflow-hidden shrink-0">
                    {product.image ? (
                      <img 
                        src={product.image.startsWith('http') ? product.image : `${(process.env.NEXT_PUBLIC_API_URL || 'http://127.0.0.1:8000/api').replace(/\/api$/, '')}/storage/${product.image}`} 
                        alt={product.name}
                        className="h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"
                        onError={(e) => {
                          (e.target as HTMLImageElement).style.display = 'none';
                          const parent = (e.target as HTMLImageElement).parentElement;
                          if (parent) {
                            const fallbackIcon = parent.querySelector('.fallback-icon');
                            if (fallbackIcon) {
                              fallbackIcon.classList.remove('hidden');
                            }
                          }
                        }}
                      />
                    ) : null}
                    
                    {/* Fallback Icon */}
                    <div className={cn("fallback-icon flex items-center justify-center h-full w-full", product.image && "hidden")}>
                      <Package className="h-5 w-5 xl:h-6 xl:w-6 text-blue-300 animate-float" />
                    </div>

                    {/* Hover overlay */}
                    <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-blue-900/10 rounded-lg">
                      <div className="h-7 w-7 rounded-full bg-white/95 flex items-center justify-center shadow-md">
                        <Plus className="h-3.5 w-3.5 text-blue-900" />
                      </div>
                    </div>
                  </div>
                  <p className="text-[11px] xl:text-xs font-semibold text-gray-700 leading-tight line-clamp-2 min-h-[2rem]">
                    {product.name}
                  </p>
                  {/* Sisa Stok Barang */}
                  <div className="mt-1 text-[9px] xl:text-[10px] text-gray-400 font-semibold">
                    Stok: <span className={cn(product.stock <= product.min_stock ? "text-red-500" : "text-blue-900")}>
                      {Math.round(Number(product.stock) - inCartBase)} {product.unit}
                    </span>
                    {product.units && product.units.length > 0 && (
                      <span className="ml-1 text-blue-500">· multi-satuan</span>
                    )}
                  </div>
                  {ruleHint && (
                    <p className="text-[8px] text-amber-600 font-medium truncate">{ruleHint}</p>
                  )}
                  <div className="mt-1 flex items-center justify-between">
                    <div>
                      {percent > 0 ? (
                        <div className="flex flex-col">
                          <p className="text-xs xl:text-sm font-bold text-blue-900">
                            {formatCurrency(current)}
                          </p>
                          <p className="text-[10px] text-gray-400 line-through">
                            {formatCurrency(original)}
                          </p>
                        </div>
                      ) : (
                        <div className="flex flex-col">
                          <p className="text-xs xl:text-sm font-bold text-gray-600">
                            {formatCurrency(original)}
                          </p>
                          <p className="text-[8px] text-gray-400">
                            / {product.unit || 'pcs'}
                            {product.units?.[0]
                              ? ` · ${formatCurrency(original * Number(product.units[0].multiplier))} / ${product.units[0].abbreviation || product.units[0].name}`
                              : ''}
                          </p>
                        </div>
                      )}
                    </div>
                    {percent > 0 ? (
                      <span className="text-[8px] xl:text-[9px] font-semibold text-red-700 bg-red-50 px-1 xl:px-1.5 py-0.5 rounded-full">
                        -{percent}%
                      </span>
                    ) : product.prices && product.prices.length > 0 ? (
                      <span className="text-[8px] xl:text-[9px] font-semibold text-green-700 bg-green-50 px-1 xl:px-1.5 py-0.5 rounded-full">
                        Tier qty
                      </span>
                    ) : product.stock <= product.min_stock ? (
                      <span className="text-[8px] xl:text-[9px] font-semibold text-red-600 bg-red-50 px-1 xl:px-1.5 py-0.5 rounded-full animate-pulse-soft">
                        Stok rendah
                      </span>
                    ) : null}
                  </div>
                  {/* Base qty badge in cart */}
                  {inCart && (
                    <span className="absolute -top-1.5 -right-1.5 flex h-5 min-w-5 px-1 xl:h-6 xl:min-w-6 items-center justify-center rounded-full bg-gradient-to-br from-blue-900 to-blue-900 text-[9px] xl:text-[10px] font-bold text-white shadow-lg animate-scale-in">
                      {inCartBase}
                    </span>
                  )}
                </button>
              );
            })}
          </div>

          {filteredProducts.length === 0 && (
            <div className="py-16 text-center animate-fade-in">
              <Search className="h-8 w-8 text-gray-600 mx-auto mb-2" />
              <p className="text-sm text-blue-400">Tidak ada produk ditemukan</p>
            </div>
          )}
          </div>
        </div>
      </div>

      {/* ============================================================
          MOBILE - Floating Cart Bar
          ============================================================ */}
      {cart.length > 0 && !showMobileCart && modalView === 'none' && (
        <button
          onClick={() => setShowMobileCart(true)}
          className="lg:hidden fixed bottom-4 left-4 right-4 z-40 flex items-center justify-between rounded-2xl bg-gradient-to-r from-blue-900 via-blue-800 to-blue-900 px-5 py-4 text-white active:scale-[0.98] transition-all animate-slide-up cursor-pointer"
          style={{ boxShadow: '0 -4px 20px rgba(37, 99, 235, 0.25)' }}
        >
          <div className="flex items-center gap-2.5 min-w-0">
            <ShoppingCart className="h-5 w-5 shrink-0" />
            <div className="min-w-0 text-left">
              <span className="text-sm font-semibold block">
                {cart.length} baris · {totalItems} qty jual
              </span>
              <span className="text-[10px] text-blue-100/80 truncate block">
                {cart
                  .slice(0, 2)
                  .map((i) => `${i.quantity}${i.unit_name ? ` ${i.unit_name}` : ''} ${i.product_name}`)
                  .join(' · ')}
                {cart.length > 2 ? '…' : ''}
              </span>
            </div>
          </div>
          <span className="text-sm font-bold shrink-0 ml-2">{formatCurrency(total > 0 ? total : 0)}</span>
        </button>
      )}

      {/* Mobile overlay */}
      {showMobileCart && (
        <div className="lg:hidden fixed inset-0 z-50 bg-black/40 animate-fade-in" onClick={() => setShowMobileCart(false)} />
      )}

      {/* ============================================================
          RIGHT PANEL - Cart (Desktop sidebar / Mobile bottom sheet)
          ============================================================ */}
      <div
        className={cn(
          'bg-white flex flex-col border-l border-blue-100',
          'lg:relative lg:w-[280px] xl:w-[360px] 2xl:w-[400px] lg:shrink-0 lg:translate-y-0 lg:h-full',
          'fixed inset-x-0 bottom-0 z-50 max-h-[92dvh] rounded-t-2xl shadow-2xl transition-transform duration-300 ease-out lg:rounded-none lg:shadow-none lg:max-h-none',
          showMobileCart ? 'translate-y-0' : 'translate-y-full lg:translate-y-0'
        )}
      >
        {/* Mobile handle */}
        <div className="lg:hidden pt-2.5 pb-1"><div className="drag-handle" /></div>

        {/* Cart Header */}
        <div className="flex items-center justify-between border-b border-blue-100 px-3 xl:px-5 py-2 xl:py-3">
          <div className="flex items-center gap-1.5">
            <Receipt className="h-3.5 w-3.5 text-blue-400" />
            <h2 className="text-xs xl:text-sm font-bold text-gray-700">Pesanan</h2>
            {cart.length > 0 && (
              <span className="rounded-full bg-blue-900 px-2 py-0.5 text-[10px] font-bold text-white">{totalItems}</span>
            )}
          </div>
          <div className="flex items-center gap-1">
            {cart.length > 0 && (
              <button onClick={clearCart} className="text-[10px] xl:text-xs text-red-500 hover:text-red-600 font-medium cursor-pointer px-1.5 py-0.5 rounded-lg hover:bg-red-50 transition-colors">
                Hapus
              </button>
            )}
            <button onClick={() => setShowMobileCart(false)} className="lg:hidden flex h-7 w-7 items-center justify-center rounded-full bg-blue-50 text-gray-500 cursor-pointer" aria-label="Tutup">
              <X className="h-3.5 w-3.5" />
            </button>
          </div>
        </div>

        {/* Customer Selection */}
        <div className="customer-select-container px-3 xl:px-5 py-1.5 xl:py-2.5 border-b border-blue-100 space-y-1 xl:space-y-2 relative">
          {/* Selected Customer or Name Input */}
          {selectedCustomer ? (
            <div className="flex items-center gap-2 rounded-lg bg-blue-50 px-2.5 py-1.5">
              <Users className="h-3 w-3 xl:h-3.5 xl:w-3.5 text-blue-600 shrink-0" />
              <div className="flex-1 min-w-0">
                <p className="text-[11px] xl:text-sm font-semibold text-gray-700 truncate">{selectedCustomer.name}</p>
                {selectedCustomer.phone && (
                  <p className="text-[9px] xl:text-[10px] text-gray-500 truncate">{selectedCustomer.phone}</p>
                )}
              </div>
              <button
                onClick={() => { setSelectedCustomer(null); setCustomerName(''); }}
                className="text-gray-400 hover:text-red-500 cursor-pointer"
              >
                <X className="h-3.5 w-3.5" />
              </button>
            </div>
          ) : (
            <div className="flex items-center gap-1.5">
              <div className="flex items-center gap-2 flex-1 rounded-lg bg-blue-50/50 px-2.5 py-1.5 min-w-0">
                <User className="h-3 w-3 xl:h-3.5 xl:w-3.5 text-blue-400 shrink-0" />
                <input
                  type="text"
                  placeholder="Nama pelanggan..."
                  value={customerName}
                  onFocus={() => {
                    if (customerName.length >= 2) {
                      setShowCustomerDropdown(true);
                    }
                  }}
                  onChange={async (e) => {
                    const val = e.target.value;
                    setCustomerName(val);
                    
                    if (val.length >= 2) {
                      setInlineCustomerLoading(true);
                      setShowCustomerDropdown(true);
                      try {
                        const results = await customerApi.search(val);
                        setInlineCustomerResults(results);
                      } catch {
                        setInlineCustomerResults([]);
                      } finally {
                        setInlineCustomerLoading(false);
                      }
                    } else {
                      setInlineCustomerResults([]);
                      setShowCustomerDropdown(false);
                    }
                  }}
                  className="flex-1 bg-transparent text-[11px] xl:text-xs text-gray-700 placeholder:text-gray-400 outline-none min-w-0"
                />
                {customerName && (
                  <button
                    onClick={() => { setCustomerName(''); setSelectedCustomer(null); setShowCustomerDropdown(false); }}
                    className="text-gray-400 hover:text-red-500 shrink-0 cursor-pointer"
                  >
                    <X className="h-3 w-3" />
                  </button>
                )}
              </div>
              <button
                onClick={() => {
                  setCustomerSearch(customerName);
                  setModalView('customer-picker');
                  setShowCustomerDropdown(false);
                }}
                className="flex items-center justify-center rounded-lg bg-blue-100 border border-blue-200 p-1.5 text-blue-900 hover:bg-blue-200 active:scale-95 transition-all cursor-pointer shrink-0"
                title="Cari Pelanggan"
              >
                <Search className="h-3.5 w-3.5" />
              </button>
              <button
                onClick={() => {
                  setNewCustomerName(customerName);
                  setModalView('add-customer');
                  setShowCustomerDropdown(false);
                }}
                className="flex items-center gap-1 rounded-lg bg-blue-900 px-2 py-1.5 text-[10px] xl:text-[11px] font-semibold text-white hover:bg-blue-800 active:scale-95 transition-all cursor-pointer shrink-0 shadow-sm"
                title="Tambah Pelanggan Baru"
              >
                <Plus className="h-3 w-3" />
                <span className="hidden sm:inline">Tambah</span>
              </button>
            </div>
          )}

          {/* Autocomplete Dropdown */}
          {showCustomerDropdown && !selectedCustomer && (
            <div 
              className="absolute left-3 right-3 top-full z-30 mt-1 max-h-56 overflow-y-auto rounded-xl border border-blue-100 bg-white p-1.5 shadow-2xl animate-fade-in"
              style={{ boxShadow: '0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1)' }}
            >
              {inlineCustomerLoading ? (
                <div className="flex items-center justify-center py-4 gap-2">
                  <LoadingSpinner size="sm" />
                  <span className="text-xs text-gray-400">Mencari pelanggan...</span>
                </div>
              ) : inlineCustomerResults.length > 0 ? (
                <div className="space-y-0.5">
                  {inlineCustomerResults.map((cust) => (
                    <button
                      key={cust.id}
                      onClick={() => {
                        setSelectedCustomer(cust);
                        setCustomerName(cust.name);
                        setShowCustomerDropdown(false);
                      }}
                      className="w-full flex items-center gap-2 rounded-lg px-2.5 py-2 hover:bg-blue-50 text-left cursor-pointer transition-colors"
                    >
                      <div className="h-6 w-6 rounded-full bg-blue-100 flex items-center justify-center shrink-0">
                        <User className="h-3.5 w-3.5 text-blue-600" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-xs font-semibold text-gray-700 truncate">{cust.name}</p>
                        {cust.phone && (
                          <p className="text-[9px] text-gray-500 truncate">{cust.phone}</p>
                        )}
                      </div>
                      {cust.outstanding_balance && cust.outstanding_balance > 0 ? (
                        <span className="text-[9px] font-bold text-red-500 bg-red-50 px-1.5 py-0.5 rounded-full shrink-0">
                          Piutang: {formatCurrency(cust.outstanding_balance)}
                        </span>
                      ) : null}
                    </button>
                  ))}
                </div>
              ) : (
                <div className="py-3 px-2.5 text-center space-y-2">
                  <p className="text-xs text-gray-400">Tidak ada pelanggan terdaftar dengan nama "{customerName}"</p>
                  <button
                    onClick={() => {
                      setNewCustomerName(customerName);
                      setModalView('add-customer');
                      setShowCustomerDropdown(false);
                    }}
                    className="inline-flex items-center gap-1 rounded-lg bg-blue-900 px-3 py-1.5 text-[10px] font-bold text-white hover:bg-blue-800 active:scale-95 transition-all cursor-pointer shadow-sm"
                  >
                    <Plus className="h-3 w-3" />
                    Tambah "{customerName}" Baru
                  </button>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Cart Items - scrollable, checkout stays fixed below */}
        <div className="flex-1 min-h-0 overflow-y-auto px-3 xl:px-5 py-1.5 space-y-1">
          {cart.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-6 xl:py-16 text-gray-400 animate-fade-in">
              <ShoppingCart className="h-8 w-8 xl:h-10 xl:w-10 mb-2 opacity-40" />
              <p className="text-xs xl:text-sm font-medium text-gray-500">Keranjang kosong</p>
              <p className="text-[11px] mt-0.5 text-gray-400">Pilih menu dari daftar</p>
            </div>
          ) : (
            cart.map((item) => (
              <div key={item._key} className="flex flex-col gap-1 rounded-lg border border-blue-100 bg-white p-2 xl:p-2.5 hover:bg-blue-50/30 transition-colors animate-slide-in-right">
                {/* Top row: Item name + delete/note */}
                <div className="flex items-start justify-between gap-1.5">
                  <div className="flex-1 min-w-0">
                    <p className="text-[11px] xl:text-sm font-semibold text-gray-700 truncate">{item.product_name}</p>
                    <div className="flex items-center gap-1.5 flex-wrap">
                      {item.discount && item.discount > 0 ? (
                        <>
                          <span className="text-[10px] xl:text-xs font-semibold text-red-600">{formatCurrency(item.unit_price * (1 - item.discount / 100))}</span>
                          <span className="text-[9px] xl:text-[10px] text-gray-400 line-through">{formatCurrency(item.unit_price)}</span>
                          <span className="text-[8px] xl:text-[9px] font-semibold text-red-700 bg-red-50 px-1 py-0.5 rounded-full">-{item.discount}%</span>
                        </>
                      ) : item.unit_price < item.product_price ? (
                        <>
                          <span className="text-[10px] xl:text-xs font-semibold text-green-600">{formatCurrency(item.unit_price)}</span>
                          <span className="text-[9px] xl:text-[10px] text-gray-400 line-through">{formatCurrency(item.product_price)}</span>
                          <span className="text-[8px] xl:text-[9px] font-semibold text-green-700 bg-green-50 px-1 py-0.5 rounded-full">Harga Grosir</span>
                        </>
                      ) : (
                        <span className="text-[10px] xl:text-xs text-gray-500">{formatCurrency(item.unit_price)}</span>
                      )}
                    </div>
                    {item.notes && (
                      <p className="text-[9px] xl:text-[10px] text-amber-600 mt-0.5 truncate">Catatan: {item.notes}</p>
                    )}
                  </div>
                  {/* Actions */}
                  <div className="flex items-center gap-0.5 shrink-0">
                    <button onClick={() => openEditItem(item)} className="flex h-5 w-5 xl:h-6 xl:w-6 items-center justify-center rounded text-gray-400 hover:text-amber-600 hover:bg-amber-50 transition-colors cursor-pointer" aria-label="Edit Item" title="Edit Item">
                      <Pencil className="h-2.5 w-2.5 xl:h-3 xl:w-3" />
                    </button>
                    <button onClick={() => removeFromCart(item._key)} className="flex h-5 w-5 xl:h-6 xl:w-6 items-center justify-center rounded text-gray-400 hover:text-red-500 hover:bg-red-50 transition-colors cursor-pointer" aria-label="Hapus">
                      <Trash2 className="h-2.5 w-2.5 xl:h-3 xl:w-3" />
                    </button>
                  </div>
                </div>

                {/* Unit selector when product has sale units */}
                {(() => {
                  const prod = products.find((p) => p.id === item.product_id);
                  const saleUnits = prod?.units || [];
                  if (saleUnits.length === 0) {
                    return (
                      <p className="text-[9px] text-gray-400">
                        {item.quantity} {item.unit_name || prod?.unit || 'pcs'}
                        {item.base_qty && item.multiplier > 1
                          ? ` (= ${item.base_qty} ${prod?.unit || 'pcs'})`
                          : ''}
                      </p>
                    );
                  }
                  return (
                    <select
                      value={item.product_unit_id ?? ''}
                      onChange={(e) => {
                        const v = e.target.value;
                        changeCartUnit(item._key, v ? Number(v) : null);
                      }}
                      className="mt-0.5 max-w-full text-[9px] xl:text-[10px] border border-blue-100 rounded px-1 py-0.5 text-gray-600 bg-white"
                    >
                      <option value="">{prod?.unit || 'pcs'}</option>
                      {saleUnits.map((u) => (
                        <option key={u.id} value={u.id}>
                          {u.abbreviation || u.name} (×{Number(u.multiplier)})
                        </option>
                      ))}
                    </select>
                  );
                })()}

                {/* Bottom row: Qty controls + subtotal */}
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-0.5">
                    <button onClick={() => updateQuantity(item._key, -1)} className="flex h-6 w-6 xl:h-7 xl:w-7 items-center justify-center rounded-md border border-blue-200 text-blue-900 hover:bg-blue-50 active:scale-90 transition-all cursor-pointer" aria-label="Kurangi">
                      <Minus className="h-2.5 w-2.5 xl:h-3 xl:w-3" />
                    </button>
                    <span className="min-w-5 xl:min-w-6 px-0.5 text-center text-[11px] xl:text-xs font-bold text-gray-700 tabular-nums">
                      {item.quantity}
                      <span className="block text-[8px] font-medium text-gray-400 leading-none">
                        {item.unit_name || 'pcs'}
                      </span>
                    </span>
                    <button onClick={() => updateQuantity(item._key, 1)} className="flex h-6 w-6 xl:h-7 xl:w-7 items-center justify-center rounded-md border border-blue-200 text-blue-900 hover:bg-blue-50 active:scale-90 transition-all cursor-pointer" aria-label="Tambah">
                      <Plus className="h-2.5 w-2.5 xl:h-3 xl:w-3" />
                    </button>
                  </div>
                  <p className="text-[11px] xl:text-xs font-bold text-gray-700 tabular-nums">
                    {formatCurrency(item.subtotal)}
                  </p>
                </div>
              </div>
            ))
          )}
        </div>

        {/* Checkout Footer - always visible, never scrolls */}
        <div className="shrink-0 border-t border-blue-100 px-3 xl:px-4 py-1.5 xl:py-2.5 space-y-1 xl:space-y-2 bg-gradient-to-t from-blue-50/30 to-white">
          {/* Discount / Promo section */}
          <div className="space-y-1">
            {selectedDiscountId && selectedDiscount ? (
              <div className="flex items-center justify-between rounded-md bg-green-50 border border-green-200 px-2 py-1 xl:px-2.5 xl:py-1.5">
                <div className="flex items-center gap-2 min-w-0">
                  <Sparkles className="h-3.5 w-3.5 text-green-400 shrink-0" />
                  <span className="text-xs font-semibold text-green-400 truncate">{selectedDiscount.label}</span>
                </div>
                <div className="flex items-center gap-2 shrink-0">
                  <span className="text-xs font-bold text-green-400 tabular-nums">-{formatCurrency(promoDiscountAmount)}</span>
                  <button
                    onClick={() => setSelectedDiscountId(null)}
                    className="text-green-500 hover:text-red-400 cursor-pointer transition-colors"
                  >
                    <X className="h-3.5 w-3.5" />
                  </button>
                </div>
              </div>
            ) : (
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-1.5">
                  <span className="text-[10px] xl:text-xs text-blue-400">Diskon</span>
                  {availableDiscounts.length > 0 && (
                    <button
                      onClick={() => setShowDiscountPicker(!showDiscountPicker)}
                      className="text-[9px] xl:text-[10px] font-semibold text-blue-900 hover:text-blue-800 cursor-pointer bg-blue-50 px-1.5 py-0.5 rounded-full border border-blue-200 transition-colors"
                    >
                      Promo
                    </button>
                  )}
                </div>
                {allowPriceOverride ? (
                  <div className="flex items-center gap-1">
                    <input
                      type="number"
                      inputMode="numeric"
                      min={0}
                      max={100}
                      value={discount || ''}
                      onChange={(e) => setDiscount(Math.max(0, Math.min(100, Number(e.target.value) || 0)))}
                      placeholder="0"
                      className="w-12 xl:w-14 text-right text-[10px] xl:text-xs font-medium text-gray-700 bg-transparent outline-none border-b border-dashed border-blue-200 focus:border-gray-500 py-0.5"
                    />
                    <span className="text-[10px] xl:text-xs text-blue-400">%</span>
                  </div>
                ) : (
                  <span className="text-[10px] xl:text-xs text-gray-400">Pilih promo</span>
                )}
              </div>
            )}

            {/* Promo picker dropdown */}
            {showDiscountPicker && !selectedDiscountId && (
              <div className="rounded-xl border border-blue-100 bg-white p-2 space-y-1 animate-fade-in max-h-40 overflow-y-auto">
                {availableDiscounts
                  .filter((d) => d.scope === 'order' && d.min_order <= subtotal)
                  .map((d) => (
                  <button
                    key={d.id}
                    onClick={() => {
                      setSelectedDiscountId(d.id);
                      setDiscount(0);
                      setShowDiscountPicker(false);
                    }}
                    className="w-full flex items-center justify-between rounded-lg px-3 py-2 text-left hover:bg-blue-100 transition-colors cursor-pointer group"
                  >
                    <div className="min-w-0">
                      <p className="text-xs font-semibold text-gray-700 truncate group-hover:text-amber-400">{d.name}</p>
                      <p className="text-[10px] text-blue-400">
                        {d.type === 'percentage' ? `${d.value}%` : formatCurrency(d.value)} off
                        {d.scope === 'category' && d.category_name ? ` - ${d.category_name}` : ''}
                        {d.scope === 'product' && d.product_name ? ` - ${d.product_name}` : ''}
                        {d.min_order > 0 ? ` (min ${formatCurrency(d.min_order)})` : ''}
                      </p>
                    </div>
                    <span className="text-[10px] font-bold text-amber-600 shrink-0 ml-2">
                      {d.type === 'percentage'
                        ? `-${d.value}%`
                        : `-${formatCurrency(d.value)}`}
                    </span>
                  </button>
                ))}
                {availableDiscounts.filter((d) => d.scope === 'order' && d.min_order <= subtotal).length === 0 && (
                  <p className="text-xs text-blue-400 text-center py-3">Tidak ada promo yang tersedia untuk subtotal ini</p>
                )}
              </div>
            )}
          </div>

          {/* Summary */}
          <div className="rounded-md xl:rounded-lg bg-white border border-blue-100 p-1.5 xl:p-2.5 space-y-0.5">
            <div className="flex justify-between text-[10px] xl:text-xs text-blue-400">
              <span>Subtotal</span>
              <span className="tabular-nums">{formatCurrency(subtotal)}</span>
            </div>
            <div className="flex justify-between items-center text-[10px] xl:text-xs text-blue-400">
              <div className="flex items-center gap-1.5">
                <span>PPN {taxRate}%</span>
                <button
                  type="button"
                  onClick={() => setTaxEnabled(!taxEnabled)}
                  className={cn(
                    "text-[8px] font-bold px-1.5 py-0.5 rounded-full border transition-all cursor-pointer",
                    taxEnabled
                      ? "bg-emerald-50 text-emerald-600 border-emerald-200 hover:bg-emerald-100"
                      : "bg-gray-50 text-gray-400 border-gray-200 hover:bg-gray-100"
                  )}
                >
                  {taxEnabled ? "Aktif" : "Nonaktif"}
                </button>
              </div>
              <span className={cn("tabular-nums", !taxEnabled && "text-gray-400 line-through")}>
                {formatCurrency(tax)}
              </span>
            </div>
            {effectiveDiscount > 0 && (
              <div className="flex justify-between text-[10px] xl:text-xs text-red-500">
                <span>{selectedDiscount ? selectedDiscount.name : `Diskon ${discount}%`}</span>
                <span className="tabular-nums">-{formatCurrency(effectiveDiscount)}</span>
              </div>
            )}
            <div className="border-t border-dashed border-blue-200 pt-1 flex justify-between">
              <span className="text-xs font-bold text-gray-700">Total</span>
              <span className="text-sm font-bold text-gray-700 tabular-nums">{formatCurrency(total > 0 ? total : 0)}</span>
            </div>
          </div>

          {/* Payment Method Quick Select */}
          <div className="grid grid-cols-3 gap-1">
            {([
              { value: 'cash' as const, label: 'Cash', icon: Banknote },
              { value: 'transfer' as const, label: 'Transfer', icon: CreditCard },
              { value: 'qris' as const, label: 'QRIS', icon: Smartphone },
            ]).map((m) => (
              <button
                key={m.value}
                onClick={() => setPaymentMethod(m.value)}
                className={cn(
                  'flex items-center justify-center gap-1 rounded-md py-1 xl:py-1.5 text-[10px] xl:text-xs font-semibold transition-all cursor-pointer active:scale-95',
                  paymentMethod === m.value
                    ? 'bg-blue-900 text-white'
                    : 'bg-white text-gray-400 hover:bg-blue-100'
                )}
              >
                <m.icon className="h-3 w-3" />
                {m.label}
              </button>
            ))}
          </div>

          {paymentStatus === 'paid' &&
            (paymentMethod === 'transfer' || paymentMethod === 'qris') && (
              <input
                type="text"
                value={paymentReference}
                onChange={(e) => setPaymentReference(e.target.value)}
                placeholder={
                  paymentMethod === 'qris'
                    ? 'No. referensi QRIS / bukti'
                    : 'No. referensi transfer / bukti'
                }
                maxLength={100}
                className="w-full rounded-md border border-blue-100 bg-white px-2 py-1.5 text-[10px] xl:text-xs text-gray-700 placeholder:text-gray-400 focus:outline-none focus:ring-1 focus:ring-blue-400"
              />
            )}

          {/* Bayar Button */}
          <button
            onClick={paymentStatus === 'paid' && paymentMethod === 'cash' ? openPayment : handleCreateOrder}
            disabled={cart.length === 0 || submitting}
            className={cn(
              'w-full rounded-lg py-2 xl:py-3 text-[11px] xl:text-sm font-bold transition-all cursor-pointer',
              cart.length > 0 && !submitting
                ? paymentStatus === 'unpaid'
                  ? 'bg-gradient-to-r from-red-600 via-red-500 to-red-600 text-white hover:from-red-700 hover:via-red-600 hover:to-red-700 active:scale-[0.98] shadow-lg shadow-red-600/25'
                  : paymentStatus === 'partial'
                  ? 'bg-gradient-to-r from-amber-600 via-amber-500 to-amber-600 text-white hover:from-amber-700 hover:via-amber-600 hover:to-amber-700 active:scale-[0.98] shadow-lg shadow-amber-600/25'
                  : 'bg-gradient-to-r from-blue-900 via-blue-800 to-blue-900 text-white hover:from-blue-900 hover:via-blue-800 hover:to-blue-900 active:scale-[0.98] shadow-lg shadow-blue-900/25'
                : 'bg-blue-50 text-blue-400 cursor-not-allowed'
            )}
          >
            {submitting ? (
              <span className="flex items-center justify-center gap-2"><LoadingSpinner size="sm" /> Memproses...</span>
            ) : (
              <span className="flex items-center justify-center gap-2">
                <Sparkles className="h-4 w-4" />
                {paymentStatus === 'unpaid'
                  ? `Buat Pesanan Tempo - ${formatCurrency(total > 0 ? total : 0)}`
                  : paymentStatus === 'partial'
                  ? `Bayar Sebagian - ${formatCurrency(Number(paidAmount) || 0)}`
                  : paymentMethod === 'cash'
                  ? `Bayar Cash - ${formatCurrency(total > 0 ? total : 0)}`
                  : `Bayar - ${formatCurrency(total > 0 ? total : 0)}`}
              </span>
            )}
          </button>
        </div>
      </div>

      {/* ============================================================
          MODALS
          ============================================================ */}

      {/* Overlay */}
      {modalView !== 'none' && (
        <div className="fixed inset-0 z-[60] bg-black/50 animate-fade-in flex items-center justify-center p-4" onClick={() => { if (modalView !== 'receipt') setModalView('none'); }}>
          <div className="w-full max-w-md" onClick={(e) => e.stopPropagation()}>

            {/* ---- EDIT ITEM MODAL ---- */}
            {modalView === 'item-note' && editingItem && (() => {
              const previewPrice = Math.max(0, parsePriceInput(editItemPrice));
              const previewDiscount = Math.max(0, Math.min(100, Number(editItemDiscount) || 0));
              const previewDiscountAmt = Math.round(previewPrice * (previewDiscount / 100));
              const previewFinal = Math.round(previewPrice - previewDiscountAmt);
              const autoDiscountPct = editingItem.product_id
                ? getProductDiscountPercent(products.find(p => p.id === editingItem.product_id) || { id: editingItem.product_id, price: editingItem.product_price, category_id: 0 } as Product)
                : 0;
              return (
              <div className="bg-white rounded-2xl shadow-2xl animate-scale-in overflow-hidden">
                {/* Modal header */}
                <div className="flex items-center justify-between px-5 pt-5 pb-3 border-b border-blue-50">
                  <div className="flex items-center gap-2">
                    <div className="flex h-7 w-7 items-center justify-center rounded-lg bg-amber-100">
                      <Pencil className="h-3.5 w-3.5 text-amber-600" />
                    </div>
                    <div>
                      <h3 className="text-sm font-bold text-gray-800">Edit Item</h3>
                      <p className="text-[10px] text-gray-400 truncate max-w-[200px]">{editingItem.product_name}</p>
                    </div>
                  </div>
                  <button onClick={() => setModalView('none')} className="flex h-7 w-7 items-center justify-center rounded-full bg-gray-100 text-gray-400 hover:bg-gray-200 hover:text-gray-600 transition-colors cursor-pointer"><X className="h-4 w-4" /></button>
                </div>

                <div className="p-5 space-y-4">
                  {/* Live Preview Panel */}
                  <div className="rounded-xl bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-100 p-3.5">
                    <p className="text-[9px] font-bold uppercase tracking-widest text-blue-400 mb-2.5">Preview Harga</p>
                    <div className="grid grid-cols-3 gap-1 text-center">
                      <div>
                        <p className="text-[9px] text-gray-400 mb-0.5">Harga Jual</p>
                        <p className="text-xs font-bold text-gray-700 tabular-nums">{formatCurrency(previewPrice)}</p>
                      </div>
                      <div className="border-x border-blue-100">
                        <p className="text-[9px] text-gray-400 mb-0.5">Potongan</p>
                        <p className="text-xs font-bold text-red-500 tabular-nums">-{formatCurrency(previewDiscountAmt)}</p>
                        {previewDiscount > 0 && <p className="text-[8px] text-red-400">{previewDiscount}%</p>}
                      </div>
                      <div>
                        <p className="text-[9px] text-gray-400 mb-0.5">Harga Final</p>
                        <p className="text-sm font-black text-blue-900 tabular-nums">{formatCurrency(previewFinal)}</p>
                      </div>
                    </div>
                    {previewPrice < editingItem.product_price && (
                      <p className="text-[9px] text-amber-500 text-center mt-2 flex items-center justify-center gap-1">
                        <AlertTriangle className="h-2.5 w-2.5" /> Harga di bawah harga normal ({formatCurrency(editingItem.product_price)})
                      </p>
                    )}
                  </div>

                  {/* Unit / base qty info */}
                  <div className="rounded-xl bg-blue-50/60 border border-blue-100 px-3 py-2 text-[11px] text-gray-600">
                    <span className="font-semibold text-gray-800">
                      {editingItem.quantity} {editingItem.unit_name || editingItem.unit || 'pcs'}
                    </span>
                    {editingItem.base_qty != null &&
                      editingItem.multiplier > 1 && (
                        <span className="text-gray-500">
                          {' '}
                          · stok {editingItem.base_qty} base @ harga per base unit
                        </span>
                      )}
                  </div>

                  {/* Price & Discount inputs — admin/manager only */}
                  {allowPriceOverride ? (
                    <>
                      <div className="grid grid-cols-2 gap-3">
                        <div>
                          <label className="block text-[10px] font-bold text-gray-500 uppercase tracking-wider mb-1.5">Harga / base (Rp)</label>
                          <div className="relative">
                            <span className="absolute left-3 top-1/2 -translate-y-1/2 text-[10px] text-gray-400 font-medium">Rp</span>
                            <input
                              type="text"
                              inputMode="numeric"
                              value={editItemPrice}
                              onChange={(e) => {
                                const raw = e.target.value.replace(/\D/g, '');
                                setEditItemPrice(raw ? parseInt(raw, 10).toLocaleString('id-ID') : '');
                              }}
                              placeholder="0"
                              className="w-full rounded-xl border border-blue-200 bg-blue-50/30 pl-7 pr-3 py-2.5 text-sm font-bold text-gray-800 outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-400/20 transition-shadow tabular-nums"
                            />
                          </div>
                          <button
                            onClick={() => setEditItemPrice(formatPriceInput(String(Math.floor(editingItem.product_price))))}
                            className="mt-1 text-[9px] text-blue-500 hover:text-blue-700 cursor-pointer"
                          >
                            Reset ke harga normal
                          </button>
                        </div>
                        <div>
                          <div className="flex items-center justify-between mb-1.5">
                            <label className="text-[10px] font-bold text-gray-500 uppercase tracking-wider">Diskon (%)</label>
                            {autoDiscountPct > 0 && (
                              <button
                                onClick={() => setEditItemDiscount(String(autoDiscountPct))}
                                className="text-[8px] font-semibold text-emerald-600 bg-emerald-50 border border-emerald-200 px-1.5 py-0.5 rounded-full hover:bg-emerald-100 cursor-pointer transition-colors"
                              >
                                Auto {autoDiscountPct}%
                              </button>
                            )}
                          </div>
                          <div className="relative">
                            <input
                              type="number"
                              inputMode="numeric"
                              min={0}
                              max={100}
                              value={editItemDiscount}
                              onChange={(e) => setEditItemDiscount(e.target.value)}
                              className="w-full rounded-xl border border-blue-200 bg-blue-50/30 px-3 py-2.5 text-sm font-bold text-gray-800 outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-400/20 transition-shadow pr-7"
                            />
                            <span className="absolute right-3 top-1/2 -translate-y-1/2 text-[10px] text-gray-400 font-medium">%</span>
                          </div>
                          <button
                            onClick={() => setEditItemDiscount('0')}
                            className="mt-1 text-[9px] text-gray-400 hover:text-red-500 cursor-pointer"
                          >
                            Hapus diskon
                          </button>
                        </div>
                      </div>

                      <div>
                        <p className="text-[9px] font-bold text-gray-400 uppercase tracking-wider mb-1.5">Diskon Cepat</p>
                        <div className="flex flex-wrap gap-1.5">
                          {[5, 10, 15, 20, 25, 30, 50].map((pct) => (
                            <button
                              key={pct}
                              onClick={() => setEditItemDiscount(String(pct))}
                              className={cn(
                                'rounded-full px-2.5 py-1 text-[10px] font-bold border transition-all active:scale-95 cursor-pointer',
                                Number(editItemDiscount) === pct
                                  ? 'bg-blue-900 text-white border-blue-900'
                                  : 'bg-white text-gray-600 border-gray-200 hover:border-blue-300 hover:bg-blue-50'
                              )}
                            >
                              -{pct}%
                            </button>
                          ))}
                        </div>
                      </div>
                    </>
                  ) : (
                    <div className="rounded-xl bg-amber-50 border border-amber-100 px-3 py-2 text-[11px] text-amber-800">
                      Harga &amp; diskon mengikuti katalog/promo. Kasir hanya bisa menambah catatan item.
                    </div>
                  )}

                  {/* Note */}
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase tracking-wider mb-1.5">Catatan Item</label>
                    <textarea
                      value={itemNote}
                      onChange={(e) => setItemNote(e.target.value)}
                      placeholder="Contoh: Kirim terpisah, Packing kardus..."
                      rows={2}
                      className="w-full rounded-xl border border-blue-200 bg-blue-50/30 px-3 py-2 text-sm text-gray-700 placeholder:text-gray-400 outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-400/20 resize-none transition-shadow"
                    />
                    <div className="flex flex-wrap gap-1 mt-1.5">
                      {['Packing kardus', 'Kirim terpisah', 'Fragile', 'Cek expired', 'Urgent'].map((q) => (
                        <button
                          key={q}
                          onClick={() => setItemNote((prev) => prev ? `${prev}, ${q}` : q)}
                          className="rounded-full bg-white border border-gray-200 px-2.5 py-0.5 text-[10px] font-medium text-gray-500 hover:bg-blue-50 hover:border-blue-200 active:scale-95 transition-all cursor-pointer"
                        >
                          {q}
                        </button>
                      ))}
                    </div>
                  </div>

                  {/* Actions */}
                  <div className="flex gap-2 pt-1">
                    <button
                      onClick={() => setModalView('none')}
                      className="flex-1 rounded-xl border border-gray-200 py-2.5 text-sm font-semibold text-gray-500 hover:bg-gray-50 active:scale-[0.98] transition-all cursor-pointer"
                    >
                      Batal
                    </button>
                    <button
                      onClick={saveEditItem}
                      className="flex-2 rounded-xl bg-gradient-to-r from-blue-900 to-blue-800 py-2.5 px-6 text-sm font-bold text-white hover:from-blue-800 hover:to-blue-700 active:scale-[0.98] transition-all cursor-pointer shadow-lg shadow-blue-900/20"
                    >
                      Simpan Perubahan
                    </button>
                  </div>
                </div>
              </div>
              );
            })()}

            {/* ---- CASH PAYMENT MODAL (Numpad) ---- */}
            {modalView === 'payment' && (
              <div className="bg-white rounded-2xl p-5 shadow-2xl animate-scale-in space-y-4">
                <div className="flex items-center justify-between">
                  <h3 className="text-sm font-bold text-gray-700">Pembayaran Cash</h3>
                  <button onClick={() => setModalView('none')} className="text-blue-400 hover:text-gray-600 cursor-pointer"><X className="h-4 w-4" /></button>
                </div>

                {/* Total */}
                <div className="text-center rounded-xl bg-white p-4">
                  <p className="text-xs text-blue-400">Total Tagihan</p>
                  <p className="text-2xl font-bold text-gray-700 font-heading tabular-nums">{formatCurrency(total)}</p>
                </div>

                {/* Cash received display */}
                <div className="text-center">
                  <p className="text-xs text-blue-400 mb-1">Uang Diterima</p>
                  <div className="rounded-xl border-2 border-blue-200 bg-white px-4 py-3 min-h-[48px] flex items-center justify-center">
                    <span className="text-2xl font-bold text-gray-700 tabular-nums">
                      {cashReceived ? formatCurrency(Number(cashReceived)) : <span className="text-gray-400">Rp 0</span>}
                    </span>
                  </div>
                  {cashReceivedNum >= total && cashReceivedNum > 0 && (
                    <p className="mt-2 text-sm font-bold text-green-600 animate-fade-in">
                      Kembalian: {formatCurrency(cashChange)}
                    </p>
                  )}
                </div>

                {/* Quick amounts */}
                <div className="grid grid-cols-4 gap-1.5">
                  {[
                    Math.ceil(total / 1000) * 1000,
                    Math.ceil(total / 5000) * 5000,
                    Math.ceil(total / 10000) * 10000,
                    Math.ceil(total / 50000) * 50000,
                  ].filter((v, i, a) => a.indexOf(v) === i && v >= total).slice(0, 4).map((amount) => (
                    <button
                      key={amount}
                      onClick={() => quickCash(amount)}
                      className={cn(
                        'rounded-lg py-2 text-xs font-semibold transition-all cursor-pointer active:scale-95',
                        cashReceivedNum === amount
                          ? 'bg-blue-900 text-white'
                          : 'bg-white text-gray-600 hover:bg-blue-100'
                      )}
                    >
                      {formatCurrency(amount)}
                    </button>
                  ))}
                </div>

                {/* Numpad */}
                <div className="grid grid-cols-3 gap-1.5">
                  {['1', '2', '3', '4', '5', '6', '7', '8', '9', '000', '0', 'backspace'].map((key) => (
                    <button
                      key={key}
                      onClick={() => handleNumpad(key)}
                      className="flex h-12 items-center justify-center rounded-xl bg-white text-base font-semibold text-gray-700 hover:bg-blue-100 active:bg-blue-100 active:scale-95 transition-all cursor-pointer"
                    >
                      {key === 'backspace' ? <Delete className="h-5 w-5" /> : key}
                    </button>
                  ))}
                </div>

                {/* Confirm */}
                <button
                  onClick={handleCreateOrder}
                  disabled={submitting || (cashReceivedNum > 0 && cashReceivedNum < total)}
                  className={cn(
                    'w-full rounded-xl py-3.5 text-sm font-bold transition-all cursor-pointer',
                    !submitting && (cashReceivedNum >= total || cashReceivedNum === 0)
                      ? 'bg-gradient-to-r from-green-600 to-green-700 text-white hover:from-green-700 hover:to-green-600 active:scale-[0.98] shadow-lg shadow-green-700/20'
                      : 'bg-gray-200 text-gray-400 cursor-not-allowed'
                  )}
                >
                  {submitting ? (
                    <span className="flex items-center justify-center gap-2"><LoadingSpinner size="sm" /> Memproses...</span>
                  ) : (
                    <span className="flex items-center justify-center gap-2">
                      <CheckCircle className="h-4 w-4" />
                      Konfirmasi Pembayaran
                    </span>
                  )}
                </button>
              </div>
            )}

            {/* ---- RECEIPT MODAL ---- */}
            {modalView === 'receipt' && completedOrder && (
              <div className="bg-white rounded-2xl shadow-2xl animate-scale-in overflow-hidden">
                {/* Receipt content - printable */}
                <div className="p-6 space-y-4 print:p-4" id="receipt">
                  {/* Header */}
                  <div className="text-center space-y-1">
                    <div className="flex justify-center mb-2">
                      <div className="h-14 w-14 rounded-full bg-green-50 flex items-center justify-center animate-bounce-in">
                        <CheckCircle className="h-7 w-7 text-green-500" />
                      </div>
                    </div>
                    <h3 className="text-lg font-bold text-gray-700 font-heading">Pesanan Berhasil!</h3>
                    <p className="text-xs text-blue-400">{new Date().toLocaleString('id-ID')}</p>
                  </div>

                  {/* Order number */}
                  <div className="text-center rounded-xl bg-white py-3 px-4">
                    <p className="text-[10px] text-blue-400 uppercase tracking-wider">No. Pesanan</p>
                    <p className="text-lg font-bold text-gray-700 font-heading tracking-wider">{completedOrder.order_number}</p>
                  </div>

                  {/* Items */}
                  <div className="space-y-1.5">
                    <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider">Item</p>
                    {completedOrder.items.map((item, idx) => {
                      const saleQty =
                        item.unit_qty != null && Number(item.unit_qty) > 0
                          ? Number(item.unit_qty)
                          : item.quantity;
                      const saleUnit = item.unit_name || item.unit || '';
                      return (
                        <div key={idx} className="flex justify-between text-xs">
                          <div className="flex-1">
                            <span className="text-gray-700">{item.product_name}</span>
                            <span className="text-blue-400 ml-1">
                              x{saleQty}
                              {saleUnit ? ` ${saleUnit}` : ''}
                            </span>
                            {item.unit_qty != null &&
                              item.unit_name &&
                              Number(item.quantity) !== Number(item.unit_qty) && (
                                <span className="text-[10px] text-gray-400 ml-1">
                                  (={item.quantity} base)
                                </span>
                              )}
                            {item.notes && <p className="text-[10px] text-amber-600">{item.notes}</p>}
                          </div>
                          <span className="text-gray-700 font-medium tabular-nums">
                            {formatCurrency(Number(item.subtotal))}
                          </span>
                        </div>
                      );
                    })}
                  </div>

                  {/* Divider */}
                  <div className="border-t border-dashed border-blue-200" />

                  {/* Totals */}
                  <div className="space-y-1">
                    <div className="flex justify-between text-xs text-blue-400">
                      <span>Subtotal</span>
                      <span className="tabular-nums">{formatCurrency(completedOrder.subtotal)}</span>
                    </div>
                    <div className="flex justify-between text-xs text-blue-400">
                      <span>PPN {taxRate}%</span>
                      <span className="tabular-nums">{formatCurrency(completedOrder.tax)}</span>
                    </div>
                    {completedOrder.discount > 0 && (
                      <div className="flex justify-between text-xs text-red-500">
                        <span>Diskon</span>
                        <span className="tabular-nums">-{formatCurrency(completedOrder.discount)}</span>
                      </div>
                    )}
                    <div className="border-t border-blue-200 pt-1.5 flex justify-between">
                      <span className="text-sm font-bold text-gray-700">Total</span>
                      <span className="text-sm font-bold text-gray-700 tabular-nums">{formatCurrency(completedOrder.total)}</span>
                    </div>
                  </div>

                  {/* Payment info */}
                  <div className="rounded-xl bg-blue-50/50 p-3 space-y-1">
                    <div className="flex justify-between text-xs">
                      <span className="text-blue-400">Pembayaran</span>
                      <span className="text-gray-700 font-medium capitalize">{completedOrder.payment_method === 'qris' ? 'QRIS' : completedOrder.payment_method}</span>
                    </div>
                    {completedOrder.customer_name && (
                      <div className="flex justify-between text-xs">
                        <span className="text-blue-400">Pelanggan</span>
                        <span className="text-gray-700 font-medium">{completedOrder.customer_name}</span>
                      </div>
                    )}
                    {completedOrder.cash_received && (
                      <>
                        <div className="flex justify-between text-xs">
                          <span className="text-blue-400">Tunai</span>
                          <span className="text-gray-700 font-medium tabular-nums">{formatCurrency(completedOrder.cash_received)}</span>
                        </div>
                        <div className="flex justify-between text-xs">
                          <span className="text-blue-400">Kembalian</span>
                          <span className="text-green-600 font-bold tabular-nums">{formatCurrency(completedOrder.cash_change || 0)}</span>
                        </div>
                      </>
                    )}
                  </div>
                </div>

                {/* Actions */}
                <div className="border-t border-blue-100 p-4 space-y-3 print:hidden">
                  {/* Auto Print Toggle */}
                  <label className="flex items-center gap-2 justify-center py-1 cursor-pointer select-none">
                    <input
                      type="checkbox"
                      checked={autoPrintEnabled}
                      onChange={(e) => {
                        const on = e.target.checked;
                        setAutoPrintEnabled(on);
                        savePrefs({ ...loadPrefs(), autoPrint: on });
                      }}
                      className="rounded border-blue-200 text-blue-900 focus:ring-blue-900 h-4 w-4 cursor-pointer"
                    />
                    <span className="text-[11px] xl:text-xs font-bold text-gray-500">Cetak Struk Otomatis (Auto-Print)</span>
                  </label>

                  <ReceiptPrintButtons receiptData={receiptData} />
                  <button
                    onClick={handleNewOrder}
                    className="w-full flex items-center justify-center gap-2 rounded-xl bg-blue-900 py-3 text-xs font-bold text-white hover:bg-blue-900 active:scale-[0.98] transition-all cursor-pointer"
                  >
                    <Plus className="h-4 w-4" />
                    Pesanan Baru
                  </button>
                </div>
              </div>
            )}

            {/* ---- CUSTOMER PICKER MODAL ---- */}
            {modalView === 'customer-picker' && (
              <div className="bg-white rounded-2xl p-5 shadow-2xl animate-scale-in space-y-4 max-h-[80vh] flex flex-col">
                <div className="flex items-center justify-between shrink-0">
                  <h3 className="text-sm font-bold text-gray-700 flex items-center gap-2">
                    <Users className="h-4 w-4 text-blue-400" />
                    Pilih Pelanggan
                  </h3>
                  <button onClick={() => setModalView('none')} className="text-blue-400 hover:text-gray-600 cursor-pointer"><X className="h-4 w-4" /></button>
                </div>

                {/* Search */}
                <div className="relative shrink-0">
                  <Search className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-blue-400" />
                  <input
                    type="text"
                    placeholder="Cari nama / telepon pelanggan..."
                    value={customerSearch}
                    onChange={async (e) => {
                      const q = e.target.value;
                      setCustomerSearch(q);
                      if (q.length >= 2) {
                        setCustomerLoading(true);
                        try {
                          const results = await customerApi.search(q);
                          setCustomerResults(results);
                        } catch {
                          setCustomerResults([]);
                        } finally {
                          setCustomerLoading(false);
                        }
                      } else {
                        setCustomerResults([]);
                      }
                    }}
                    className="w-full rounded-xl border border-blue-200 bg-white py-2.5 pl-10 pr-4 text-sm text-gray-700 placeholder:text-gray-400 focus:border-blue-800 focus:ring-2 focus:ring-blue-800/20 outline-none"
                    autoFocus
                  />
                </div>

                {/* Results */}
                <div className="flex-1 overflow-y-auto space-y-1.5">
                  {customerLoading ? (
                    <div className="py-8 text-center">
                      <LoadingSpinner size="sm" />
                      <p className="text-xs text-gray-400 mt-2">Mencari...</p>
                    </div>
                  ) : customerResults.length > 0 ? (
                    customerResults.map((cust) => (
                      <button
                        key={cust.id}
                        onClick={() => {
                          setSelectedCustomer(cust);
                          setCustomerName(cust.name);
                          setCustomerSearch('');
                          setCustomerResults([]);
                          setModalView('none');
                        }}
                        className="w-full flex items-center gap-3 rounded-xl border border-blue-100 px-4 py-3 hover:bg-blue-50 transition-colors cursor-pointer group active:scale-[0.98] text-left"
                      >
                        <div className="h-8 w-8 rounded-full bg-blue-100 flex items-center justify-center shrink-0">
                          <User className="h-4 w-4 text-blue-600" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-semibold text-gray-700 group-hover:text-blue-900 truncate">{cust.name}</p>
                          <div className="flex items-center gap-2 text-[10px] text-gray-500">
                            {cust.phone && (
                              <span className="flex items-center gap-0.5">
                                <Phone className="h-2.5 w-2.5" />
                                {cust.phone}
                              </span>
                            )}
                          </div>
                        </div>
                        {cust.outstanding_balance && cust.outstanding_balance > 0 && (
                          <span className="text-[10px] font-semibold text-red-500 shrink-0">
                            Piutang: {formatCurrency(cust.outstanding_balance)}
                          </span>
                        )}
                      </button>
                    ))
                  ) : customerSearch.length >= 2 ? (
                    <div className="py-8 text-center text-gray-400 space-y-3">
                      <Users className="h-8 w-8 mx-auto mb-1 opacity-40" />
                      <p className="text-sm">Pelanggan tidak ditemukan</p>
                      <button
                        onClick={() => {
                          setNewCustomerName(customerSearch);
                          setModalView('add-customer');
                        }}
                        className="inline-flex items-center gap-1.5 rounded-xl bg-blue-900 px-4 py-2 text-xs font-bold text-white hover:bg-blue-800 active:scale-95 transition-all cursor-pointer shadow-md"
                      >
                        <Plus className="h-3.5 w-3.5" />
                        Tambah "{customerSearch}" Baru
                      </button>
                    </div>
                  ) : (
                    <div className="py-8 text-center text-gray-400 space-y-3">
                      <Search className="h-8 w-8 mx-auto mb-1 opacity-40" />
                      <p className="text-xs">Ketik minimal 2 karakter untuk mencari</p>
                      <button
                        onClick={() => {
                          setNewCustomerName(customerName);
                          setModalView('add-customer');
                        }}
                        className="inline-flex items-center gap-1.5 rounded-xl bg-blue-50 border border-blue-200 px-4 py-2 text-xs font-bold text-blue-900 hover:bg-blue-100 active:scale-95 transition-all cursor-pointer"
                      >
                        <Plus className="h-3.5 w-3.5" />
                        Tambah Pelanggan Baru
                      </button>
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* ---- TAMBAH PELANGGAN MODAL ---- */}
            {modalView === 'add-customer' && (
              <div className="bg-white rounded-2xl shadow-2xl animate-scale-in overflow-hidden">
                {/* Modal header */}
                <div className="flex items-center justify-between px-5 pt-5 pb-3 border-b border-blue-50">
                  <div className="flex items-center gap-2">
                    <div className="flex h-7 w-7 items-center justify-center rounded-lg bg-blue-100">
                      <Plus className="h-3.5 w-3.5 text-blue-900" />
                    </div>
                    <h3 className="text-sm font-bold text-gray-800">Tambah Pelanggan Baru</h3>
                  </div>
                  <button
                    onClick={() => {
                      setNewCustomerName('');
                      setNewCustomerPhone('');
                      setNewCustomerAddress('');
                      setNewCustomerNotes('');
                      setModalView('none');
                    }}
                    className="flex h-7 w-7 items-center justify-center rounded-full bg-gray-100 text-gray-400 hover:bg-gray-200 hover:text-gray-600 transition-colors cursor-pointer"
                  >
                    <X className="h-4 w-4" />
                  </button>
                </div>

                {/* Form fields */}
                <div className="p-5 space-y-3.5">
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase tracking-wider mb-1">Nama Lengkap *</label>
                    <input
                      type="text"
                      placeholder="Masukkan nama pelanggan..."
                      value={newCustomerName}
                      onChange={(e) => setNewCustomerName(e.target.value)}
                      className="w-full rounded-xl border border-blue-200 bg-blue-50/10 px-3.5 py-2.5 text-xs text-gray-700 placeholder:text-gray-400 outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900/10 transition-all"
                      required
                    />
                  </div>

                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase tracking-wider mb-1">No. Telepon</label>
                    <input
                      type="tel"
                      placeholder="cth. 081234567890"
                      value={newCustomerPhone}
                      onChange={(e) => setNewCustomerPhone(e.target.value)}
                      className="w-full rounded-xl border border-blue-200 bg-blue-50/10 px-3.5 py-2.5 text-xs text-gray-700 placeholder:text-gray-400 outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900/10 transition-all"
                    />
                  </div>

                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase tracking-wider mb-1">Alamat Lengkap</label>
                    <textarea
                      placeholder="Masukkan alamat..."
                      value={newCustomerAddress}
                      onChange={(e) => setNewCustomerAddress(e.target.value)}
                      rows={2}
                      className="w-full rounded-xl border border-blue-200 bg-blue-50/10 px-3.5 py-2 text-xs text-gray-700 placeholder:text-gray-400 outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900/10 resize-none transition-all"
                    />
                  </div>

                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase tracking-wider mb-1">Catatan Tambahan</label>
                    <input
                      type="text"
                      placeholder="cth. Pelanggan VIP, tempo 7 hari..."
                      value={newCustomerNotes}
                      onChange={(e) => setNewCustomerNotes(e.target.value)}
                      className="w-full rounded-xl border border-blue-200 bg-blue-50/10 px-3.5 py-2.5 text-xs text-gray-700 placeholder:text-gray-400 outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900/10 transition-all"
                    />
                  </div>

                  {/* Actions */}
                  <div className="flex gap-2 pt-2">
                    <button
                      onClick={() => {
                        setNewCustomerName('');
                        setNewCustomerPhone('');
                        setNewCustomerAddress('');
                        setNewCustomerNotes('');
                        setModalView('none');
                      }}
                      className="flex-1 rounded-xl border border-gray-200 py-2.5 text-xs font-semibold text-gray-500 hover:bg-gray-50 active:scale-[0.98] transition-all cursor-pointer"
                    >
                      Batal
                    </button>
                    <button
                      onClick={handleCreateCustomer}
                      disabled={creatingCustomer || !newCustomerName.trim()}
                      className={cn(
                        "flex-2 rounded-xl py-2.5 px-6 text-xs font-bold text-white transition-all cursor-pointer shadow-lg",
                        newCustomerName.trim() && !creatingCustomer
                          ? "bg-gradient-to-r from-blue-900 to-blue-800 hover:from-blue-800 hover:to-blue-700 active:scale-[0.98] shadow-blue-900/20"
                          : "bg-blue-50 text-blue-400 shadow-none cursor-not-allowed"
                      )}
                    >
                      {creatingCustomer ? (
                        <span className="flex items-center justify-center gap-1.5">
                          <LoadingSpinner size="sm" />
                          Menyimpan...
                        </span>
                      ) : (
                        <span className="flex items-center justify-center gap-1">
                          <CheckCircle className="h-3.5 w-3.5" />
                          Simpan Pelanggan
                        </span>
                      )}
                    </button>
                  </div>
                </div>
              </div>
            )}

            {/* ---- UNIT PICKER MODAL ---- */}
            {modalView === 'unit-picker' && unitPickerProduct && (
              <div className="bg-white rounded-2xl p-5 shadow-2xl animate-scale-in space-y-3 w-full max-w-sm">
                <div className="flex items-center justify-between">
                  <div>
                    <h3 className="text-sm font-bold text-gray-800">Pilih satuan jual</h3>
                    <p className="text-[11px] text-gray-500 mt-0.5">{unitPickerProduct.name}</p>
                  </div>
                  <button
                    onClick={() => {
                      setUnitPickerProduct(null);
                      setModalView('none');
                    }}
                    className="text-gray-400 hover:text-gray-600 cursor-pointer"
                  >
                    <X className="h-4 w-4" />
                  </button>
                </div>
                <p className="text-[10px] text-gray-400">
                  Stok: {Math.round(Number(unitPickerProduct.stock))} {unitPickerProduct.unit}
                  {qtyRuleMessage(unitPickerProduct) ? ` · ${qtyRuleMessage(unitPickerProduct)}` : ''}
                </p>
                <div className="space-y-1.5">
                  <button
                    onClick={() => {
                      addToCartWithUnit(unitPickerProduct, null);
                      setUnitPickerProduct(null);
                      setModalView('none');
                    }}
                    className="w-full flex items-center justify-between rounded-xl border border-blue-100 bg-blue-50/40 px-3.5 py-2.5 text-left hover:bg-blue-50 active:scale-[0.99] transition-all cursor-pointer"
                  >
                    <span className="text-xs font-semibold text-gray-800">
                      {unitPickerProduct.unit || 'pcs'} (satuan dasar)
                    </span>
                    <span className="text-[10px] text-gray-500">×1</span>
                  </button>
                  {(unitPickerProduct.units || []).map((u) => (
                    <button
                      key={u.id}
                      onClick={() => {
                        addToCartWithUnit(unitPickerProduct, u);
                        setUnitPickerProduct(null);
                        setModalView('none');
                      }}
                      className="w-full flex items-center justify-between rounded-xl border border-blue-100 px-3.5 py-2.5 text-left hover:bg-blue-50 active:scale-[0.99] transition-all cursor-pointer"
                    >
                      <span className="text-xs font-semibold text-gray-800">
                        {u.name}
                        {u.abbreviation ? ` (${u.abbreviation})` : ''}
                      </span>
                      <span className="text-[10px] text-gray-500">
                        1 = {Number(u.multiplier)} {unitPickerProduct.unit}
                      </span>
                    </button>
                  ))}
                </div>
              </div>
            )}

            {/* ---- HELD ORDERS MODAL ---- */}
            {modalView === 'held-orders' && (
              <div className="bg-white rounded-2xl p-5 shadow-2xl animate-scale-in space-y-4 max-h-[80vh] flex flex-col">
                <div className="flex items-center justify-between">
                  <h3 className="text-sm font-bold text-gray-700 flex items-center gap-2">
                    <Clock className="h-4 w-4 text-blue-400" />
                    Open Bill ({heldOrders.length})
                  </h3>
                  <button onClick={() => setModalView('none')} className="text-blue-400 hover:text-gray-600 cursor-pointer"><X className="h-4 w-4" /></button>
                </div>

                <div className="flex-1 overflow-y-auto space-y-2">
                  {heldOrders.length === 0 ? (
                    <div className="py-12 text-center text-gray-400">
                      <Clock className="h-8 w-8 mx-auto mb-2 opacity-40" />
                      <p className="text-sm">Tidak ada pesanan tersimpan</p>
                    </div>
                  ) : (
                    heldOrders.map((held) => {
                      const heldTotal = held.cart_data.reduce((s, i) => s + Number(i.subtotal), 0);
                      const heldItems = held.cart_data.reduce((s, i) => s + i.quantity, 0);
                      return (
                        <div key={held.id} className="rounded-xl border border-blue-100 p-3 space-y-2 hover:bg-blue-50/30 transition-colors">
                          <div className="flex items-center justify-between">
                            <div>
                              <p className="text-sm font-semibold text-gray-700">{held.label || 'Pesanan'}</p>
                              <p className="text-[10px] text-blue-400">{new Date(held.created_at).toLocaleString('id-ID')} - {heldItems} item</p>
                            </div>
                            <p className="text-sm font-bold text-gray-700 tabular-nums">{formatCurrency(heldTotal)}</p>
                          </div>
                          <div className="text-xs text-blue-400 truncate">
                            {held.cart_data.map((i) => `${i.product_name} x${i.quantity}`).join(', ')}
                          </div>
                          <div className="flex gap-2">
                            <button
                              onClick={() => resumeHeldOrder(held)}
                              className="flex-1 flex items-center justify-center gap-1.5 rounded-lg bg-blue-900 py-2 text-xs font-semibold text-white hover:bg-blue-900 active:scale-95 transition-all cursor-pointer"
                            >
                              <Play className="h-3 w-3" />
                              Lanjutkan
                            </button>
                            <button
                              onClick={() => deleteHeldOrder(held.id)}
                              className="flex items-center justify-center gap-1.5 rounded-lg border border-red-200 px-3 py-2 text-xs font-medium text-red-500 hover:bg-red-50 active:scale-95 transition-all cursor-pointer"
                            >
                              <Trash2 className="h-3 w-3" />
                            </button>
                          </div>
                        </div>
                      );
                    })
                  )}
                </div>
              </div>
            )}

          </div>
        </div>
      )}
    </div>
  );
}


