<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { Head, useForm, router } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Search, Grid, Plus, Edit2, Trash2, Link as LinkIcon, Unlink, Store, HelpCircle, X, QrCode } from 'lucide-vue-next';

// Multi-selection states
const selectedTableIds = ref<number[]>([]);
const isBulkQrModalOpen = ref(false);
const printScope = ref<'selected' | 'all'>('selected');
const printTemplate = ref<'a4-1' | 'a4-3' | 'thermal'>('a4-1');

const toggleSelectTable = (id: number) => {
    const idx = selectedTableIds.value.indexOf(id);
    if (idx > -1) {
        selectedTableIds.value.splice(idx, 1);
    } else {
        selectedTableIds.value.push(id);
    }
};

const isAllSelected = computed(() => {
    return props.tables.length > 0 && selectedTableIds.value.length === props.tables.length;
});

const toggleSelectAll = () => {
    if (isAllSelected.value) {
        selectedTableIds.value = [];
    } else {
        selectedTableIds.value = props.tables.map(t => t.id);
    }
};

const openBulkQrModal = () => {
    if (selectedTableIds.value.length > 0) {
        printScope.value = 'selected';
    } else {
        printScope.value = 'all';
    }
    isBulkQrModalOpen.value = true;
};

// Filter tables for bulk printing based on selected scope
const tablesToPrint = computed(() => {
    if (printScope.value === 'selected') {
        return props.tables.filter(t => selectedTableIds.value.includes(t.id));
    }
    return props.tables;
});

const triggerPrint = () => {
    window.print();
};

interface TableData {
    id: number;
    outlet_id: number;
    number: string;
    capacity: number;
    status: 'available' | 'occupied' | 'reserved';
    merged_to_id: number | null;
    merged_to?: TableData | null;
    outlet?: { id: number; name: string };
}

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

const props = defineProps<{
    tables: TableData[];
    outlets: Outlet[];
    filters: {
        outlet_id?: string;
    };
}>();

const selectedOutletId = ref(props.filters.outlet_id || (props.outlets[0] ? String(props.outlets[0].id) : ''));

// Filter table list when outlet changes
watch(selectedOutletId, (newVal) => {
    router.get(
        route('tables.index'),
        { outlet_id: newVal },
        { preserveState: true, replace: true }
    );
});

// Modal states
const isFormModalOpen = ref(false);
const isMergeModalOpen = ref(false);
const isQrModalOpen = ref(false);
const editingTable = ref<TableData | null>(null);
const activeQrTable = ref<TableData | null>(null);

const openQrModal = (table: TableData) => {
    activeQrTable.value = table;
    isQrModalOpen.value = true;
};

const getQrCodeUrl = (table: TableData) => {
    const appUrl = window.location.origin;
    const url = `${appUrl}/order/outlet/${table.outlet_id}/table/${table.id}`;
    return `https://api.qrserver.com/v1/create-qr-code/?size=350x350&data=${encodeURIComponent(url)}`;
};

// Forms configuration
const form = useForm({
    outlet_id: selectedOutletId.value ? Number(selectedOutletId.value) : 0,
    number: '',
    capacity: 2,
    status: 'available',
});

const mergeForm = useForm({
    source_table_id: '',
    target_table_id: '',
});

const openCreateModal = () => {
    editingTable.value = null;
    form.clearErrors();
    form.reset();
    form.outlet_id = selectedOutletId.value ? Number(selectedOutletId.value) : 0;
    isFormModalOpen.value = true;
};

const openEditModal = (table: TableData) => {
    editingTable.value = table;
    form.clearErrors();
    form.outlet_id = table.outlet_id;
    form.number = table.number;
    form.capacity = table.capacity;
    form.status = table.status;
    isFormModalOpen.value = true;
};

const submitForm = () => {
    if (editingTable.value) {
        form.put(route('tables.update', editingTable.value.id), {
            onSuccess: () => {
                isFormModalOpen.value = false;
                form.reset();
            },
        });
    } else {
        form.post(route('tables.store'), {
            onSuccess: () => {
                isFormModalOpen.value = false;
                form.reset();
            },
        });
    }
};

const deleteTable = (table: TableData) => {
    if (confirm(`Apakah Anda yakin ingin menghapus ${table.number}?`)) {
        router.delete(route('tables.destroy', table.id));
    }
};

