<script setup lang="ts">
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Head, router } from '@inertiajs/vue3';
import { ref, computed, onMounted } from 'vue';
import VueApexCharts from 'vue3-apexcharts';
import type { ApexOptions } from 'apexcharts';
import {
    TrendingUp, TrendingDown, Minus,
    ShoppingBag, ReceiptText, BarChart3, AlertTriangle,
    Store, Package, Truck, ArrowRight, CreditCard,
    Banknote, QrCode, RefreshCw, Clock, Filter, X
} from 'lucide-vue-next';

// ── Props ────────────────────────────────────────────────────────────────────
const props = defineProps<{
    kpi: {
        revenue_today: number;
        revenue_today_pct: number;
        revenue_week: number;
        revenue_month: number;
        tx_today: number;
        tx_today_pct: number;
        tx_month: number;
        avg_ticket_today: number;
        avg_ticket_pct: number;
        low_stock_count: number;
        active_outlets: number;
        active_products: number;
        total_suppliers: number;
    };
    salesTrend: { date: string; total: number; count: number }[];
    topProducts: { name: string; category: string; qty: number; sales: number }[];
    paymentSplit: { method: string; count: number; total: number }[];
    revenueByOutlet: { outlet: string; total: number; count: number }[];
    recentTransactions: {
        id: number;
        transaction_number: string;
        outlet_name: string;
        cashier_name: string;
        total_amount: number;
        payment_method: string;
        items_count: number;
        created_at: string;
    }[];
    lowStockAlerts: {
        type: string;
        name: string;
        outlet_name: string;
        stock_qty: number;
        threshold_qty: number;
        unit: string;
    }[];
    outlets: { id: number; name: string }[];
    filters: { month: string; outlet_id: number | null };
    appName: string;
}>();

// ── Filter state ─────────────────────────────────────────────────────────────
const filterMonth    = ref(props.filters.month);
const filterOutletId = ref(props.filters.outlet_id ? String(props.filters.outlet_id) : '');

const applyFilters = () => {
    router.get(
        route('dashboard'),
        {
            month:     filterMonth.value || undefined,
            outlet_id: filterOutletId.value || undefined,
        },
        { preserveScroll: true, replace: true }
    );
};

const resetFilters = () => {
    filterMonth.value    = new Date().toISOString().slice(0, 7);
    filterOutletId.value = '';
    applyFilters();
};

const hasActiveFilters = computed(() =>
    filterMonth.value !== new Date().toISOString().slice(0, 7) || filterOutletId.value !== ''
);

// ── Helpers ──────────────────────────────────────────────────────────────────
const formatCurrency = (val: number) =>
    'Rp ' + new Intl.NumberFormat('id-ID').format(Math.round(val));

const formatNumber = (val: number) =>
    new Intl.NumberFormat('id-ID').format(val);

const formatDate = (str: string) => {
    const d = new Date(str);
    return d.toLocaleDateString('id-ID', { day: '2-digit', month: 'short' });
};

const isDark = ref(document.documentElement.classList.contains('dark'));
const chartKey = ref(0);

// Watch for class changes on html element
onMounted(() => {
    const observer = new MutationObserver(() => {
        isDark.value = document.documentElement.classList.contains('dark');
    });
    observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
    
    // Force chart re-evaluation after initial paint resolves grid/flexbox sizing
    setTimeout(() => {
        chartKey.value++;
    }, 100);
});

const chartTextColor  = computed(() => isDark.value ? '#94a3b8' : '#64748b');
const chartGridColor  = computed(() => isDark.value ? '#1e293b' : '#f1f5f9');
const chartBgColor    = computed(() => isDark.value ? '#0f172a' : '#ffffff');

// ── Payment label helper ──────────────────────────────────────────────────
const paymentLabel = (method: string) => {
    const map: Record<string,string> = { cash: 'Cash', transfer: 'Transfer', qris: 'QRIS' };
    return map[method] ?? method;
};
const paymentIcon = (method: string) => {
    const map: Record<string, any> = { cash: Banknote, transfer: CreditCard, qris: QrCode };
    return map[method] ?? CreditCard;
};
const paymentColor = (method: string) => {
    const map: Record<string,string> = { cash: 'text-emerald-500', transfer: 'text-blue-500', qris: 'text-violet-500' };
    return map[method] ?? 'text-slate-400';
};
const paymentBg = (method: string) => {
    const map: Record<string,string> = { cash: 'bg-emerald-500/10', transfer: 'bg-blue-500/10', qris: 'bg-violet-500/10' };
    return map[method] ?? 'bg-slate-500/10';
};

