<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { Head, router, usePage } from '@inertiajs/vue3';
import { Search, ShoppingBag, Plus, Minus, X, Check, Heart, User, Sparkles, CreditCard, ChevronRight, CheckCircle2, Receipt, Clock } from 'lucide-vue-next';

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

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

interface CartItem {
    product: Product;
    qty: number;
    variant: 'hot' | 'ice' | null;
    selectedModifiers: Modifier[];
    notes: string;
}

interface TableOrderItemModifier {
    name: string;
    price: number;
}

interface TableOrderItem {
    id: number;
    name: string;
    qty: number;
    variant: string | null;
    price: number;
    subtotal: number;
    kitchen_status: string | null;
    modifiers: TableOrderItemModifier[];
}

interface TableOrder {
    id: number;
    transaction_number: string;
    customer_name: string;
    status: 'pending' | 'success' | 'cancelled';
    payment_method: string;
    total_amount: number;
    created_at: string;
    items: TableOrderItem[];
}

const props = defineProps<{
    outlet: {
        id: number;
        name: string;
    };
    table: {
        id: number;
        number: string;
    };
    products: Product[];
    ingredientStock: Record<number, number>;
    productStock: Record<number, number>;
    modifiers: Modifier[];
    taxPercentage: number;
    servicePercentage: number;
    tableOrders?: TableOrder[];
}>();

// Customer name state (required to order, persisted in localStorage)
const customerName = ref('');
const showNamePrompt = ref(true);
const showOrdersModal = ref(false);

onMounted(() => {
    try {
        const savedName = localStorage.getItem('cafepos_customer_name');
        if (savedName && savedName.trim()) {
            customerName.value = savedName.trim();
            showNamePrompt.value = false;
        }
    } catch (e) {}
});

const saveCustomerName = () => {
    if (customerName.value.trim()) {
        try {
            localStorage.setItem('cafepos_customer_name', customerName.value.trim());
        } catch (e) {}
        showNamePrompt.value = false;
    }
};

const myOrdersList = computed(() => {
    return props.tableOrders || [];
});

// Search & Filter
const searchQuery = ref('');
const selectedCategory = ref('All');

const categories = computed(() => {
    const list = new Set(props.products.map(p => p.category));
    return ['All', ...Array.from(list)];
});

// Stock checking logic
const getAvailableStock = (product: Product, variant: 'hot' | 'ice' | null = null): number => {
    if (!product.has_recipe) {
        return props.productStock[product.id] || 0;
    }
    // Recipe based stock check
    let minStock = 9999;
    const relevantRecipes = product.recipes.filter(r => r.variant === null || r.variant === variant);
    
    if (relevantRecipes.length === 0) return 0;

    for (const recipe of relevantRecipes) {
        const currentInv = props.ingredientStock[recipe.ingredient_id] || 0;
        const potential = currentInv / recipe.usage_qty;
        if (potential < minStock) {
            minStock = potential;
        }
    }
    return Math.floor(minStock);
};

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

// Cart states
const cart = ref<CartItem[]>([]);
const isCartOpen = ref(false);

// Active modification modal state
const activeProduct = ref<Product | null>(null);
const activeVariant = ref<'hot' | 'ice' | null>(null);
const activeModifiers = ref<Modifier[]>([]);
const activeNotes = ref('');

const openModifiersModal = (product: Product) => {
    activeProduct.value = product;
    // Default to 'ice' if category is Beverage/Coffee or has recipes with variant
    const hasIceVariant = product.recipes.some(r => r.variant === 'ice');
    activeVariant.value = hasIceVariant ? 'ice' : null;
    activeModifiers.value = [];
    activeNotes.value = '';
};

const toggleModifier = (mod: Modifier) => {
    const idx = activeModifiers.value.findIndex(m => m.id === mod.id);
    if (idx > -1) {
        activeModifiers.value.splice(idx, 1);
    } else {
        activeModifiers.value.push(mod);
    }
};

const addToCartFromModal = () => {
    if (!activeProduct.value) return;
    
    const existingIndex = cart.value.findIndex(item => {
        const sameProd = item.product.id === activeProduct.value!.id;
        const sameVariant = item.variant === activeVariant.value;
        const sameMods = item.selectedModifiers.length === activeModifiers.value.length && 
                          item.selectedModifiers.every(m => activeModifiers.value.some(am => am.id === m.id));
        return sameProd && sameVariant && sameMods;
    });

    if (existingIndex > -1) {
        cart.value[existingIndex].qty += 1;
    } else {
        cart.value.push({
            product: activeProduct.value,
            qty: 1,
            variant: activeVariant.value,
            selectedModifiers: [...activeModifiers.value],
            notes: activeNotes.value
        });
    }

    activeProduct.value = null;
};

