<script setup lang="ts">
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue';
import { Head, Link, useForm, router, usePage } from '@inertiajs/vue3';
import { Search, ShoppingCart, Coffee, Snowflake, Flame, Trash2, Printer, AlertTriangle, Plus, Minus, Check, CheckCircle2, Sun, Moon, Users, Grid, Tag, Split, FileText, ChevronRight, X, Maximize, Minimize, History, User, LogOut, LayoutDashboard, Settings, RefreshCw, Receipt } from 'lucide-vue-next';
import { 
    DropdownMenuRoot, 
    DropdownMenuTrigger, 
    DropdownMenuPortal, 
    DropdownMenuContent, 
    DropdownMenuItem, 
    DropdownMenuSeparator 
} from 'radix-vue';
import DemoModeBanner from '@/Components/DemoModeBanner.vue';

interface RecipeItem {
    ingredient_id: number;
    usage_qty: number;
    variant: string | null;
}

interface Product {
    id: number;
    name: string;
    price: number;
    category: string;
    description: string | null;
    image_path: string | null;
    has_recipe: boolean;
    recipes: RecipeItem[];
    modifiers?: Modifier[];
}

interface Outlet {
    id: number;
    name: string;
}

interface Table {
    id: number;
    number: string;
    capacity: number;
    status: 'available' | 'occupied' | 'reserved';
}

interface Customer {
    id: number;
    name: string;
    is_member: boolean;
    loyalty_points: number;
    birth_date: string | null;
}

interface Modifier {
    id: number;
    name: string;
    price: number;
    ingredient_id: number | null;
    usage_qty: number | null;
}

interface Promo {
    id: number;
    name: string;
    type: 'percent' | 'nominal' | 'bogo';
    value: number;
    min_purchase: number;
    product_id: number | null;
}

interface CartItem {
    product: Product;
    qty: number;
    variant: 'hot' | 'ice' | null;
    notes: string;
    selectedModifiers: number[]; // array of modifier IDs
}

interface PendingQrOrder {
    id: number;
    transaction_number: string;
    table_number: string;
    customer_name: string;
    total_amount: number;
    payment_method: string;
    created_at: string;
    items_count: number;
    items: {
        name: string;
        qty: number;
        variant: string | null;
        price: number;
        subtotal: number;
        modifiers: string[];
    }[];
}

const props = defineProps<{
    products: Product[];
    outlets: Outlet[];
    selectedOutletId: number | null;
    ingredientStock: Record<number, number>;
    productStock: Record<number, number>;
    taxPercentage: number;
    servicePercentage: number;
    // New Props for Complete POS Phases
    tables: Table[];
    customers: Customer[];
    modifiers: Modifier[];
    promos: Promo[];
    recentTransactions: any[];
    pendingQrOrders?: PendingQrOrder[];
    waiters: { id: number; name: string }[];
    couriers: { id: number; name: string; phone?: string; vehicle_number?: string }[];
}>();

const activeConfirmQrOrder = ref<PendingQrOrder | null>(null);
const isConfirmQrModalOpen = ref(false);
const isConfirmingPayment = ref(false);
const isPendingQrListModalOpen = ref(false);
const isKitchenPrintPromptOpen = ref(false);
const kitchenPrintPromptTxnId = ref<number | null>(null);

const openConfirmQrModal = (order: PendingQrOrder) => {
    activeConfirmQrOrder.value = order;
    isConfirmQrModalOpen.value = true;
};

const executeConfirmQrPayment = () => {
    if (!activeConfirmQrOrder.value) return;
    
    const txnId = activeConfirmQrOrder.value.id;
    isConfirmingPayment.value = true;
    router.post(route('transactions.confirm-payment', txnId), {}, {
        preserveScroll: true,
        onSuccess: () => {
            isConfirmingPayment.value = false;
            isConfirmQrModalOpen.value = false;
            activeConfirmQrOrder.value = null;
            triggerAlert('success', 'Pembayaran pesanan QR berhasil dikonfirmasi (Lunas).');
            
            // Auto-print customer receipt, then prompt for kitchen print
            handleManualPrint(txnId, 'pos');
            kitchenPrintPromptTxnId.value = txnId;
            isKitchenPrintPromptOpen.value = true;
        },
        onError: () => {
            isConfirmingPayment.value = false;
        }
    });
};

const confirmKitchenPrint = () => {
    if (kitchenPrintPromptTxnId.value) {
        handleManualPrint(kitchenPrintPromptTxnId.value, 'kitchen');
    }
    isKitchenPrintPromptOpen.value = false;
    kitchenPrintPromptTxnId.value = null;
};

const skipKitchenPrint = () => {
    isKitchenPrintPromptOpen.value = false;
    kitchenPrintPromptTxnId.value = null;
};

// Selected outlet state
const outletId = ref(props.selectedOutletId || (props.outlets[0] ? props.outlets[0].id : null));

// Reload POS if outlet changes
watch(outletId, (newVal) => {
    if (newVal) {
        router.get(route('pos.index'), { outlet_id: newVal }, { preserveState: true, replace: true });
    }
});

// Search & category filters
const search = ref('');
const activeCategory = ref('All');
const defaultCategories = ['Coffee', 'Non-Coffee', 'Food', 'Snacks', 'Dessert', 'Bakery', 'Retail', 'Other'];
const categories = computed(() => {
    const fromProducts = props.products ? props.products.map(p => p.category) : [];
    const set = new Set([...fromProducts, ...defaultCategories]);
    return ['All', ...Array.from(set).filter(Boolean)];
});

// Cart state
const cart = ref<CartItem[]>([]);

// POS Order extensions
const orderType = ref<'dine_in' | 'take_away' | 'delivery'>('take_away');
const selectedTableId = ref<number | null>(null);
const selectedCustomerId = ref<number>(1); // Defaults to Walk-in (assumed ID 1)
const selectedPromoId = ref<number | null>(null);
const pointsToRedeem = ref<number>(0);
const selectedWaiterId = ref<number | null>(null);
const selectedCourierId = ref<number | null>(null);
const voucherCode = ref<string>('');
const appliedVoucher = ref<any>(null);
const voucherError = ref<string>('');

// Filtered products list
const filteredProducts = computed(() => {
    return props.products.filter(p => {
        const matchesSearch = p.name.toLowerCase().includes(search.value.toLowerCase());
        const matchesCategory = activeCategory.value === 'All' || p.category === activeCategory.value;
        return matchesSearch && matchesCategory;
    });
});

// Dynamic available stock calculator
const getAvailableQty = (product: Product, variant: 'hot' | 'ice' | null): number => {
    if (!outletId.value) return 0;

    if (product.has_recipe) {
        let minAvailable = 999999;
        
        // Filter recipe items that apply to this variant
        const applicableRecipes = product.recipes.filter(r => r.variant === null || r.variant === variant);
        
        if (applicableRecipes.length === 0) return 0;

        for (const recipe of applicableRecipes) {
            // Find base stock in current outlet
            const baseStock = props.ingredientStock[recipe.ingredient_id] || 0;
            
            // Calculate how much is already consumed by items in the cart
            let consumedInCart = 0;
            for (const item of cart.value) {
                const itemRecipes = item.product.recipes.filter(r => r.variant === null || r.variant === item.variant);
                const matchingRecipe = itemRecipes.find(r => r.ingredient_id === recipe.ingredient_id);
                if (matchingRecipe) {
                    consumedInCart += item.qty * matchingRecipe.usage_qty;
                }

                // Check if any modifiers selected use this ingredient
                for (const modId of item.selectedModifiers) {
                    const mod = props.modifiers.find(m => m.id === modId);
                    if (mod && mod.ingredient_id === recipe.ingredient_id && mod.usage_qty) {
                        consumedInCart += item.qty * mod.usage_qty;
                    }
                }
            }

            const remainder = baseStock - consumedInCart;
            const availableForThisIngredient = Math.floor(remainder / recipe.usage_qty);
            
            if (availableForThisIngredient < minAvailable) {
                minAvailable = availableForThisIngredient;
            }
        }
        
        return Math.max(0, minAvailable);
    } else {
        // Direct product stock (retail)
        const baseStock = props.productStock[product.id] || 0;
        let consumedInCart = 0;
        for (const item of cart.value) {
            if (item.product.id === product.id) {
                consumedInCart += item.qty;
            }
        }
        return Math.max(0, baseStock - consumedInCart);
    }
};

// Add product to cart
const addToCart = (product: Product) => {
    const defaultVariant = (product.category === 'Coffee' || product.category === 'Non-Coffee') ? 'ice' : null;
    const available = getAvailableQty(product, defaultVariant);
    if (available <= 0) return;

    const existingIdx = cart.value.findIndex(item => item.product.id === product.id && item.variant === defaultVariant && item.selectedModifiers.length === 0);
    if (existingIdx > -1) {
        if (getAvailableQty(product, defaultVariant) > 0) {
            const existingItem = cart.value[existingIdx];
            existingItem.qty += 1;
            cart.value.splice(existingIdx, 1);
            cart.value.unshift(existingItem);
        }
    } else {
        cart.value.unshift({
            product,
            qty: 1,
            variant: defaultVariant,
            notes: '',
            selectedModifiers: [],
        });
    }
};

const incrementQty = (item: CartItem) => {
    if (getAvailableQty(item.product, item.variant) > 0) {
        item.qty += 1;
    }
};

const decrementQty = (item: CartItem) => {
    if (item.qty > 1) {
        item.qty -= 1;
    } else {
        removeFromCart(item);
    }
};

const removeFromCart = (item: CartItem) => {
    const idx = cart.value.indexOf(item);
    if (idx > -1) {
        cart.value.splice(idx, 1);
    }
};

const changeVariant = (item: CartItem, newVariant: 'hot' | 'ice' | null) => {
    const currentQty = item.qty;
    const oldVariant = item.variant;
    
    item.variant = newVariant;
    const available = getAvailableQty(item.product, newVariant);
    
    if (available < 0) {
        item.variant = oldVariant;
    }
};

const toggleModifier = (item: CartItem, modId: number) => {
    const idx = item.selectedModifiers.indexOf(modId);
    if (idx > -1) {
        item.selectedModifiers.splice(idx, 1);
    } else {
        item.selectedModifiers.push(modId);
    }
};

// Cart Calculations
const subtotal = computed(() => {
    return cart.value.reduce((sum, item) => {
        const modifiersPrice = item.selectedModifiers.reduce((modSum, modId) => {
            const mod = props.modifiers.find(m => m.id === modId);
            return modSum + (mod ? mod.price : 0);
        }, 0);
        return sum + ((item.product.price + modifiersPrice) * item.qty);
    }, 0);
});

import axios from 'axios';

const applyVoucher = () => {
    if (!voucherCode.value) return;
    axios.post(route('vouchers.verify'), {
        code: voucherCode.value,
        subtotal: subtotal.value
    }).then(response => {
        if (response.data.valid) {
            appliedVoucher.value = response.data.voucher;
            voucherError.value = '';
        } else {
            appliedVoucher.value = null;
            voucherError.value = response.data.message;
        }
    }).catch(err => {
        appliedVoucher.value = null;
        voucherError.value = err.response?.data?.message || 'Gagal memverifikasi voucher';
    });
};

const birthdayDiscount = computed(() => {
    if (!selectedCustomerId.value) return 0;
    const customer = props.customers.find(c => c.id === selectedCustomerId.value);
    if (customer && customer.birth_date) {
        const today = new Date();
        const birthDate = new Date(customer.birth_date);
        if (today.getDate() === birthDate.getDate() && today.getMonth() === birthDate.getMonth()) {
            return subtotal.value * 0.10; // 10% birthday discount!
        }
    }
    return 0;
});

// Auto-apply promo or calculate discount based on selection
const discountAmount = computed(() => {
    let disc = 0;
    if (selectedPromoId.value) {
        const promo = props.promos.find(p => p.id === selectedPromoId.value);
        if (promo && subtotal.value >= promo.min_purchase) {
            if (promo.type === 'percent') {
                disc = (subtotal.value * promo.value) / 100;
            } else if (promo.type === 'nominal') {
                disc = promo.value;
            }
        }
    }

    // Voucher Coupon Discount
    if (appliedVoucher.value) {
        const v = appliedVoucher.value;
        if (v.type === 'nominal') {
            disc += Math.min(v.value, subtotal.value);
        } else if (v.type === 'percent') {
            let vDisc = (subtotal.value * v.value) / 100;
            if (v.max_discount) {
                vDisc = Math.min(vDisc, v.max_discount);
            }
            disc += Math.min(vDisc, subtotal.value);
        }
    }

    // Birthday CRM discount
    disc += birthdayDiscount.value;

    // Loyalty Point redemption (1 point = Rp 1.000 discount)
    disc += pointsToRedeem.value * 1000;
    return disc;
});

const serviceCharge = computed(() => {
    return (subtotal.value * props.servicePercentage) / 100;
});

const tax = computed(() => {
    return ((subtotal.value + serviceCharge.value) * props.taxPercentage) / 100;
});

const grandTotal = computed(() => {
    return Math.max(0, subtotal.value + serviceCharge.value + tax.value - discountAmount.value);
});

// Checkout states
const paymentMethod = ref<'cash' | 'transfer' | 'qris'>('cash');
const cashReceived = ref<number>(0);
const changeDue = computed(() => {
    return Math.max(0, cashReceived.value - grandTotal.value);
});

// Receipt popup states
const isReceiptModalOpen = ref(false);
const receiptData = ref<any>(null);

// Split Bill states
const isSplitModalOpen = ref(false);
const splitItems = ref<{ itemIndex: number; qty: number }[]>([]);

const openSplitModal = () => {
    if (cart.value.length === 0) return;
    splitItems.value = cart.value.map((item, idx) => ({
        itemIndex: idx,
        qty: 0,
    }));
    isSplitModalOpen.value = true;
};

const handleSplitCheckout = () => {
    // Collect split cart items
    const splitCart: CartItem[] = [];
    const remainingCart: CartItem[] = [];

    splitItems.value.forEach((split, idx) => {
        const originalItem = cart.value[split.itemIndex];
        if (split.qty > 0) {
            splitCart.push({
                ...originalItem,
                qty: split.qty,
            });
        }
        if (originalItem.qty - split.qty > 0) {
            remainingCart.push({
                ...originalItem,
                qty: originalItem.qty - split.qty,
            });
        }
    });

    if (splitCart.length === 0) return;

    // Checkout split cart first
    isCheckingOut.value = true;
    const payload = {
        outlet_id: outletId.value,
        payment_method: paymentMethod.value,
        order_type: orderType.value,
        table_id: selectedTableId.value,
        customer_id: selectedCustomerId.value,
        discount_amount: discountAmount.value,
        points_redeemed: pointsToRedeem.value,
        waiter_id: selectedWaiterId.value,
        courier_id: selectedCourierId.value,
        voucher_code: appliedVoucher.value ? appliedVoucher.value.code : null,
        items: splitCart.map(item => ({
            product_id: item.product.id,
            qty: item.qty,
            variant: item.variant,
            price: item.product.price,
            modifiers: item.selectedModifiers,
        })),
    };

    router.post(route('pos.checkout'), payload, {
        preserveScroll: true,
        onSuccess: (page) => {
            isCheckingOut.value = false;
            isSplitModalOpen.value = false;
            const flash = page.props.flash as any;
            const lastTxn = flash?.last_transaction;
            
            if (lastTxn) {
                receiptData.value = {
                    id: lastTxn.id,
                    transaction_number: lastTxn.transaction_number,
                    outlet_name: props.outlets.find(o => o.id === outletId.value)?.name || 'Outlet',
                    cashier_name: usePage().props.auth.user.name,
                    items: [...splitCart],
                    subtotal: splitCart.reduce((sum, item) => sum + (item.product.price * item.qty), 0),
                    service: 0,
                    tax: 0,
                    total: splitCart.reduce((sum, item) => sum + (item.product.price * item.qty), 0),
                    payment_method: paymentMethod.value,
                    cash_received: paymentMethod.value === 'cash' ? cashReceived.value : grandTotal.value,
                    change: paymentMethod.value === 'cash' ? changeDue.value : 0,
                    date: lastTxn.created_at,
                };
                isReceiptModalOpen.value = true;
                triggerAutoPrint(lastTxn.id);
                
                // Update cart to only contain remaining items
                cart.value = remainingCart;
                cashReceived.value = 0;
                appliedVoucher.value = null;
                voucherCode.value = '';
                selectedWaiterId.value = null;
                selectedCourierId.value = null;
            }
        },
        onError: () => {
            isCheckingOut.value = false;
        }
    });
};