// ── Chart: Sales Trend ────────────────────────────────────────────────────
const salesTrendOptions = computed((): ApexOptions => ({
    chart: {
        type: 'area' as const,
        height: '100%',
        background: 'transparent',
        toolbar: { show: false },
        sparkline: { enabled: false },
        animations: { enabled: true, speed: 800 },
    },
    dataLabels: { enabled: false },
    stroke: { curve: 'smooth' as const, width: 2.5 },
    fill: {
        type: 'gradient',
        gradient: {
            shadeIntensity: 1,
            opacityFrom: 0.35,
            opacityTo: 0.02,
            stops: [0, 100],
        },
    },
    colors: ['#8c5a3c'],
    xaxis: {
        categories: props.salesTrend.map(d => formatDate(d.date)),
        labels: { style: { colors: chartTextColor.value, fontSize: '11px' } },
        axisBorder: { show: false },
        axisTicks: { show: false },
    },
    yaxis: {
        labels: {
            style: { colors: chartTextColor.value, fontSize: '11px' },
            formatter: (val: number) => 'Rp ' + new Intl.NumberFormat('id-ID', { notation: 'compact', maximumFractionDigits: 1 }).format(val),
        },
    },
    grid: {
        borderColor: chartGridColor.value,
        strokeDashArray: 4,
        xaxis: { lines: { show: false } },
    },
    tooltip: {
        theme: (isDark.value ? 'dark' : 'light') as 'dark' | 'light',
        y: { formatter: (val: number) => formatCurrency(val) },
    },
}));

const salesTrendSeries = computed(() => [{
    name: 'Revenue',
    data: props.salesTrend.map(d => d.total),
}]);

// ── Chart: Payment Split Donut ────────────────────────────────────────────
const paymentDonutOptions = computed((): ApexOptions => ({
    chart: {
        type: 'donut' as const,
        background: 'transparent',
        animations: { enabled: true, speed: 800 },
    },
    labels: props.paymentSplit.map(p => paymentLabel(p.method)),
    colors: ['#10b981', '#3b82f6', '#8b5cf6'],
    dataLabels: { enabled: false },
    legend: {
        position: 'bottom' as const,
        labels: { colors: chartTextColor.value },
        fontSize: '12px',
    },
    plotOptions: {
        pie: {
            donut: {
                size: '68%',
                labels: {
                    show: true,
                    total: {
                        show: true,
                        label: 'Transactions',
                        color: chartTextColor.value,
                        formatter: (w: any) => formatNumber(w.globals.seriesTotals.reduce((a: number, b: number) => a + b, 0)),
                    },
                    value: { color: isDark.value ? '#f1f5f9' : '#0f172a', fontSize: '20px', fontWeight: '700' },
                },
            },
        },
    },
    stroke: { show: false },
    tooltip: {
        theme: (isDark.value ? 'dark' : 'light') as 'dark' | 'light',
        y: { formatter: (val: number) => `${val} transactions` },
    },
}));

const paymentDonutSeries = computed(() => props.paymentSplit.map(p => p.count));

// ── Chart: Top Products ───────────────────────────────────────────────────
const topProductsOptions = computed((): ApexOptions => ({
    chart: {
        type: 'bar' as const,
        background: 'transparent',
        toolbar: { show: false },
        animations: { enabled: true, speed: 800 },
    },
    plotOptions: {
        bar: {
            horizontal: true,
            borderRadius: 6,
            barHeight: '55%',
            distributed: true,
        },
    },
    colors: ['#8c5a3c', '#a17050', '#b48057', '#c79b7b', '#ebd5c5'],
    dataLabels: { enabled: false },
    xaxis: {
        labels: {
            style: { colors: chartTextColor.value, fontSize: '11px' },
            formatter: (val: number) => formatNumber(val) + ' pcs',
        },
        axisBorder: { show: false },
        axisTicks: { show: false },
    },
    yaxis: {
        labels: {
            style: { colors: isDark.value ? '#f1f5f9' : '#0f172a', fontSize: '12px', fontWeight: '600' },
        },
    },
    grid: { borderColor: chartGridColor.value, strokeDashArray: 4 },
    legend: { show: false },
    tooltip: {
        theme: (isDark.value ? 'dark' : 'light') as 'dark' | 'light',
        y: { formatter: (val: number) => `${formatNumber(val)} sold` },
    },
}));

