<script setup lang="ts">
import { ref, watch, computed, onMounted, onUnmounted } from 'vue';
import { Head, Link, router, usePage } from '@inertiajs/vue3';
import { Store, Clock, Play, Check, CheckCircle2, ChevronRight, RefreshCw, Sun, Moon, Maximize, Minimize, List, ClipboardList, History, LogOut, AlertTriangle, X } from 'lucide-vue-next';
import DemoModeBanner from '@/Components/DemoModeBanner.vue';

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

interface ItemModifier {
    id: number;
    modifier?: Modifier | null;
}

interface Transaction {
    id: number;
    transaction_number: string;
    order_type: 'dine_in' | 'take_away' | 'delivery';
    queue_number: string | null;
    table?: { id: number; number: string } | null;
    created_at: string;
}

interface TransactionItem {
    id: number;
    transaction_id: number;
    product_id: number;
    qty: number;
    variant: 'hot' | 'ice' | null;
    kitchen_status: 'pending' | 'cooking' | 'ready' | 'served';
    created_at: string;
    product?: { id: number; name: string } | null;
    modifiers: ItemModifier[];
    transaction?: Transaction | null;
}

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

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

const selectedOutletId = ref(props.filters.outlet_id || (props.outlets[0] ? String(props.outlets[0].id) : ''));
const activeTab = ref<'order' | 'item' | 'history'>('order');

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

const updateStatus = (item: TransactionItem, newStatus: string) => {
    router.post(route('kds.items.status', item.id), {
        status: newStatus,
    }, {
        preserveScroll: true,
        preserveState: true,
    });
};

const getStatusBadge = (status: string) => {
    switch (status) {
        case 'pending': return 'bg-rose-500/10 text-rose-600 dark:text-rose-400 border-rose-500/20';
        case 'cooking': return 'bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20';
        case 'ready': return 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20';
        default: return 'bg-slate-500/10 text-slate-600 dark:text-slate-400 border-slate-500/20';
    }
};

const getElapsedMinutes = (createdAtString: string) => {
    const created = new Date(createdAtString).getTime();
    const now = Date.now();
    const diff = Math.floor((now - created) / 60000);
    return diff > 0 ? `${diff}m ago` : 'just now';
};

// Filter active (cooking, ready, pending) vs served history
const activeItems = computed(() => {
    return props.items.filter(item => item.kitchen_status !== 'served');
});

const servedItems = computed(() => {
    return props.items
        .filter(item => item.kitchen_status === 'served')
        .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()); // Newest served first
});

// Group active items by order/transaction
const groupedTransactions = computed(() => {
    const txns: Record<number, {
        id: number;
        transaction_number: string;
        order_type: 'dine_in' | 'take_away' | 'delivery';
        queue_number: string | null;
        table_number: string | null;
        created_at: string;
        items: TransactionItem[];
    }> = {};

    for (const item of activeItems.value) {
        if (!item.transaction) continue;
        const tId = item.transaction_id;
        if (!txns[tId]) {
            txns[tId] = {
                id: tId,
                transaction_number: item.transaction.transaction_number,
                order_type: item.transaction.order_type,
                queue_number: item.transaction.queue_number,
                table_number: item.transaction.table?.number || null,
                created_at: item.transaction.created_at,
                items: [],
            };
        }
        txns[tId].items.push(item);
    }

    return Object.values(txns).sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
});

// Automatic poll/refresh interval to load new tickets
let intervalId: any = null;
const isDark = ref(false);
const isFullscreen = ref(false);

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

    intervalId = setInterval(() => {
        router.reload();
    }, 15000); // refresh every 15 seconds
});

onUnmounted(() => {
    if (intervalId) clearInterval(intervalId);
});

const forceRefresh = () => {
    router.reload();
};

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

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

const logout = () => {
    router.post(route('logout'));
};

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

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

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

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