// Checkout trigger
const isCheckingOut = ref(false);
const handleCheckout = () => {
    if (cart.value.length === 0) return;
    if (paymentMethod.value === 'cash' && cashReceived.value < grandTotal.value) {
        alert('Uang tunai yang diterima kurang!');
        return;
    }
    if (orderType.value === 'dine_in' && !selectedTableId.value) {
        alert('Silakan pilih meja untuk pesanan Dine In!');
        return;
    }

    isCheckingOut.value = true;
    
    // Prepare checkout payload
    const payload = {
        outlet_id: outletId.value,
        payment_method: paymentMethod.value,
        order_type: orderType.value,
        table_id: selectedTableId.value,
        customer_id: selectedCustomerId.value,
        discount_amount: discountAmount.value,
        points_redeemed: pointsToRedeem.value,
        waiter_id: selectedWaiterId.value,
        courier_id: selectedCourierId.value,
        voucher_code: appliedVoucher.value ? appliedVoucher.value.code : null,
        items: cart.value.map(item => ({
            product_id: item.product.id,
            qty: item.qty,
            variant: item.variant,
            price: item.product.price,
            modifiers: item.selectedModifiers,
        })),
    };

    router.post(route('pos.checkout'), payload, {
        preserveScroll: true,
        onSuccess: (page) => {
            isCheckingOut.value = false;
            const flash = page.props.flash as any;
            const lastTxn = flash?.last_transaction;
            
            if (lastTxn) {
                receiptData.value = {
                    id: lastTxn.id,
                    transaction_number: lastTxn.transaction_number,
                    outlet_name: props.outlets.find(o => o.id === outletId.value)?.name || 'Outlet',
                    cashier_name: usePage().props.auth.user.name,
                    table_number: props.tables?.find(t => t.id === selectedTableId.value)?.number || null,
                    items: [...cart.value],
                    subtotal: subtotal.value,
                    service: serviceCharge.value,
                    tax: tax.value,
                    total: grandTotal.value,
                    payment_method: paymentMethod.value,
                    cash_received: paymentMethod.value === 'cash' ? cashReceived.value : grandTotal.value,
                    change: paymentMethod.value === 'cash' ? changeDue.value : 0,
                    date: lastTxn.created_at,
                };
                
                isReceiptModalOpen.value = true;
                triggerAutoPrint(lastTxn.id);
                cart.value = [];
                cashReceived.value = 0;
                pointsToRedeem.value = 0;
                selectedPromoId.value = null;
                appliedVoucher.value = null;
                voucherCode.value = '';
                selectedWaiterId.value = null;
                selectedCourierId.value = null;
            }
        },
        onError: () => {
            isCheckingOut.value = false;
        }
    });
};

const selectQuickCash = (amount: number) => {
    cashReceived.value = amount;
};

const getProductInitials = (name: string) => {
    return name.slice(0, 2).toUpperCase();
};

const isDark = ref(false);
const isFullscreen = ref(false);

onMounted(() => {
    isDark.value = document.documentElement.classList.contains('dark');
    document.addEventListener('fullscreenchange', () => {
        isFullscreen.value = !!document.fullscreenElement;
    });
});

const toggleFullscreen = () => {
    if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen().then(() => {
            isFullscreen.value = true;
        }).catch(err => {
            console.error(err);
        });
    } else {
        document.exitFullscreen().then(() => {
            isFullscreen.value = false;
        });
    }
};

const toggleTheme = () => {
    if (document.documentElement.classList.contains('dark')) {
        document.documentElement.classList.remove('dark');
        localStorage.setItem('theme', 'light');
        isDark.value = false;
    } else {
        document.documentElement.classList.add('dark');
        localStorage.setItem('theme', 'dark');
        isDark.value = true;
    }
};

const selectedCustomerPoints = computed(() => {
    const cust = props.customers.find(c => c.id === selectedCustomerId.value);
    return cust ? cust.loyalty_points : 0;
});

// Global Notifications Alert State (Flash Messages)
const activeAlert = ref<{ type: 'success' | 'error'; message: string } | null>(null);
let alertTimeoutId: ReturnType<typeof setTimeout> | null = null;

const triggerAlert = (type: 'success' | 'error', message: string) => {
    if (alertTimeoutId) clearTimeout(alertTimeoutId);
    activeAlert.value = { type, message };
    
    // Auto-dismiss after 4 seconds
    alertTimeoutId = setTimeout(() => {
        activeAlert.value = null;
    }, 4000);
};

const dismissAlert = () => {
    if (alertTimeoutId) clearTimeout(alertTimeoutId);
    activeAlert.value = null;
};

// Watch for flash updates from Inertia
const page = usePage();
watch(
    () => page.props.flash as any,
    (flash) => {
        if (flash?.success) {
            triggerAlert('success', String(flash.success));
        } else if (flash?.error) {
            triggerAlert('error', String(flash.error));
        }
    },
    { deep: true, immediate: true }
);

// Role permission helper for Admin / SuperAdmin only controls
const userRoles = computed(() => (page.props as any).auth?.user?.roles || []);
const isAdminOrSuperAdmin = computed(() => {
    const roles = userRoles.value;
    return roles.includes('superadmin') || roles.includes('admin') || roles.includes('Super Admin') || roles.includes('Admin');
});

// Active tab for mobile layout
const activeMobileTab = ref<'menu' | 'cart' | 'history'>('menu');

// Show receipt details from history list
const showReceiptFromHistory = (txn: any) => {
    receiptData.value = {
        id: txn.id,
        transaction_number: txn.transaction_number,
        outlet_name: props.outlets.find(o => o.id === txn.outlet_id)?.name || 'Outlet',
        cashier_name: txn.user?.name || 'Staff',
        items: txn.items.map((item: any) => ({
            product: {
                id: item.product?.id,
                name: item.product?.name || 'Menu deleted',
                price: item.price,
            },
            qty: item.qty,
            variant: item.variant,
            selectedModifiers: item.modifiers?.map((m: any) => m.modifier_id || m.id) || [],
            notes: item.notes || '',
        })),
        subtotal: txn.items.reduce((sum: number, item: any) => sum + (item.price * item.qty), 0),
        service: txn.service_charge_amount,
        tax: txn.tax_amount,
        total: txn.total_amount,
        payment_method: txn.payment_method,
        cash_received: txn.total_amount,
        change: 0,
        date: txn.created_at,
    };
    isReceiptModalOpen.value = true;
};

// Void transaction from history list
const confirmVoid = (txn: any) => {
    if (confirm(`Apakah Anda yakin ingin melakukan void (pembatalan) pada transaksi ${txn.transaction_number}? Tindakan ini akan mengembalikan stok inventaris.`)) {
        router.post(route('transactions.void', txn.id), {}, {
            preserveScroll: true,
            onSuccess: () => {
                triggerAlert('success', 'Transaksi berhasil di-void.');
            },
        });
    }
};

import {
    getPrintSettings,
    savePrintSettings,
    connectQZ,
    getAvailablePrinters,
    printReceipt,
    type PrintSettings,
    isPrinting,
    printStatus
} from '@/lib/printService';

// Printer Settings States
const isPrinterSettingsOpen = ref(false);
const printSettings = ref<PrintSettings>({
    method: 'browser',
    posPrinter: '',
    kitchenPrinter: '',
    autoPrintPos: false,
    autoPrintKitchen: false,
    zoomScale: 100
});
const availablePrinters = ref<string[]>([]);
const isConnectingQZ = ref(false);
const qzConnectionStatus = ref<'disconnected' | 'connected' | 'error'>('disconnected');

let selfOrderPollInterval: ReturnType<typeof setInterval> | null = null;

// Load settings on mount & start 1-minute poll for Self-Order
onMounted(() => {
    printSettings.value = getPrintSettings();
    if (printSettings.value.method === 'qz') {
        checkQzConnection();
    }

    // Auto-refresh pending Self-Order QR orders every 1 minute (60,000 ms)
    selfOrderPollInterval = setInterval(() => {
        router.reload({
            only: ['pendingQrOrders'],
        });
    }, 60000);
});

onBeforeUnmount(() => {
    if (selfOrderPollInterval) {
        clearInterval(selfOrderPollInterval);
    }
});

const checkQzConnection = async () => {
    isConnectingQZ.value = true;
    try {
        const connected = await connectQZ();
        if (connected) {
            qzConnectionStatus.value = 'connected';
            availablePrinters.value = await getAvailablePrinters();
        } else {
            qzConnectionStatus.value = 'disconnected';
            availablePrinters.value = [];
        }
    } catch (e) {
        qzConnectionStatus.value = 'error';
        availablePrinters.value = [];
    } finally {
        isConnectingQZ.value = false;
    }
};

const saveSettings = () => {
    savePrintSettings(printSettings.value);
    isPrinterSettingsOpen.value = false;
    triggerAlert('success', 'Pengaturan printer berhasil disimpan.');
};

const triggerAutoPrint = async (txnId: number) => {
    const settings = getPrintSettings();
    if (settings.method === 'qz') {
        if (settings.autoPrintPos && settings.posPrinter) {
            printReceipt(txnId, 'pos');
        }
    }
};

const handleManualPrint = async (txnId: number, type: 'pos' | 'kitchen', cashReceived?: number, change?: number) => {
    const res = await printReceipt(txnId, type, cashReceived, change);
    if (res.error) {
        triggerAlert('error', res.error);
    } else if (res.method === 'qz') {
        triggerAlert('success', `Berhasil mengirim cetak ${type === 'pos' ? 'Struk Kasir' : 'Tiket Dapur'} ke printer.`);
    }
};
</script>