const topProductsSeries = computed(() => [{
    name: 'Qty Sold',
    data: props.topProducts.map(p => ({ x: p.name, y: p.qty })),
}]);

// ── Chart: Revenue by Outlet ──────────────────────────────────────────────
const outletRevenueOptions = computed((): ApexOptions => ({
    chart: {
        type: 'bar' as const,
        background: 'transparent',
        toolbar: { show: false },
        animations: { enabled: true, speed: 800 },
    },
    plotOptions: {
        bar: { borderRadius: 6, columnWidth: '45%', distributed: true },
    },
    colors: ['#8c5a3c', '#f59e0b', '#3b82f6', '#10b981', '#8b5cf6'],
    dataLabels: { enabled: false },
    xaxis: {
        categories: props.revenueByOutlet.map(o => o.outlet),
        labels: { style: { colors: chartTextColor.value, fontSize: '11px' } },
        axisBorder: { show: false },
        axisTicks: { show: false },
    },
    yaxis: {
        labels: {
            style: { colors: chartTextColor.value, fontSize: '11px' },
            formatter: (val: number) => 'Rp ' + new Intl.NumberFormat('id-ID', { notation: 'compact', maximumFractionDigits: 1 }).format(val),
        },
    },
    grid: { borderColor: chartGridColor.value, strokeDashArray: 4 },
    legend: { show: false },
    tooltip: {
        theme: (isDark.value ? 'dark' : 'light') as 'dark' | 'light',
        y: { formatter: (val: number) => formatCurrency(val) },
    },
}));

const outletRevenueSeries = computed(() => [{
    name: 'Revenue',
    data: props.revenueByOutlet.map(o => o.total),
}]);

// ── Trend badge ───────────────────────────────────────────────────────────
const trendClass = (pct: number) => pct > 0 ? 'text-emerald-500' : pct < 0 ? 'text-rose-500' : 'text-slate-400';
const trendBg    = (pct: number) => pct > 0 ? 'bg-emerald-500/10' : pct < 0 ? 'bg-rose-500/10' : 'bg-slate-500/10';
const trendIcon  = (pct: number) => pct > 0 ? TrendingUp : pct < 0 ? TrendingDown : Minus;

// ── Stock level pct ───────────────────────────────────────────────────────
const stockPct = (item: { stock_qty: number; threshold_qty: number }) => {
    if (item.threshold_qty <= 0) return 0;
    return Math.min(100, Math.round((item.stock_qty / item.threshold_qty) * 100));
};

const nowStr = ref(new Date().toLocaleString('id-ID', { dateStyle: 'long', timeStyle: 'short' }));

const refresh = () => router.reload();
</script>