<template>
    <Head title="KDS (Kitchen Display System)" />

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

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

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

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

        <DemoModeBanner />
        <!-- KDS Header Bar -->
        <header v-if="!isFullscreen" class="h-16 border-b border-slate-200 dark:border-slate-900 bg-white dark:bg-slate-950 px-6 flex items-center justify-between flex-shrink-0 z-10 shadow-sm transition-colors">
            <div class="flex items-center gap-3">
                <div class="h-8 w-8 rounded-lg bg-[#8c5a3c] flex items-center justify-center font-extrabold text-white text-base">
                    <span>K</span>
                </div>
                <div class="flex flex-col">
                    <span class="font-black text-sm tracking-widest uppercase leading-none text-slate-900 dark:text-white">CafePOS KDS</span>
                    <span class="text-[9px] text-slate-400 dark:text-slate-500 mt-1 leading-none">Kitchen Display System</span>
                </div>
            </div>

            <!-- Tab Navigation inside Header -->
            <div class="flex rounded-xl bg-slate-100 dark:bg-slate-900 p-1 border border-slate-200 dark:border-slate-800">
                <button
                    @click="activeTab = 'order'"
                    :class="[
                        'px-3.5 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer',
                        activeTab === 'order'
                            ? 'bg-[#8c5a3c] text-white shadow-sm'
                            : 'text-slate-500 dark:text-slate-400 hover:text-slate-800 dark:hover:text-slate-200'
                    ]"
                >
                    <ClipboardList class="h-3.5 w-3.5" />
                    <span>Tampilan Order</span>
                </button>
                <button
                    @click="activeTab = 'item'"
                    :class="[
                        'px-3.5 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer',
                        activeTab === 'item'
                            ? 'bg-[#8c5a3c] text-white shadow-sm'
                            : 'text-slate-500 dark:text-slate-400 hover:text-slate-800 dark:hover:text-slate-200'
                    ]"
                >
                    <List class="h-3.5 w-3.5" />
                    <span>Tampilan Item</span>
                </button>
                <button
                    @click="activeTab = 'history'"
                    :class="[
                        'px-3.5 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer',
                        activeTab === 'history'
                            ? 'bg-[#8c5a3c] text-white shadow-sm'
                            : 'text-slate-500 dark:text-slate-400 hover:text-slate-800 dark:hover:text-slate-200'
                    ]"
                >
                    <History class="h-3.5 w-3.5" />
                    <span>Riwayat Selesai</span>
                </button>
            </div>

            <!-- Outlet Selector & Actions -->
            <div class="flex items-center gap-3">
                <div class="flex items-center gap-2">
                    <span class="text-[10px] text-slate-400 dark:text-slate-550 font-bold uppercase tracking-wider">Outlet:</span>
                    <select
                        v-model="selectedOutletId"
                        class="h-8 px-2.5 border border-slate-200 dark:border-slate-800 rounded-lg bg-slate-50 dark:bg-slate-900 text-xs font-semibold focus:outline-none 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>
                <Link
                    :href="route('dashboard')"
                    class="h-8 px-3 rounded-lg border border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-900 flex items-center justify-center text-xs font-bold text-slate-750 dark:text-slate-300 hover:text-[#8c5a3c] dark:hover:text-white cursor-pointer transition-colors"
                >
                    Dashboard
                </Link>
                <button
                    @click="forceRefresh"
                    class="h-8 w-8 rounded-lg border border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-900 flex items-center justify-center text-slate-500 hover:text-slate-800 dark:text-slate-400 dark:hover:text-white cursor-pointer transition-colors"
                    title="Muat Ulang"
                >
                    <RefreshCw class="h-4 w-4" />
                </button>
                <!-- Theme Toggle Button -->
                <button
                    @click="toggleTheme"
                    class="h-8 w-8 rounded-lg border border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-900 flex items-center justify-center text-slate-555 dark:text-slate-400 cursor-pointer transition-colors"
                    title="Ganti Tema"
                >
                    <Sun v-if="isDark" class="h-4 w-4 text-amber-500" />
                    <Moon v-else class="h-4 w-4" />
                </button>
                <!-- Fullscreen Toggle Button -->
                <button
                    @click="toggleFullscreen"
                    class="h-8 w-8 rounded-lg border border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-900 flex items-center justify-center text-slate-555 dark:text-slate-400 cursor-pointer transition-colors"
                    title="Toggle Layar Penuh"
                >
                    <Minimize v-if="isFullscreen" class="h-4 w-4" />
                    <Maximize v-else class="h-4 w-4" />
                </button>
                <!-- Logout Button -->
                <button
                    @click="logout"
                    class="h-8 w-8 rounded-lg border border-rose-200 dark:border-rose-900/50 bg-rose-50 dark:bg-rose-950/30 flex items-center justify-center text-rose-500 hover:text-rose-700 dark:text-rose-400 dark:hover:text-rose-300 cursor-pointer transition-colors"
                    title="Logout"
                >
                    <LogOut class="h-4 w-4" />
                </button>
            </div>
        </header>

        <!-- Fullscreen Exit floating helper -->
        <div v-if="isFullscreen" class="fixed top-4 right-4 z-50 flex items-center gap-2">
            <button
                @click="toggleFullscreen"
                class="px-3 py-1.5 rounded-lg bg-slate-900/80 hover:bg-slate-950 text-white text-xs font-bold shadow-md flex items-center gap-1.5 cursor-pointer backdrop-blur-sm"
            >
                <Minimize class="h-3.5 w-3.5" />
                <span>Keluar Layar Penuh (Esc)</span>
            </button>
        </div>

        <!-- KDS Tickets Work Area -->
        <main class="flex-1 p-6 overflow-y-auto">
            
            <!-- 1. GROUPED ORDER VIEW TAB -->
            <div v-if="activeTab === 'order'">
                <div v-if="groupedTransactions.length > 0" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                    <div
                        v-for="txn in groupedTransactions"
                        :key="txn.id"
                        class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-sm overflow-hidden flex flex-col justify-between"
                    >
                        <!-- Card Header -->
                        <div class="px-4 py-3 bg-slate-50/80 dark:bg-slate-950 border-b border-slate-200 dark:border-slate-850 flex items-center justify-between">
                            <div class="flex flex-col">
                                <span class="text-xs font-black text-slate-900 dark:text-white">
                                    {{ txn.order_type === 'dine_in' ? txn.table_number : (txn.queue_number || 'Take Away') }}
                                </span>
                                <span class="text-[9px] text-slate-400 font-medium">#{{ txn.transaction_number.slice(-6) }}</span>
                            </div>
                            <div class="flex items-center gap-2">
                                <span class="text-[9px] font-extrabold uppercase px-1.5 py-0.5 rounded border border-slate-200 dark:border-slate-800 text-slate-500 bg-white dark:bg-slate-900">
                                    {{ txn.order_type === 'dine_in' ? 'DINE IN' : 'TAKE AWAY' }}
                                </span>
                                <span class="text-[9px] text-slate-400 font-bold flex items-center gap-1">
                                    <Clock class="h-3 w-3" />
                                    {{ getElapsedMinutes(txn.created_at) }}
                                </span>
                            </div>
                        </div>

                        <!-- Card Body (Items inside Order) -->
                        <div class="p-4 flex-1 divide-y divide-slate-100 dark:divide-slate-850 space-y-3">
                            <div v-for="item in txn.items" :key="item.id" class="pt-3 first:pt-0 flex flex-col justify-between gap-2.5">
                                <div class="flex items-start justify-between gap-3">
                                    <div class="flex-1">
                                        <div class="font-extrabold text-sm text-slate-800 dark:text-white leading-tight">
                                            {{ item.product?.name }}
                                        </div>
                                        <div v-if="item.variant" class="text-[9px] font-black uppercase text-[#8c5a3c] mt-0.5">
                                            {{ item.variant }}
                                        </div>
                                        <!-- Modifiers -->
                                        <div v-if="item.modifiers.length > 0" class="mt-1 space-y-0.5">
                                            <div v-for="m in item.modifiers" :key="m.id" class="text-[9px] font-bold text-slate-450 dark:text-slate-500 flex items-center gap-1">
                                                <span class="h-1 w-1 bg-amber-500 rounded-full"></span>
                                                <span>{{ m.modifier?.name }}</span>
                                            </div>
                                        </div>
                                    </div>
                                    <span class="text-sm font-black px-2 py-0.5 bg-slate-100 dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-lg">
                                        x{{ item.qty }}
                                    </span>
                                </div>

                                <!-- Action button for this item -->
                                <div class="flex items-center justify-between gap-3">
                                    <span :class="['px-2 py-0.5 border rounded-full text-[9px] font-black uppercase tracking-wider', getStatusBadge(item.kitchen_status)]">
                                        {{ item.kitchen_status }}
                                    </span>

                                    <button
                                        v-if="item.kitchen_status === 'pending'"
                                        @click="updateStatus(item, 'cooking')"
                                        class="px-3 py-1 bg-rose-600 hover:bg-rose-500 text-white rounded-lg text-[10px] font-bold cursor-pointer flex items-center gap-1"
                                    >
                                        <Play class="h-3 w-3 fill-current" />
                                        Mulai Masak
                                    </button>
                                    <button
                                        v-else-if="item.kitchen_status === 'cooking'"
                                        @click="updateStatus(item, 'ready')"
                                        class="px-3 py-1 bg-sky-600 hover:bg-sky-500 text-white rounded-lg text-[10px] font-bold cursor-pointer flex items-center gap-1"
                                    >
                                        <Check class="h-3 w-3" />
                                        Selesai Masak
                                    </button>
                                    <button
                                        v-else-if="item.kitchen_status === 'ready'"
                                        @click="updateStatus(item, 'served')"
                                        class="px-3 py-1 bg-emerald-600 hover:bg-emerald-500 text-white rounded-lg text-[10px] font-bold cursor-pointer flex items-center gap-1"
                                    >
                                        <CheckCircle2 class="h-3 w-3" />
                                        Sajikan
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div v-else class="h-[60vh] flex flex-col items-center justify-center text-center">
                    <CheckCircle2 class="h-12 w-12 text-slate-300 dark:text-slate-800 mb-3" />
                    <h3 class="text-base font-bold text-slate-450 dark:text-slate-500">Tidak ada antrean pesanan dapur</h3>
                    <p class="text-xs text-slate-400 mt-1">Dapur bersih! Semua hidangan telah disajikan.</p>
                </div>
            </div>

            <!-- 2. FLAT ITEM LIST VIEW TAB -->
            <div v-else-if="activeTab === 'item'">
                <div v-if="activeItems.length > 0" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6">
                    <div
                        v-for="item in activeItems"
                        :key="item.id"
                        class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800/80 rounded-2xl p-4 flex flex-col justify-between space-y-4 shadow-sm hover:border-slate-300 dark:hover:border-slate-700/80 transition-all relative overflow-hidden"
                    >
                        <div
                            class="absolute inset-y-0 left-0 w-1.5"
                            :class="[
                                item.kitchen_status === 'pending' ? 'bg-rose-500' : '',
                                item.kitchen_status === 'cooking' ? 'bg-sky-500' : '',
                                item.kitchen_status === 'ready' ? 'bg-emerald-500' : ''
                            ]"
                        />

                        <div class="pl-2 space-y-2">
                            <div class="flex items-center justify-between">
                                <span class="text-[10px] font-extrabold uppercase px-2 py-0.5 border border-slate-200 dark:border-slate-800 rounded-md text-slate-500 dark:text-slate-400 bg-slate-50 dark:bg-slate-950">
                                    {{ item.transaction?.order_type === 'dine_in' ? 'DINE IN' : 'TAKE AWAY' }}
                                </span>
                                <span class="text-[10px] text-slate-400 dark:text-slate-500 font-bold flex items-center gap-1">
                                    <Clock class="h-3 w-3" />
                                    {{ getElapsedMinutes(item.created_at) }}
                                </span>
                            </div>

                            <div class="flex items-baseline justify-between gap-1.5 pt-1">
                                <span class="text-sm font-black text-slate-900 dark:text-white">
                                    {{ item.transaction?.order_type === 'dine_in' ? item.transaction?.table?.number : (item.transaction?.queue_number || 'Take Away') }}
                                </span>
                                <span class="text-[9px] font-bold text-slate-450 dark:text-slate-500 truncate max-w-[100px]">
                                    #{{ item.transaction?.transaction_number.slice(-6) }}
                                </span>
                            </div>
                        </div>

                        <div class="pl-2 flex-1 space-y-2.5">
                            <div class="flex items-start justify-between gap-3">
                                <div class="flex-1 space-y-1">
                                    <div class="font-extrabold text-sm text-slate-800 dark:text-white leading-tight">
                                        {{ item.product?.name }}
                                    </div>
                                    <div v-if="item.variant" class="text-[9px] font-black uppercase tracking-wider text-[#8c5a3c]">
                                        {{ item.variant }}
                                    </div>
                                </div>
                                <div class="text-lg font-black text-slate-900 dark:text-white bg-slate-50 dark:bg-slate-955 px-2.5 py-0.5 border border-slate-200 dark:border-slate-800 rounded-lg">
                                    x{{ item.qty }}
                                </div>
                            </div>

                            <div v-if="item.modifiers.length > 0" class="space-y-1 pt-1.5 border-t border-slate-100 dark:border-slate-800/60">
                                <div class="text-[8px] font-bold uppercase tracking-wider text-slate-455">Add-ons:</div>
                                <ul class="space-y-0.5 pl-1.5">
                                    <li v-for="m in item.modifiers" :key="m.id" class="text-[10px] font-bold text-slate-550 dark:text-slate-400 flex items-center gap-1.5">
                                        <span class="h-1 w-1 bg-amber-500 rounded-full"></span>
                                        <span>{{ m.modifier?.name }}</span>
                                    </li>
                                </ul>
                            </div>
                        </div>

                        <div class="pl-2 pt-3 border-t border-slate-100 dark:border-slate-800/80">
                            <button
                                v-if="item.kitchen_status === 'pending'"
                                @click="updateStatus(item, 'cooking')"
                                class="w-full py-2 bg-rose-600 hover:bg-rose-500 text-white rounded-xl text-xs font-bold transition-colors cursor-pointer flex items-center justify-center gap-1.5 shadow-md shadow-rose-900/10"
                            >
                                <Play class="h-3.5 w-3.5 fill-current" />
                                Mulai Masak
                            </button>
                            <button
                                v-else-if="item.kitchen_status === 'cooking'"
                                @click="updateStatus(item, 'ready')"
                                class="w-full py-2 bg-sky-600 hover:bg-sky-500 text-white rounded-xl text-xs font-bold transition-colors cursor-pointer flex items-center justify-center gap-1.5 shadow-md shadow-sky-900/10"
                            >
                                <Check class="h-3.5 w-3.5" />
                                Selesai Masak
                            </button>
                            <button
                                v-else-if="item.kitchen_status === 'ready'"
                                @click="updateStatus(item, 'served')"
                                class="w-full py-2 bg-emerald-600 hover:bg-emerald-500 text-white rounded-xl text-xs font-bold transition-colors cursor-pointer flex items-center justify-center gap-1.5 shadow-md shadow-emerald-900/10"
                            >
                                <CheckCircle2 class="h-3.5 w-3.5" />
                                Sajikan Menu
                            </button>
                        </div>
                    </div>
                </div>
                <div v-else class="h-[60vh] flex flex-col items-center justify-center text-center">
                    <CheckCircle2 class="h-12 w-12 text-slate-300 dark:text-slate-800 mb-3" />
                    <h3 class="text-base font-bold text-slate-450 dark:text-slate-550">Tidak ada antrean pesanan dapur</h3>
                    <p class="text-xs text-slate-400 mt-1">Dapur bersih! Semua hidangan telah disajikan.</p>
                </div>
            </div>

            <!-- 3. COMPLETED HISTORY VIEW TAB -->
            <div v-else-if="activeTab === 'history'">
                <div v-if="servedItems.length > 0" class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-sm overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="w-full text-left border-collapse">
                            <thead>
                                <tr class="border-b border-slate-100 dark:border-slate-850 bg-slate-50/50 dark:bg-slate-950/50 text-[10px] font-bold text-slate-400 uppercase tracking-wider">
                                    <th class="px-6 py-3.5">No. Transaksi</th>
                                    <th class="px-6 py-3.5">Tipe / Meja / Antrean</th>
                                    <th class="px-6 py-3.5">Nama Menu</th>
                                    <th class="px-6 py-3.5 text-center">Qty</th>
                                    <th class="px-6 py-3.5">Add-ons</th>
                                    <th class="px-6 py-3.5">Selesai Pada</th>
                                    <th class="px-6 py-3.5 text-right">Tindakan</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 dark:divide-slate-850 text-xs">
                                <tr v-for="item in servedItems" :key="item.id" class="hover:bg-slate-50/50 dark:hover:bg-slate-950/20 font-semibold text-slate-700 dark:text-slate-300">
                                    <td class="px-6 py-4 text-slate-450">
                                        #{{ item.transaction?.transaction_number }}
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="flex items-center gap-1.5">
                                            <span class="text-[9px] font-extrabold uppercase px-1.5 py-0.5 rounded border border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-900 text-slate-555">
                                                {{ item.transaction?.order_type }}
                                            </span>
                                            <span class="font-bold text-slate-800 dark:text-white">
                                                {{ item.transaction?.order_type === 'dine_in' ? item.transaction?.table?.number : (item.transaction?.queue_number || 'Take Away') }}
                                            </span>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="font-bold text-slate-900 dark:text-white">{{ item.product?.name }}</div>
                                        <span v-if="item.variant" class="text-[9px] font-black uppercase text-[#8c5a3c]">{{ item.variant }}</span>
                                    </td>
                                    <td class="px-6 py-4 text-center font-extrabold text-slate-900 dark:text-white">
                                        x{{ item.qty }}
                                    </td>
                                    <td class="px-6 py-4">
                                        <span v-if="item.modifiers.length === 0" class="text-slate-400">-</span>
                                        <div v-else class="flex flex-wrap gap-1">
                                            <span
                                                v-for="m in item.modifiers"
                                                :key="m.id"
                                                class="px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-850 text-[9px] text-slate-500"
                                            >
                                                {{ m.modifier?.name }}
                                            </span>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 text-slate-400">
                                        {{ new Date(item.created_at).toLocaleString('id-ID', { hour: '2-digit', minute: '2-digit', second: '2-digit' }) }}
                                    </td>
                                    <td class="px-6 py-4 text-right">
                                        <button
                                            @click="updateStatus(item, 'ready')"
                                            class="px-2.5 py-1 border border-[#8c5a3c]/30 hover:bg-[#8c5a3c]/10 text-[#8c5a3c] rounded-lg text-[10px] font-bold cursor-pointer transition-colors"
                                            title="Kembalikan ke antrean dapur jika terjadi kesalahan"
                                        >
                                            Panggil Kembali
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div v-else class="h-[60vh] flex flex-col items-center justify-center text-center">
                    <CheckCircle2 class="h-12 w-12 text-slate-200 dark:text-slate-800 mb-3" />
                    <h3 class="text-base font-bold text-slate-400">Belum ada riwayat order disajikan</h3>
                    <p class="text-xs text-slate-655 mt-1">Gunakan tombol 'Sajikan Menu' pada tab antrean pesanan untuk melacak hari ini.</p>
                </div>
            </div>
        </main>
    </div>
</template>
