<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Menu — {{ $outlet->name }}</title>
    @vite(['resources/css/app.css', 'resources/js/app.js'])
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
</head>
<body class="bg-slate-50 text-slate-900 antialiased">

<div
    x-data="customerApp({
        categories: @js($categories),
        products: @js($products),
        taxPercent: {{ (int) $outlet->tax_percent }},
        servicePercent: {{ (int) $outlet->service_percent }},
        orderStoreUrl: '{{ route('customer.order.store', $table->qr_token) }}',
        csrf: '{{ csrf_token() }}'
    })"
    x-init="init()"
>
    {{-- STEP: menu --}}
    <div x-show="step === 'menu'">
        {{-- Header --}}
        <header class="sticky top-0 z-20 border-b border-slate-200 bg-white shadow-sm">
            <div class="mx-auto max-w-lg px-4 py-3">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-bold text-slate-900">{{ $outlet->name }}</p>
                        <p class="text-xs text-slate-500">{{ $table->name }}</p>
                    </div>
                    <button
                        x-show="cart.length"
                        @click="step = 'cart'"
                        class="relative rounded-xl bg-slate-900 px-3 py-2 text-xs font-semibold text-white">
                        Keranjang
                        <span class="ml-1 rounded-full bg-emerald-400 px-1.5 py-0.5 text-[10px] font-bold text-slate-900" x-text="cartCount"></span>
                    </button>
                </div>

                {{-- Search --}}
                <input
                    x-model="search"
                    placeholder="Cari menu..."
                    class="mt-2 w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm outline-none focus:border-sky-300 focus:bg-white">

                {{-- Category filter --}}
                <div class="mt-2 flex gap-2 overflow-x-auto pb-1">
                    <button
                        @click="activeCategory = null"
                        class="shrink-0 rounded-xl px-3 py-1.5 text-xs font-medium transition"
                        :class="activeCategory === null ? 'bg-slate-900 text-white' : 'bg-slate-100 text-slate-600'">
                        Semua
                    </button>
                    <template x-for="cat in categories" :key="cat.id">
                        <button
                            @click="activeCategory = cat.id"
                            class="shrink-0 rounded-xl px-3 py-1.5 text-xs font-medium transition"
                            :class="activeCategory === cat.id ? 'bg-slate-900 text-white' : 'bg-slate-100 text-slate-600'">
                            <span x-text="cat.name"></span>
                        </button>
                    </template>
                </div>
            </div>
        </header>

        {{-- Product grid --}}
        <main class="mx-auto max-w-lg px-4 pb-32 pt-4">
            <div class="grid grid-cols-2 gap-3">
                <template x-for="product in filteredProducts" :key="product.id">
                    <button
                        @click="openModal(product)"
                        class="overflow-hidden rounded-2xl border border-slate-200 bg-white text-left transition hover:shadow-md active:scale-95">
                        <div class="aspect-[4/3] bg-slate-100">
                            <img
                                :src="product.image_url || '/icons/icon-512.svg'"
                                :alt="product.name"
                                class="h-full w-full object-cover">
                        </div>
                        <div class="p-3">
                            <p class="truncate text-sm font-semibold text-slate-800" x-text="product.name"></p>
                            <p class="mt-1 text-sm font-bold text-slate-900" x-text="'Rp ' + fmt(product.base_price)"></p>
                        </div>
                    </button>
                </template>
                <p x-show="!filteredProducts.length" class="col-span-2 py-8 text-center text-sm text-slate-400">Tidak ada menu ditemukan.</p>
            </div>
        </main>

        {{-- Cart sticky bottom bar --}}
        <div
            x-show="cart.length"
            x-transition
            class="fixed inset-x-0 bottom-0 z-10 border-t border-slate-200 bg-white p-4 shadow-lg">
            <div class="mx-auto max-w-lg">
                <button
                    @click="step = 'cart'"
                    class="flex w-full items-center justify-between rounded-2xl bg-slate-900 px-4 py-3 text-white">
                    <span class="text-sm font-semibold" x-text="cartCount + ' item'"></span>
                    <span class="text-sm font-bold" x-text="'Rp ' + fmt(total)"></span>
                    <span class="text-sm font-semibold">Lihat Keranjang →</span>
                </button>
            </div>
        </div>
    </div>

    {{-- STEP: cart --}}
    <div x-show="step === 'cart'" class="mx-auto max-w-lg">
        <header class="sticky top-0 z-20 border-b border-slate-200 bg-white shadow-sm">
            <div class="flex items-center gap-3 px-4 py-3">
                <button @click="step = 'menu'" class="rounded-lg border border-slate-200 p-2 text-slate-600">
                    <svg class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7"/>
                    </svg>
                </button>
                <h2 class="text-sm font-bold">Keranjang</h2>
            </div>
        </header>

        <div class="px-4 pb-40 pt-4">
            <div class="space-y-3">
                <template x-for="(item, idx) in cart" :key="idx">
                    <div class="rounded-2xl border border-slate-200 bg-white p-3">
                        <div class="flex items-start justify-between gap-2">
                            <div class="min-w-0 flex-1">
                                <p class="truncate text-sm font-semibold" x-text="item.name"></p>
                                <p class="text-xs text-slate-500" x-text="'Rp ' + fmt(item.unit_price)"></p>
                                <p class="truncate text-[11px] text-slate-400" x-show="item.variant_label" x-text="item.variant_label"></p>
                                <p class="truncate text-[11px] text-slate-400" x-show="item.addons_label" x-text="item.addons_label"></p>
                                <p class="truncate text-[11px] text-emerald-600" x-show="item.note" x-text="'Catatan: ' + item.note"></p>
                            </div>
                            <button @click="removeItem(idx)" class="shrink-0 rounded-lg border border-rose-200 px-2 py-1 text-xs text-rose-500">Hapus</button>
                        </div>
                        <div class="mt-2 flex items-center gap-3">
                            <button @click="decQty(idx)" class="h-7 w-7 rounded-full border border-slate-300 text-sm font-bold leading-none">-</button>
                            <span class="min-w-[20px] text-center text-sm font-semibold" x-text="item.qty"></span>
                            <button @click="incQty(idx)" class="h-7 w-7 rounded-full border border-slate-300 text-sm font-bold leading-none">+</button>
                            <span class="ml-auto text-sm font-bold text-slate-900" x-text="'Rp ' + fmt(item.unit_price * item.qty)"></span>
                        </div>
                    </div>
                </template>
            </div>

            <button @click="step = 'menu'" class="mt-4 w-full rounded-xl border border-slate-200 bg-white py-2 text-sm text-slate-600">
                + Tambah Menu Lagi
            </button>

            {{-- Totals --}}
            <div class="mt-4 space-y-1 rounded-2xl border border-slate-200 bg-white p-4 text-sm">
                <div class="flex justify-between text-slate-600"><span>Subtotal</span><span x-text="'Rp ' + fmt(subtotal)"></span></div>
                <div class="flex justify-between text-slate-600"><span>Pajak ({{ (int) $outlet->tax_percent }}%)</span><span x-text="'Rp ' + fmt(tax)"></span></div>
                <div class="flex justify-between text-slate-600"><span>Service ({{ (int) $outlet->service_percent }}%)</span><span x-text="'Rp ' + fmt(service)"></span></div>
                <div class="flex justify-between border-t pt-2 text-base font-bold text-slate-900"><span>Total</span><span x-text="'Rp ' + fmt(total)"></span></div>
            </div>
        </div>

        {{-- Checkout button --}}
        <div class="fixed inset-x-0 bottom-0 border-t border-slate-200 bg-white p-4">
            <div class="mx-auto max-w-lg">
                <button
                    @click="step = 'payment'"
                    class="w-full rounded-2xl bg-slate-900 py-3 text-sm font-bold text-white">
                    Lanjut Bayar — Rp <span x-text="fmt(total)"></span>
                </button>
            </div>
        </div>
    </div>

    {{-- STEP: payment --}}
    <div x-show="step === 'payment'" class="mx-auto max-w-lg">
        <header class="sticky top-0 z-20 border-b border-slate-200 bg-white shadow-sm">
            <div class="flex items-center gap-3 px-4 py-3">
                <button @click="step = 'cart'" class="rounded-lg border border-slate-200 p-2 text-slate-600">
                    <svg class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7"/>
                    </svg>
                </button>
                <h2 class="text-sm font-bold">Pembayaran</h2>
            </div>
        </header>

        <div class="px-4 pb-40 pt-6">
            {{-- QRIS Simulation --}}
            <div class="rounded-2xl border border-slate-200 bg-white p-6 text-center">
                <p class="mb-1 text-xs font-semibold uppercase tracking-wide text-slate-500">Scan QR Code untuk Bayar</p>
                <p class="mb-4 text-2xl font-bold text-slate-900" x-text="'Rp ' + fmt(total)"></p>

                {{-- Fake QR --}}
                <div class="mx-auto mb-4 flex h-48 w-48 items-center justify-center rounded-2xl border-4 border-slate-900 bg-white">
                    <svg viewBox="0 0 200 200" class="h-44 w-44">
                        {{-- QR code pattern simulation --}}
                        <rect x="10" y="10" width="60" height="60" fill="none" stroke="#0f172a" stroke-width="6"/>
                        <rect x="25" y="25" width="30" height="30" fill="#0f172a"/>
                        <rect x="130" y="10" width="60" height="60" fill="none" stroke="#0f172a" stroke-width="6"/>
                        <rect x="145" y="25" width="30" height="30" fill="#0f172a"/>
                        <rect x="10" y="130" width="60" height="60" fill="none" stroke="#0f172a" stroke-width="6"/>
                        <rect x="25" y="145" width="30" height="30" fill="#0f172a"/>
                        <rect x="80" y="10" width="10" height="10" fill="#0f172a"/>
                        <rect x="100" y="10" width="10" height="10" fill="#0f172a"/>
                        <rect x="110" y="20" width="10" height="10" fill="#0f172a"/>
                        <rect x="80" y="30" width="10" height="10" fill="#0f172a"/>
                        <rect x="90" y="40" width="10" height="10" fill="#0f172a"/>
                        <rect x="110" y="40" width="10" height="10" fill="#0f172a"/>
                        <rect x="80" y="60" width="10" height="10" fill="#0f172a"/>
                        <rect x="100" y="60" width="10" height="10" fill="#0f172a"/>
                        <rect x="80" y="80" width="10" height="10" fill="#0f172a"/>
                        <rect x="90" y="90" width="10" height="10" fill="#0f172a"/>
                        <rect x="110" y="80" width="10" height="10" fill="#0f172a"/>
                        <rect x="130" y="80" width="10" height="10" fill="#0f172a"/>
                        <rect x="150" y="80" width="10" height="10" fill="#0f172a"/>
                        <rect x="170" y="90" width="10" height="10" fill="#0f172a"/>
                        <rect x="80" y="100" width="10" height="10" fill="#0f172a"/>
                        <rect x="100" y="100" width="10" height="10" fill="#0f172a"/>
                        <rect x="120" y="110" width="10" height="10" fill="#0f172a"/>
                        <rect x="140" y="100" width="10" height="10" fill="#0f172a"/>
                        <rect x="160" y="110" width="10" height="10" fill="#0f172a"/>
                        <rect x="80" y="120" width="10" height="10" fill="#0f172a"/>
                        <rect x="90" y="130" width="10" height="10" fill="#0f172a"/>
                        <rect x="110" y="120" width="10" height="10" fill="#0f172a"/>
                        <rect x="80" y="150" width="10" height="10" fill="#0f172a"/>
                        <rect x="100" y="140" width="10" height="10" fill="#0f172a"/>
                        <rect x="120" y="150" width="10" height="10" fill="#0f172a"/>
                        <rect x="130" y="130" width="10" height="10" fill="#0f172a"/>
                        <rect x="150" y="140" width="10" height="10" fill="#0f172a"/>
                        <rect x="170" y="130" width="10" height="10" fill="#0f172a"/>
                        <rect x="80" y="170" width="10" height="10" fill="#0f172a"/>
                        <rect x="100" y="170" width="10" height="10" fill="#0f172a"/>
                        <rect x="140" y="160" width="10" height="10" fill="#0f172a"/>
                        <rect x="160" y="170" width="10" height="10" fill="#0f172a"/>
                        <text x="100" y="105" text-anchor="middle" font-size="9" fill="#0f172a" font-weight="bold">QRIS</text>
                    </svg>
                </div>

                <p class="mb-1 text-xs text-amber-600">⚠ Ini adalah simulasi pembayaran</p>
                <p class="text-xs text-slate-500">Gunakan aplikasi dompet digital untuk scan</p>
            </div>

            {{-- Order summary --}}
            <div class="mt-4 rounded-2xl border border-slate-200 bg-white p-4">
                <p class="mb-2 text-xs font-semibold text-slate-500">Ringkasan Pesanan</p>
                <template x-for="item in cart" :key="item.product_id + '_' + item.variant_option_id">
                    <div class="flex items-center justify-between py-1 text-sm">
                        <span class="text-slate-700" x-text="item.qty + 'x ' + item.name"></span>
                        <span class="font-semibold" x-text="'Rp ' + fmt(item.unit_price * item.qty)"></span>
                    </div>
                </template>
                <div class="mt-2 flex justify-between border-t pt-2 text-sm font-bold">
                    <span>Total</span>
                    <span x-text="'Rp ' + fmt(total)"></span>
                </div>
            </div>
        </div>

        {{-- Confirm button --}}
        <div class="fixed inset-x-0 bottom-0 border-t border-slate-200 bg-white p-4">
            <div class="mx-auto max-w-lg">
                <button
                    @click="submitOrder()"
                    :disabled="submitting"
                    class="w-full rounded-2xl bg-emerald-600 py-3 text-sm font-bold text-white disabled:opacity-60">
                    <span x-show="!submitting">✓ Saya Sudah Bayar</span>
                    <span x-show="submitting">Memproses...</span>
                </button>
                <p class="mt-2 text-center text-xs text-slate-400">Tekan tombol di atas setelah pembayaran berhasil</p>
            </div>
        </div>
    </div>

    {{-- Modifier modal --}}
    <div x-show="modalOpen" x-transition class="fixed inset-0 z-50 flex items-end justify-center bg-slate-900/40 p-0 sm:items-center sm:p-4">
        <div class="w-full max-w-lg overflow-hidden rounded-t-3xl bg-white p-4 sm:rounded-2xl">
            <div class="mb-3 flex items-center justify-between">
                <h3 class="text-base font-bold" x-text="selectedProduct?.name"></h3>
                <button @click="closeModal()" class="rounded-lg border px-3 py-1 text-xs">Tutup</button>
            </div>

            <div class="max-h-96 space-y-4 overflow-auto text-sm">
                <template x-for="variant in (selectedProduct?.variants || [])" :key="variant.id">
                    <div>
                        <p class="mb-2 text-xs font-semibold text-slate-500" x-text="variant.name"></p>
                        <div class="flex flex-wrap gap-2">
                            <template x-for="option in (variant.options || [])" :key="option.id">
                                <button
                                    @click="selectedVariantOptionId = option.id"
                                    class="rounded-xl border px-3 py-1.5 text-xs transition"
                                    :class="selectedVariantOptionId === option.id ? 'border-slate-900 bg-slate-900 text-white' : 'border-slate-200 bg-white text-slate-700'">
                                    <span x-text="option.name"></span>
                                    <span x-show="option.price_delta > 0" x-text="' (+Rp ' + fmt(option.price_delta) + ')'"></span>
                                </button>
                            </template>
                        </div>
                    </div>
                </template>

                <div x-show="(selectedProduct?.addons || []).length">
                    <p class="mb-2 text-xs font-semibold text-slate-500">Tambahan</p>
                    <div class="flex flex-wrap gap-2">
                        <template x-for="addon in (selectedProduct?.addons || [])" :key="addon.id">
                            <button
                                @click="toggleAddon(addon.id)"
                                class="rounded-xl border px-3 py-1.5 text-xs transition"
                                :class="selectedAddonIds.includes(addon.id) ? 'border-slate-900 bg-slate-900 text-white' : 'border-slate-200 bg-white text-slate-700'">
                                <span x-text="addon.name"></span>
                                <span x-text="' +Rp ' + fmt(addon.price)"></span>
                            </button>
                        </template>
                    </div>
                </div>

                <textarea x-model="itemNote" rows="2" placeholder="Catatan (opsional, misal: tidak pedas)"
                          class="w-full rounded-xl border border-slate-200 px-3 py-2 text-xs outline-none focus:border-sky-300"></textarea>

                <p class="text-sm font-bold text-slate-900">
                    Harga: <span x-text="'Rp ' + fmt(modalUnitPrice)"></span>
                </p>
            </div>

            <button
                @click="addToCart()"
                class="mt-4 w-full rounded-2xl bg-slate-900 py-3 text-sm font-bold text-white">
                Tambah ke Keranjang
            </button>
        </div>
    </div>