<template>
    <Head title="POS Cashier Terminal" />

    <div class="min-h-screen lg:h-screen bg-slate-50 dark:bg-slate-900 text-slate-900 dark:text-slate-100 flex flex-col overflow-y-auto lg:overflow-hidden select-none">
        <!-- Global Notification Toast -->
        <transition name="toast-slide">
            <div
                v-if="activeAlert"
                class="fixed top-6 right-6 z-[100] w-full max-w-sm overflow-hidden rounded-xl border bg-white/95 dark:bg-slate-955/95 backdrop-blur-md shadow-lg transition-all duration-300 pointer-events-auto select-none font-sans"
                :class="activeAlert.type === 'success' ? 'border-emerald-500/30' : 'border-rose-500/30'"
            >
                <div class="p-4 flex items-start gap-3 relative">
                    <!-- Indicator border -->
                    <div 
                        class="absolute left-0 top-0 bottom-0 w-1"
                        :class="activeAlert.type === 'success' ? 'bg-emerald-500' : 'bg-rose-500'"
                    />

                    <!-- Icon -->
                    <div class="flex-shrink-0 mt-0.5">
                        <component 
                            :is="activeAlert.type === 'success' ? CheckCircle2 : AlertTriangle"
                            :class="['h-5 w-5', activeAlert.type === 'success' ? 'text-emerald-500' : 'text-rose-500']"
                        />
                    </div>

                    <!-- Message text -->
                    <div class="flex-1 min-w-0 pr-2">
                        <p class="text-[10px] font-extrabold uppercase tracking-widest leading-none mb-1.5" :class="activeAlert.type === 'success' ? 'text-emerald-600 dark:text-emerald-400' : 'text-rose-600 dark:text-rose-400'">
                            {{ activeAlert.type === 'success' ? 'Berhasil' : 'Peringatan' }}
                        </p>
                        <p class="text-xs text-slate-700 dark:text-slate-300 font-bold leading-normal">
                            {{ activeAlert.message }}
                        </p>
                    </div>

                    <!-- Dismiss button -->
                    <button 
                        @click="dismissAlert"
                        class="flex-shrink-0 p-1 hover:bg-slate-100 dark:hover:bg-slate-900 rounded-lg text-slate-400 dark:text-slate-500 hover:text-slate-700 dark:hover:text-slate-300 transition-colors cursor-pointer"
                    >
                        <X class="h-4 w-4" />
                    </button>
                </div>
            </div>
        </transition>

        <DemoModeBanner />
        <!-- Cashier Header -->
        <header class="h-16 border-b border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-950 px-4 xs:px-6 flex items-center justify-between flex-shrink-0 shadow-sm z-10 select-none">
            <!-- Left: Brand Logo & Title -->
            <div class="flex items-center gap-2">
                <div v-if="$page.props.settings.site_logo" class="h-8 w-8 rounded-lg overflow-hidden border border-slate-100 dark:border-slate-800 flex items-center justify-center bg-slate-50 flex-shrink-0">
                    <img :src="$page.props.settings.site_logo" alt="Logo" class="max-h-6 object-contain" />
                </div>
                <div v-else class="h-8 w-8 rounded-lg bg-[#8c5a3c] flex items-center justify-center flex-shrink-0 text-white font-bold text-base">
                    <span>{{ $page.props.settings.site_name?.charAt(0) ?? 'C' }}</span>
                </div>
                <div class="flex flex-col">
                    <span class="font-extrabold text-xs tracking-wider uppercase leading-none truncate max-w-[80px] xs:max-w-[120px]">{{ $page.props.settings.site_name }}</span>
                    <span class="text-[8px] text-slate-400 dark:text-slate-500 mt-0.5 leading-none hidden xs:inline">Terminal Kasir</span>
                </div>
            </div>

            <!-- Middle: Outlet Selector / Indicator -->
            <div class="flex items-center gap-1.5 max-w-[130px] xs:max-w-none">
                <span class="text-[9px] text-slate-450 dark:text-slate-500 font-bold uppercase tracking-wider hidden xs:inline">Outlet:</span>
                <select
                    v-if="!$page.props.auth.user.outlet_id"
                    v-model="outletId"
                    class="px-2 py-1 border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent text-[11px] font-bold focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-900 dark:text-slate-100 cursor-pointer max-w-[90px] xs:max-w-none truncate"
                >
                    <option v-for="ot in outlets" :key="ot.id" :value="ot.id">{{ ot.name }}</option>
                </select>
                <span v-else class="text-[11px] font-bold px-2 py-1 bg-slate-100 dark:bg-slate-800 rounded-lg border border-slate-200 dark:border-slate-800 text-slate-700 dark:text-slate-300 max-w-[90px] xs:max-w-none truncate">
                    {{ outlets.find(o => o.id === outletId)?.name }}
                </span>
            </div>

            <!-- Right: Session profile, back-to-admin and logouts -->
            <div class="flex items-center gap-2">
                <!-- Mobile Actions Dropdown (Radix UI) -->
                <div class="sm:hidden">
                    <DropdownMenuRoot>
                        <DropdownMenuTrigger class="focus:outline-none cursor-pointer flex items-center justify-center h-8 w-8 rounded-full bg-[#8c5a3c]/10 text-[#8c5a3c] border border-[#8c5a3c]/20 hover:bg-[#8c5a3c]/20 transition-all select-none">
                            <span class="text-xs font-bold font-mono">{{ getProductInitials($page.props.auth.user.name) }}</span>
                        </DropdownMenuTrigger>
                        <DropdownMenuPortal>
                            <DropdownMenuContent 
                                class="z-[100] min-w-[180px] bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl p-1.5 shadow-lg animate-in fade-in slide-in-from-top-1 duration-200"
                                :align="'end'"
                                :side-offset="8"
                            >
                                <div class="px-2 py-2 flex flex-col">
                                    <span class="font-extrabold text-xs text-slate-850 dark:text-slate-250 leading-none">{{ $page.props.auth.user.name }}</span>
                                    <span class="text-[9px] text-slate-400 dark:text-slate-500 mt-1 leading-none">{{ $page.props.auth.user.roles[0] || 'Staff' }}</span>
                                </div>
                                <DropdownMenuSeparator class="h-px bg-slate-200 dark:bg-slate-800 my-1" />
                                
                                <DropdownMenuItem 
                                    v-if="$page.props.auth.user.roles.includes('Super Admin') || $page.props.auth.user.roles.includes('Owner') || $page.props.auth.user.roles.includes('Admin')"
                                    class="cursor-pointer select-none rounded-lg px-2 py-2 text-[11px] font-semibold hover:bg-slate-50 dark:hover:bg-slate-800 focus:bg-slate-50 dark:focus:bg-slate-800 focus:outline-none text-slate-700 dark:text-slate-350"
                                >
                                    <Link :href="route('dashboard')" class="w-full h-full flex items-center gap-1.5">
                                        <LayoutDashboard class="h-3.5 w-3.5" />
                                        <span>Dashboard Admin</span>
                                    </Link>
                                </DropdownMenuItem>

                                <DropdownMenuItem 
                                    @click="toggleTheme"
                                    class="cursor-pointer select-none rounded-lg px-2 py-2 text-[11px] font-semibold hover:bg-slate-50 dark:hover:bg-slate-800 focus:bg-slate-50 dark:focus:bg-slate-800 focus:outline-none text-slate-700 dark:text-slate-350 flex items-center gap-1.5"
                                >
                                    <Sun v-if="isDark" class="h-3.5 w-3.5 text-amber-500" />
                                    <Moon v-else class="h-3.5 w-3.5 text-slate-500 dark:text-slate-450" />
                                    <span>Tema: {{ isDark ? 'Terang' : 'Gelap' }}</span>
                                </DropdownMenuItem>

                                <DropdownMenuItem 
                                    @click="toggleFullscreen"
                                    class="cursor-pointer select-none rounded-lg px-2 py-2 text-[11px] font-semibold hover:bg-slate-50 dark:hover:bg-slate-800 focus:bg-slate-50 dark:focus:bg-slate-800 focus:outline-none text-slate-700 dark:text-slate-350 flex items-center gap-1.5"
                                >
                                    <Minimize v-if="isFullscreen" class="h-3.5 w-3.5" />
                                    <Maximize v-else class="h-3.5 w-3.5" />
                                    <span>{{ isFullscreen ? 'Keluar Fullscreen' : 'Layar Penuh' }}</span>
                                </DropdownMenuItem>

                                <DropdownMenuItem 
                                    @click="isPrinterSettingsOpen = true"
                                    class="cursor-pointer select-none rounded-lg px-2 py-2 text-[11px] font-semibold hover:bg-slate-50 dark:hover:bg-slate-800 focus:bg-slate-50 dark:focus:bg-slate-800 focus:outline-none text-slate-700 dark:text-slate-350 flex items-center gap-1.5"
                                >
                                    <Settings class="h-3.5 w-3.5" />
                                    <span>Pengaturan Printer</span>
                                </DropdownMenuItem>
                                
                                <DropdownMenuSeparator class="h-px bg-slate-200 dark:bg-slate-800 my-1" />
                                
                                <DropdownMenuItem class="cursor-pointer select-none rounded-lg px-2 py-2 text-[11px] font-bold hover:bg-rose-50 dark:hover:bg-rose-950/20 focus:bg-rose-50 dark:focus:bg-rose-955/20 focus:outline-none text-rose-600">
                                    <Link :href="route('logout')" method="post" as="button" class="w-full text-left h-full flex items-center gap-1.5 font-bold">
                                        <LogOut class="h-3.5 w-3.5" />
                                        <span>Keluar</span>
                                    </Link>
                                </DropdownMenuItem>
                            </DropdownMenuContent>
                        </DropdownMenuPortal>
                    </DropdownMenuRoot>
                </div>

                <!-- Desktop Actions -->
                <div class="hidden sm:flex items-center gap-3">
                    <div class="flex items-center gap-2.5">
                        <div class="h-8 w-8 rounded-full bg-[#8c5a3c]/10 text-[#8c5a3c] flex items-center justify-center font-bold text-xs">
                            {{ getProductInitials($page.props.auth.user.name) }}
                        </div>
                        <div class="flex flex-col text-left leading-none">
                            <span class="text-xs font-semibold leading-none">{{ $page.props.auth.user.name }}</span>
                            <span class="text-[9px] text-slate-400 dark:text-slate-550 mt-1 leading-none">
                                {{ $page.props.auth.user.roles[0] || 'Staff' }}
                            </span>
                        </div>
                    </div>

                    <div class="h-5 w-[1px] bg-slate-200 dark:bg-slate-800"></div>

                    <div class="flex items-center gap-2">
                        <Link
                            :href="route('transactions.index')"
                            class="px-3 py-1.5 border border-slate-200 dark:border-slate-800 rounded-lg text-xs font-semibold hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors cursor-pointer text-slate-700 dark:text-slate-300 flex items-center gap-1.5"
                        >
                            <Receipt class="h-3.5 w-3.5 text-[#8c5a3c]" />
                            <span>Riwayat Transaksi</span>
                        </Link>
                        <Link
                            v-if="$page.props.auth.user.roles.includes('Super Admin') || $page.props.auth.user.roles.includes('Owner') || $page.props.auth.user.roles.includes('Admin')"
                            :href="route('dashboard')"
                            class="px-3 py-1.5 border border-slate-200 dark:border-slate-800 rounded-lg text-xs font-semibold hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors cursor-pointer text-slate-700 dark:text-slate-300"
                        >
                            Dashboard Admin
                        </Link>
                        <button
                            @click="toggleTheme"
                            class="h-8 w-8 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-900 flex items-center justify-center text-slate-555 dark:text-slate-400 cursor-pointer transition-colors"
                            aria-label="Toggle Theme"
                        >
                            <Sun v-if="isDark" class="h-4.5 w-4.5 text-amber-500" />
                            <Moon v-else class="h-4.5 w-4.5 text-slate-650 dark:text-slate-400" />
                        </button>
                        <button
                            @click="toggleFullscreen"
                            class="h-8 w-8 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-900 flex items-center justify-center text-slate-555 dark:text-slate-400 cursor-pointer transition-colors"
                            title="Toggle Layar Penuh"
                        >
                            <Minimize v-if="isFullscreen" class="h-4.5 w-4.5" />
                            <Maximize v-else class="h-4.5 w-4.5" />
                        </button>
                        <button
                            @click="isPendingQrListModalOpen = true"
                            class="px-3 py-1.5 rounded-xl bg-amber-500/10 hover:bg-amber-500/20 border border-amber-500/30 text-amber-900 dark:text-amber-200 text-xs font-bold flex items-center gap-2 cursor-pointer transition-all relative shadow-sm"
                            title="Lihat Pesanan Self-Order QR Pending"
                        >
                            <div class="relative flex items-center justify-center">
                                <Receipt class="h-4 w-4 text-amber-600 dark:text-amber-400" />
                                <span v-if="pendingQrOrders && pendingQrOrders.length > 0" class="absolute -top-1.5 -right-1.5 flex h-2.5 w-2.5">
                                    <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-rose-400 opacity-75"></span>
                                    <span class="relative inline-flex rounded-full h-2.5 w-2.5 bg-rose-500"></span>
                                </span>
                            </div>
                            <span class="hidden sm:inline">Pesanan Self-Order</span>
                            <span v-if="pendingQrOrders && pendingQrOrders.length > 0" class="px-1.5 py-0.2 bg-rose-600 text-white text-[10px] font-black rounded-full shadow-sm">
                                {{ pendingQrOrders.length }}
                            </span>
                        </button>
                        <button
                            @click="isPrinterSettingsOpen = true"
                            class="h-8 w-8 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-900 flex items-center justify-center text-slate-555 dark:text-slate-400 cursor-pointer transition-colors"
                            title="Pengaturan Printer"
                        >
                            <Settings class="h-4.5 w-4.5" />
                        </button>
                        <Link
                            :href="route('logout')"
                            method="post"
                            as="button"
                            class="px-3 py-1.5 bg-rose-600 hover:bg-rose-500 text-white rounded-lg text-xs font-semibold transition-colors cursor-pointer"
                        >
                            Keluar
                        </Link>
                    </div>
                </div>
            </div>
        </header>

        <!-- POS Workspace container -->
        <main class="flex-1 p-6 overflow-visible lg:overflow-hidden min-h-0 flex flex-col bg-slate-50 dark:bg-slate-900">
            <!-- Split POS screen layout (Desktop) -->
            <div class="hidden lg:grid grid-cols-12 gap-6 lg:h-full lg:overflow-hidden min-h-0">
                <!-- Left Side: Product Selector (8 cols) -->
                <div class="lg:col-span-7 xl:col-span-8 flex flex-col lg:h-full space-y-4 min-w-0 min-h-0">
                    <!-- POS Header Filters -->
                    <div class="flex flex-wrap items-center justify-between gap-4 bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl p-4 shadow-sm flex-shrink-0">
                        <div class="relative flex-1 max-w-sm">
                            <Search class="absolute left-3 top-2.5 h-4 w-4 text-slate-400" />
                            <input
                                v-model="search"
                                type="text"
                                placeholder="Cari menu kopi atau makanan..."
                                class="w-full pl-9 pr-4 py-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent text-sm focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c] transition-all text-slate-900 dark:text-slate-100"
                            />
                        </div>

                        <!-- Order Type Selection -->
                        <div class="flex items-center gap-1.5">
                            <button
                                v-for="type in ['dine_in', 'take_away', 'delivery']"
                                :key="type"
                                @click="orderType = type as any"
                                :class="[
                                    'px-3 py-1.5 border rounded-lg text-[10px] font-bold uppercase tracking-wider transition-all cursor-pointer',
                                    orderType === type
                                        ? 'bg-[#8c5a3c] border-[#8c5a3c] text-white'
                                        : 'bg-transparent border-slate-200 dark:border-slate-800 text-slate-500 dark:text-slate-400'
                                ]"
                            >
                                {{ type === 'dine_in' ? 'Dine In' : (type === 'delivery' ? 'Delivery' : 'Take Away') }}
                            </button>
                        </div>
                    </div>

                    <!-- Category Tabs -->
                    <div class="flex gap-2 overflow-x-auto pb-1 flex-shrink-0 scrollbar-thin scrollbar-thumb-slate-200 dark:scrollbar-thumb-slate-800">
                        <button
                            v-for="cat in categories"
                            :key="cat"
                            @click="activeCategory = cat"
                            :class="[
                                'px-4 py-2 rounded-full text-xs font-semibold whitespace-nowrap transition-all cursor-pointer border',
                                activeCategory === cat
                                    ? 'bg-[#8c5a3c] border-[#8c5a3c] text-white shadow-sm'
                                    : 'bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-800 hover:border-slate-300 dark:hover:border-slate-600'
                            ]"
                        >
                            {{ cat }}
                        </button>
                    </div>

                    <!-- Product Grid -->
                    <div class="flex-1 overflow-y-auto pr-1 min-h-0">
                        <div v-if="filteredProducts.length === 0" class="flex flex-col items-center justify-center p-12 text-slate-400 bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl h-full shadow-sm">
                            <Coffee class="h-12 w-12 text-slate-300 mb-2" />
                            <p class="text-sm">Tidak ada produk ditemukan.</p>
                        </div>
                        
                        <div v-else class="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-4 gap-4">
                            <div
                                v-for="p in filteredProducts"
                                :key="p.id"
                                @click="addToCart(p)"
                                :class="[
                                    'bg-white dark:bg-slate-950 border rounded-xl overflow-hidden shadow-sm flex flex-col transition-all duration-200 group relative select-none',
                                    getAvailableQty(p, (p.category === 'Coffee' || p.category === 'Non-Coffee') ? 'ice' : null) > 0
                                        ? 'hover:-translate-y-0.5 hover:shadow-md border-slate-200 dark:border-slate-800 cursor-pointer'
                                        : 'opacity-60 border-slate-200 dark:border-slate-900 cursor-not-allowed'
                                ]"
                            >
                                <!-- Product Image -->
                                <div class="aspect-square w-full relative overflow-hidden bg-slate-50/50 dark:bg-slate-900/30 flex-shrink-0">
                                    <img 
                                        v-if="p.image_path" 
                                        :src="p.image_path" 
                                        alt="Product Photo" 
                                        class="h-full w-full object-cover group-hover:scale-105 transition-transform duration-300" 
                                    />
                                    <div v-else class="h-full w-full bg-gradient-to-br from-[#8c5a3c]/20 to-orange-550/20 text-[#8c5a3c] flex items-center justify-center font-bold text-xl">
                                        {{ getProductInitials(p.name) }}
                                    </div>

                                    <!-- Live Availability Badge -->
                                    <div class="absolute bottom-2 right-2">
                                        <span 
                                            v-if="getAvailableQty(p, (p.category === 'Coffee' || p.category === 'Non-Coffee') ? 'ice' : null) > 0"
                                            class="inline-flex px-1.5 py-0.5 rounded text-[9px] font-bold uppercase bg-emerald-500 text-white shadow-sm"
                                        >
                                            In Stock ({{ getAvailableQty(p, (p.category === 'Coffee' || p.category === 'Non-Coffee') ? 'ice' : null) }})
                                        </span>
                                        <span 
                                            v-else
                                            class="inline-flex px-1.5 py-0.5 rounded text-[9px] font-bold uppercase bg-rose-600 text-white shadow-sm"
                                        >
                                            Habis
                                        </span>
                                    </div>
                                </div>

                                <!-- Product Info -->
                                <div class="p-3 flex-1 flex flex-col justify-between">
                                    <div>
                                        <h4 class="text-sm font-semibold text-slate-900 dark:text-slate-100 truncate group-hover:text-[#8c5a3c] transition-colors">{{ p.name }}</h4>
                                        <p class="text-[10px] text-slate-400 mt-0.5 truncate">{{ p.description || 'Tidak ada deskripsi' }}</p>
                                    </div>
                                    <p class="text-sm font-bold text-slate-900 dark:text-slate-100 mt-2">
                                        Rp {{ Number(p.price).toLocaleString('id-ID') }}
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Right Side: POS Cart (5 cols) -->
                <div class="lg:col-span-5 xl:col-span-4 bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-sm flex flex-col h-[550px] lg:h-full overflow-hidden min-h-0 flex-shrink-0">
                    <!-- Cart Title -->
                    <div class="p-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between flex-shrink-0 bg-slate-50/50 dark:bg-slate-900/10">
                        <div class="flex items-center gap-2">
                            <ShoppingCart class="h-4.5 w-4.5 text-slate-500" />
                            <h3 class="text-sm font-bold text-slate-900 dark:text-slate-100">Keranjang Belanja</h3>
                        </div>
                        <div class="flex items-center gap-1.5">
                            <button
                                @click="openSplitModal"
                                class="p-1 text-slate-555 hover:text-[#8c5a3c] hover:bg-slate-100 dark:hover:bg-slate-900 rounded-lg cursor-pointer"
                                title="Split Bill"
                            >
                                <Split class="h-4 w-4" />
                            </button>
                            <span class="text-xs px-2 py-0.5 bg-[#8c5a3c]/10 text-[#8c5a3c] rounded-full font-bold">
                                {{ cart.length }} Item(s)
                            </span>
                        </div>
                    </div>

                    <!-- Dine In Table selector / Delivery label in Cart -->
                    <div v-if="orderType === 'dine_in'" class="p-3 border-b border-slate-200 dark:border-slate-800 bg-[#8c5a3c]/5 flex items-center justify-between gap-4">
                        <div class="flex items-center gap-1.5 text-xs text-[#8c5a3c] font-bold">
                            <Grid class="h-4 w-4" />
                            <span>Pilih Meja:</span>
                        </div>
                        <select
                            v-model="selectedTableId"
                            class="h-8 px-2.5 border border-[#8c5a3c]/20 rounded-lg bg-white dark:bg-slate-950 text-xs font-semibold focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-900 dark:text-slate-100 cursor-pointer"
                        >
                            <option :value="null">Pilih...</option>
                            <option v-for="t in tables" :key="t.id" :value="t.id">{{ t.number }} ({{ t.capacity }}p)</option>
                        </select>
                    </div>

                    <!-- Waiter selector (Admin / SuperAdmin only) -->
                    <div v-if="isAdminOrSuperAdmin" class="p-3 border-b border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/10 flex items-center justify-between gap-4">
                        <div class="flex items-center gap-1.5 text-xs text-slate-500 font-bold">
                            <User class="h-4 w-4 text-slate-400" />
                            <span>Pilih Pelayan:</span>
                        </div>
                        <select
                            v-model="selectedWaiterId"
                            class="h-8 px-2.5 border border-slate-250 dark:border-slate-800 rounded-lg bg-white dark:bg-slate-955 text-xs font-semibold focus:outline-none text-slate-900 dark:text-slate-100 cursor-pointer"
                        >
                            <option :value="null">Pilih pelayan...</option>
                            <option v-for="w in waiters" :key="w.id" :value="w.id">{{ w.name }}</option>
                        </select>
                    </div>

                    <!-- Courier selector -->
                    <div v-if="orderType === 'delivery'" class="p-3 border-b border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/10 flex items-center justify-between gap-4">
                        <div class="flex items-center gap-1.5 text-xs text-slate-500 font-bold">
                            <Users class="h-4 w-4 text-slate-400" />
                            <span>Pilih Kurir:</span>
                        </div>
                        <select
                            v-model="selectedCourierId"
                            class="h-8 px-2.5 border border-slate-250 dark:border-slate-800 rounded-lg bg-white dark:bg-slate-955 text-xs font-semibold focus:outline-none text-slate-900 dark:text-slate-100 cursor-pointer"
                        >
                            <option :value="null">Pilih kurir...</option>
                            <option v-for="c in couriers" :key="c.id" :value="c.id">{{ c.name }}</option>
                        </select>
                    </div>

                    <!-- Cart Items List -->
                    <div class="flex-1 overflow-y-auto p-4 space-y-4 min-h-0">
                        <div v-if="cart.length === 0" class="flex flex-col items-center justify-center p-8 text-slate-400 h-full">
                            <ShoppingCart class="h-10 w-10 text-slate-200 mb-2" />
                            <p class="text-xs text-center">Keranjang kosong.<br/>Klik menu di kiri untuk menambahkan.</p>
                        </div>

                        <div 
                            v-else
                            v-for="(item, idx) in cart" 
                            :key="idx" 
                            class="p-3 bg-slate-50/50 dark:bg-slate-900/20 rounded-xl border border-slate-100 dark:border-slate-900 flex flex-col space-y-2.5 animate-in slide-in-from-bottom-2 duration-150"
                        >
                            <!-- Item Header info -->
                            <div class="flex items-start justify-between gap-2">
                                <div>
                                    <h4 class="text-sm font-semibold text-slate-900 dark:text-slate-100 leading-tight">{{ item.product.name }}</h4>
                                    <span class="text-xs text-slate-450 font-medium">Rp {{ Number(item.product.price).toLocaleString('id-ID') }}</span>
                                </div>
                                <button
                                    @click="removeFromCart(item)"
                                    class="p-1 text-slate-400 hover:text-rose-500 rounded-lg transition-colors cursor-pointer"
                                >
                                    <Trash2 class="h-4 w-4" />
                                </button>
                            </div>

                             <!-- Modifiers Toggle in Item -->
                             <div v-if="item.product.modifiers && item.product.modifiers.length > 0" class="flex flex-wrap items-center gap-1.5 pt-1.5 border-t border-slate-100 dark:border-slate-900">
                                 <span class="text-[9px] font-bold text-slate-400 uppercase tracking-wide">Add-ons:</span>
                                 <button
                                     v-for="mod in item.product.modifiers"
                                     :key="mod.id"
                                     @click="toggleModifier(item, mod.id)"
                                     :class="[
                                         'px-2 py-0.5 border rounded-lg text-[9px] font-semibold transition-all cursor-pointer',
                                         item.selectedModifiers.includes(mod.id)
                                             ? 'bg-[#8c5a3c]/10 border-[#8c5a3c] text-[#8c5a3c] font-bold'
                                             : 'bg-white dark:bg-slate-955 border-slate-200 dark:border-slate-800 text-slate-550'
                                     ]"
                                 >
                                     +{{ mod.name }} (+Rp{{ Number(mod.price).toLocaleString('id-ID') }})
                                 </button>
                             </div>

                            <!-- Notes & Variant Selector -->
                            <div class="flex flex-wrap items-center justify-between gap-2 pt-2 border-t border-slate-100 dark:border-slate-900">
                                <!-- Hot/Ice Variant toggle -->
                                <div class="flex rounded-lg bg-slate-100 dark:bg-slate-800 p-0.5" v-if="item.variant !== null">
                                    <button
                                        type="button"
                                        @click="changeVariant(item, 'ice')"
                                        :class="[
                                            'px-2 py-1 rounded-md text-[10px] font-bold uppercase flex items-center gap-1 transition-all cursor-pointer',
                                            item.variant === 'ice'
                                                ? 'bg-white dark:bg-slate-955 text-blue-600 dark:text-blue-400 shadow-sm'
                                                : 'text-slate-400'
                                        ]"
                                    >
                                        <Snowflake class="h-3 w-3" />
                                        Es
                                    </button>
                                    <button
                                        type="button"
                                        @click="changeVariant(item, 'hot')"
                                        :class="[
                                            'px-2 py-1 rounded-md text-[10px] font-bold uppercase flex items-center gap-1 transition-all cursor-pointer',
                                            item.variant === 'hot'
                                                ? 'bg-white dark:bg-slate-955 text-red-650 dark:text-red-400 shadow-sm'
                                                : 'text-slate-400'
                                        ]"
                                    >
                                        <Flame class="h-3 w-3" />
                                        Panas
                                    </button>
                                </div>
                                <div v-else class="text-[10px] text-slate-400 italic">No variants</div>

                                <!-- Qty adjuster -->
                                <div class="flex items-center gap-2">
                                    <button
                                        @click="decrementQty(item)"
                                        class="h-6 w-6 rounded bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 cursor-pointer"
                                    >
                                        <Minus class="h-3.5 w-3.5" />
                                    </button>
                                    <span class="text-sm font-bold w-6 text-center text-slate-900 dark:text-slate-100">{{ item.qty }}</span>
                                    <button
                                        @click="incrementQty(item)"
                                        :disabled="getAvailableQty(item.product, item.variant) <= 0"
                                        class="h-6 w-6 rounded bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 disabled:opacity-40 cursor-pointer"
                                    >
                                        <Plus class="h-3.5 w-3.5" />
                                    </button>
                                </div>
                            </div>

                            <!-- Custom Note Input -->
                            <input
                                v-model="item.notes"
                                type="text"
                                placeholder="Catatan (misal: kurang manis, take away)..."
                                class="w-full px-2.5 py-1 text-[11px] border border-slate-200 dark:border-slate-800 rounded bg-white dark:bg-slate-900 text-slate-700 dark:text-slate-300 placeholder-slate-400 dark:placeholder-slate-600 focus:outline-none focus:border-[#8c5a3c]"
                            />
                        </div>

                        <!-- Checkout Config Inputs (only show if cart has items) -->
                        <div v-if="cart.length > 0" class="pt-4 border-t border-slate-200 dark:border-slate-800/60 space-y-4">
                            <!-- CRM & Member Selector -->
                            <div class="space-y-1.5">
                                <span class="text-[9px] font-bold uppercase text-slate-400 tracking-wider">Customer / Member</span>
                                <div class="grid grid-cols-2 gap-2">
                                    <select
                                        v-model="selectedCustomerId"
                                        class="h-8 px-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-white dark:bg-slate-950 text-xs font-semibold focus:outline-none text-slate-900 dark:text-slate-100 cursor-pointer"
                                    >
                                        <option v-for="c in customers" :key="c.id" :value="c.id">{{ c.name }} {{ c.is_member ? '(Member)' : '' }}</option>
                                    </select>

                                    <!-- Points redemption input (if member selected) -->
                                    <div class="flex items-center gap-1.5" v-if="customers.find(c => c.id === selectedCustomerId)?.is_member">
                                        <span class="text-[9px] font-bold text-[#8c5a3c]">PTS: {{ selectedCustomerPoints }}</span>
                                        <input
                                            type="number"
                                            v-model="pointsToRedeem"
                                            min="0"
                                            :max="selectedCustomerPoints"
                                            placeholder="Redeem pts"
                                            class="w-full h-8 px-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-white dark:bg-slate-955 text-xs text-right font-bold focus:outline-none"
                                        />
                                    </div>
                                </div>
                            </div>

                            <!-- Promo codes engine -->
                            <div class="space-y-1.5" v-if="promos.length > 0">
                                <span class="text-[9px] font-bold uppercase text-slate-400 tracking-wider">Terapkan Kupon Promo</span>
                                <select
                                    v-model="selectedPromoId"
                                    class="w-full h-8 px-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-white dark:bg-slate-950 text-xs font-semibold focus:outline-none text-slate-900 dark:text-slate-100 cursor-pointer"
                                >
                                    <option :value="null">Pilih promo...</option>
                                    <option v-for="p in promos" :key="p.id" :value="p.id" :disabled="subtotal < p.min_purchase">
                                        {{ p.name }} (Min. Rp{{ Number(p.min_purchase).toLocaleString('id-ID') }})
                                    </option>
                                </select>
                            </div>

                            <!-- Voucher / Promo Code input -->
                            <div class="space-y-1.5">
                                <span class="text-[9px] font-bold uppercase text-slate-400 tracking-wider">Kupon Voucher Kustom</span>
                                <div class="flex gap-2">
                                    <input
                                        type="text"
                                        v-model="voucherCode"
                                        placeholder="Masukkan kode..."
                                        class="flex-1 h-8 px-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-white dark:bg-slate-955 text-xs font-semibold focus:outline-none text-slate-900 dark:text-slate-100 uppercase"
                                    />
                                    <button
                                        type="button"
                                        @click="applyVoucher"
                                        class="h-8 px-3 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-lg cursor-pointer transition-colors"
                                    >
                                        Terapkan
                                    </button>
                                </div>
                                <!-- Success / Error messages -->
                                <p v-if="appliedVoucher" class="text-[9px] font-semibold text-emerald-600 dark:text-emerald-400">
                                    Kupon diterapkan: {{ appliedVoucher.code }} (Potongan Rp {{ appliedVoucher.value.toLocaleString('id-ID') }}{{ appliedVoucher.type === 'percent' ? '%' : '' }})
                                </p>
                                <p v-if="voucherError" class="text-[9px] font-semibold text-rose-600 dark:text-rose-400">
                                    {{ voucherError }}
                                </p>
                            </div>

                            <!-- Birthday Notification Banner -->
                            <div v-if="birthdayDiscount > 0" class="p-2 border border-emerald-500/20 bg-emerald-500/10 rounded-lg text-[9px] text-emerald-700 dark:text-emerald-400 font-bold flex items-center gap-1.5 animate-pulse">
                                <span>🎉</span>
                                <span>Ulang Tahun Member! Diskon 10% Otomatis + Bonus 50 Poin!</span>
                            </div>
                        </div>
                    </div>

                    <!-- Pinned Summary & Checkout Block (Pinned Bottom) -->
                    <div class="border-t border-slate-200 dark:border-slate-800 p-4 space-y-4 bg-slate-50/50 dark:bg-slate-900/10 flex-shrink-0">

                        <!-- Calculations -->
                        <div class="space-y-1.5 text-xs text-slate-600 dark:text-slate-400">
                            <div class="flex justify-between">
                                <span>Subtotal</span>
                                <span class="font-semibold text-slate-900 dark:text-slate-100">Rp {{ subtotal.toLocaleString('id-ID') }}</span>
                            </div>
                            <div class="flex justify-between" v-if="servicePercentage > 0">
                                <span>Biaya Layanan ({{ servicePercentage }}%)</span>
                                <span class="font-semibold text-slate-900 dark:text-slate-100">Rp {{ serviceCharge.toLocaleString('id-ID') }}</span>
                            </div>
                            <div class="flex justify-between" v-if="taxPercentage > 0">
                                <span>Pajak Restoran ({{ taxPercentage }}%)</span>
                                <span class="font-semibold text-slate-900 dark:text-slate-100">Rp {{ tax.toLocaleString('id-ID') }}</span>
                            </div>
                            <div class="flex justify-between text-rose-500 font-bold" v-if="discountAmount > 0">
                                <span>Potongan Diskon</span>
                                <span>-Rp {{ discountAmount.toLocaleString('id-ID') }}</span>
                            </div>
                            <div class="flex justify-between text-sm font-bold text-slate-900 dark:text-slate-100 pt-1.5 border-t border-slate-200 dark:border-slate-800">
                                <span>Total Tagihan</span>
                                <span class="text-[#8c5a3c]">Rp {{ grandTotal.toLocaleString('id-ID') }}</span>
                            </div>
                        </div>

                        <!-- Payment methods selector -->
                        <div class="space-y-2">
                            <span class="text-[10px] font-bold uppercase text-slate-400 tracking-wider">Metode Pembayaran</span>
                            <div class="grid grid-cols-3 gap-2">
                                <button
                                    v-for="method in ['cash', 'transfer', 'qris']"
                                    :key="method"
                                    @click="paymentMethod = method as any"
                                    :class="[
                                        'py-2 text-xs font-semibold rounded-lg border text-center transition-all cursor-pointer uppercase',
                                        paymentMethod === method
                                            ? 'bg-[#8c5a3c]/10 border-[#8c5a3c] text-[#8c5a3c]'
                                            : 'border-slate-200 dark:border-slate-850 text-slate-500 dark:text-slate-400 bg-white dark:bg-slate-950'
                                    ]"
                                >
                                    {{ method }}
                                </button>
                            </div>
                        </div>

                        <!-- Cash calculator -->
                        <div v-if="paymentMethod === 'cash'" class="space-y-2 pt-2 border-t border-dashed border-slate-200 dark:border-slate-800">
                            <div class="flex items-center justify-between gap-4">
                                <span class="text-[10px] font-bold uppercase text-slate-400 dark:text-slate-500">Uang Diterima</span>
                                <input
                                    v-model.number="cashReceived"
                                    type="number"
                                    class="w-32 px-2 py-1 text-right border border-slate-200 dark:border-slate-700 rounded bg-white dark:bg-slate-900 text-slate-900 dark:text-slate-100 text-sm focus:outline-none focus:border-[#8c5a3c] font-bold"
                                />
                            </div>
                            
                            <div class="flex flex-wrap gap-1.5 pt-1">
                                <button
                                    type="button"
                                    @click="selectQuickCash(grandTotal)"
                                    class="px-2 py-1 rounded bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300 text-[10px] font-semibold hover:bg-slate-200 dark:hover:bg-slate-700 cursor-pointer transition-colors"
                                >
                                    Pas
                                </button>
                                <button
                                    v-for="amt in [20000, 50000, 100000]"
                                    :key="amt"
                                    v-show="amt >= grandTotal"
                                    type="button"
                                    @click="selectQuickCash(amt)"
                                    class="px-2 py-1 rounded bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300 text-[10px] font-semibold hover:bg-slate-200 dark:hover:bg-slate-700 cursor-pointer transition-colors"
                                >
                                    Rp {{ amt.toLocaleString('id-ID') }}
                                </button>
                            </div>

                            <div v-if="cashReceived >= grandTotal" class="flex justify-between items-center text-xs font-semibold text-emerald-600 dark:text-emerald-400 pt-1.5">
                                <span>Kembalian</span>
                                <span class="font-bold text-sm">Rp {{ changeDue.toLocaleString('id-ID') }}</span>
                            </div>
                        </div>

                        <!-- Submit checkout -->
                        <button
                            @click="handleCheckout"
                            :disabled="cart.length === 0 || isCheckingOut || (paymentMethod === 'cash' && cashReceived < grandTotal)"
                            class="w-full py-3 bg-[#8c5a3c] hover:bg-[#734a31] text-white rounded-lg text-sm font-semibold shadow-sm focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 disabled:opacity-40 transition-all cursor-pointer flex items-center justify-center gap-2"
                        >
                            <span>{{ isCheckingOut ? 'Memproses Transaksi...' : 'Selesaikan Pembayaran' }}</span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Mobile Layout (Tabbed POS Terminal) -->
            <div class="lg:hidden flex flex-col h-full space-y-4">
                <!-- VIEW 1: Pilih Menu -->
                <div v-if="activeMobileTab === 'menu'" class="flex flex-col space-y-4 pb-20 animate-in fade-in duration-200">
                    <!-- POS Header Filters -->
                    <div class="flex flex-wrap items-center justify-between gap-3 bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl p-3 shadow-sm">
                        <div class="relative flex-1">
                            <Search class="absolute left-3 top-2.5 h-4 w-4 text-slate-400" />
                            <input
                                v-model="search"
                                type="text"
                                placeholder="Cari menu kopi atau makanan..."
                                class="w-full pl-9 pr-4 py-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent text-xs focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c] transition-all text-slate-900 dark:text-slate-100"
                            />
                        </div>

                        <!-- Order Type Selection -->
                        <div class="flex items-center gap-1">
                            <button
                                v-for="type in ['dine_in', 'take_away', 'delivery']"
                                :key="type"
                                @click="orderType = type as any"
                                :class="[
                                    'px-2 py-1.5 border rounded-lg text-[9px] font-bold uppercase tracking-wider transition-all cursor-pointer',
                                    orderType === type
                                        ? 'bg-[#8c5a3c] border-[#8c5a3c] text-white'
                                        : 'bg-transparent border-slate-200 dark:border-slate-800 text-slate-550'
                                ]"
                            >
                                {{ type === 'dine_in' ? 'Dine In' : (type === 'delivery' ? 'Deliv' : 'Take Away') }}
                            </button>
                        </div>
                    </div>

                    <!-- Category Tabs -->
                    <div class="flex gap-1.5 overflow-x-auto pb-1 flex-shrink-0 scrollbar-none">
                        <button
                            v-for="cat in categories"
                            :key="cat"
                            @click="activeCategory = cat"
                            :class="[
                                'px-3.5 py-1.5 rounded-full text-[11px] font-semibold whitespace-nowrap transition-all cursor-pointer border',
                                activeCategory === cat
                                    ? 'bg-[#8c5a3c] border-[#8c5a3c] text-white shadow-sm'
                                    : 'bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-700 text-slate-650 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-800'
                            ]"
                        >
                            {{ cat }}
                        </button>
                    </div>

                    <!-- Product Grid -->
                    <div class="flex-1">
                        <div v-if="filteredProducts.length === 0" class="flex flex-col items-center justify-center p-12 text-slate-400 bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-sm">
                            <Coffee class="h-10 w-10 text-slate-300 mb-2" />
                            <p class="text-xs">Tidak ada produk ditemukan.</p>
                        </div>
                        
                        <div v-else class="grid grid-cols-2 gap-3">
                            <div
                                v-for="p in filteredProducts"
                                :key="p.id"
                                @click="addToCart(p)"
                                :class="[
                                    'bg-white dark:bg-slate-950 border rounded-xl overflow-hidden shadow-sm flex flex-col transition-all duration-200 relative',
                                    getAvailableQty(p, (p.category === 'Coffee' || p.category === 'Non-Coffee') ? 'ice' : null) > 0
                                        ? 'border-slate-200 dark:border-slate-800 cursor-pointer active:scale-[0.98]'
                                        : 'opacity-60 border-slate-200 dark:border-slate-900 cursor-not-allowed'
                                ]"
                            >
                                <!-- Product Image -->
                                <div class="aspect-square w-full relative overflow-hidden bg-slate-50/50 dark:bg-slate-900/30 flex-shrink-0">
                                    <img 
                                        v-if="p.image_path" 
                                        :src="p.image_path" 
                                        alt="Product Photo" 
                                        class="h-full w-full object-cover" 
                                    />
                                    <div v-else class="h-full w-full bg-gradient-to-br from-[#8c5a3c]/20 to-orange-550/20 text-[#8c5a3c] flex items-center justify-center font-bold text-lg">
                                        {{ getProductInitials(p.name) }}
                                    </div>

                                    <!-- Live Availability Badge -->
                                    <div class="absolute bottom-1.5 right-1.5">
                                        <span 
                                            v-if="getAvailableQty(p, (p.category === 'Coffee' || p.category === 'Non-Coffee') ? 'ice' : null) > 0"
                                            class="inline-flex px-1 py-0.5 rounded text-[8px] font-extrabold uppercase bg-emerald-500 text-white shadow-sm"
                                        >
                                            In Stock ({{ getAvailableQty(p, (p.category === 'Coffee' || p.category === 'Non-Coffee') ? 'ice' : null) }})
                                        </span>
                                        <span 
                                            v-else
                                            class="inline-flex px-1 py-0.5 rounded text-[8px] font-extrabold uppercase bg-rose-600 text-white shadow-sm"
                                        >
                                            Habis
                                        </span>
                                    </div>
                                </div>

                                <!-- Product Info -->
                                <div class="p-2 flex-1 flex flex-col justify-between space-y-1">
                                    <div>
                                        <h4 class="text-xs font-bold text-slate-900 dark:text-slate-100 truncate">{{ p.name }}</h4>
                                        <p class="text-[9px] text-slate-400 truncate">{{ p.description || 'Tidak ada deskripsi' }}</p>
                                    </div>
                                    <p class="text-xs font-black text-slate-900 dark:text-slate-100">
                                        Rp {{ Number(p.price).toLocaleString('id-ID') }}
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- VIEW 2: Keranjang Belanja & Proses Checkout -->
                <div v-if="activeMobileTab === 'cart'" class="flex flex-col space-y-4 pb-20 animate-in fade-in duration-200">
                    <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-sm flex flex-col overflow-hidden">
                        <!-- Cart Title -->
                        <div class="p-3 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between bg-slate-50/50 dark:bg-slate-900/10">
                            <div class="flex items-center gap-1.5">
                                <ShoppingCart class="h-4.5 w-4.5 text-slate-500" />
                                <h3 class="text-xs font-extrabold text-slate-900 dark:text-slate-100">Keranjang Belanja</h3>
                            </div>
                            <div class="flex items-center gap-1.5">
                                <button
                                    @click="openSplitModal"
                                    class="p-1 text-slate-555 hover:text-[#8c5a3c] hover:bg-slate-100 dark:hover:bg-slate-900 rounded-lg cursor-pointer"
                                    title="Split Bill"
                                >
                                    <Split class="h-4 w-4" />
                                </button>
                                <span class="text-[10px] px-2 py-0.5 bg-[#8c5a3c]/10 text-[#8c5a3c] rounded-full font-bold">
                                    {{ cart.length }} Item(s)
                                </span>
                            </div>
                        </div>

                        <!-- Dine In Table selector -->
                        <div v-if="orderType === 'dine_in'" class="p-3 border-b border-slate-200 dark:border-slate-800 bg-[#8c5a3c]/5 flex items-center justify-between gap-4">
                            <div class="flex items-center gap-1 text-xs text-[#8c5a3c] font-bold">
                                <Grid class="h-3.5 w-3.5" />
                                <span>Pilih Meja:</span>
                            </div>
                            <select
                                v-model="selectedTableId"
                                class="h-8 px-2 border border-[#8c5a3c]/20 rounded-lg bg-white dark:bg-slate-950 text-xs font-semibold focus:outline-none text-slate-900 dark:text-slate-100 cursor-pointer"
                            >
                                <option :value="null">Pilih meja...</option>
                                <option v-for="t in tables" :key="t.id" :value="t.id">{{ t.number }} ({{ t.capacity }}p)</option>
                            </select>
                        </div>

                        <!-- Waiter selector (Admin / SuperAdmin only) -->
                        <div v-if="isAdminOrSuperAdmin" class="p-3 border-b border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/10 flex items-center justify-between gap-4">
                            <div class="flex items-center gap-1.5 text-xs text-slate-500 font-bold">
                                <User class="h-3.5 w-3.5 text-slate-400" />
                                <span>Pilih Pelayan:</span>
                            </div>
                            <select
                                v-model="selectedWaiterId"
                                class="h-8 px-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-white dark:bg-slate-950 text-xs font-semibold focus:outline-none text-slate-900 dark:text-slate-100 cursor-pointer"
                            >
                                <option :value="null">Pilih pelayan...</option>
                                <option v-for="w in waiters" :key="w.id" :value="w.id">{{ w.name }}</option>
                            </select>
                        </div>

                        <!-- Courier selector -->
                        <div v-if="orderType === 'delivery'" class="p-3 border-b border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/10 flex items-center justify-between gap-4">
                            <div class="flex items-center gap-1.5 text-xs text-slate-500 font-bold">
                                <Users class="h-3.5 w-3.5 text-slate-400" />
                                <span>Pilih Kurir:</span>
                            </div>
                            <select
                                v-model="selectedCourierId"
                                class="h-8 px-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-white dark:bg-slate-955 text-xs font-semibold focus:outline-none text-slate-900 dark:text-slate-100 cursor-pointer"
                            >
                                <option :value="null">Pilih kurir...</option>
                                <option v-for="c in couriers" :key="c.id" :value="c.id">{{ c.name }}</option>
                            </select>
                        </div>

                        <!-- Cart Items List -->
                        <div class="p-3 space-y-3.5 divide-y divide-slate-100 dark:divide-slate-900">
                            <div v-if="cart.length === 0" class="flex flex-col items-center justify-center p-8 text-slate-400">
                                <ShoppingCart class="h-8 w-8 text-slate-200 mb-2" />
                                <p class="text-xs text-center">Keranjang kosong.<br/>Pilih menu terlebih dahulu.</p>
                            </div>

                            <div 
                                v-else
                                v-for="(item, idx) in cart" 
                                :key="idx" 
                                class="pt-3 first:pt-0 flex flex-col space-y-2 animate-in slide-in-from-bottom-2 duration-150"
                            >
                                <!-- Item Header info -->
                                <div class="flex items-start justify-between gap-2">
                                    <div>
                                        <h4 class="text-xs font-bold text-slate-900 dark:text-slate-100 leading-tight">{{ item.product.name }}</h4>
                                        <span class="text-[10px] text-slate-400 font-bold">Rp {{ Number(item.product.price).toLocaleString('id-ID') }}</span>
                                    </div>
                                    <button
                                        @click="removeFromCart(item)"
                                        class="p-1 text-slate-450 hover:text-rose-500 rounded-lg cursor-pointer"
                                    >
                                        <Trash2 class="h-3.5 w-3.5" />
                                    </button>
                                </div>

                                <!-- Modifiers Toggle in Item -->
                                <div v-if="item.product.modifiers && item.product.modifiers.length > 0" class="flex flex-wrap items-center gap-1 pt-1">
                                    <span class="text-[8px] font-black text-slate-400 uppercase tracking-wide">Add-ons:</span>
                                    <button
                                        v-for="mod in item.product.modifiers"
                                        :key="mod.id"
                                        @click="toggleModifier(item, mod.id)"
                                        :class="[
                                            'px-1.5 py-0.5 border rounded-lg text-[8px] font-bold transition-all cursor-pointer',
                                            item.selectedModifiers.includes(mod.id)
                                                ? 'bg-[#8c5a3c]/10 border-[#8c5a3c] text-[#8c5a3c]'
                                                : 'bg-white dark:bg-slate-950 border-slate-200 dark:border-slate-800 text-slate-555'
                                        ]"
                                    >
                                        +{{ mod.name }} (+Rp{{ Number(mod.price).toLocaleString('id-ID') }})
                                    </button>
                                </div>

                                <!-- Notes & Variant Selector -->
                                <div class="flex flex-wrap items-center justify-between gap-2 pt-1">
                                    <!-- Hot/Ice Variant toggle -->
                                    <div class="flex rounded-lg bg-slate-100 dark:bg-slate-800 p-0.5" v-if="item.variant !== null">
                                        <button
                                            type="button"
                                            @click="changeVariant(item, 'ice')"
                                            :class="[
                                                'px-1.5 py-0.5 rounded-md text-[9px] font-black uppercase flex items-center gap-0.5 transition-all cursor-pointer',
                                                item.variant === 'ice'
                                                    ? 'bg-white dark:bg-slate-955 text-blue-600 dark:text-blue-400 shadow-sm'
                                                    : 'text-slate-450'
                                            ]"
                                        >
                                            <Snowflake class="h-2.5 w-2.5" />
                                            Es
                                        </button>
                                        <button
                                            type="button"
                                            @click="changeVariant(item, 'hot')"
                                            :class="[
                                                'px-1.5 py-0.5 rounded-md text-[9px] font-black uppercase flex items-center gap-0.5 transition-all cursor-pointer',
                                                item.variant === 'hot'
                                                    ? 'bg-white dark:bg-slate-955 text-red-655 dark:text-red-400 shadow-sm'
                                                    : 'text-slate-455'
                                            ]"
                                        >
                                            <Flame class="h-2.5 w-2.5" />
                                            Panas
                                        </button>
                                    </div>
                                    <div v-else class="text-[9px] text-slate-400 italic">No variants</div>

                                    <!-- Qty adjuster -->
                                    <div class="flex items-center gap-1.5">
                                        <button
                                            @click="decrementQty(item)"
                                            class="h-6 w-6 rounded bg-slate-100 dark:bg-slate-850 flex items-center justify-center text-slate-655 dark:text-slate-350 cursor-pointer"
                                        >
                                            <Minus class="h-3 w-3" />
                                        </button>
                                        <span class="text-xs font-bold w-5 text-center text-slate-905 dark:text-slate-100">{{ item.qty }}</span>
                                        <button
                                            @click="incrementQty(item)"
                                            :disabled="getAvailableQty(item.product, item.variant) <= 0"
                                            class="h-6 w-6 rounded bg-slate-100 dark:bg-slate-850 flex items-center justify-center text-slate-655 dark:text-slate-350 disabled:opacity-40 cursor-pointer"
                                        >
                                            <Plus class="h-3 w-3" />
                                        </button>
                                    </div>
                                </div>

                                <!-- Custom Note Input -->
                                <input
                                    v-model="item.notes"
                                    type="text"
                                    placeholder="Catatan menu..."
                                    class="w-full px-2.5 py-1 text-[10px] border border-slate-200 dark:border-slate-805 rounded bg-white dark:bg-slate-900 text-slate-700 dark:text-slate-355 placeholder-slate-400 focus:outline-none focus:border-[#8c5a3c]"
                                />
                            </div>
                        </div>

                        <!-- Calculation Summary & Checkout Block -->
                        <div class="border-t border-slate-200 dark:border-slate-800 p-3 space-y-4 bg-slate-50/50 dark:bg-slate-900/10">
                            
                            <!-- CRM & Member Selector -->
                            <div class="space-y-1">
                                <span class="text-[8px] font-black uppercase text-slate-450 tracking-wider">Customer / Member</span>
                                <div class="grid grid-cols-2 gap-2">
                                    <select
                                        v-model="selectedCustomerId"
                                        class="h-8 px-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-white dark:bg-slate-955 text-xs font-semibold focus:outline-none text-slate-900 dark:text-slate-100 cursor-pointer"
                                    >
                                        <option v-for="c in customers" :key="c.id" :value="c.id">{{ c.name }} {{ c.is_member ? '(Member)' : '' }}</option>
                                    </select>

                                    <!-- Points redemption input -->
                                    <div class="flex items-center gap-1.5" v-if="customers.find(c => c.id === selectedCustomerId)?.is_member">
                                        <span class="text-[8px] font-bold text-[#8c5a3c]">PTS: {{ selectedCustomerPoints }}</span>
                                        <input
                                            type="number"
                                            v-model="pointsToRedeem"
                                            min="0"
                                            :max="selectedCustomerPoints"
                                            placeholder="Redeem pts"
                                            class="w-full h-8 px-2 border border-slate-200 dark:border-slate-805 rounded-lg bg-white dark:bg-slate-955 text-xs text-right font-bold focus:outline-none"
                                        />
                                    </div>
                                </div>
                            </div>

                            <!-- Promo codes -->
                            <div class="space-y-1" v-if="promos.length > 0">
                                <span class="text-[8px] font-black uppercase text-slate-450 tracking-wider">Terapkan Kupon Promo</span>
                                <select
                                    v-model="selectedPromoId"
                                    class="w-full h-8 px-2 border border-slate-200 dark:border-slate-805 rounded-lg bg-white dark:bg-slate-955 text-xs font-semibold focus:outline-none text-slate-900 dark:text-slate-100 cursor-pointer"
                                >
                                    <option :value="null">Pilih promo...</option>
                                    <option v-for="p in promos" :key="p.id" :value="p.id" :disabled="subtotal < p.min_purchase">
                                        {{ p.name }} (Min. Rp{{ Number(p.min_purchase).toLocaleString('id-ID') }})
                                    </option>
                                </select>
                            </div>

                            <!-- Voucher / Promo Code input -->
                            <div class="space-y-1">
                                <span class="text-[8px] font-black uppercase text-slate-455 tracking-wider">Kupon Voucher Kustom</span>
                                <div class="flex gap-2">
                                    <input
                                        type="text"
                                        v-model="voucherCode"
                                        placeholder="Masukkan kode..."
                                        class="flex-1 h-8 px-2 border border-slate-200 dark:border-slate-805 rounded-lg bg-white dark:bg-slate-955 text-xs font-semibold focus:outline-none text-slate-900 dark:text-slate-100 uppercase"
                                    />
                                    <button
                                        type="button"
                                        @click="applyVoucher"
                                        class="h-8 px-3 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-lg cursor-pointer transition-colors"
                                    >
                                        Terapkan
                                    </button>
                                </div>
                                <!-- Success / Error messages -->
                                <p v-if="appliedVoucher" class="text-[9px] font-semibold text-emerald-600 dark:text-emerald-400">
                                    Kupon diterapkan: {{ appliedVoucher.code }} (Potongan Rp {{ appliedVoucher.value.toLocaleString('id-ID') }}{{ appliedVoucher.type === 'percent' ? '%' : '' }})
                                </p>
                                <p v-if="voucherError" class="text-[9px] font-semibold text-rose-600 dark:text-rose-400">
                                    {{ voucherError }}
                                </p>
                            </div>

                            <!-- Birthday Notification Banner -->
                            <div v-if="birthdayDiscount > 0" class="p-2 border border-emerald-500/20 bg-emerald-500/10 rounded-lg text-[9px] text-emerald-700 dark:text-emerald-400 font-bold flex items-center gap-1.5 animate-pulse">
                                <span>🎉</span>
                                <span>Ulang Ulang Tahun Member! Diskon 10% Otomatis + Bonus 50 Poin!</span>
                            </div>

                            <!-- Calculations -->
                            <div class="space-y-1 text-[11px] text-slate-600 dark:text-slate-400">
                                <div class="flex justify-between">
                                    <span>Subtotal</span>
                                    <span class="font-bold text-slate-900 dark:text-slate-100">Rp {{ subtotal.toLocaleString('id-ID') }}</span>
                                </div>
                                <div class="flex justify-between" v-if="servicePercentage > 0">
                                    <span>Biaya Layanan ({{ servicePercentage }}%)</span>
                                    <span class="font-bold text-slate-900 dark:text-slate-100">Rp {{ serviceCharge.toLocaleString('id-ID') }}</span>
                                </div>
                                <div class="flex justify-between" v-if="taxPercentage > 0">
                                    <span>Pajak Restoran ({{ taxPercentage }}%)</span>
                                    <span class="font-bold text-slate-900 dark:text-slate-100">Rp {{ tax.toLocaleString('id-ID') }}</span>
                                </div>
                                <div class="flex justify-between text-rose-500 font-bold" v-if="discountAmount > 0">
                                    <span>Potongan Diskon</span>
                                    <span>-Rp {{ discountAmount.toLocaleString('id-ID') }}</span>
                                </div>
                                <div class="flex justify-between text-xs font-extrabold text-slate-900 dark:text-slate-100 pt-1.5 border-t border-slate-200 dark:border-slate-800">
                                    <span>Total Tagihan</span>
                                    <span class="text-[#8c5a3c]">Rp {{ grandTotal.toLocaleString('id-ID') }}</span>
                                </div>
                            </div>

                            <!-- Payment methods selector -->
                            <div class="space-y-1.5">
                                <span class="text-[8px] font-black uppercase text-slate-450 tracking-wider">Metode Pembayaran</span>
                                <div class="grid grid-cols-3 gap-2">
                                    <button
                                        v-for="method in ['cash', 'transfer', 'qris']"
                                        :key="method"
                                        @click="paymentMethod = method as any"
                                        :class="[
                                            'py-1.5 text-xs font-bold rounded-lg border text-center transition-all cursor-pointer uppercase',
                                            paymentMethod === method
                                                ? 'bg-[#8c5a3c]/10 border-[#8c5a3c] text-[#8c5a3c]'
                                                : 'border-slate-200 dark:border-slate-800 text-slate-500 bg-white dark:bg-slate-950'
                                        ]"
                                    >
                                        {{ method }}
                                    </button>
                                </div>
                            </div>

                            <!-- Cash calculator -->
                            <div v-if="paymentMethod === 'cash'" class="space-y-2 pt-2 border-t border-dashed border-slate-200 dark:border-slate-800 animate-in fade-in duration-200">
                                <div class="flex items-center justify-between gap-4">
                                    <span class="text-[8px] font-black uppercase text-slate-450">Uang Diterima</span>
                                    <input
                                        v-model.number="cashReceived"
                                        type="number"
                                        class="w-28 px-2 py-1 text-right border border-slate-200 dark:border-slate-800 rounded bg-white dark:bg-slate-955 text-slate-900 dark:text-slate-100 text-xs focus:outline-none focus:border-[#8c5a3c] font-bold"
                                    />
                                </div>
                                
                                <div class="flex flex-wrap gap-1">
                                    <button
                                        type="button"
                                        @click="selectQuickCash(grandTotal)"
                                        class="px-2 py-1 rounded bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300 text-[9px] font-bold hover:bg-slate-250 cursor-pointer"
                                    >
                                        Pas
                                    </button>
                                    <button
                                        v-for="amt in [20000, 50000, 100000]"
                                        :key="amt"
                                        v-show="amt >= grandTotal"
                                        type="button"
                                        @click="selectQuickCash(amt)"
                                        class="px-2 py-1 rounded bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300 text-[9px] font-bold hover:bg-slate-200 cursor-pointer"
                                    >
                                        Rp {{ amt.toLocaleString('id-ID') }}
                                    </button>
                                </div>

                                <div v-if="cashReceived >= grandTotal" class="flex justify-between items-center text-[10px] font-bold text-emerald-600 dark:text-emerald-400 pt-1">
                                    <span>Kembalian</span>
                                    <span class="font-extrabold text-xs">Rp {{ changeDue.toLocaleString('id-ID') }}</span>
                                </div>
                            </div>

                            <!-- Submit checkout -->
                            <button
                                @click="handleCheckout"
                                :disabled="cart.length === 0 || isCheckingOut || (paymentMethod === 'cash' && cashReceived < grandTotal)"
                                class="w-full py-2.5 bg-[#8c5a3c] hover:bg-[#734a31] text-white rounded-lg text-xs font-bold shadow-sm focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 disabled:opacity-40 transition-all cursor-pointer flex items-center justify-center gap-1.5"
                            >
                                <span>{{ isCheckingOut ? 'Memproses...' : 'Selesaikan Pembayaran' }}</span>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- VIEW 3: List Riwayat Transaksi -->
                <div v-if="activeMobileTab === 'history'" class="flex flex-col space-y-4 pb-20 animate-in fade-in duration-200">
                    <div class="flex items-center justify-between">
                        <h3 class="text-xs font-extrabold text-slate-805 dark:text-slate-200 flex items-center gap-1.5">
                            <History class="h-4.5 w-4.5 text-[#8c5a3c]" />
                            <span>Riwayat Transaksi Terakhir</span>
                        </h3>
                        <span class="text-[9px] bg-[#8c5a3c]/10 text-[#8c5a3c] px-2 py-0.5 rounded-full font-bold">
                            Outlet: {{ outlets.find(o => o.id === outletId)?.name }}
                        </span>
                    </div>

                    <div v-if="!recentTransactions || recentTransactions.length === 0" class="flex flex-col items-center justify-center p-12 text-slate-450 bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-sm">
                        <History class="h-10 w-10 text-slate-350 mb-2" />
                        <p class="text-xs">Belum ada transaksi di outlet ini.</p>
                    </div>

                    <div v-else class="space-y-3">
                        <div 
                            v-for="txn in recentTransactions" 
                            :key="txn.id"
                            class="bg-white dark:bg-slate-955 border border-slate-205 dark:border-slate-850 rounded-xl p-4 shadow-sm flex flex-col space-y-3"
                        >
                            <!-- Header: ID & Status -->
                            <div class="flex items-center justify-between text-xs border-b border-slate-100 dark:border-slate-900 pb-2">
                                <span class="font-mono font-bold text-slate-850 dark:text-slate-200">{{ txn.transaction_number }}</span>
                                <span 
                                    :class="[
                                        'px-2 py-0.5 rounded-full text-[9px] font-black uppercase tracking-wider',
                                        txn.status === 'success' ? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-450' : 'bg-rose-500/10 text-rose-600 dark:text-rose-455'
                                    ]"
                                >
                                    {{ txn.status === 'success' ? 'Sukses' : 'Void' }}
                                </span>
                            </div>

                            <!-- Details -->
                            <div class="grid grid-cols-2 gap-y-2 text-[10px] text-slate-500 dark:text-slate-400 font-bold">
                                <div>Antrean: <span class="text-slate-800 dark:text-slate-200">{{ txn.queue_number }}</span></div>
                                <div>Waktu: <span class="text-slate-800 dark:text-slate-200">{{ txn.created_at }}</span></div>
                                <div>Order: <span class="uppercase text-slate-800 dark:text-slate-200">{{ txn.order_type.replace('_', ' ') }}</span></div>
                                <div>Metode: <span class="uppercase text-[#8c5a3c] font-black">{{ txn.payment_method }}</span></div>
                                <div v-if="txn.table" class="col-span-2">Meja: <span class="text-slate-800 dark:text-slate-200 font-extrabold">{{ txn.table.number }}</span></div>
                                <div v-if="txn.customer" class="col-span-2">Customer: <span class="text-slate-800 dark:text-slate-200 font-extrabold">{{ txn.customer.name }}</span></div>
                            </div>

                            <!-- Items List Summary -->
                            <div class="text-[10px] text-slate-450 dark:text-slate-500 bg-slate-50 dark:bg-slate-900/30 p-2.5 rounded-lg border border-slate-100 dark:border-slate-900 space-y-1.5">
                                <div v-for="item in txn.items" :key="item.id" class="flex justify-between items-start leading-tight">
                                    <div class="max-w-[200px]">
                                        <span class="font-bold text-slate-700 dark:text-slate-350">{{ item.qty }}x {{ item.product?.name }}</span>
                                        <span v-if="item.variant" class="text-[8px] text-[#8c5a3c] uppercase block">[{{ item.variant }}]</span>
                                    </div>
                                    <span class="font-bold text-slate-800 dark:text-slate-300">Rp {{ item.subtotal.toLocaleString('id-ID') }}</span>
                                </div>
                            </div>

                            <!-- Total -->
                            <div class="flex justify-between items-center border-t border-slate-100 dark:border-slate-900 pt-2 text-xs">
                                <span class="font-bold text-slate-400">Total Tagihan</span>
                                <span class="text-sm font-extrabold text-[#8c5a3c]">Rp {{ txn.total_amount.toLocaleString('id-ID') }}</span>
                            </div>

                            <!-- Action buttons -->
                            <div class="flex gap-2 pt-1.5">
                                <button 
                                    @click="showReceiptFromHistory(txn)" 
                                    class="flex-1 py-2 bg-slate-100 dark:bg-slate-900 hover:bg-[#8c5a3c]/15 text-slate-700 dark:text-slate-300 hover:text-[#8c5a3c] border border-slate-200/50 dark:border-slate-800 rounded-xl text-[10px] font-bold flex items-center justify-center gap-1.5 transition-colors cursor-pointer"
                                >
                                    <Printer class="h-3.5 w-3.5" />
                                    <span>Detail Struk</span>
                                </button>
                                <button 
                                    v-if="txn.status !== 'cancelled'"
                                    @click="confirmVoid(txn)"
                                    class="py-2 px-4 bg-rose-500/10 hover:bg-rose-600 text-rose-600 hover:text-white border border-rose-500/20 rounded-xl text-[10px] font-bold flex items-center justify-center gap-1.5 transition-all cursor-pointer"
                                >
                                    <span>Void</span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Floating Menu View Cart Indicator (UX masterclass) -->
            <div v-if="activeMobileTab === 'menu' && cart.length > 0" class="lg:hidden fixed bottom-18 left-4 right-4 z-40 animate-bounce">
                <button 
                    @click="activeMobileTab = 'cart'" 
                    class="w-full bg-[#8c5a3c] hover:bg-[#734a31] text-white py-3 px-4 rounded-xl shadow-lg flex items-center justify-between text-xs font-bold shadow-[#8c5a3c]/30 border border-[#8c5a3c]/20 transition-all"
                >
                    <div class="flex items-center gap-2">
                        <ShoppingCart class="h-4.5 w-4.5" />
                        <span class="bg-white/20 px-1.5 py-0.5 rounded-full text-[9px] font-extrabold">{{ cart.reduce((sum, item) => sum + item.qty, 0) }} Menu</span>
                    </div>
                    <span class="flex items-center gap-1">
                        <span>Bayar</span>
                        <ChevronRight class="h-4 w-4" />
                        <span class="text-sm font-black">Rp {{ grandTotal.toLocaleString('id-ID') }}</span>
                    </span>
                </button>
            </div>

            <!-- Mobile Bottom Bar Navigation -->
            <div class="lg:hidden fixed bottom-0 left-0 right-0 z-40 bg-white dark:bg-slate-950 border-t border-slate-200 dark:border-slate-850 flex items-center justify-around py-2 shadow-lg select-none">
                <button 
                    @click="activeMobileTab = 'menu'"
                    :class="[
                        'flex flex-col items-center gap-1 py-1 px-4 rounded-xl transition-all cursor-pointer active:scale-95',
                        activeMobileTab === 'menu' ? 'text-[#8c5a3c]' : 'text-slate-400 dark:text-slate-500'
                    ]"
                >
                    <Coffee class="h-5 w-5" />
                    <span class="text-[9px] font-extrabold">Pilih Menu</span>
                </button>
                
                <button 
                    @click="activeMobileTab = 'cart'"
                    :class="[
                        'flex flex-col items-center gap-1 py-1 px-4 rounded-xl transition-all cursor-pointer relative active:scale-95',
                        activeMobileTab === 'cart' ? 'text-[#8c5a3c]' : 'text-slate-400 dark:text-slate-500'
                    ]"
                >
                    <ShoppingCart class="h-5 w-5" />
                    <span class="text-[9px] font-extrabold">Keranjang</span>
                    <!-- Cart Count Badge -->
                    <span 
                        v-if="cart.length > 0" 
                        class="absolute -top-0.5 right-3.5 flex h-4.5 w-4.5 items-center justify-center rounded-full bg-rose-600 text-[8px] font-black text-white ring-2 ring-white dark:ring-slate-955 shadow-sm"
                    >
                        {{ cart.reduce((sum, item) => sum + item.qty, 0) }}
                    </span>
                </button>
                
                <button 
                    @click="activeMobileTab = 'history'"
                    :class="[
                        'flex flex-col items-center gap-1 py-1 px-4 rounded-xl transition-all cursor-pointer active:scale-95',
                        activeMobileTab === 'history' ? 'text-[#8c5a3c]' : 'text-slate-400 dark:text-slate-500'
                    ]"
                >
                    <History class="h-5 w-5" />
                    <span class="text-[9px] font-extrabold">Riwayat</span>
                </button>
            </div>
        </main>

        <!-- Receipt printing Modal -->
        <div v-if="isReceiptModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/65 backdrop-blur-sm">
            <div id="receipt-print-modal" class="w-full max-w-sm bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl p-6 animate-in zoom-in-95 duration-200 space-y-6 text-slate-900 dark:text-slate-100">
                <div class="text-center space-y-1">
                    <h2 class="text-xl font-bold tracking-wider uppercase text-slate-900 dark:text-slate-100">{{ $page.props.settings.site_name }}</h2>
                    <p class="text-xs font-medium text-slate-500 dark:text-slate-400">{{ receiptData?.outlet_name }}</p>
                    <p class="text-[10px] text-slate-400 dark:text-slate-500">{{ receiptData?.date }}</p>
                </div>

                <div class="border-t border-b border-dashed border-slate-200 dark:border-slate-700 py-3 text-xs space-y-1.5 font-mono text-slate-800 dark:text-slate-200">
                    <div class="flex justify-between">
                        <span>No Transaksi:</span>
                        <span>{{ receiptData?.transaction_number }}</span>
                    </div>
                    <div class="flex justify-between">
                        <span>Kasir:</span>
                        <span>{{ receiptData?.cashier_name }}</span>
                    </div>
                    <div class="flex justify-between" v-if="receiptData?.table_number">
                        <span>Nomor Meja:</span>
                        <span class="font-bold">Meja {{ receiptData?.table_number }}</span>
                    </div>
                    <div class="flex justify-between uppercase">
                        <span>Metode Bayar:</span>
                        <span>{{ receiptData?.payment_method }}</span>
                    </div>
                </div>

                <!-- Items -->
                <div class="space-y-2.5 font-mono text-xs">
                    <div v-for="(item, idx) in receiptData?.items" :key="idx" class="flex justify-between items-start">
                        <div class="max-w-[200px]">
                            <p class="font-semibold">{{ item.product.name }}</p>
                            <span v-if="item.variant" class="text-[10px] text-slate-400 uppercase">[{{ item.variant }}]</span>
                            <!-- Modifiers print details -->
                            <div v-if="item.selectedModifiers && item.selectedModifiers.length > 0" class="pl-2 space-y-0.5">
                                <span v-for="mId in item.selectedModifiers" :key="mId" class="text-[9px] text-slate-500 block">
                                    + {{ modifiers.find(m => m.id === mId)?.name }}
                                </span>
                            </div>
                            <span v-if="item.notes" class="text-[10px] text-slate-400 block italic">* {{ item.notes }}</span>
                        </div>
                        <span class="flex-shrink-0">{{ item.qty }} x Rp{{ Number(item.product.price).toLocaleString('id-ID') }}</span>
                    </div>
                </div>

                <!-- Totals -->
                <div class="border-t border-dashed border-slate-200 dark:border-slate-700 pt-3 space-y-1.5 font-mono text-xs text-slate-800 dark:text-slate-200">
                    <div class="flex justify-between">
                        <span>Subtotal</span>
                        <span>Rp {{ Number(receiptData?.subtotal).toLocaleString('id-ID') }}</span>
                    </div>
                    <div class="flex justify-between" v-if="receiptData?.service > 0">
                        <span>Biaya Layanan</span>
                        <span>Rp {{ Number(receiptData?.service).toLocaleString('id-ID') }}</span>
                    </div>
                    <div class="flex justify-between" v-if="receiptData?.tax > 0">
                        <span>Pajak Restoran</span>
                        <span>Rp {{ Number(receiptData?.tax).toLocaleString('id-ID') }}</span>
                    </div>
                    <div class="flex justify-between text-sm font-bold pt-1.5 border-t border-slate-200 dark:border-slate-800">
                        <span>Total Tagihan</span>
                        <span>Rp {{ Number(receiptData?.total).toLocaleString('id-ID') }}</span>
                    </div>
                    <div class="flex justify-between pt-1 text-slate-600 dark:text-slate-350">
                        <span>Bayar</span>
                        <span>Rp {{ Number(receiptData?.cash_received).toLocaleString('id-ID') }}</span>
                    </div>
                    <div class="flex justify-between text-emerald-600 dark:text-emerald-400 font-bold" v-if="receiptData?.payment_method === 'cash'">
                        <span>Kembalian</span>
                        <span>Rp {{ Number(receiptData?.change).toLocaleString('id-ID') }}</span>
                    </div>
                </div>

                <!-- Action buttons -->
                <div class="flex flex-col gap-2 pt-4 border-t border-slate-200 dark:border-slate-800 print:hidden">
                    <div class="flex gap-2">
                        <button
                            v-if="receiptData"
                            @click="handleManualPrint(receiptData.id, 'pos', receiptData.cash_received, receiptData.change)"
                            :disabled="isPrinting"
                            class="flex-1 py-2 border border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-900 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg text-xs font-semibold text-slate-700 dark:text-slate-300 transition-all flex items-center justify-center gap-1.5 cursor-pointer text-center"
                        >
                            <Printer class="h-3.5 w-3.5" />
                            Struk Kasir
                        </button>
                        <button
                            v-if="receiptData"
                            @click="handleManualPrint(receiptData.id, 'kitchen')"
                            :disabled="isPrinting"
                            class="flex-1 py-2 border border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-900 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg text-xs font-semibold text-[#8c5a3c] transition-all flex items-center justify-center gap-1.5 cursor-pointer text-center"
                        >
                            <FileText class="h-3.5 w-3.5" />
                            Tiket Dapur
                        </button>
                    </div>
                    <button
                        @click="isReceiptModalOpen = false; receiptData = null;"
                        class="w-full py-2 bg-[#8c5a3c] hover:bg-[#734a31] text-white rounded-lg text-xs font-semibold shadow-sm focus:outline-none transition-all cursor-pointer text-center"
                    >
                        Selesai
                    </button>
                </div>
            </div>
        </div>

        <!-- Split Bill Modal -->
        <div v-if="isSplitModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/65 backdrop-blur-sm animate-in fade-in duration-150">
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl w-full max-w-lg overflow-hidden flex flex-col transform transition-all max-h-[90vh]">
                <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between">
                    <h3 class="text-sm font-extrabold text-slate-900 dark:text-slate-100 flex items-center gap-2">
                        <Split class="h-4 w-4 text-[#8c5a3c]" />
                        <span>Split Bill (Pisah Pembayaran)</span>
                    </h3>
                    <button @click="isSplitModalOpen = false" class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-900 rounded-lg text-slate-400 cursor-pointer">
                        <X class="h-4 w-4" />
                    </button>
                </div>

                <!-- Split items assignment table -->
                <div class="flex-1 overflow-y-auto p-6 space-y-4">
                    <p class="text-xs text-slate-400">Tentukan jumlah qty item yang ingin dibayar pada tagihan pertama (Split Bill). Sisa item akan tetap berada di keranjang untuk pembayaran berikutnya.</p>
                    
                    <div class="border border-slate-200 dark:border-slate-800 rounded-xl overflow-hidden">
                        <table class="w-full text-left border-collapse bg-white dark:bg-slate-950">
                            <thead>
                                <tr class="bg-slate-50 dark:bg-slate-900 text-[10px] font-bold text-slate-400 dark:text-slate-500 border-b border-slate-200 dark:border-slate-800">
                                    <th class="p-3">Nama Menu</th>
                                    <th class="p-3 text-center">Keranjang Qty</th>
                                    <th class="p-3 text-center" style="width: 130px;">Split Qty</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                                <tr v-for="(split, index) in splitItems" :key="index" class="text-xs font-semibold hover:bg-slate-50 dark:hover:bg-slate-900/50 transition-colors">
                                    <td class="p-3">
                                        <span class="text-slate-800 dark:text-slate-200 block">{{ cart[split.itemIndex].product.name }}</span>
                                        <span v-if="cart[split.itemIndex].variant" class="text-[9px] text-[#8c5a3c] font-black uppercase">{{ cart[split.itemIndex].variant }}</span>
                                    </td>
                                    <td class="p-3 text-center font-bold text-slate-700 dark:text-slate-300">
                                        {{ cart[split.itemIndex].qty }}
                                    </td>
                                    <td class="p-3">
                                        <div class="flex items-center justify-center gap-2">
                                            <button
                                                type="button"
                                                @click="split.qty = Math.max(0, split.qty - 1)"
                                                class="h-6 w-6 rounded bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 flex items-center justify-center cursor-pointer transition-colors"
                                            >
                                                -
                                            </button>
                                            <span class="w-6 text-center font-extrabold text-slate-900 dark:text-slate-100">{{ split.qty }}</span>
                                            <button
                                                type="button"
                                                @click="split.qty = Math.min(cart[split.itemIndex].qty, split.qty + 1)"
                                                class="h-6 w-6 rounded bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 flex items-center justify-center cursor-pointer transition-colors"
                                            >
                                                +
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Modal Actions Footer -->
                <div class="px-6 py-4 border-t border-slate-200 dark:border-slate-800 flex items-center justify-end gap-3 bg-slate-50/50 dark:bg-slate-900/10">
                    <button
                        type="button"
                        @click="isSplitModalOpen = false"
                        class="px-4 py-2 border border-slate-200 dark:border-slate-800 text-slate-700 dark:text-slate-350 text-xs font-bold rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 cursor-pointer"
                    >
                        Batal
                    </button>
                    <button
                        type="button"
                        @click="handleSplitCheckout"
                        :disabled="isCheckingOut || !splitItems.some(s => s.qty > 0)"
                        class="px-4 py-2 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-xl cursor-pointer disabled:opacity-50"
                    >
                        Bayar Bagian Ini
                    </button>
                </div>
            </div>
        </div>

        <!-- Printer Settings Modal -->
        <div v-if="isPrinterSettingsOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/65 backdrop-blur-sm animate-in fade-in duration-150">
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl w-full max-w-md overflow-hidden flex flex-col transform transition-all">
                <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between">
                    <h3 class="text-sm font-extrabold text-slate-900 dark:text-slate-100 flex items-center gap-2">
                        <Settings class="h-4 w-4 text-[#8c5a3c]" />
                        <span>Pengaturan Printer POS</span>
                    </h3>
                    <button @click="isPrinterSettingsOpen = false" class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-900 rounded-lg text-slate-400 cursor-pointer">
                        <X class="h-4 w-4" />
                    </button>
                </div>

                <div class="p-6 space-y-4 max-h-[70vh] overflow-y-auto font-sans">
                    <!-- Metode Cetak Selection -->
                    <div class="space-y-1.5">
                        <label class="block text-xs font-bold text-slate-650 dark:text-slate-350">Metode Pencetakan</label>
                        <select
                            v-model="printSettings.method"
                            class="w-full px-3 py-2 text-xs border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-850 dark:text-slate-150"
                        >
                            <option value="browser">Browser Print (Buka Tab Baru)</option>
                            <option value="qz">QZ Tray (Cetak Otomatis / Silent)</option>
                        </select>
                    </div>

                    <!-- QZ Tray Connection Status -->
                    <div v-if="printSettings.method === 'qz'" class="p-3 bg-slate-50 dark:bg-slate-900/30 border border-slate-200 dark:border-slate-800 rounded-xl space-y-3">
                        <div class="flex items-center justify-between">
                            <span class="text-[10px] font-bold uppercase tracking-wider text-slate-400">Status QZ Tray</span>
                            <span 
                                :class="[
                                    'inline-flex px-2 py-0.5 rounded-full text-[9px] font-bold uppercase',
                                    qzConnectionStatus === 'connected' ? 'bg-emerald-50 dark:bg-emerald-95/30 text-emerald-700' : 'bg-rose-50 dark:bg-rose-95/30 text-rose-700'
                                ]"
                            >
                                {{ qzConnectionStatus === 'connected' ? 'Terhubung' : 'Terputus' }}
                            </span>
                        </div>

                        <button
                            type="button"
                            @click="checkQzConnection"
                            :disabled="isConnectingQZ"
                            class="w-full py-1.5 border border-slate-200 dark:border-slate-800 hover:bg-slate-100 dark:hover:bg-slate-900 text-slate-700 dark:text-slate-300 text-xs font-bold rounded-lg transition-colors cursor-pointer flex items-center justify-center gap-1.5 disabled:opacity-50"
                        >
                            <RefreshCw class="h-3 w-3" :class="{'animate-spin': isConnectingQZ}" />
                            <span>Hubungkan Ulang / Cek Koneksi</span>
                        </button>
                    </div>

                    <!-- Printer Choices -->
                    <div v-if="printSettings.method === 'qz'" class="space-y-3">
                        <!-- POS Printer Selection -->
                        <div class="space-y-1.5">
                            <label class="block text-xs font-bold text-slate-650 dark:text-slate-350">Printer Kasir (Struk)</label>
                            <select
                                v-if="availablePrinters.length > 0"
                                v-model="printSettings.posPrinter"
                                class="w-full px-3 py-2 text-xs border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-850 dark:text-slate-150"
                            >
                                <option value="">-- Pilih Printer Kasir --</option>
                                <option v-for="printer in availablePrinters" :key="printer" :value="printer">{{ printer }}</option>
                            </select>
                            <input
                                v-else
                                v-model="printSettings.posPrinter"
                                type="text"
                                placeholder="Masukkan nama printer (e.g. POS-58)"
                                class="w-full px-3 py-2 text-xs border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-850 dark:text-slate-150"
                            />
                        </div>

                        <!-- Kitchen Printer Selection -->
                        <div class="space-y-1.5">
                            <label class="block text-xs font-bold text-slate-650 dark:text-slate-350">Printer Dapur (Tiket)</label>
                            <select
                                v-if="availablePrinters.length > 0"
                                v-model="printSettings.kitchenPrinter"
                                class="w-full px-3 py-2 text-xs border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-850 dark:text-slate-150"
                            >
                                <option value="">-- Pilih Printer Dapur --</option>
                                <option v-for="printer in availablePrinters" :key="printer" :value="printer">{{ printer }}</option>
                            </select>
                            <input
                                v-else
                                v-model="printSettings.kitchenPrinter"
                                type="text"
                                placeholder="Masukkan nama printer (e.g. Kitchen-Printer)"
                                class="w-full px-3 py-2 text-xs border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-850 dark:text-slate-150"
                            />
                        </div>

                        <!-- Auto Print Options -->
                        <div class="pt-2 space-y-2.5">
                            <div class="flex items-center justify-between">
                                <span class="text-xs font-semibold text-slate-700 dark:text-slate-300">Auto-Print Struk Kasir</span>
                                <input
                                    v-model="printSettings.autoPrintPos"
                                    type="checkbox"
                                    class="h-4 w-4 rounded border-slate-300 text-[#8c5a3c] focus:ring-[#8c5a3c] cursor-pointer"
                                />
                            </div>
                        </div>

                        <!-- Zoom Scale -->
                        <div class="pt-1 space-y-1.5">
                            <label class="block text-xs font-bold text-slate-650 dark:text-slate-350">
                                Zoom Scale Cetak (%)
                            </label>
                            <div class="flex items-center gap-3">
                                <input
                                    v-model.number="printSettings.zoomScale"
                                    type="range"
                                    min="40"
                                    max="120"
                                    step="5"
                                    class="flex-1 h-1.5 accent-[#8c5a3c] cursor-pointer"
                                />
                                <span class="text-xs font-bold text-[#8c5a3c] w-10 text-right">{{ printSettings.zoomScale }}%</span>
                            </div>
                            <p class="text-[10px] text-slate-400 dark:text-slate-500">Default: 100%. Turunkan jika hasil cetak terpotong di sisi kanan.</p>
                        </div>
                    </div>
                </div>

                <div class="px-6 py-4 border-t border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-900/30 flex items-center justify-end gap-3">
                    <button
                        type="button"
                        @click="isPrinterSettingsOpen = false"
                        class="px-4 py-2 border border-slate-200 dark:border-slate-800 text-slate-700 dark:text-slate-300 text-xs font-bold rounded-xl hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors cursor-pointer"
                    >
                        Batal
                    </button>
                    <button
                        type="button"
                        @click="saveSettings"
                        class="px-4 py-2 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-xl cursor-pointer"
                    >
                        Simpan Pengaturan
                    </button>
                </div>
            </div>
        </div>

        <!-- Silent Printing Loading Overlay -->
        <Transition
            enter-active-class="transition ease-out duration-300"
            enter-from-class="opacity-0 scale-95"
            enter-to-class="opacity-100 scale-100"
            leave-active-class="transition ease-in duration-200"
            leave-from-class="opacity-100 scale-100"
            leave-to-class="opacity-0 scale-95"
        >
            <div 
                v-if="isPrinting" 
                class="fixed inset-0 z-[200] flex items-center justify-center p-4 bg-slate-950/65 backdrop-blur-md"
            >
                <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl p-6 w-full max-w-sm text-center space-y-4 transform transition-all">
                    <!-- Rotating Premium Spinner -->
                    <div class="relative w-16 h-16 mx-auto flex items-center justify-center">
                        <div class="absolute inset-0 rounded-full border-4 border-slate-100 dark:border-slate-900"></div>
                        <div class="absolute inset-0 rounded-full border-4 border-t-[#8c5a3c] dark:border-t-[#8c5a3c] animate-spin"></div>
                        <Printer class="h-6 w-6 text-[#8c5a3c]" />
                    </div>
                    
                    <div class="space-y-1">
                        <h3 class="text-sm font-bold text-slate-900 dark:text-slate-100">
                            Sedang Mencetak Struk
                        </h3>
                        <p class="text-xs text-slate-500 dark:text-slate-400 animate-pulse font-medium">
                            {{ printStatus || 'Menghubungkan ke printer...' }}
                        </p>
                    </div>
                </div>
            </div>
        </Transition>
        <!-- Shadcn UI Confirm QR Payment Modal -->
        <div v-if="isConfirmQrModalOpen && activeConfirmQrOrder" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/70 backdrop-blur-sm animate-in fade-in duration-200">
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-3xl shadow-2xl w-full max-w-md overflow-hidden flex flex-col transform transition-all animate-in zoom-in-95 duration-200">
                <!-- Header -->
                <div class="px-6 py-5 border-b border-slate-100 dark:border-slate-800 flex items-start justify-between bg-slate-50/50 dark:bg-slate-900/30">
                    <div class="flex items-center gap-3">
                        <div class="h-10 w-10 bg-emerald-500/10 rounded-2xl flex items-center justify-center text-emerald-600 shrink-0">
                            <CheckCircle2 class="h-5 w-5" />
                        </div>
                        <div>
                            <h3 class="text-sm font-black text-slate-900 dark:text-slate-100 uppercase tracking-wider">
                                Konfirmasi Pembayaran
                            </h3>
                            <p class="text-xs text-slate-400 font-medium mt-0.5">
                                Pelunasan transaksi Self-Order QR
                            </p>
                        </div>
                    </div>
                    <button 
                        @click="isConfirmQrModalOpen = false; activeConfirmQrOrder = null;" 
                        class="p-1.5 hover:bg-slate-200 dark:hover:bg-slate-800 rounded-xl text-slate-400 cursor-pointer transition-colors"
                    >
                        <X class="h-4 w-4" />
                    </button>
                </div>

                <!-- Body / Order Breakdown -->
                <div class="p-6 space-y-4">
                    <!-- Order Meta Card -->
                    <div class="bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3">
                        <div class="flex items-center justify-between">
                            <span class="px-2.5 py-1 bg-[#8c5a3c] text-white text-xs font-black rounded-xl shadow-sm">
                                MEJA {{ activeConfirmQrOrder.table_number }}
                            </span>
                            <span class="px-2.5 py-0.5 bg-amber-100 dark:bg-amber-950/50 text-amber-800 dark:text-amber-300 text-[10px] font-black rounded-full uppercase">
                                {{ activeConfirmQrOrder.payment_method === 'qris' ? 'QRIS Manual' : 'Bayar Kasir' }}
                            </span>
                        </div>

                        <div class="space-y-1 text-xs">
                            <div class="flex justify-between">
                                <span class="text-slate-400">Pemesan:</span>
                                <span class="font-bold text-slate-900 dark:text-slate-100">{{ activeConfirmQrOrder.customer_name }}</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-slate-400">Waktu Order:</span>
                                <span class="font-mono text-slate-600 dark:text-slate-400">{{ activeConfirmQrOrder.created_at }}</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-slate-400">No. Transaksi:</span>
                                <span class="font-mono text-slate-600 dark:text-slate-400 text-[10px]">{{ activeConfirmQrOrder.transaction_number }}</span>
                            </div>
                        </div>
                    </div>

                    <!-- Items List -->
                    <div class="space-y-2">
                        <p class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Rincian Item Pesanan</p>
                        <div class="max-h-36 overflow-y-auto divide-y divide-slate-100 dark:divide-slate-800 border border-slate-100 dark:border-slate-800 rounded-xl px-3 bg-white dark:bg-slate-950">
                            <div v-for="(item, idx) in activeConfirmQrOrder.items" :key="idx" class="py-2 flex justify-between items-center text-xs">
                                <div>
                                    <span class="font-bold text-slate-800 dark:text-slate-200 block">{{ item.name }}</span>
                                    <span v-if="item.variant" class="text-[9px] text-[#8c5a3c] font-black uppercase block">[{{ item.variant }}]</span>
                                    <span v-if="item.modifiers && item.modifiers.length > 0" class="text-[9px] text-slate-400 italic block">
                                        + {{ item.modifiers.join(', ') }}
                                    </span>
                                </div>
                                <div class="text-right shrink-0 ml-3">
                                    <span class="font-mono font-bold text-slate-700 dark:text-slate-300">{{ item.qty }}x</span>
                                    <span class="font-mono text-slate-500 block text-[10px]">Rp {{ item.subtotal.toLocaleString('id-ID') }}</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Total Amount Banner -->
                    <div class="flex justify-between items-center bg-emerald-50 dark:bg-emerald-950/30 border border-emerald-200 dark:border-emerald-900/50 rounded-2xl p-4">
                        <div>
                            <span class="text-[10px] font-black text-emerald-700 dark:text-emerald-400 uppercase tracking-wider block">Total Pembayaran</span>
                            <span class="text-xs text-slate-500">Status akan menjadi LUNAS</span>
                        </div>
                        <span class="text-lg font-black text-emerald-700 dark:text-emerald-300 font-mono">
                            Rp {{ activeConfirmQrOrder.total_amount.toLocaleString('id-ID') }}
                        </span>
                    </div>
                </div>

                <!-- Footer Actions -->
                <div class="px-6 py-4 border-t border-slate-100 dark:border-slate-800 flex items-center justify-end gap-3 bg-slate-50/50 dark:bg-slate-900/10">
                    <button
                        type="button"
                        @click="isConfirmQrModalOpen = false; activeConfirmQrOrder = null;"
                        class="px-4 py-2.5 border border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800 text-xs font-bold rounded-xl transition-all cursor-pointer"
                    >
                        Batal
                    </button>
                    <button
                        type="button"
                        @click="executeConfirmQrPayment"
                        :disabled="isConfirmingPayment"
                        class="px-5 py-2.5 bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white text-xs font-extrabold rounded-xl transition-all shadow-md shadow-emerald-600/20 flex items-center gap-2 cursor-pointer active:scale-95"
                    >
                        <Check class="h-4 w-4" />
                        <span>{{ isConfirmingPayment ? 'Memproses...' : 'Konfirmasi & Lunaskan' }}</span>
                    </button>
                </div>
            </div>
        </div>

        <!-- Self-Order QR Pending List Modal -->
        <div v-if="isPendingQrListModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/70 backdrop-blur-sm animate-in fade-in duration-200">
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-3xl shadow-2xl w-full max-w-3xl overflow-hidden flex flex-col max-h-[85vh] transform transition-all animate-in zoom-in-95 duration-200">
                <!-- Modal Header -->
                <div class="px-6 py-4 border-b border-slate-100 dark:border-slate-800 flex items-center justify-between bg-slate-50/50 dark:bg-slate-900/30">
                    <div class="flex items-center gap-3">
                        <div class="h-10 w-10 bg-amber-500/10 rounded-2xl flex items-center justify-center text-amber-600 shrink-0 relative">
                            <Receipt class="h-5 w-5" />
                            <span v-if="pendingQrOrders && pendingQrOrders.length > 0" class="absolute -top-1 -right-1 flex h-3 w-3">
                                <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-rose-400 opacity-75"></span>
                                <span class="relative inline-flex rounded-full h-3 w-3 bg-rose-500"></span>
                            </span>
                        </div>
                        <div>
                            <h3 class="text-sm font-black text-slate-900 dark:text-slate-100 uppercase tracking-wider flex items-center gap-2">
                                <span>Pesanan Self-Order QR Pending</span>
                                <span v-if="pendingQrOrders" class="px-2 py-0.5 bg-rose-600 text-white rounded-full text-[10px] font-black">
                                    {{ pendingQrOrders.length }}
                                </span>
                            </h3>
                            <p class="text-xs text-slate-400 font-medium">
                                Daftar transaksi dari HP pelanggan yang menunggu konfirmasi bayar di kasir.
                            </p>
                        </div>
                    </div>
                    <button 
                        @click="isPendingQrListModalOpen = false" 
                        class="p-2 hover:bg-slate-200 dark:hover:bg-slate-800 rounded-xl text-slate-400 cursor-pointer transition-colors"
                    >
                        <X class="h-5 w-5" />
                    </button>
                </div>

                <!-- Modal Body: Grid of Pending Orders -->
                <div class="p-6 overflow-y-auto flex-1">
                    <div v-if="!pendingQrOrders || pendingQrOrders.length === 0" class="text-center py-16 space-y-3">
                        <div class="h-16 w-16 bg-slate-100 dark:bg-slate-900 rounded-full flex items-center justify-center mx-auto text-slate-400">
                            <CheckCircle2 class="h-8 w-8 text-emerald-500" />
                        </div>
                        <h4 class="text-sm font-bold text-slate-800 dark:text-slate-200">Tidak Ada Pesanan Pending</h4>
                        <p class="text-xs text-slate-400 max-w-sm mx-auto">
                            Semua pesanan Self-Order HP telah dikonfirmasi lunas atau belum ada pelanggan baru yang memesan.
                        </p>
                    </div>

                    <div v-else class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div 
                            v-for="order in pendingQrOrders" 
                            :key="order.id"
                            class="bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 flex flex-col justify-between space-y-3 hover:border-amber-500 dark:hover:border-amber-600 transition-all shadow-sm"
                        >
                            <div class="flex justify-between items-start">
                                <div>
                                    <div class="flex items-center gap-1.5">
                                        <span class="px-2.5 py-0.5 bg-[#8c5a3c] text-white text-[10px] font-black rounded-lg shadow-sm">
                                            MEJA {{ order.table_number }}
                                        </span>
                                        <span class="text-[10px] font-mono text-slate-400 font-semibold">{{ order.created_at }}</span>
                                    </div>
                                    <p class="text-xs font-black text-slate-900 dark:text-slate-100 truncate mt-1">
                                        {{ order.customer_name }}
                                    </p>
                                    <p class="text-[9.5px] font-mono text-slate-400">{{ order.transaction_number }}</p>
                                </div>
                                <span class="px-2 py-0.5 bg-amber-100 text-amber-800 dark:bg-amber-950/60 dark:text-amber-300 rounded-md text-[9px] font-black uppercase border border-amber-200 dark:border-amber-800">
                                    {{ order.payment_method === 'qris' ? 'QRIS Manual' : 'Bayar Kasir' }}
                                </span>
                            </div>

                            <!-- Items List -->
                            <div class="text-xs space-y-1 bg-white dark:bg-slate-950 p-2.5 rounded-xl border border-slate-200/60 dark:border-slate-800 max-h-24 overflow-y-auto">
                                <div v-for="(it, idx) in order.items" :key="idx" class="flex justify-between items-center">
                                    <span class="font-semibold text-slate-800 dark:text-slate-200 truncate">
                                        {{ it.qty }}x {{ it.name }} <span v-if="it.variant" class="text-[#8c5a3c] uppercase">[{{ it.variant }}]</span>
                                    </span>
                                    <span class="font-mono text-slate-500 text-[10px]">Rp {{ it.subtotal.toLocaleString('id-ID') }}</span>
                                </div>
                            </div>

                            <!-- Footer Action -->
                            <div class="pt-2 border-t border-slate-200/60 dark:border-slate-800 flex justify-between items-center">
                                <div>
                                    <span class="text-[9px] text-slate-400 block uppercase font-bold">Total Tagihan</span>
                                    <span class="text-sm font-black text-slate-900 dark:text-slate-100 font-mono">Rp {{ order.total_amount.toLocaleString('id-ID') }}</span>
                                </div>

                                <button
                                    @click="isPendingQrListModalOpen = false; openConfirmQrModal(order);"
                                    class="px-4 py-2 bg-emerald-600 hover:bg-emerald-500 text-white rounded-xl text-xs font-extrabold shadow-md transition-all cursor-pointer flex items-center gap-1.5 active:scale-95"
                                >
                                    <Check class="h-4 w-4" />
                                    <span>Konfirmasi Bayar</span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Modal Footer -->
                <div class="px-6 py-4 border-t border-slate-100 dark:border-slate-800 flex items-center justify-end bg-slate-50/50 dark:bg-slate-900/30">
                    <button
                        type="button"
                        @click="isPendingQrListModalOpen = false"
                        class="px-4 py-2 border border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800 text-xs font-bold rounded-xl transition-all cursor-pointer"
                    >
                        Tutup
                    </button>
                </div>
            </div>
        </div>

        <!-- Kitchen Print Prompt Modal -->
        <div v-if="isKitchenPrintPromptOpen" class="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-slate-950/60 backdrop-blur-sm animate-in fade-in duration-200">
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl w-full max-w-xs p-6 space-y-5 animate-in zoom-in-95 duration-200 text-center">
                <!-- Icon -->
                <div class="flex flex-col items-center gap-3">
                    <div class="h-14 w-14 rounded-2xl bg-orange-50 dark:bg-orange-950/20 flex items-center justify-center text-orange-500">
                        <Printer class="h-7 w-7" />
                    </div>
                    <div>
                        <h3 class="text-sm font-extrabold text-slate-900 dark:text-slate-100">Cetak Struk Dapur?</h3>
                        <p class="text-xs text-slate-500 dark:text-slate-400 mt-1">Struk pelanggan telah dicetak. Apakah Anda juga ingin mencetak tiket dapur untuk pesanan ini?</p>
                    </div>
                </div>

                <!-- Actions -->
                <div class="flex gap-2.5">
                    <button
                        type="button"
                        @click="skipKitchenPrint"
                        class="flex-1 py-2.5 border border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-900 text-xs font-bold rounded-xl transition-all cursor-pointer"
                    >
                        Tidak, Lewati
                    </button>
                    <button
                        type="button"
                        @click="confirmKitchenPrint"
                        class="flex-1 py-2.5 bg-orange-500 hover:bg-orange-400 text-white text-xs font-extrabold rounded-xl transition-all shadow-md shadow-orange-500/20 flex items-center justify-center gap-1.5 cursor-pointer active:scale-95"
                    >
                        <Printer class="h-3.5 w-3.5" />
                        <span>Ya, Cetak Dapur</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<style>
@media print {
    body * {
        visibility: hidden;
    }
    #receipt-print-modal, #receipt-print-modal * {
        visibility: visible;
    }
    #receipt-print-modal {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        max-width: 100%;
        border: none !important;
        box-shadow: none !important;
        padding: 0 !important;
        margin: 0 !important;
    }
}
</style>