// Quick Add directly if no options
const quickAdd = (product: Product) => {
    const needsOptions = product.recipes.some(r => r.variant !== null) || (product.modifiers && product.modifiers.length > 0);
    if (needsOptions) {
        openModifiersModal(product);
    } else {
        const existingIndex = cart.value.findIndex(item => item.product.id === product.id);
        if (existingIndex > -1) {
            cart.value[existingIndex].qty += 1;
        } else {
            cart.value.push({
                product,
                qty: 1,
                variant: null,
                selectedModifiers: [],
                notes: ''
            });
        }
    }
};

const updateCartQty = (idx: number, amount: number) => {
    cart.value[idx].qty += amount;
    if (cart.value[idx].qty <= 0) {
        cart.value.splice(idx, 1);
    }
};

// Summary computations
const subtotal = computed(() => {
    return cart.value.reduce((sum, item) => {
        const modSum = item.selectedModifiers.reduce((s, m) => s + m.price, 0);
        return sum + (item.product.price + modSum) * item.qty;
    }, 0);
});

const serviceCharge = computed(() => (subtotal.value * props.servicePercentage) / 100);
const taxAmount = computed(() => ((subtotal.value + serviceCharge.value) * props.taxPercentage) / 100);
const grandTotal = computed(() => subtotal.value + serviceCharge.value + taxAmount.value);

// Checkout
const paymentMethod = ref<'cashier' | 'qris'>('cashier');
const isCheckoutProcessing = ref(false);
const showQrisPaymentModal = ref(false);

// Device-specific transaction tracking to avoid customer name collision across phones
const getMyOrderTxnNumbers = (): string[] => {
    try {
        const stored = localStorage.getItem('cafepos_my_orders');
        return stored ? JSON.parse(stored) : [];
    } catch (e) {
        return [];
    }
};

const myOrderTxnNumbers = ref<string[]>(getMyOrderTxnNumbers());

const saveMyOrderTxnNumber = (txnNumber: string) => {
    if (!txnNumber) return;
    if (!myOrderTxnNumbers.value.includes(txnNumber)) {
        myOrderTxnNumbers.value.unshift(txnNumber);
        try {
            localStorage.setItem('cafepos_my_orders', JSON.stringify(myOrderTxnNumbers.value));
        } catch (e) {}
    }
};

// Filtered table orders belonging ONLY to this specific phone / customer session
const filteredMyOrders = computed(() => {
    if (!props.tableOrders) return [];
    
    // If phone has stored transaction numbers, filter by those numbers
    if (myOrderTxnNumbers.value.length > 0) {
        const matched = props.tableOrders.filter(order => myOrderTxnNumbers.value.includes(order.transaction_number));
        if (matched.length > 0) {
            return matched;
        }
    }
    
    // Fallback: match customer name if no stored txn numbers yet
    if (customerName.value.trim()) {
        return props.tableOrders.filter(order => 
            order.customer_name.trim().toLowerCase() === customerName.value.trim().toLowerCase()
        );
    }
    
    return props.tableOrders;
});

const activeQrisAmount = ref(0);

const checkout = () => {
    if (!customerName.value.trim()) {
        showNamePrompt.value = true;
        return;
    }

    submitOrder();
};

const submitOrder = () => {
    isCheckoutProcessing.value = true;
    activeQrisAmount.value = grandTotal.value;
    
    // Save customer name to localStorage
    if (customerName.value.trim()) {
        try {
            localStorage.setItem('cafepos_customer_name', customerName.value.trim());
        } catch (e) {}
    }
    
    router.post(route('pos.qr-checkout', { outlet: props.outlet.id, table: props.table.id }), {
        customer_name: customerName.value,
        payment_method: paymentMethod.value,
        items: cart.value.map(item => ({
            product_id: item.product.id,
            qty: item.qty,
            variant: item.variant,
            price: item.product.price,
            modifiers: item.selectedModifiers.map(m => m.id),
        }))
    }, {
        onSuccess: (page: any) => {
            cart.value = [];
            isCartOpen.value = false;
            isCheckoutProcessing.value = false;
            
            // Save newly created transaction number to this phone's localStorage
            const latestTxn = page.props?.flash?.latest_txn_number || (props.tableOrders && props.tableOrders[0] ? props.tableOrders[0].transaction_number : null);
            if (latestTxn) {
                saveMyOrderTxnNumber(latestTxn);
            }
            
            // Pop open orders modal & if QRIS, show QRIS modal for display
            showOrdersModal.value = true;
            if (paymentMethod.value === 'qris') {
                showQrisPaymentModal.value = true;
            }
        },
        onError: (err) => {
            isCheckoutProcessing.value = false;
            alert(Object.values(err).join('\n'));
        }
    });
};
</script>