<template>
    <Head title="Dashboard" />

    <AdminLayout>
        <!-- ── Header ───────────────────────────────────────────────────── -->
        <div class="mb-6">
            <!-- Title + Refresh row -->
            <div class="flex flex-col sm:flex-row sm:items-start justify-between gap-3 mb-4">
                <div>
                    <h1 class="text-2xl font-extrabold text-slate-900 dark:text-slate-50 tracking-tight">
                        Business Overview
                    </h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-0.5 flex items-center gap-1.5">
                        <Clock class="h-3.5 w-3.5" />
                        {{ nowStr }}
                    </p>
                </div>
            <div class="flex items-center gap-2 self-start flex-shrink-0">
                <button
                    @click="refresh"
                    class="flex items-center gap-2 px-4 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-300 text-sm font-semibold transition-all cursor-pointer border-0 flex-shrink-0"
                >
                    <RefreshCw class="h-4 w-4" />
                    Refresh
                </button>
            </div>
            </div>

            <!-- Premium Filter Bar -->
            <div class="flex flex-wrap items-center gap-3 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl px-4 py-3 shadow-sm">
                <!-- Icon + Label -->
                <div class="flex items-center gap-2 pr-3 border-r border-slate-200 dark:border-slate-700 flex-shrink-0">
                    <div class="p-1.5 rounded-lg bg-red-500/10">
                        <Filter class="h-3.5 w-3.5 text-red-500" />
                    </div>
                    <span class="text-xs font-bold text-slate-700 dark:text-slate-300 uppercase tracking-wider">Filter</span>
                </div>

                <!-- Month -->
                <div class="flex items-center gap-2">
                    <span class="text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-wide flex-shrink-0">Bulan</span>
                    <input
                        type="month"
                        v-model="filterMonth"
                        @change="applyFilters"
                        class="h-8 px-2.5 text-xs font-semibold border border-slate-200 dark:border-slate-700 rounded-lg bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all cursor-pointer"
                    />
                </div>

                <!-- Divider -->
                <div class="h-5 w-px bg-slate-200 dark:bg-slate-700 flex-shrink-0"></div>

                <!-- Outlet -->
                <div class="flex items-center gap-2">
                    <span class="text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-wide flex-shrink-0">Outlet</span>
                    <select
                        v-model="filterOutletId"
                        @change="applyFilters"
                        class="h-8 px-2.5 pr-7 text-xs font-semibold border border-slate-200 dark:border-slate-700 rounded-lg bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all cursor-pointer appearance-none"
                    >
                        <option value="">Semua Outlet</option>
                        <option v-for="o in outlets" :key="o.id" :value="String(o.id)">{{ o.name }}</option>
                    </select>
                </div>

                <!-- Active badge + Reset -->
                <div class="flex items-center gap-2 ml-auto">
                    <!-- Active info chip -->
                    <div class="hidden sm:flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-slate-100 dark:bg-slate-800 text-xs font-semibold text-slate-600 dark:text-slate-300">
                        <span class="text-slate-400">📅</span>
                        {{ new Date(filterMonth + '-01').toLocaleDateString('id-ID', { month: 'short', year: 'numeric' }) }}
                        <template v-if="filterOutletId">
                            <span class="text-slate-300 dark:text-slate-600">·</span>
                            <span>{{ outlets.find(o => String(o.id) === filterOutletId)?.name }}</span>
                        </template>
                    </div>

                    <!-- Reset button -->
                    <transition name="fade">
                        <button
                            v-if="hasActiveFilters"
                            @click="resetFilters"
                            class="flex items-center gap-1 h-8 px-3 text-xs font-bold rounded-lg text-rose-600 dark:text-rose-400 bg-rose-50 dark:bg-rose-500/10 hover:bg-rose-100 dark:hover:bg-rose-500/20 transition-colors cursor-pointer border-0 flex-shrink-0"
                        >
                            <X class="h-3 w-3" />
                            Reset
                        </button>
                    </transition>
                </div>
            </div>
        </div>

        <!-- ── KPI Cards Row ────────────────────────────────────────────── -->
        <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4 mb-6">
            <!-- Revenue Today -->
            <div class="relative overflow-hidden bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 shadow-sm group hover:shadow-md transition-shadow">
                <div class="absolute inset-x-0 top-0 h-0.5 bg-gradient-to-r from-rose-500 via-red-500 to-orange-400 rounded-t-2xl" />
                <div class="flex items-start justify-between mb-3">
                    <div class="p-2.5 rounded-xl bg-rose-500/10">
                        <ShoppingBag class="h-5 w-5 text-rose-500" />
                    </div>
                    <span :class="['flex items-center gap-1 text-xs font-bold px-2 py-1 rounded-lg', trendBg(kpi.revenue_today_pct), trendClass(kpi.revenue_today_pct)]">
                        <component :is="trendIcon(kpi.revenue_today_pct)" class="h-3.5 w-3.5" />
                        {{ Math.abs(kpi.revenue_today_pct) }}%
                    </span>
                </div>
                <div class="text-2xl font-black text-slate-900 dark:text-slate-50 tracking-tight">
                    {{ formatCurrency(kpi.revenue_today) }}
                </div>
                <div class="text-xs font-semibold text-slate-500 dark:text-slate-400 mt-1">Revenue Today</div>
                <div class="text-xs text-slate-400 mt-0.5">vs yesterday</div>
            </div>

            <!-- Transactions Today -->
            <div class="relative overflow-hidden bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 shadow-sm group hover:shadow-md transition-shadow">
                <div class="absolute inset-x-0 top-0 h-0.5 bg-gradient-to-r from-blue-500 to-cyan-400 rounded-t-2xl" />
                <div class="flex items-start justify-between mb-3">
                    <div class="p-2.5 rounded-xl bg-blue-500/10">
                        <ReceiptText class="h-5 w-5 text-blue-500" />
                    </div>
                    <span :class="['flex items-center gap-1 text-xs font-bold px-2 py-1 rounded-lg', trendBg(kpi.tx_today_pct), trendClass(kpi.tx_today_pct)]">
                        <component :is="trendIcon(kpi.tx_today_pct)" class="h-3.5 w-3.5" />
                        {{ Math.abs(kpi.tx_today_pct) }}%
                    </span>
                </div>
                <div class="text-2xl font-black text-slate-900 dark:text-slate-50 tracking-tight">
                    {{ formatNumber(kpi.tx_today) }}
                </div>
                <div class="text-xs font-semibold text-slate-500 dark:text-slate-400 mt-1">Transactions Today</div>
                <div class="text-xs text-slate-400 mt-0.5">{{ formatNumber(kpi.tx_month) }} this month</div>
            </div>

            <!-- Avg Ticket -->
            <div class="relative overflow-hidden bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 shadow-sm group hover:shadow-md transition-shadow">
                <div class="absolute inset-x-0 top-0 h-0.5 bg-gradient-to-r from-violet-500 to-purple-400 rounded-t-2xl" />
                <div class="flex items-start justify-between mb-3">
                    <div class="p-2.5 rounded-xl bg-violet-500/10">
                        <BarChart3 class="h-5 w-5 text-violet-500" />
                    </div>
                    <span :class="['flex items-center gap-1 text-xs font-bold px-2 py-1 rounded-lg', trendBg(kpi.avg_ticket_pct), trendClass(kpi.avg_ticket_pct)]">
                        <component :is="trendIcon(kpi.avg_ticket_pct)" class="h-3.5 w-3.5" />
                        {{ Math.abs(kpi.avg_ticket_pct) }}%
                    </span>
                </div>
                <div class="text-2xl font-black text-slate-900 dark:text-slate-50 tracking-tight">
                    {{ formatCurrency(kpi.avg_ticket_today) }}
                </div>
                <div class="text-xs font-semibold text-slate-500 dark:text-slate-400 mt-1">Avg. Ticket Today</div>
                <div class="text-xs text-slate-400 mt-0.5">per transaction</div>
            </div>

            <!-- Low Stock Alert -->
            <div class="relative overflow-hidden bg-white dark:bg-slate-900 border rounded-2xl p-5 shadow-sm group hover:shadow-md transition-shadow"
                 :class="kpi.low_stock_count > 0 ? 'border-rose-300 dark:border-rose-900' : 'border-slate-200 dark:border-slate-800'">
                <div class="absolute inset-x-0 top-0 h-0.5 rounded-t-2xl"
                     :class="kpi.low_stock_count > 0 ? 'bg-gradient-to-r from-rose-500 to-orange-400' : 'bg-gradient-to-r from-emerald-500 to-teal-400'" />
                <div class="flex items-start justify-between mb-3">
                    <div class="p-2.5 rounded-xl" :class="kpi.low_stock_count > 0 ? 'bg-rose-500/10' : 'bg-emerald-500/10'">
                        <AlertTriangle class="h-5 w-5" :class="kpi.low_stock_count > 0 ? 'text-rose-500' : 'text-emerald-500'" />
                    </div>
                    <span v-if="kpi.low_stock_count > 0" class="flex items-center gap-1 text-xs font-bold px-2 py-1 rounded-lg bg-rose-500/10 text-rose-500 animate-pulse">
                        Critical
                    </span>
                    <span v-else class="flex items-center gap-1 text-xs font-bold px-2 py-1 rounded-lg bg-emerald-500/10 text-emerald-500">
                        All Good
                    </span>
                </div>
                <div class="text-2xl font-black tracking-tight" :class="kpi.low_stock_count > 0 ? 'text-rose-500' : 'text-slate-900 dark:text-slate-50'">
                    {{ formatNumber(kpi.low_stock_count) }}
                </div>
                <div class="text-xs font-semibold text-slate-500 dark:text-slate-400 mt-1">Low Stock Alerts</div>
                <div class="text-xs text-slate-400 mt-0.5">items at or below threshold</div>
            </div>
        </div>

        <!-- ── Secondary Stats Row ──────────────────────────────────────── -->
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6">
            <div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 shadow-sm flex items-center gap-4">
                <div class="p-3 rounded-xl bg-amber-500/10 flex-shrink-0">
                    <ShoppingBag class="h-6 w-6 text-amber-500" />
                </div>
                <div>
                    <div class="text-xl font-black text-slate-900 dark:text-slate-50">{{ formatCurrency(kpi.revenue_month) }}</div>
                    <div class="text-xs font-semibold text-slate-500 dark:text-slate-400">Revenue This Month</div>
                    <div class="text-xs text-slate-400">{{ formatCurrency(kpi.revenue_week) }} this week</div>
                </div>
            </div>
            <div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 shadow-sm flex items-center gap-4">
                <div class="p-3 rounded-xl bg-sky-500/10 flex-shrink-0">
                    <Store class="h-6 w-6 text-sky-500" />
                </div>
                <div>
                    <div class="text-xl font-black text-slate-900 dark:text-slate-50">{{ kpi.active_outlets }}</div>
                    <div class="text-xs font-semibold text-slate-500 dark:text-slate-400">Active Outlets</div>
                    <div class="text-xs text-slate-400">{{ kpi.active_products }} active products</div>
                </div>
            </div>
            <div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 shadow-sm flex items-center gap-4">
                <div class="p-3 rounded-xl bg-indigo-500/10 flex-shrink-0">
                    <Truck class="h-6 w-6 text-indigo-500" />
                </div>
                <div>
                    <div class="text-xl font-black text-slate-900 dark:text-slate-50">{{ kpi.total_suppliers }}</div>
                    <div class="text-xs font-semibold text-slate-500 dark:text-slate-400">Registered Suppliers</div>
                    <div class="text-xs text-slate-400">across all outlets</div>
                </div>
            </div>
        </div>

        <!-- ── Charts Row 1: Trend + Donut ─────────────────────────────── -->
        <div class="grid grid-cols-1 xl:grid-cols-3 gap-4 mb-6 items-stretch">
            <!-- Sales Trend -->
            <div class="xl:col-span-2 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 shadow-sm flex flex-col">
                <div class="flex items-center justify-between mb-1 flex-shrink-0">
                    <h2 class="text-sm font-bold text-slate-900 dark:text-slate-50">Sales Trend</h2>
                    <span class="text-xs text-slate-400 font-medium">{{ new Date(filterMonth + '-01').toLocaleDateString('id-ID', { month: 'long', year: 'numeric' }) }}</span>
                </div>
                <div v-if="salesTrend.length > 0" class="flex-1 w-full min-h-[280px]">
                    <VueApexCharts
                        :key="chartKey"
                        type="area"
                        height="100%"
                        :options="salesTrendOptions"
                        :series="salesTrendSeries"
                    />
                </div>
                <div v-else class="flex-1 flex items-center justify-center text-slate-400 text-sm italic min-h-[200px]">
                    No sales data in this period.
                </div>
            </div>

            <!-- Payment Split Donut -->
            <div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 shadow-sm">
                <div class="flex items-center justify-between mb-1">
                    <h2 class="text-sm font-bold text-slate-900 dark:text-slate-50">Payment Methods</h2>
                    <span class="text-xs text-slate-400 font-medium">This month</span>
                </div>
                <p class="text-xs text-slate-500 dark:text-slate-400 mb-2">Transaction split by method</p>
                <div v-if="paymentSplit.length > 0">
                    <VueApexCharts
                        type="donut"
                        height="220"
                        :options="paymentDonutOptions"
                        :series="paymentDonutSeries"
                    />
                    <!-- Legend detail -->
                    <div class="mt-2 space-y-2">
                        <div v-for="p in paymentSplit" :key="p.method" class="flex items-center justify-between text-xs">
                            <div class="flex items-center gap-2">
                                <div :class="['p-1.5 rounded-md', paymentBg(p.method)]">
                                    <component :is="paymentIcon(p.method)" :class="['h-3 w-3', paymentColor(p.method)]" />
                                </div>
                                <span class="font-semibold text-slate-700 dark:text-slate-300">{{ paymentLabel(p.method) }}</span>
                            </div>
                            <div class="text-right">
                                <div class="font-bold text-slate-900 dark:text-slate-100">{{ formatCurrency(p.total) }}</div>
                                <div class="text-slate-400">{{ p.count }} txn</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div v-else class="h-52 flex items-center justify-center text-slate-400 text-sm italic">
                    No transactions this month.
                </div>
            </div>
        </div>

        <!-- ── Charts Row 2: Top Products + Outlet Revenue ─────────────── -->
        <div class="grid grid-cols-1 xl:grid-cols-2 gap-4 mb-6">
            <!-- Top Products -->
            <div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 shadow-sm">
                <div class="flex items-center justify-between mb-1">
                    <h2 class="text-sm font-bold text-slate-900 dark:text-slate-50">Top 5 Products</h2>
                    <span class="text-xs text-slate-400 font-medium">This month</span>
                </div>
                <p class="text-xs text-slate-500 dark:text-slate-400 mb-3">By quantity sold</p>
                <div v-if="topProducts.length > 0">
                    <VueApexCharts
                        type="bar"
                        height="220"
                        :options="topProductsOptions"
                        :series="topProductsSeries"
                    />
                </div>
                <div v-else class="h-52 flex items-center justify-center text-slate-400 text-sm italic">
                    No product sales data.
                </div>
            </div>

            <!-- Revenue by Outlet -->
            <div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 shadow-sm">
                <div class="flex items-center justify-between mb-1">
                    <h2 class="text-sm font-bold text-slate-900 dark:text-slate-50">Revenue by Outlet</h2>
                    <span class="text-xs text-slate-400 font-medium">This month</span>
                </div>
                <p class="text-xs text-slate-500 dark:text-slate-400 mb-3">Contribution per location</p>
                <div v-if="revenueByOutlet.length > 0">
                    <VueApexCharts
                        type="bar"
                        height="220"
                        :options="outletRevenueOptions"
                        :series="outletRevenueSeries"
                    />
                </div>
                <div v-else class="h-52 flex items-center justify-center text-slate-400 text-sm italic">
                    No outlet revenue data.
                </div>
            </div>
        </div>

        <!-- ── Bottom Row: Recent Txns + Low Stock ──────────────────────── -->
        <div class="grid grid-cols-1 xl:grid-cols-2 gap-4 mb-4">
            <!-- Recent Transactions -->
            <div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-sm overflow-hidden">
                <div class="px-5 py-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between">
                    <div>
                        <h2 class="text-sm font-bold text-slate-900 dark:text-slate-50">Recent Transactions</h2>
                        <p class="text-xs text-slate-400 mt-0.5">Last 8 successful orders</p>
                    </div>
                    <a href="/admin/transactions" class="flex items-center gap-1 text-xs font-semibold text-rose-500 hover:text-rose-600 transition-colors">
                        View All <ArrowRight class="h-3.5 w-3.5" />
                    </a>
                </div>
                <div v-if="recentTransactions.length > 0" class="divide-y divide-slate-100 dark:divide-slate-800">
                    <div
                        v-for="tx in recentTransactions"
                        :key="tx.id"
                        class="flex items-center gap-3 px-5 py-3 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors"
                    >
                        <div class="flex-shrink-0">
                            <div :class="['p-2 rounded-lg', paymentBg(tx.payment_method)]">
                                <component :is="paymentIcon(tx.payment_method)" :class="['h-3.5 w-3.5', paymentColor(tx.payment_method)]" />
                            </div>
                        </div>
                        <div class="flex-1 min-w-0">
                            <div class="text-xs font-bold text-slate-900 dark:text-slate-100 truncate">
                                {{ tx.transaction_number }}
                            </div>
                            <div class="text-xs text-slate-400 truncate">
                                {{ tx.outlet_name }} · {{ tx.items_count }} item(s) · {{ tx.cashier_name }}
                            </div>
                        </div>
                        <div class="text-right flex-shrink-0">
                            <div class="text-xs font-bold text-slate-900 dark:text-slate-100">
                                {{ formatCurrency(tx.total_amount) }}
                            </div>
                            <div class="text-xs text-slate-400">{{ tx.created_at }}</div>
                        </div>
                    </div>
                </div>
                <div v-else class="p-8 text-center text-slate-400 text-sm italic">
                    No transactions yet.
                </div>
            </div>

            <!-- Low Stock Alerts -->
            <div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-sm overflow-hidden">
                <div class="px-5 py-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between">
                    <div>
                        <h2 class="text-sm font-bold text-slate-900 dark:text-slate-50 flex items-center gap-2">
                            Low Stock Alerts
                            <span v-if="lowStockAlerts.length > 0" class="inline-flex items-center px-1.5 py-0.5 rounded-full bg-rose-500 text-white text-xs font-bold">
                                {{ lowStockAlerts.length }}
                            </span>
                        </h2>
                        <p class="text-xs text-slate-400 mt-0.5">Items at or below safety threshold</p>
                    </div>
                    <a href="/admin/ingredients" class="flex items-center gap-1 text-xs font-semibold text-rose-500 hover:text-rose-600 transition-colors">
                        Manage <ArrowRight class="h-3.5 w-3.5" />
                    </a>
                </div>
                <div v-if="lowStockAlerts.length > 0" class="divide-y divide-slate-100 dark:divide-slate-800 max-h-80 overflow-y-auto">
                    <div
                        v-for="(item, idx) in lowStockAlerts"
                        :key="idx"
                        class="px-5 py-3 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors"
                    >
                        <div class="flex items-center justify-between mb-1.5">
                            <div class="flex items-center gap-2 min-w-0">
                                <span :class="['text-xs font-bold px-1.5 py-0.5 rounded-md flex-shrink-0', item.type === 'Ingredient' ? 'bg-amber-500/10 text-amber-600 dark:text-amber-400' : 'bg-sky-500/10 text-sky-600 dark:text-sky-400']">
                                    {{ item.type === 'Ingredient' ? 'ING' : 'RTL' }}
                                </span>
                                <span class="text-xs font-bold text-slate-900 dark:text-slate-100 truncate">{{ item.name }}</span>
                            </div>
                            <span class="text-xs text-slate-400 flex-shrink-0 ml-2">{{ item.outlet_name }}</span>
                        </div>
                        <div class="flex items-center gap-2">
                            <div class="flex-1 bg-slate-200 dark:bg-slate-700 rounded-full h-1.5 overflow-hidden">
                                <div
                                    class="h-full rounded-full transition-all"
                                    :class="stockPct(item) <= 30 ? 'bg-rose-500' : stockPct(item) <= 70 ? 'bg-amber-500' : 'bg-emerald-500'"
                                    :style="{ width: stockPct(item) + '%' }"
                                />
                            </div>
                            <span class="text-xs font-semibold text-slate-500 dark:text-slate-400 flex-shrink-0 w-28 text-right">
                                {{ item.stock_qty }} / {{ item.threshold_qty }} {{ item.unit }}
                            </span>
                        </div>
                    </div>
                </div>
                <div v-else class="p-8 text-center">
                    <div class="inline-flex items-center justify-center p-3 rounded-full bg-emerald-500/10 mb-3">
                        <Package class="h-6 w-6 text-emerald-500" />
                    </div>
                    <p class="text-sm font-semibold text-slate-700 dark:text-slate-300">All stock levels are healthy</p>
                    <p class="text-xs text-slate-400 mt-1">No items are below their safety threshold.</p>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>

<style scoped>
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.2s ease, transform 0.2s ease;
}
.fade-enter-from,
.fade-leave-to {
    opacity: 0;
    transform: scale(0.95);
}
</style>