</div>

<script>
function customerApp(config) {
    return {
        categories: config.categories,
        products: config.products,
        taxPercent: config.taxPercent,
        servicePercent: config.servicePercent,
        step: 'menu',
        search: '',
        activeCategory: null,
        cart: [],
        submitting: false,

        // Modal state
        modalOpen: false,
        selectedProduct: null,
        selectedVariantOptionId: null,
        selectedAddonIds: [],
        itemNote: '',

        get filteredProducts() {
            return this.products.filter((p) => {
                const matchCat = !this.activeCategory || p.category_id === this.activeCategory;
                const matchSearch = !this.search || p.name.toLowerCase().includes(this.search.toLowerCase());
                return matchCat && matchSearch;
            });
        },
        get cartCount() {
            return this.cart.reduce((acc, it) => acc + it.qty, 0);
        },
        get subtotal() {
            return this.cart.reduce((acc, it) => acc + (it.unit_price * it.qty), 0);
        },
        get tax() {
            return Math.floor(this.subtotal * this.taxPercent / 100);
        },
        get service() {
            return Math.floor(this.subtotal * this.servicePercent / 100);
        },
        get total() {
            return this.subtotal + this.tax + this.service;
        },
        get modalUnitPrice() {
            if (!this.selectedProduct) return 0;
            const base = Number(this.selectedProduct.base_price || 0);
            const variantDelta = this.getVariantDelta(this.selectedProduct, this.selectedVariantOptionId);
            const addonsTotal = this.getAddonsTotal(this.selectedProduct, this.selectedAddonIds);
            return base + variantDelta + addonsTotal;
        },

        fmt(v) { return Number(v || 0).toLocaleString('id-ID'); },

        getVariantDelta(product, optionId) {
            if (!optionId) return 0;
            for (const variant of (product.variants || [])) {
                const found = (variant.options || []).find((o) => Number(o.id) === Number(optionId));
                if (found) return Number(found.price_delta || 0);
            }
            return 0;
        },
        getAddonsTotal(product, addonIds) {
            const ids = addonIds || [];
            return (product.addons || [])
                .filter((a) => ids.includes(a.id))
                .reduce((acc, a) => acc + Number(a.price || 0), 0);
        },
        resolveVariantLabel(product, optionId) {
            if (!optionId) return '';
            for (const variant of (product.variants || [])) {
                const found = (variant.options || []).find((o) => Number(o.id) === Number(optionId));
                if (found) return `${variant.name}: ${found.name}`;
            }
            return '';
        },
        resolveAddonsLabel(product, addonIds) {
            if (!addonIds?.length) return '';
            return (product.addons || [])
                .filter((a) => addonIds.includes(a.id))
                .map((a) => a.name)
                .join(', ');
        },

        openModal(product) {
            this.selectedProduct = product;
            this.selectedVariantOptionId = product.variants?.[0]?.options?.[0]?.id ?? null;
            this.selectedAddonIds = [];
            this.itemNote = '';
            this.modalOpen = true;
        },
        closeModal() {
            this.modalOpen = false;
            this.selectedProduct = null;
            this.selectedVariantOptionId = null;
            this.selectedAddonIds = [];
            this.itemNote = '';
        },
        toggleAddon(addonId) {
            if (this.selectedAddonIds.includes(addonId)) {
                this.selectedAddonIds = this.selectedAddonIds.filter((id) => id !== addonId);
            } else {
                this.selectedAddonIds.push(addonId);
            }
        },
        addToCart() {
            if (!this.selectedProduct) return;
            const unitPrice = this.modalUnitPrice;
            const variantLabel = this.resolveVariantLabel(this.selectedProduct, this.selectedVariantOptionId);
            const addonsLabel = this.resolveAddonsLabel(this.selectedProduct, this.selectedAddonIds);

            this.cart.push({
                product_id: this.selectedProduct.id,
                name: this.selectedProduct.name,
                qty: 1,
                unit_price: unitPrice,
                variant_option_id: this.selectedVariantOptionId,
                addon_ids: [...this.selectedAddonIds],
                note: this.itemNote,
                variant_label: variantLabel,
                addons_label: addonsLabel,
            });
            this.closeModal();
        },
        removeItem(idx) { this.cart.splice(idx, 1); },
        incQty(idx) { this.cart[idx].qty += 1; },
        decQty(idx) { if (this.cart[idx].qty > 1) this.cart[idx].qty -= 1; else this.removeItem(idx); },

        async submitOrder() {
            if (!this.cart.length || this.submitting) return;
            this.submitting = true;

            const payload = {
                order_type: 'dine-in',
                items: this.cart.map((it) => ({
                    product_id: it.product_id,
                    qty: it.qty,
                    note: it.note || null,
                    variant_option_id: it.variant_option_id || null,
                    addon_ids: it.addon_ids || [],
                })),
            };

            try {
                const response = await fetch(config.orderStoreUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': config.csrf,
                    },
                    body: JSON.stringify(payload),
                });

                if (response.redirected) {
                    window.location.href = response.url;
                    return;
                }

                if (response.ok) {
                    const data = await response.json();
                    if (data.redirect) {
                        window.location.href = data.redirect;
                    }
                } else {
                    const err = await response.json().catch(() => ({}));
                    alert(err.message || 'Gagal memproses pesanan. Coba lagi.');
                    this.submitting = false;
                }
            } catch (e) {
                alert('Koneksi bermasalah. Pastikan internet aktif.');
                this.submitting = false;
            }
        },

        init() {
            this.activeCategory = this.categories[0]?.id ?? null;
        },
    };
}
</script>
</body>
</html>