<template>
    <Head title="Self-Order Menu" />

    <div class="min-h-screen bg-[#faf6f0] text-slate-800 font-sans pb-24">
        <!-- Banner/Header -->
        <header class="bg-gradient-to-b from-[#8c5a3c] via-[#7c4d32] to-[#6a3f27] text-white px-5 pt-6 pb-5 rounded-b-[2.5rem] shadow-xl relative overflow-hidden space-y-3.5">
            <div class="absolute -right-10 -top-10 h-36 w-36 bg-white/5 rounded-full blur-2xl pointer-events-none"></div>
            <div class="absolute -left-10 -bottom-10 h-36 w-36 bg-amber-500/10 rounded-full blur-2xl pointer-events-none"></div>

            <!-- Row 1: Outlet Name & Meja Badge -->
            <div class="flex justify-between items-center relative z-10">
                <span class="px-3 py-1 bg-white/15 backdrop-blur-md rounded-full text-[10px] font-black uppercase tracking-wider border border-white/15 text-amber-100 shadow-sm">
                    Outlet {{ outlet.name }}
                </span>
                
                <div class="bg-white text-[#8c5a3c] px-3.5 py-1.5 rounded-2xl flex items-center gap-1.5 shadow-md border border-white/20">
                    <span class="text-[9px] font-black uppercase tracking-wider text-slate-400">MEJA</span>
                    <span class="text-base font-black leading-none text-[#8c5a3c]">{{ table.number }}</span>
                </div>
            </div>

            <!-- Row 2: Greeting Header -->
            <div class="relative z-10 space-y-0.5">
                <h1 class="text-2xl font-black tracking-tight leading-none text-white">Selamat Datang!</h1>
                <p class="text-xs text-amber-100/90 font-medium">Pesan makanan & minuman langsung dari meja Anda.</p>
            </div>

            <!-- Row 3: Dedicated Action Bar for "Pesanan Saya" & User Badge -->
            <div class="relative z-10 pt-1 space-y-2">
                <!-- Pesanan Saya Button (Full Width Mobile Action Pill) -->
                <button 
                    @click="showOrdersModal = true"
                    class="w-full bg-amber-400 hover:bg-amber-300 text-[#4a2e1d] px-4 py-2.5 rounded-2xl flex items-center justify-between shadow-lg border border-amber-300 transition-all cursor-pointer active:scale-[0.98]"
                    title="Lihat Riwayat Pesanan Saya"
                >
                    <div class="flex items-center gap-2">
                        <Receipt class="h-4.5 w-4.5 text-[#5c3a26]" />
                        <span class="text-xs font-black uppercase tracking-wider">Pesanan Saya</span>
                    </div>
                    <div class="flex items-center gap-2">
                        <span v-if="tableOrders && tableOrders.length > 0" class="text-[10px] font-black bg-[#5c3a26] text-white px-2 py-0.5 rounded-full">
                            {{ tableOrders.length }} Pesanan
                        </span>
                        <span v-else class="text-[10px] font-bold text-[#5c3a26]/80">
                            Lihat Riwayat
                        </span>
                        <ChevronRight class="h-4 w-4 text-[#5c3a26]" />
                    </div>
                </button>

                <!-- Active Customer Name Indicator -->
                <div v-if="customerName" class="flex items-center justify-between gap-2 text-xs text-amber-100 bg-black/20 backdrop-blur-md px-3.5 py-2 rounded-2xl border border-white/10">
                    <div class="flex items-center gap-1.5 truncate">
                        <User class="h-3.5 w-3.5 text-amber-300 shrink-0" />
                        <span class="truncate text-[11px]">Nama: <strong class="text-white font-bold">{{ customerName }}</strong></span>
                    </div>
                    <button @click="showNamePrompt = true" class="text-[10px] font-bold text-amber-200 hover:text-white underline shrink-0 cursor-pointer">Ubah</button>
                </div>
            </div>
        </header>

        <!-- Flash Success / Pending Notification -->
        <div v-if="$page.props.flash?.success" class="mx-5 mt-4 p-4 bg-amber-50 border border-amber-200 text-amber-900 rounded-2xl text-xs font-bold flex items-center gap-2 shadow-sm animate-in fade-in">
            <CheckCircle2 class="h-5 w-5 text-amber-600 flex-shrink-0" />
            <span>{{ $page.props.flash.success }}</span>
        </div>

        <!-- Category pills -->
        <div class="px-5 mt-6 scrollbar-hide overflow-x-auto flex gap-2">
            <button
                v-for="cat in categories"
                :key="cat"
                @click="selectedCategory = cat"
                :class="[
                    'px-4 py-2 rounded-full text-xs font-bold transition-all shadow-sm flex-shrink-0 cursor-pointer',
                    selectedCategory === cat 
                        ? 'bg-[#8c5a3c] text-white scale-105' 
                        : 'bg-white text-slate-600 hover:bg-slate-50'
                ]"
            >
                {{ cat }}
            </button>
        </div>

        <!-- Search Bar -->
        <div class="px-5 mt-4">
            <div class="relative w-full">
                <Search class="absolute left-3.5 top-3 h-4 w-4 text-slate-400" />
                <input
                    v-model="searchQuery"
                    type="text"
                    placeholder="Cari menu kopi atau makanan favoritmu..."
                    class="w-full h-10 pl-10 pr-4 bg-white border border-slate-100 rounded-xl text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c] shadow-sm transition-all"
                />
            </div>
        </div>

        <!-- Menu Grid -->
        <div class="px-5 mt-6 space-y-4">
            <div class="flex items-center justify-between">
                <h2 class="text-sm font-black uppercase tracking-wider text-slate-650">Daftar Menu</h2>
                <span class="text-xs text-slate-400 font-medium">{{ filteredProducts.length }} items</span>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div 
                    v-for="prod in filteredProducts" 
                    :key="prod.id"
                    class="bg-white border border-slate-100/50 rounded-2xl p-4 flex gap-4 shadow-sm relative overflow-hidden transition-all hover:shadow-md"
                >
                    <!-- Product Image -->
                    <div class="h-20 w-20 bg-slate-50 rounded-xl flex-shrink-0 overflow-hidden border border-slate-100 flex items-center justify-center">
                        <img 
                            v-if="prod.image_path" 
                            :src="prod.image_path.startsWith('http') ? prod.image_path : '/' + prod.image_path" 
                            alt="Product Image" 
                            class="h-full w-full object-cover"
                        />
                        <Sparkles v-else class="h-6 w-6 text-amber-500" />
                    </div>

                    <!-- Product Details -->
                    <div class="flex-1 min-w-0 flex flex-col justify-between">
                        <div>
                            <span class="text-[9px] font-bold uppercase tracking-wider text-[#8c5a3c]">{{ prod.category }}</span>
                            <h3 class="text-xs font-bold text-slate-900 truncate mt-0.5">{{ prod.name }}</h3>
                            <p class="text-[10px] text-slate-400 line-clamp-2 mt-0.5">{{ prod.description || 'Nikmati kelezatan menu premium racikan khas dari barista kami.' }}</p>
                        </div>

                        <div class="flex justify-between items-center mt-2">
                            <span class="text-xs font-black text-slate-900">Rp {{ prod.price.toLocaleString('id-ID') }}</span>
                            
                            <!-- Stock & Add block -->
                            <div v-if="getAvailableStock(prod) > 0">
                                <button 
                                    @click="quickAdd(prod)"
                                    class="h-7 w-7 rounded-lg bg-[#8c5a3c] hover:bg-[#734a31] text-white flex items-center justify-center shadow-sm hover:scale-105 transition-all cursor-pointer"
                                >
                                    <Plus class="h-4 w-4" />
                                </button>
                            </div>
                            <span v-else class="text-[9px] font-bold text-rose-500 uppercase">Habis</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Persistent Bottom Cart Bar -->
        <div 
            v-if="cart.length > 0" 
            class="fixed bottom-0 left-0 right-0 p-4 bg-white/90 backdrop-blur-md border-t border-slate-100 shadow-2xl flex items-center justify-between z-40 max-w-lg mx-auto rounded-t-3xl"
        >
            <div class="flex items-center gap-3">
                <div class="h-10 w-10 bg-[#8c5a3c] rounded-xl flex items-center justify-center text-white relative shadow-md">
                    <ShoppingBag class="h-5 w-5" />
                    <span class="absolute -top-1.5 -right-1.5 bg-red-500 text-white text-[9px] font-black h-4 w-4 rounded-full flex items-center justify-center border-2 border-white">
                        {{ cart.reduce((sum, item) => sum + item.qty, 0) }}
                    </span>
                </div>
                <div>
                    <p class="text-[10px] text-slate-400 font-semibold uppercase">Total Bayar</p>
                    <p class="text-sm font-black text-slate-900">Rp {{ grandTotal.toLocaleString('id-ID') }}</p>
                </div>
            </div>

            <button 
                @click="isCartOpen = true"
                class="px-5 py-2.5 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-xl flex items-center gap-1 cursor-pointer transition-all shadow-md"
            >
                <span>Lihat Keranjang</span>
                <ChevronRight class="h-4 w-4" />
            </button>
        </div>

        <!-- Customer Name Prompt Modal -->
        <div v-if="showNamePrompt" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/70 backdrop-blur-sm">
            <div class="bg-white border border-slate-100 rounded-3xl shadow-2xl w-full max-w-sm p-6 text-center space-y-5 animate-in zoom-in-95 duration-200">
                <div class="h-12 w-12 bg-[#8c5a3c]/10 rounded-full flex items-center justify-center text-[#8c5a3c] mx-auto">
                    <User class="h-6 w-6" />
                </div>
                <div class="space-y-1">
                    <h3 class="text-sm font-black uppercase tracking-wider text-slate-800">Nama Pelanggan</h3>
                    <p class="text-xs text-slate-400">Masukkan nama Anda untuk mencatat pesanan di meja.</p>
                </div>

                <div>
                    <input
                        type="text"
                        v-model="customerName"
                        placeholder="Masukkan nama lengkap Anda..."
                        class="w-full h-11 px-4 border border-slate-200 rounded-xl bg-slate-50 text-xs font-bold text-center focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c]"
                    />
                </div>

                <button
                    @click="saveCustomerName"
                    :disabled="!customerName.trim()"
                    class="w-full h-11 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-xl cursor-pointer disabled:opacity-50 transition-colors shadow-md"
                >
                    Mulai Memesan
                </button>
            </div>
        </div>

        <!-- Custom Modifier/Variant Dialog Modal -->
        <div v-if="activeProduct" class="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4 bg-slate-950/60 backdrop-blur-sm">
            <div class="bg-white border border-slate-100 rounded-t-3xl sm:rounded-3xl shadow-2xl w-full max-w-md overflow-hidden animate-in slide-in-from-bottom duration-200">
                <!-- Header -->
                <div class="p-5 border-b border-slate-100 flex justify-between items-center">
                    <div>
                        <span class="text-[9px] font-bold uppercase tracking-wider text-[#8c5a3c]">{{ activeProduct.category }}</span>
                        <h3 class="text-sm font-black text-slate-900 mt-0.5">{{ activeProduct.name }}</h3>
                    </div>
                    <button @click="activeProduct = null" class="p-1.5 hover:bg-slate-50 rounded-lg text-slate-400 cursor-pointer">
                        <X class="h-4 w-4" />
                    </button>
                </div>

                <!-- Body Options -->
                <div class="p-5 space-y-6 max-h-[60vh] overflow-y-auto">
                    <!-- Variant Selector -->
                    <div v-if="activeProduct.recipes.some(r => r.variant !== null)" class="space-y-2">
                        <label class="block text-[10px] font-extrabold uppercase tracking-widest text-slate-400">Pilih Penyajian</label>
                        <div class="grid grid-cols-2 gap-3">
                            <button
                                @click="activeVariant = 'ice'"
                                :class="[
                                    'py-3 border-2 rounded-xl text-xs font-bold cursor-pointer transition-all text-center',
                                    activeVariant === 'ice' 
                                        ? 'border-[#8c5a3c] bg-[#8c5a3c]/5 text-[#8c5a3c]' 
                                        : 'border-slate-100 hover:bg-slate-50 text-slate-500'
                                ]"
                            >
                                Ice (Dingin)
                            </button>
                            <button
                                @click="activeVariant = 'hot'"
                                :class="[
                                    'py-3 border-2 rounded-xl text-xs font-bold cursor-pointer transition-all text-center',
                                    activeVariant === 'hot' 
                                        ? 'border-[#8c5a3c] bg-[#8c5a3c]/5 text-[#8c5a3c]' 
                                        : 'border-slate-100 hover:bg-slate-50 text-slate-500'
                                ]"
                            >
                                Hot (Panas)
                            </button>
                        </div>
                    </div>

                    <!-- Modifiers / Addons list -->
                    <div class="space-y-2" v-if="activeProduct.modifiers && activeProduct.modifiers.length > 0">
                        <label class="block text-[10px] font-extrabold uppercase tracking-widest text-slate-400">Tambahan (Addons)</label>
                        <div class="space-y-2">
                            <div 
                                v-for="mod in activeProduct.modifiers" 
                                :key="mod.id"
                                @click="toggleModifier(mod)"
                                :class="[
                                    'p-3 border rounded-xl flex items-center justify-between text-xs font-semibold cursor-pointer transition-all',
                                    activeModifiers.some(m => m.id === mod.id)
                                        ? 'border-[#8c5a3c] bg-[#8c5a3c]/5 text-[#8c5a3c]'
                                        : 'border-slate-100 dark:border-slate-800 text-slate-650 dark:text-slate-350 hover:bg-slate-50 dark:hover:bg-slate-900/30'
                                ]"
                            >
                                <span class="font-bold">{{ mod.name }}</span>
                                <span class="font-bold">+Rp {{ mod.price.toLocaleString('id-ID') }}</span>
                            </div>
                        </div>
                    </div>

                    <!-- Notes -->
                    <div class="space-y-2">
                        <label class="block text-[10px] font-extrabold uppercase tracking-widest text-slate-400">Catatan Khusus</label>
                        <textarea
                            v-model="activeNotes"
                            placeholder="Contoh: Kurangi gula, es batu sedikit saja..."
                            rows="2"
                            class="w-full p-3 border border-slate-200 rounded-xl text-xs font-semibold focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] bg-slate-50"
                        ></textarea>
                    </div>
                </div>

                <!-- Footer Action -->
                <div class="p-5 border-t border-slate-100 bg-slate-50 flex gap-4">
                    <button
                        @click="addToCartFromModal"
                        class="flex-1 py-3 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-xl cursor-pointer shadow-md text-center"
                    >
                        Tambah Ke Keranjang
                    </button>
                </div>
            </div>
        </div>

        <!-- Cart View Overlay (Slide over) -->
        <div v-if="isCartOpen" class="fixed inset-0 z-50 flex justify-end bg-slate-950/70 backdrop-blur-sm animate-fade-in">
            <div class="w-full max-w-md bg-white h-full flex flex-col justify-between shadow-2xl animate-in slide-in-from-right duration-200">
                <!-- Header -->
                <div class="p-5 border-b border-slate-100 flex justify-between items-center">
                    <div class="flex items-center gap-2">
                        <ShoppingBag class="h-5 w-5 text-[#8c5a3c]" />
                        <h3 class="text-sm font-black uppercase tracking-wider text-slate-900">Keranjang Belanja</h3>
                    </div>
                    <button @click="isCartOpen = false" class="p-1.5 hover:bg-slate-50 rounded-lg text-slate-400 cursor-pointer">
                        <X class="h-5 w-5" />
                    </button>
                </div>

                <!-- Cart Items List -->
                <div class="flex-1 overflow-y-auto p-5 space-y-4">
                    <div 
                        v-for="(item, idx) in cart" 
                        :key="idx"
                        class="p-4 border border-slate-100 rounded-2xl flex gap-3 shadow-sm"
                    >
                        <div class="flex-1 min-w-0">
                            <h4 class="text-xs font-bold text-slate-900 truncate">{{ item.product.name }}</h4>
                            <p v-if="item.variant" class="text-[9px] font-extrabold uppercase text-amber-600 mt-0.5">[{{ item.variant }}]</p>
                            
                            <!-- Addons display -->
                            <div v-if="item.selectedModifiers.length > 0" class="flex flex-wrap gap-1 mt-1">
                                <span 
                                    v-for="m in item.selectedModifiers" 
                                    :key="m.id"
                                    class="px-1.5 py-0.5 bg-slate-50 text-[9px] font-semibold text-slate-500 rounded border border-slate-100"
                                >
                                    +{{ m.name }}
                                </span>
                            </div>

                            <p v-if="item.notes" class="text-[9px] text-slate-400 italic mt-1.5">Note: "{{ item.notes }}"</p>
                        </div>

                        <div class="flex flex-col justify-between items-end">
                            <span class="text-xs font-bold text-slate-800">
                                Rp {{ ((item.product.price + item.selectedModifiers.reduce((s, m) => s + m.price, 0)) * item.qty).toLocaleString('id-ID') }}
                            </span>
                            
                            <!-- Counter -->
                            <div class="flex items-center border border-slate-200 rounded-lg h-7">
                                <button @click="updateCartQty(idx, -1)" class="h-6 w-6 flex items-center justify-center hover:bg-slate-50 text-slate-500 cursor-pointer">
                                    <Minus class="h-3 w-3" />
                                </button>
                                <span class="px-2 text-xs font-bold text-slate-800">{{ item.qty }}</span>
                                <button @click="updateCartQty(idx, 1)" class="h-6 w-6 flex items-center justify-center hover:bg-slate-50 text-slate-500 cursor-pointer">
                                    <Plus class="h-3 w-3" />
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Payment Methods & Cost Summary -->
                <div class="p-5 border-t border-slate-100 bg-slate-50 space-y-4">
                    <!-- Method Select -->
                    <div class="space-y-2">
                        <label class="block text-[10px] font-extrabold uppercase tracking-widest text-slate-400">Metode Pembayaran</label>
                        <div class="grid grid-cols-2 gap-3">
                            <button
                                @click="paymentMethod = 'cashier'"
                                :class="[
                                    'py-3 border-2 rounded-xl text-xs font-bold cursor-pointer transition-all flex flex-col items-center gap-1 text-center',
                                    paymentMethod === 'cashier' 
                                        ? 'border-[#8c5a3c] bg-white text-[#8c5a3c]' 
                                        : 'border-transparent bg-white/50 text-slate-500'
                                ]"
                            >
                                <CreditCard class="h-4 w-4" />
                                <span>Bayar di Kasir</span>
                            </button>
                            <button
                                @click="paymentMethod = 'qris'"
                                :class="[
                                    'py-3 border-2 rounded-xl text-xs font-bold cursor-pointer transition-all flex flex-col items-center gap-1 text-center',
                                    paymentMethod === 'qris' 
                                        ? 'border-[#8c5a3c] bg-white text-[#8c5a3c]' 
                                        : 'border-transparent bg-white/50 text-slate-500'
                                ]"
                            >
                                <Sparkles class="h-4 w-4 text-orange-500" />
                                <span>QRIS Manual</span>
                            </button>
                        </div>
                    </div>

                    <!-- Cost Breakdowns -->
                    <div class="text-xs space-y-1.5 font-medium text-slate-500 border-t border-slate-200/60 pt-3">
                        <div class="flex justify-between">
                            <span>Subtotal</span>
                            <span>Rp {{ subtotal.toLocaleString('id-ID') }}</span>
                        </div>
                        <div class="flex justify-between" v-if="serviceCharge > 0">
                            <span>Service Charge ({{ servicePercentage }}%)</span>
                            <span>Rp {{ serviceCharge.toLocaleString('id-ID') }}</span>
                        </div>
                        <div class="flex justify-between" v-if="taxAmount > 0">
                            <span>Tax ({{ taxPercentage }}%)</span>
                            <span>Rp {{ taxAmount.toLocaleString('id-ID') }}</span>
                        </div>
                        <div class="flex justify-between text-sm font-black text-slate-900 pt-2 border-t border-dashed border-slate-200 mt-2">
                            <span>Grand Total</span>
                            <span>Rp {{ grandTotal.toLocaleString('id-ID') }}</span>
                        </div>
                    </div>

                    <!-- Checkout Button -->
                    <button
                        @click="checkout"
                        :disabled="isCheckoutProcessing"
                        class="w-full py-3 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-xl cursor-pointer shadow-md text-center block transition-colors disabled:opacity-50"
                    >
                        {{ isCheckoutProcessing ? 'Mengirim Pesanan...' : 'Konfirmasi & Pesan Sekarang' }}
                    </button>
                </div>
            </div>
        </div>

        <!-- Dynamic Mock QRIS Modal -->
        <div v-if="showQrisPaymentModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/70 backdrop-blur-sm">
            <div class="bg-white border border-slate-100 rounded-3xl shadow-2xl w-full max-w-sm p-6 text-center space-y-5 animate-in zoom-in-95 duration-200">
                <div class="flex items-center justify-between border-b border-slate-100 pb-3">
                    <h3 class="text-sm font-extrabold text-[#8c5a3c] flex items-center gap-1.5">
                        <Sparkles class="h-4.5 w-4.5 text-orange-500" />
                        Pembayaran QRIS Manual
                    </h3>
                    <button @click="showQrisPaymentModal = false" class="p-1.5 hover:bg-slate-50 rounded-lg text-slate-400 cursor-pointer">
                        <X class="h-4 w-4" />
                    </button>
                </div>

                <div class="space-y-1">
                    <p class="text-xs text-slate-400 font-semibold uppercase">TOTAL TAGIHAN</p>
                    <h2 class="text-lg font-black text-slate-900">Rp {{ (activeQrisAmount || grandTotal).toLocaleString('id-ID') }}</h2>
                </div>

                <div class="flex flex-col items-center justify-center p-4 bg-slate-50 rounded-2xl border border-slate-100">
                    <img 
                        :src="$page.props.settings.qris_image || '/images/radhcloud-qris.png'"
                        alt="QRIS Payment" 
                        class="h-56 w-56 object-contain shadow-sm border border-slate-100 rounded-xl bg-white p-2"
                    />
                    <p class="text-[9px] font-bold text-slate-400 uppercase mt-3 tracking-widest">NMID: NM-89304723904</p>
                </div>

                <p class="text-[10px] text-slate-500 leading-relaxed">
                    Silakan scan QRIS di atas menggunakan aplikasi e-wallet Anda. Setelah itu tunjukkan bukti bayar ke kasir (pesanan akan dikirim dalam status Pending).
                </p>

                <div class="pt-1">
                    <button
                        @click="showQrisPaymentModal = false"
                        class="w-full py-3 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-extrabold rounded-xl cursor-pointer shadow-md transition-colors active:scale-95"
                    >
                        Tutup / Selesai
                    </button>
                </div>
            </div>
        </div>

        <!-- Table Orders / History Modal -->
        <div v-if="showOrdersModal" class="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4 bg-slate-950/70 backdrop-blur-sm">
            <div class="bg-white rounded-t-[2.5rem] sm:rounded-3xl shadow-2xl w-full max-w-md max-h-[85vh] flex flex-col overflow-hidden animate-in slide-in-from-bottom duration-200">
                <!-- Header -->
                <div class="p-5 border-b border-slate-100 flex justify-between items-center bg-slate-50/50">
                    <div class="flex items-center gap-2">
                        <div class="h-9 w-9 bg-[#8c5a3c]/10 text-[#8c5a3c] rounded-xl flex items-center justify-center font-bold">
                            <Receipt class="h-5 w-5" />
                        </div>
                        <div>
                            <h3 class="text-sm font-black text-slate-900">Riwayat Pesanan Saya</h3>
                            <p class="text-[10px] text-slate-400 font-semibold">Daftar Pesanan Meja {{ table.number }} Hari Ini</p>
                        </div>
                    </div>
                    <button @click="showOrdersModal = false" class="p-2 hover:bg-slate-100 rounded-xl text-slate-400 cursor-pointer">
                        <X class="h-5 w-5" />
                    </button>
                </div>

                <!-- Orders List -->
                <div class="p-5 overflow-y-auto space-y-4 flex-1">
                    <div v-if="!filteredMyOrders || filteredMyOrders.length === 0" class="text-center py-10 space-y-3">
                        <div class="h-16 w-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto text-slate-400">
                            <ShoppingBag class="h-8 w-8" />
                        </div>
                        <p class="text-xs font-bold text-slate-500">Belum ada riwayat pesanan perangkat ini.</p>
                        <p class="text-[10px] text-slate-400">Silakan pilih menu favorit Anda di katalog dan buat pesanan pertama!</p>
                    </div>

                    <div 
                        v-for="order in filteredMyOrders" 
                        :key="order.id"
                        class="bg-white border border-slate-100 rounded-2xl p-4 shadow-sm space-y-3 relative overflow-hidden"
                    >
                        <!-- Order Header -->
                        <div class="flex justify-between items-start border-b border-slate-100 pb-2.5">
                            <div>
                                <span class="font-mono text-[10px] font-extrabold text-slate-400 uppercase tracking-wider block">{{ order.transaction_number }}</span>
                                <span class="text-xs font-black text-slate-900">Atas Nama: {{ order.customer_name }}</span>
                            </div>
                            <div class="text-right">
                                <span 
                                    :class="[
                                        'px-2.5 py-0.5 rounded-full text-[9px] font-black uppercase inline-block',
                                        order.status === 'pending'
                                            ? 'bg-amber-100 text-amber-800 border border-amber-200'
                                            : 'bg-emerald-100 text-emerald-800 border border-emerald-200'
                                    ]"
                                >
                                    {{ order.status === 'pending' ? 'PENDING (Kasir)' : 'LUNAS' }}
                                </span>
                                <span class="text-[9px] text-slate-400 block mt-0.5 font-medium flex items-center justify-end gap-1">
                                    <Clock class="h-3 w-3 inline" /> {{ order.created_at }}
                                </span>
                            </div>
                        </div>

                        <!-- Status Notice if Pending -->
                        <div v-if="order.status === 'pending'" class="p-3 bg-amber-50 border border-amber-200/70 rounded-xl text-[10px] text-amber-900 font-semibold space-y-2">
                            <div class="flex items-center gap-2">
                                <Sparkles class="h-4 w-4 text-amber-600 shrink-0" />
                                <span>Silakan bayar atau tunjukkan bukti bayar ke kasir untuk memproses pesanan.</span>
                            </div>
                            
                            <div v-if="order.payment_method === 'qris'" class="pt-1 flex justify-end">
                                <button 
                                    @click="activeQrisAmount = order.total_amount; showOrdersModal = false; showQrisPaymentModal = true;"
                                    class="px-3 py-1.5 bg-[#8c5a3c] hover:bg-[#734a31] text-white font-extrabold text-[11px] rounded-xl flex items-center gap-1.5 shadow-sm transition-all cursor-pointer active:scale-95"
                                >
                                    <CreditCard class="h-3.5 w-3.5" />
                                    <span>Tampilkan Kode QRIS</span>
                                </button>
                            </div>
                        </div>

                        <!-- Items List -->
                        <div class="space-y-2">
                            <div 
                                v-for="item in order.items" 
                                :key="item.id"
                                class="flex justify-between items-start text-xs"
                            >
                                <div>
                                    <span class="font-bold text-slate-800">{{ item.qty }}x {{ item.name }}</span>
                                    <span v-if="item.variant" class="text-[9px] font-extrabold text-amber-700 ml-1 uppercase">[{{ item.variant }}]</span>
                                    
                                    <div v-if="item.modifiers.length > 0" class="flex flex-wrap gap-1 mt-0.5">
                                        <span v-for="(m, idx) in item.modifiers" :key="idx" class="text-[9px] text-slate-400">
                                            + {{ m.name }}
                                        </span>
                                    </div>
                                </div>
                                <span class="font-black text-slate-900">Rp {{ item.subtotal.toLocaleString('id-ID') }}</span>
                            </div>
                        </div>

                        <!-- Total Footer -->
                        <div class="border-t border-dashed border-slate-200 pt-2.5 flex justify-between items-center text-xs">
                            <span class="font-bold text-slate-500 text-[10px] uppercase">Total Tagihan ({{ order.payment_method === 'qris' ? 'QRIS Manual' : 'Bayar di Kasir' }})</span>
                            <span class="font-black text-sm text-[#8c5a3c]">Rp {{ order.total_amount.toLocaleString('id-ID') }}</span>
                        </div>
                    </div>
                </div>

                <!-- Footer Action -->
                <div class="p-4 border-t border-slate-100 bg-slate-50">
                    <button
                        @click="showOrdersModal = false"
                        class="w-full py-3 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-xl cursor-pointer shadow-md text-center"
                    >
                        Tutup & Kembali ke Menu
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
.scrollbar-hide::-webkit-scrollbar {
    display: none;
}
.scrollbar-hide {
    -ms-overflow-style: none;
    scrollbar-width: none;
}
.line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}
</style>