const openMergeModal = (table: TableData) => {
    mergeForm.reset();
    mergeForm.source_table_id = String(table.id);
    isMergeModalOpen.value = true;
};

const submitMerge = () => {
    mergeForm.post(route('tables.merge'), {
        onSuccess: () => {
            isMergeModalOpen.value = false;
            mergeForm.reset();
        }
    });
};

const splitTable = (table: TableData) => {
    if (confirm(`Apakah Anda yakin ingin memisahkan ${table.number}?`)) {
        router.post(route('tables.split'), { table_id: table.id });
    }
};

// Find mergeable targets (available tables in same outlet)
const mergeableTargets = computed(() => {
    if (!mergeForm.source_table_id) return [];
    const sourceId = Number(mergeForm.source_table_id);
    return props.tables.filter(t => t.id !== sourceId && t.status === 'available' && !t.merged_to_id);
});

const getStatusBadgeClass = (status: string) => {
    switch (status) {
        case 'available': return 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20';
        case 'occupied': return 'bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20';
        case 'reserved': return 'bg-indigo-500/10 text-indigo-600 dark:text-indigo-400 border-indigo-500/20';
        default: return 'bg-slate-500/10 text-slate-600 dark:text-slate-400 border-slate-500/20';
    }
};
</script>

<template>
    <Head title="Table Management" />

    <AdminLayout>
        <div class="space-y-6">
            <!-- Header section -->
            <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                    <h1 class="text-2xl font-extrabold text-slate-900 dark:text-slate-50 tracking-tight">
                        Table Management
                    </h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                        Kelola kapasitas, merge, status, dan okupansi meja restoran.
                    </p>
                </div>
                <button
                    @click="openCreateModal"
                    class="flex items-center justify-center gap-2 px-4 py-2 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-sm font-bold rounded-xl transition-all cursor-pointer shadow-lg shadow-[#8c5a3c]/10"
                >
                    <Plus class="h-4 w-4" />
                    Tambah Meja
                </button>
            </div>

            <!-- Controls row -->
            <div class="flex flex-wrap items-center justify-between gap-4 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl px-5 py-4 shadow-sm">
                <!-- Left: Outlet Filter & Bulk Selection -->
                <div class="flex flex-wrap items-center gap-5">
                    <div class="flex items-center gap-3">
                        <Store class="h-5 w-5 text-slate-400" />
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-wide">Cabang Outlet:</span>
                        <select
                            v-model="selectedOutletId"
                            class="h-9 px-3 border border-slate-200 dark:border-slate-700 rounded-lg bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 text-slate-900 dark:text-slate-100 cursor-pointer"
                        >
                            <option v-for="ot in outlets" :key="ot.id" :value="String(ot.id)">{{ ot.name }}</option>
                        </select>
                    </div>

                    <!-- Multi-select Controls -->
                    <div v-if="tables.length > 0" class="flex items-center gap-4 pl-4 border-l border-slate-250 dark:border-slate-800">
                        <label class="flex items-center gap-2 text-xs font-semibold text-slate-700 dark:text-slate-300 cursor-pointer select-none">
                            <input
                                type="checkbox"
                                :checked="isAllSelected"
                                @change="toggleSelectAll"
                                class="h-4 w-4 rounded border-slate-300 text-[#8c5a3c] focus:ring-[#8c5a3c]"
                            />
                            <span>Pilih Semua ({{ selectedTableIds.length }}/{{ tables.length }})</span>
                        </label>

                        <button
                            @click="openBulkQrModal"
                            class="h-9 px-3 bg-[#8c5a3c]/10 hover:bg-[#8c5a3c]/20 text-[#8c5a3c] dark:text-[#a17150] text-xs font-bold rounded-lg transition-colors cursor-pointer flex items-center gap-1.5"
                        >
                            <QrCode class="h-3.5 w-3.5" />
                            <span>Cetak QR Massal</span>
                        </button>
                    </div>
                </div>

                <!-- Stats summary -->
                <div class="flex items-center gap-4 text-xs font-semibold text-slate-500">
                    <span class="flex items-center gap-1.5"><span class="h-2.5 w-2.5 rounded-full bg-emerald-500"></span> Available: {{ tables.filter(t => t.status === 'available').length }}</span>
                    <span class="flex items-center gap-1.5"><span class="h-2.5 w-2.5 rounded-full bg-amber-500"></span> Occupied: {{ tables.filter(t => t.status === 'occupied').length }}</span>
                    <span class="flex items-center gap-1.5"><span class="h-2.5 w-2.5 rounded-full bg-indigo-500"></span> Reserved: {{ tables.filter(t => t.status === 'reserved').length }}</span>
                </div>
            </div>

            <!-- Visual Tables Grid Map -->
            <div v-if="tables.length > 0" class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-4 xl:grid-cols-4 gap-6">
                <div
                    v-for="table in tables"
                    :key="table.id"
                    class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 shadow-sm hover:shadow-md transition-shadow relative flex flex-col justify-between"
                >
                    <!-- Selection checkbox -->
                    <div class="absolute top-3.5 left-3.5 z-10">
                        <input
                            type="checkbox"
                            :checked="selectedTableIds.includes(table.id)"
                            @change="toggleSelectTable(table.id)"
                            class="h-4 w-4 rounded border-slate-300 text-[#8c5a3c] focus:ring-[#8c5a3c] cursor-pointer"
                        />
                    </div>

                    <!-- Status stripe indicator -->
                    <div
                        class="absolute inset-x-0 top-0 h-1.5 rounded-t-2xl"
                        :class="[
                            table.status === 'available' ? 'bg-emerald-500' : '',
                            table.status === 'occupied' ? 'bg-amber-500' : '',
                            table.status === 'reserved' ? 'bg-indigo-500' : ''
                        ]"
                    />

                    <!-- Table Detail Body -->
                    <div class="space-y-3 pt-2">
                        <div class="flex items-start justify-between">
                            <span class="text-base font-extrabold text-slate-900 dark:text-slate-50 pl-6">{{ table.number }}</span>
                            <span :class="['px-2 py-0.5 border rounded-full text-[9px] font-extrabold uppercase tracking-wider', getStatusBadgeClass(table.status)]">
                                {{ table.status }}
                            </span>
                        </div>
                        
                        <div class="text-[11px] text-slate-400">
                            Kapasitas: <span class="font-bold text-slate-700 dark:text-slate-300">{{ table.capacity }} kursi</span>
                        </div>

                        <!-- Merged Badge indicator -->
                        <div v-if="table.merged_to_id" class="flex items-center gap-1 px-2 py-1 rounded bg-amber-500/10 text-[9px] font-bold text-amber-700 dark:text-amber-400">
                            <LinkIcon class="h-3 w-3" />
                            <span>Merged to {{ tables.find(t => t.id === table.merged_to_id)?.number }}</span>
                        </div>
                    </div>

                    <!-- Actions Footer -->
                    <div class="flex items-center justify-end gap-1.5 mt-4 pt-3 border-t border-slate-100 dark:border-slate-800">
                        <button
                            v-if="!table.merged_to_id && table.status === 'available'"
                            @click="openMergeModal(table)"
                            title="Gabung Meja"
                            class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-500 hover:text-slate-800 dark:hover:text-slate-200 rounded-lg transition-colors cursor-pointer"
                        >
                            <LinkIcon class="h-3.5 w-3.5" />
                        </button>
                        <button
                            v-if="table.merged_to_id"
                            @click="splitTable(table)"
                            title="Pisah Meja"
                            class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-500 hover:text-rose-600 rounded-lg transition-colors cursor-pointer"
                        >
                            <Unlink class="h-3.5 w-3.5 text-rose-500" />
                        </button>
                        <button
                            @click="openQrModal(table)"
                            title="Tampilkan QR Code"
                            class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-800 text-[#8c5a3c] hover:text-[#734a31] rounded-lg transition-colors cursor-pointer"
                        >
                            <QrCode class="h-3.5 w-3.5" />
                        </button>
                        <button
                            @click="openEditModal(table)"
                            title="Edit"
                            class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-500 hover:text-slate-800 dark:hover:text-slate-200 rounded-lg transition-colors cursor-pointer"
                        >
                            <Edit2 class="h-3.5 w-3.5" />
                        </button>
                        <button
                            @click="deleteTable(table)"
                            title="Hapus"
                            class="p-1.5 hover:bg-slate-105 dark:hover:bg-slate-800 text-slate-550 hover:text-rose-600 rounded-lg transition-colors cursor-pointer"
                        >
                            <Trash2 class="h-3.5 w-3.5" />
                        </button>
                    </div>
                </div>
            </div>
            <div v-else class="text-center py-16 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-sm">
                <Grid class="h-10 w-10 text-slate-350 dark:text-slate-600 mx-auto mb-3" />
                <h3 class="text-sm font-bold text-slate-800 dark:text-slate-200">Belum ada meja</h3>
                <p class="text-xs text-slate-400 mt-1">Silakan tambahkan meja pertama Anda di outlet ini.</p>
            </div>

            <!-- Create/Edit Modal -->
            <div v-if="isFormModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/60 backdrop-blur-sm">
                <div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl w-full max-w-md overflow-hidden transform transition-all">
                    <!-- Modal Header -->
                    <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">
                            {{ editingTable ? 'Edit Detail Meja' : 'Tambah Meja Baru' }}
                        </h3>
                        <button @click="isFormModalOpen = 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>

                    <!-- Modal Body -->
                    <form @submit.prevent="submitForm" class="p-6 space-y-4">
                        <div>
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Nomor / Kode Meja</label>
                            <input
                                type="text"
                                v-model="form.number"
                                required
                                placeholder="Contoh: Meja 12, VIP-1"
                                class="w-full h-10 px-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c]"
                            />
                        </div>

                        <div>
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Kapasitas (Kursi)</label>
                            <input
                                type="number"
                                v-model="form.capacity"
                                required
                                min="1"
                                class="w-full h-10 px-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c]"
                            />
                        </div>

                        <div>
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Status</label>
                            <select
                                v-model="form.status"
                                required
                                class="w-full h-10 px-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c] cursor-pointer"
                            >
                                <option value="available">Available (Kosong)</option>
                                <option value="occupied">Occupied (Terisi)</option>
                                <option value="reserved">Reserved (Dipesan)</option>
                            </select>
                        </div>

                        <!-- Modal Actions Footer -->
                        <div class="flex items-center justify-end gap-3 pt-4 border-t border-slate-100 dark:border-slate-800">
                            <button
                                type="button"
                                @click="isFormModalOpen = 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="submit"
                                :disabled="form.processing"
                                class="px-4 py-2 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-xl cursor-pointer disabled:opacity-50"
                            >
                                {{ form.processing ? 'Menyimpan...' : 'Simpan' }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Merge Modal -->
            <div v-if="isMergeModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/60 backdrop-blur-sm">
                <div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl w-full max-w-md overflow-hidden transform transition-all">
                    <!-- Modal Header -->
                    <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">
                            <LinkIcon class="h-4 w-4 text-[#8c5a3c]" />
                            <span>Gabungkan Meja</span>
                        </h3>
                        <button @click="isMergeModalOpen = 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>

                    <!-- Modal Body -->
                    <form @submit.prevent="submitMerge" class="p-6 space-y-4">
                        <div class="bg-slate-50 dark:bg-slate-800/40 p-4 rounded-xl text-xs space-y-1">
                            <p class="font-bold text-slate-700 dark:text-slate-300">Bagaimana cara kerjanya?</p>
                            <p class="text-slate-500">Meja asal (source) akan diarahkan/digabungkan ke meja tujuan (target). Meja asal akan berubah status menjadioccupied.</p>
                        </div>

                        <div>
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Meja Asal</label>
                            <input
                                type="text"
                                :value="tables.find(t => String(t.id) === mergeForm.source_table_id)?.number"
                                readonly
                                class="w-full h-10 px-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-100 dark:bg-slate-800 text-xs font-semibold focus:outline-none"
                            />
                        </div>

                        <div>
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Gabungkan ke Meja (Target)</label>
                            <select
                                v-model="mergeForm.target_table_id"
                                required
                                class="w-full h-10 px-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c] cursor-pointer"
                            >
                                <option value="">Pilih meja tujuan...</option>
                                <option v-for="t in mergeableTargets" :key="t.id" :value="String(t.id)">{{ t.number }} (Kapasitas: {{ t.capacity }} kursi)</option>
                            </select>
                        </div>

                        <!-- Modal Actions Footer -->
                        <div class="flex items-center justify-end gap-3 pt-4 border-t border-slate-100 dark:border-slate-800">
                            <button
                                type="button"
                                @click="isMergeModalOpen = 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="submit"
                                :disabled="mergeForm.processing || !mergeForm.target_table_id"
                                class="px-4 py-2 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-xl cursor-pointer disabled:opacity-50"
                            >
                                {{ mergeForm.processing ? 'Menggabungkan Meja...' : 'Gabungkan Meja' }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- QR Code Modal -->
            <div v-if="isQrModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/60 backdrop-blur-sm animate-fade-in">
                <div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl w-full max-w-sm overflow-hidden p-6 text-center space-y-4 animate-in zoom-in-95 duration-200">
                    <div class="flex items-center justify-between border-b border-slate-100 dark:border-slate-800 pb-3">
                        <h3 class="text-sm font-extrabold text-slate-900 dark:text-slate-100">
                            Self-Order QR Code
                        </h3>
                        <button @click="isQrModalOpen = 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="space-y-1">
                        <h4 class="text-lg font-black text-[#8c5a3c]">Meja {{ activeQrTable?.number }}</h4>
                        <p class="text-xs text-slate-400">Scan QR Code untuk memesan menu secara mandiri.</p>
                    </div>

                    <div class="flex justify-center p-4 bg-slate-50 dark:bg-slate-950 rounded-2xl border border-slate-100 dark:border-slate-900">
                        <img 
                            v-if="activeQrTable" 
                            :src="getQrCodeUrl(activeQrTable)" 
                            alt="Table QR Code" 
                            class="h-56 w-56 object-contain"
                        />
                    </div>

                    <div class="flex gap-3">
                        <a
                            v-if="activeQrTable"
                            :href="getQrCodeUrl(activeQrTable)"
                            target="_blank"
                            class="flex-1 py-2 px-4 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-xl cursor-pointer shadow-md text-center block"
                        >
                            Unduh Gambar
                        </a>
                        <button
                            @click="isQrModalOpen = false"
                            class="flex-1 py-2 px-4 border border-slate-200 dark:border-slate-800 text-slate-500 rounded-xl text-xs font-bold hover:bg-slate-50 dark:hover:bg-slate-800 cursor-pointer"
                        >
                            Tutup
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Bulk QR Code Printing Modal -->
        <div v-if="isBulkQrModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/65 backdrop-blur-sm animate-fade-in">
            <div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl w-full max-w-4xl overflow-hidden flex flex-col transform transition-all font-sans max-h-[90vh]">
                <!-- Modal Header -->
                <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">
                        <QrCode class="h-4 w-4 text-[#8c5a3c]" />
                        <span>Bulk Print QR Code Meja</span>
                    </h3>
                    <button @click="isBulkQrModalOpen = 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>

                <!-- Modal Body -->
                <div class="p-6 flex flex-col md:flex-row gap-6 overflow-hidden flex-1">
                    <!-- Left Side: Controls -->
                    <div class="w-full md:w-80 space-y-5 flex-shrink-0">
                        <!-- Print Scope -->
                        <div class="space-y-2">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider">Cakupan Cetak Meja</label>
                            <div class="grid grid-cols-2 gap-2">
                                <button
                                    type="button"
                                    @click="printScope = 'selected'"
                                    :disabled="selectedTableIds.length === 0"
                                    :class="[
                                        'py-2 px-3 text-xs border rounded-xl font-bold cursor-pointer transition-all disabled:opacity-50 disabled:cursor-not-allowed',
                                        printScope === 'selected' ? 'bg-[#8c5a3c]/10 border-[#8c5a3c] text-[#8c5a3c]' : 'border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-800/30'
                                    ]"
                                >
                                    Pilihan ({{ selectedTableIds.length }})
                                </button>
                                <button
                                    type="button"
                                    @click="printScope = 'all'"
                                    :class="[
                                        'py-2 px-3 text-xs border rounded-xl font-bold cursor-pointer transition-all',
                                        printScope === 'all' ? 'bg-[#8c5a3c]/10 border-[#8c5a3c] text-[#8c5a3c]' : 'border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-800/30'
                                    ]"
                                >
                                    Semua Meja ({{ tables.length }})
                                </button>
                            </div>
                        </div>

                        <!-- Print Template/Layout Size -->
                        <div class="space-y-2">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider">Template & Kertas</label>
                            <div class="flex flex-col gap-2">
                                <label class="flex items-center gap-2.5 p-3 rounded-xl border border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-900/30 text-xs font-bold text-slate-700 dark:text-slate-300 cursor-pointer select-none">
                                    <input type="radio" v-model="printTemplate" value="a4-3" class="text-[#8c5a3c] focus:ring-[#8c5a3c]" />
                                    <div class="flex flex-col">
                                        <span>Kertas A4 - 3 Kolom</span>
                                        <span class="text-[10px] text-slate-400 leading-normal">Kecil, hemat kertas (3 QR per baris)</span>
                                    </div>
                                </label>
                                <label class="flex items-center gap-2.5 p-3 rounded-xl border border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-900/30 text-xs font-bold text-slate-700 dark:text-slate-300 cursor-pointer select-none">
                                    <input type="radio" v-model="printTemplate" value="a4-1" class="text-[#8c5a3c] focus:ring-[#8c5a3c]" />
                                    <div class="flex flex-col">
                                        <span>Kertas A4 - 1 Kolom (Full Center)</span>
                                        <span class="text-[10px] text-slate-400 leading-normal">1 kertas 1 meja, posisi tengah horizontal & vertikal</span>
                                    </div>
                                </label>
                                <label class="flex items-center gap-2.5 p-3 rounded-xl border border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-900/30 text-xs font-bold text-slate-700 dark:text-slate-300 cursor-pointer select-none">
                                    <input type="radio" v-model="printTemplate" value="thermal" class="text-[#8c5a3c] focus:ring-[#8c5a3c]" />
                                    <div class="flex flex-col">
                                        <span>Thermal 80mm</span>
                                        <span class="text-[10px] text-slate-400 leading-normal">Cetak satu per satu di printer kasir</span>
                                    </div>
                                </label>
                            </div>
                        </div>

                        <!-- Quick info -->
                        <div class="p-4 bg-slate-50 dark:bg-slate-900/40 rounded-xl border border-slate-200 dark:border-slate-800 text-[11px] leading-relaxed text-slate-500 space-y-1.5">
                            <div class="flex items-center gap-1 font-bold text-slate-700 dark:text-slate-300 text-xs mb-1">
                                <Info class="h-4 w-4 text-[#8c5a3c]" />
                                <span>Petunjuk Potong</span>
                            </div>
                            <p>Lembar cetakan dilengkapi garis putus-putus untuk membantu pemotongan agar rapi.</p>
                            <p>Tempelkan QR Code pada meja makan untuk memudahkan pelanggan memesan via smartphone.</p>
                        </div>
                    </div>

                    <!-- Right Side: Interactive Print Preview -->
                    <div class="flex-1 flex flex-col border border-slate-200 dark:border-slate-800 rounded-2xl overflow-hidden bg-slate-100 dark:bg-slate-950 p-4">
                        <div class="flex items-center justify-between mb-3">
                            <span class="text-[11px] font-bold uppercase tracking-wider text-slate-400">Live Print Preview</span>
                            <span class="text-xs text-slate-500 font-bold">{{ tablesToPrint.length }} Meja Terbuka</span>
                        </div>

                        <div class="flex-1 overflow-y-auto max-h-[50vh] p-6 bg-white dark:bg-slate-900 border border-slate-250 dark:border-slate-800 rounded-xl shadow-inner relative">
                            <!-- Empty State inside preview -->
                            <div v-if="tablesToPrint.length === 0" class="absolute inset-0 flex flex-col items-center justify-center p-4 text-center">
                                <QrCode class="h-8 w-8 text-slate-300 mb-2" />
                                <span class="text-xs font-bold text-slate-400">Silakan pilih meja terlebih dahulu.</span>
                            </div>

                            <!-- Live Sheet Rendering Grid -->
                            <div 
                                v-else 
                                :class="[
                                    'gap-6',
                                    printTemplate === 'a4-1' ? 'flex flex-col items-center space-y-6 w-full' : '',
                                    printTemplate === 'a4-3' ? 'grid grid-cols-3' : '',
                                    printTemplate === 'thermal' ? 'flex flex-col items-center max-w-[280px] mx-auto' : ''
                                ]"
                            >
                                <div 
                                    v-for="t in tablesToPrint" 
                                    :key="t.id" 
                                    :class="[
                                        'border border-dashed border-slate-300 dark:border-slate-800 text-center bg-white dark:bg-slate-900/50 qr-print-card',
                                        printTemplate === 'a4-1' ? 'w-full max-w-sm min-h-[300px] flex flex-col items-center justify-center p-6 rounded-2xl space-y-4' : 'p-4 rounded-xl space-y-3'
                                    ]"
                                >
                                    <div class="space-y-1 leading-none">
                                        <span class="text-[10px] font-extrabold uppercase tracking-widest text-[#8c5a3c] block">
                                            {{ t.outlet?.name || 'CafePOS' }}
                                        </span>
                                        <span :class="printTemplate === 'a4-1' ? 'text-2xl font-black text-slate-900 dark:text-slate-100 block mt-1' : 'text-xs font-black text-slate-800 dark:text-slate-100'">
                                            MEJA {{ t.number }}
                                        </span>
                                    </div>
                                    <div class="flex justify-center p-3 bg-slate-50 dark:bg-slate-950 rounded-xl border border-slate-100 dark:border-slate-800">
                                        <img :src="getQrCodeUrl(t)" alt="QR Code" :class="printTemplate === 'a4-1' ? 'h-40 w-40 object-contain' : 'h-28 w-28 object-contain'" />
                                    </div>
                                    <span class="text-[9px] font-bold text-slate-400 block leading-tight tracking-wider uppercase">
                                        SCAN UNTUK PESAN MANDIRI
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Modal Footer -->
                <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="isBulkQrModalOpen = 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="triggerPrint"
                        :disabled="tablesToPrint.length === 0"
                        class="px-4 py-2 bg-[#8c5a3c] hover:bg-[#734a31] disabled:opacity-50 text-white text-xs font-bold rounded-xl shadow-md cursor-pointer transition-all flex items-center gap-1.5"
                    >
                        <span>Cetak Sekarang</span>
                    </button>
                </div>
            </div>
        </div>

    </AdminLayout>

    <!-- Hidden printable container during normal screen display, visible during @media print -->
    <div id="bulk-qr-print-area">
        <div 
            :class="[
                printTemplate === 'a4-1' ? 'flex flex-col items-center w-full' : '',
                printTemplate === 'a4-3' ? 'grid grid-cols-3 gap-8 p-6' : '',
                printTemplate === 'thermal' ? 'flex flex-col items-center max-w-[72mm] mx-auto space-y-12' : ''
            ]"
        >
            <div 
                v-for="t in tablesToPrint" 
                :key="t.id" 
                :class="[
                    'border border-dashed border-slate-400 text-center bg-white text-black qr-print-card shadow-none',
                    printTemplate === 'a4-1' ? 'w-full min-h-[92vh] flex flex-col items-center justify-center p-12 my-auto' : 'p-6 rounded-2xl space-y-4'
                ]"
                :style="
                    printTemplate === 'a4-1' ? 'page-break-after: always; break-after: page; display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 92vh; margin: auto;' :
                    (printTemplate === 'thermal' ? 'page-break-after: always; break-after: page; width: 68mm; margin-bottom: 20px;' : '')
                "
            >
                <div class="space-y-2 leading-none text-center">
                    <span class="text-xs font-black uppercase tracking-widest text-[#8c5a3c] block">
                        {{ t.outlet?.name || 'CafePOS' }}
                    </span>
                    <span :class="printTemplate === 'a4-1' ? 'text-5xl font-black text-black tracking-tight block my-4' : 'text-base font-black text-black'">
                        MEJA {{ t.number }}
                    </span>
                </div>
                <div class="flex justify-center p-6 bg-slate-50 border border-slate-300 rounded-3xl my-4">
                    <img :src="getQrCodeUrl(t)" alt="QR Code" :class="printTemplate === 'a4-1' ? 'h-72 w-72 object-contain' : 'h-36 w-36 object-contain'" />
                </div>
                <span :class="printTemplate === 'a4-1' ? 'text-xs font-black text-slate-700 block leading-tight tracking-widest uppercase mt-4' : 'text-[9px] font-extrabold text-slate-500 block leading-tight'">
                    SCAN UNTUK PESAN MANDIRI (SELF-ORDER)
                </span>
            </div>
        </div>
    </div>
</template>

<style>
/* Hide printable area on screen display */
@media screen {
    #bulk-qr-print-area {
        display: none !important;
    }
}

/* Print Specific overrides */
@media print {
    /* Hide everything on print */
    body * {
        visibility: hidden !important;
    }
    /* Show only the printable bulk area */
    #bulk-qr-print-area, #bulk-qr-print-area * {
        visibility: visible !important;
    }
    #bulk-qr-print-area {
        display: block !important;
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        background: white !important;
        color: black !important;
        padding: 0 !important;
        margin: 0 !important;
    }
    
    .qr-print-card {
        page-break-inside: avoid;
        break-inside: avoid;
    }
}
</style>
