<!DOCTYPE html>
<html lang="en">
    <head>
        <!--
      PaceEvents – Premium Analytics Dashboard

      Tech stack:
      - Tailwind CSS via CDN (utility-first, minimal bloat when used intentionally)
      - Chart.js for professional data visualizations
      - Inter variable font for refined, legible typography

      Design goals implemented here:
      - Clean layout, generous spacing, premium typography
      - Responsive across mobile, tablet, desktop
      - Subtle animations and micro-interactions
      - Cohesive color system, high contrast, accessible components
      - Performance-conscious: minimal dependencies, deferred scripts, reduced motion support
    -->

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>PaceEvents • Analytics Dashboard</title>

        <!-- Inter variable font -->
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
        <link
            href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap"
            rel="stylesheet"
        />

        <!-- Tailwind CSS CDN with custom theme config -->
        <script src="https://cdn.tailwindcss.com"></script>
        <script>
            tailwind.config = {
                theme: {
                    extend: {
                        fontFamily: {
                            sans: [
                                "Inter",
                                "system-ui",
                                "-apple-system",
                                "Segoe UI",
                                "Roboto",
                                "Ubuntu",
                                "Cantarell",
                                "Noto Sans",
                                "sans-serif",
                            ],
                        },
                        colors: {
                            brand: {
                                50: "#FFF1F2",
                                100: "#FFE4E6",
                                200: "#FECDD3",
                                300: "#FDA4AF",
                                400: "#FB7185",
                                500: "#F43F5E",
                                600: "#E30613",
                                700: "#C50F1A",
                                800: "#9F0B14",
                                900: "#7A0810",
                            },
                            secondary: {
                                50: "#FFFBEB",
                                100: "#FEF3C7",
                                200: "#FDE68A",
                                300: "#FCD34D",
                                400: "#FBBF24",
                                500: "#F5B300",
                                600: "#E29E00",
                                700: "#C58700",
                                800: "#A16E00",
                                900: "#7A5200",
                            },
                            accent: {
                                500: "#B00020",
                                600: "#8C0019",
                            },
                        },
                        boxShadow: {
                            soft: "0 10px 25px -10px rgba(17,24,39,0.15)",
                        },
                    },
                },
                darkMode: "class",
            };
        </script>

        <!-- Base styles for premium feel and reduced motion support -->
        <style>
            /* Smooth font rendering */
            html {
                -webkit-font-smoothing: antialiased;
                -moz-osx-font-smoothing: grayscale;
            }
            /* Respect reduced motion */
            @media (prefers-reduced-motion: reduce) {
                * {
                    animation-duration: 0.01ms !important;
                    animation-iteration-count: 1 !important;
                    transition-duration: 0.01ms !important;
                    scroll-behavior: auto !important;
                }
            }
            .theme-select {
                appearance: none;
                background-color: #fff;
                background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="%23E30613"><path d="M7 10l5 5 5-5"/></svg>');
                background-repeat: no-repeat;
                background-position: right 0.5rem center;
                padding-right: 2rem;
                border-color: #cbd5e1;
                transition: box-shadow 0.2s, border-color 0.2s;
            }
            .theme-select:focus {
                outline: none;
                box-shadow: 0 0 0 2px rgba(227, 6, 19, 0.25);
                border-color: #e30613;
            }
            .theme-select:hover {
                border-color: #94a3b8;
            }
            .theme-select[multiple] {
                background-image: none;
                min-height: 2.5rem;
                padding-top: 0.375rem;
                padding-bottom: 0.375rem;
            }
            .theme-select option {
                padding: 0.25rem 0.5rem;
            }
            .dt-sort {
                display: inline-flex;
                align-items: center;
                gap: 0.25rem;
                color: #334155;
            }
            .dt-sort:hover {
                color: #e30613;
            }
            .dt-sort[aria-sort="ascending"]::after {
                content: "▲";
                font-size: 0.65rem;
                color: #e30613;
            }
            .dt-sort[aria-sort="descending"]::after {
                content: "▼";
                font-size: 0.65rem;
                color: #e30613;
            }

            /* ===== MOBILE-SPECIFIC STYLES ===== */
            
            /* Mobile sidebar overlay backdrop */
            #sidebar-backdrop {
                position: fixed;
                inset: 0;
                background-color: rgba(15, 23, 42, 0.5);
                z-index: 35;
                opacity: 0;
                pointer-events: none;
                transition: opacity 0.3s ease;
            }
            #sidebar-backdrop.active {
                opacity: 1;
                pointer-events: auto;
            }

            /* Touch-friendly tap states */
            @media (hover: none) and (pointer: coarse) {
                button:active, a:active, .hover\:bg-slate-100:active {
                    opacity: 0.7;
                    transform: scale(0.98);
                }
            }

            /* Mobile optimizations for screens < 640px */
            @media (max-width: 640px) {
                /* Larger base font for better mobile readability */
                html {
                    font-size: 16px;
                }

                /* Hide desktop-only elements on mobile */
                .hidden-mobile {
                    display: none !important;
                }

                /* Optimize header spacing */
                header {
                    padding-left: 1rem !important;
                    padding-right: 1rem !important;
                }

                /* Reduce card padding on mobile */
                main > section > div[class*="p-5"],
                main > section[class*="p-5"] {
                    padding: 1rem !important;
                }

                /* Make KPI cards more compact */
                [data-kpi-card] {
                    padding: 1rem !important;
                }
                [data-kpi-card] .text-2xl {
                    font-size: 1.5rem !important;
                }

                /* Optimize chart containers */
                canvas {
                    max-height: 200px !important;
                }

                /* Stack filter controls vertically */
                .grid.grid-cols-1.lg\:grid-cols-12 {
                    display: flex !important;
                    flex-direction: column !important;
                    gap: 0.5rem !important;
                }

                /* Full width inputs on mobile */
                input[type="text"],
                select {
                    width: 100% !important;
                    font-size: 16px !important; /* Prevent zoom on iOS */
                }

                /* Mobile search optimization */
                header .relative {
                    width: 100% !important;
                }

                /* Make buttons full width in mobile filters */
                #dt-clear, #dt-reload {
                    flex: 1;
                }

                /* Optimize export buttons for mobile */
                #dt-export-csv, #dt-export-xls, #dt-export-pdf {
                    font-size: 0.75rem;
                    padding-left: 0.5rem;
                    padding-right: 0.5rem;
                }

                /* Period buttons should scroll horizontally */
                .period-btn {
                    white-space: nowrap;
                }
            }

            /* Card-based table view for mobile */
            @media (max-width: 768px) {
                /* Hide traditional table on mobile */
                #transactions-table {
                    display: none !important;
                }

                /* Create card-based layout */
                .mobile-table-cards {
                    display: block !important;
                }

                .mobile-table-card {
                    background: white;
                    border: 1px solid #e2e8f0;
                    border-radius: 0.75rem;
                    padding: 1rem;
                    margin-bottom: 0.75rem;
                    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
                    transition: box-shadow 0.2s ease;
                }

                .mobile-table-card:active {
                    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.15);
                }

                .mobile-card-row {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 0.5rem 0;
                    border-bottom: 1px solid #f1f5f9;
                }

                .mobile-card-row:last-child {
                    border-bottom: none;
                }

                .mobile-card-label {
                    font-size: 0.75rem;
                    color: #64748b;
                    font-weight: 500;
                    text-transform: uppercase;
                    letter-spacing: 0.025em;
                }

                .mobile-card-value {
                    font-size: 0.875rem;
                    color: #334155;
                    font-weight: 500;
                    text-align: right;
                }

                .mobile-card-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: flex-start;
                    margin-bottom: 0.75rem;
                    padding-bottom: 0.75rem;
                    border-bottom: 2px solid #f1f5f9;
                }

                .mobile-card-title {
                    font-size: 0.875rem;
                    font-weight: 600;
                    color: #1e293b;
                }

                .mobile-card-subtitle {
                    font-size: 0.75rem;
                    color: #64748b;
                    margin-top: 0.125rem;
                }

                /* Expandable details */
                .mobile-card-details {
                    max-height: 0;
                    overflow: hidden;
                    transition: max-height 0.3s ease;
                }

                .mobile-card-details.expanded {
                    max-height: 500px;
                }

                .mobile-expand-toggle {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 100%;
                    padding: 0.5rem;
                    margin-top: 0.5rem;
                    background: #f8fafc;
                    border-radius: 0.5rem;
                    color: #64748b;
                    font-size: 0.75rem;
                    font-weight: 500;
                    cursor: pointer;
                    transition: background-color 0.2s;
                }

                .mobile-expand-toggle:active {
                    background: #e2e8f0;
                }
            }

            /* Tablet optimizations (640px - 1024px) */
            @media (min-width: 640px) and (max-width: 1024px) {
                /* Adjust grid for tablets */
                .md\:grid-cols-3 {
                    grid-template-columns: repeat(2, 1fr) !important;
                }

                /* Optimize chart layout */
                .xl\:col-span-2 {
                    grid-column: span 2 !important;
                }
            }

            /* Touch target optimization - ensure minimum 44px */
            @media (pointer: coarse) {
                button, a, input[type="checkbox"], select {
                    min-height: 44px;
                    min-width: 44px;
                }

                .h-8 {
                    height: 44px !important;
                }

                .h-10 {
                    height: 44px !important;
                }
            }

            /* Smooth momentum scrolling on mobile */
            @media (max-width: 640px) {
                body, .overflow-x-auto {
                    -webkit-overflow-scrolling: touch;
                }
            }

            /* Optimize sidebar for mobile */
            @media (max-width: 1024px) {
                #sidebar {
                    box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
                }
            }

            /* ===== KPI CARD STYLES ===== */
            .kpi-card {
                background: #ffffff;
                border: 1.5px solid #e2e8f0;
                border-radius: 1.25rem;
                padding: 1.25rem;
                transition: all 0.3s ease;
                cursor: pointer;
                position: relative;
                overflow: hidden;
            }

            .kpi-card:hover {
                border-color: #cbd5e1;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
                transform: translateY(-2px);
            }

            .kpi-card:active {
                transform: translateY(0);
            }

            .kpi-card-header {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                margin-bottom: 1rem;
            }

            .kpi-card-label {
                font-size: 0.875rem;
                font-weight: 500;
                color: #64748b;
                text-transform: uppercase;
                letter-spacing: 0.025em;
                margin-bottom: 0.25rem;
            }

            .kpi-card-change {
                display: inline-flex;
                align-items: center;
                padding: 0.25rem 0.625rem;
                border-radius: 0.5rem;
                font-size: 0.75rem;
                font-weight: 600;
                letter-spacing: 0.025em;
            }

            .kpi-card-change.positive {
                background: #dcfce7;
                color: #16a34a;
            }

            .kpi-card-change.negative {
                background: #fee2e2;
                color: #dc2626;
            }

            .kpi-card-change.neutral {
                background: #f1f5f9;
                color: #64748b;
            }

            .kpi-card-body {
                display: flex;
                justify-content: space-between;
                align-items: center;
                gap: 0.75rem;
            }

            .kpi-card-value {
                font-size: 2rem;
                font-weight: 700;
                line-height: 1.2;
                color: #1e293b;
                letter-spacing: -0.02em;
                flex: 1;
                min-width: 0; /* Allow text to shrink */
                overflow: hidden;
            }

            @media (min-width: 640px) {
                .kpi-card-value {
                    font-size: 2.25rem;
                }
            }

            .kpi-card-icon {
                flex-shrink: 0;
                width: 44px;
                height: 44px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: transform 0.2s ease;
            }

            .kpi-card:hover .kpi-card-icon {
                transform: scale(1.1);
            }

            .kpi-card-icon svg {
                width: 20px;
                height: 20px;
            }

            .kpi-card-icon.positive {
                background: #dcfce7;
                color: #16a34a;
            }

            .kpi-card-icon.negative {
                background: #fee2e2;
                color: #dc2626;
            }

            .kpi-card-icon.neutral {
                background: #f1f5f9;
                color: #64748b;
            }

            /* Mobile KPI card optimizations */
            @media (max-width: 640px) {
                .kpi-card {
                    padding: 1rem;
                    border-radius: 1rem;
                }

                .kpi-card-body {
                    gap: 0.5rem;
                }

                .kpi-card-value {
                    font-size: 1.5rem;
                    word-break: break-word;
                }

                /* Dynamically reduce font size for long values */
                .kpi-card-value span {
                    display: inline-block;
                    max-width: 100%;
                }

                /* Extra small font for very long revenue values */
                [data-kpi-card="total_revenue"] .kpi-card-value,
                [data-kpi-card="today_revenue"] .kpi-card-value {
                    font-size: 1.25rem;
                }

                .kpi-card-icon {
                    width: 36px;
                    height: 36px;
                    flex-shrink: 0; /* Prevent icon from shrinking */
                }

                .kpi-card-icon svg {
                    width: 16px;
                    height: 16px;
                }
            }

            /* 2-column layout on mobile, 3rd card wraps to new row */
            @media (max-width: 768px) {
                #kpis-section {
                    display: grid !important;
                    grid-template-columns: repeat(2, 1fr) !important;
                    gap: 0.75rem !important;
                }
            }
        </style>

        <!-- Chart.js (deferred for performance) -->
        <script
            src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"
            defer
        ></script>
    </head>

    <body class="min-h-screen bg-slate-50 text-slate-800">
        <!--
      Layout: Sidebar (nav) + Topbar (actions) + Main content
      - Sidebar collapses on mobile and can be toggled with the Menu button
      - Topbar includes date range, search, and export action
    -->

        <div id="app" class="flex min-h-screen">
            <!-- Mobile sidebar backdrop -->
            <div id="sidebar-backdrop"></div>

             <nav
                id="sidebar"
                class="fixed inset-y-0 left-0 z-40 transition-transform -translate-x-full border-r w-72 bg-white/80 backdrop-blur shadow-soft border-slate-200"
            >
                <!-- Brand -->
                <div class="flex items-center h-16 gap-3 px-6 border-b border-slate-200">
                    <img 
                        src="{{ asset('assets/img/logo/logo.png') }}" 
                        alt="PaceEvents Logo"
                        class="object-contain h-9 w-9 rounded-xl"
                    />
                    <div class="flex flex-col">
                        <span class="font-semibold tracking-tight text-slate-900">PaceEvents</span>
                        {{-- <span class="text-xs text-slate-500"></span> --}}
                    </div>
                </div>

                <!-- Nav Items -->
                 <div class="px-3 py-4 space-y-1">
                    <!-- Each item uses subtle hover and active state -->
                    <a
                        href="{{ route('dashboard') }}"
                        class="flex items-center gap-3 px-3 py-2 transition-colors rounded-lg group text-slate-700 hover:bg-brand-50 hover:text-brand-700"
                    >
                        <svg
                            class="w-5 h-5 text-slate-400 group-hover:text-brand-600"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="1.6"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                        >
                            <path d="M3 13h8V3H3v10zm10 8h8V11h-8v10z" />
                        </svg>
                        <span>Dashboard</span>
                    </a>
                    <a
                        href="#"
                        class="flex items-center gap-3 px-3 py-2 transition-colors rounded-lg group text-slate-700 hover:bg-brand-50 hover:text-brand-700"
                    >
                        <svg
                            class="w-5 h-5 text-slate-400 group-hover:text-brand-600"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="1.6"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                        >
                            <path
                                d="M21 15V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9"
                            />
                            <path d="M3 21h18" />
                            <path d="M7 21v-4" />
                            <path d="M17 21v-2" />
                        </svg>
                        <span>Events</span>
                    </a>
                    <a
                        href="{{ route('tickets.index') }}"
                        class="flex items-center gap-3 px-3 py-2 transition-colors rounded-lg group text-slate-700 hover:bg-brand-50 hover:text-brand-700"
                    >
                        <svg
                            class="w-5 h-5 text-slate-400 group-hover:text-brand-600"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="1.6"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                        >
                            <rect x="3" y="4" width="18" height="16" rx="2" />
                            <path d="M7 8h10" />
                            <path d="M7 12h6" />
                        </svg>
                        <span>Tickets</span>
                    </a>
                    <div class="pt-2">
                        <div class="px-3 text-xs font-medium text-slate-500">
                            Analytics
                        </div>
                        <a
                            href="{{ route('tickets.analytics') }}"
                            class="flex items-center gap-3 px-3 py-2 mt-1 rounded-lg group bg-brand-50 text-brand-700"
                        >
                            <svg
                                class="w-5 h-5 text-brand-600"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                stroke-width="1.6"
                                stroke-linecap="round"
                                stroke-linejoin="round"
                            >
                                <path d="M3 3v18h18" />
                                <path d="M7 13l3-3 3 4 4-5" />
                            </svg>
                            <span>Analytics</span>
                        </a>
                        <a
                            href="#"
                            class="flex items-center gap-3 px-3 py-2 transition-colors rounded-lg group text-slate-700 hover:bg-brand-50 hover:text-brand-700"
                        >
                            <svg
                                class="w-5 h-5 text-slate-400 group-hover:text-brand-600"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                stroke-width="1.6"
                                stroke-linecap="round"
                                stroke-linejoin="round"
                            >
                                <path d="M3 7h18" />
                                <path d="M5 11h14" />
                                <path d="M7 15h10" />
                            </svg>
                            <span>Reports</span>
                        </a>
                    </div>
                    <a
                        href="{{ route('sms.index') }}"
                        class="flex items-center gap-3 px-3 py-2 transition-colors rounded-lg group text-slate-700 hover:bg-brand-50 hover:text-brand-700"
                    >
                        <svg
                            class="w-5 h-5 text-slate-400 group-hover:text-brand-600"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="1.6"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                        >
                            <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778" />
                            <path d="M17 11v6l-2-2" />
                        </svg>
                        <span>SMS Manager</span>
                    </a>
                    <a
                        href="{{ route('complimentary.tickets.index') }}"
                        class="flex items-center gap-3 px-3 py-2 transition-colors rounded-lg group text-slate-700 hover:bg-brand-50 hover:text-brand-700"
                    >
                        <svg
                            class="w-5 h-5 text-slate-400 group-hover:text-brand-600"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="1.6"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                        >
                            <path d="M12 2v4m0 12v4M4.93 4.93l2.83 2.83m8.48 8.48l2.83 2.83M2 12h4m12 0h4M4.93 19.07l2.83-2.83m8.48-8.48l2.83-2.83" />
                        </svg>
                        <span>Complimentary</span>
                    </a>
                    <a
                        href="{{ route('csv.index') }}"
                        class="flex items-center gap-3 px-3 py-2 transition-colors rounded-lg group text-slate-700 hover:bg-brand-50 hover:text-brand-700"
                    >
                        <svg
                            class="w-5 h-5 text-slate-400 group-hover:text-brand-600"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="1.6"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                        >
                            <path d="M14 2v4a2 2 0 0 0 2 2h4" />
                            <path d="M14 3h4a1 1 0 0 1 1 1v4" />
                            <path d="M16 13H8" />
                            <path d="M16 17H8" />
                            <path d="M10 9H8" />
                            <rect x="4" y="4" width="16" height="16" rx="2" />
                        </svg>
                        <span>CSV Processor</span>
                    </a>
                    <a
                        href="{{ route('contacts.import.form') }}"
                        class="flex items-center gap-3 px-3 py-2 transition-colors rounded-lg group text-slate-700 hover:bg-brand-50 hover:text-brand-700"
                    >
                        <svg
                            class="w-5 h-5 text-slate-400 group-hover:text-brand-600"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="1.6"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                        >
                            <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
                            <circle cx="9" cy="7" r="4" />
                            <path d="M23 21v-2a4 4 0 0 0-3-3.87" />
                            <path d="M16 3.13a4 4 0 0 1 0 7.75" />
                        </svg>
                        <span>Contacts</span>
                    </a>

                    <!-- User section -->
                <div class="pt-4 mt-4 border-t border-slate-200">
                    <div class="flex items-center gap-3 px-3" style="display: none">
                        <img
                            alt="User"
                            class="object-cover rounded-full h-9 w-9"
                            src="https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?q=80&w=200&auto=format&fit=crop"
                        />
                        <div>
                            <div class="text-sm font-medium text-slate-900">
                                {{ Auth::user()->name }}
                            </div>
                            <div class="text-xs text-slate-500">
                                {{ Auth::user()->email }}
                            </div>
                        </div>
                    </div>
                    
                    {{-- <!-- Profile Link -->
                    <a
                        href="{{ route('profile.edit') }}"
                        class="flex items-center gap-3 px-3 py-2 mt-3 transition-colors rounded-lg group text-slate-700 hover:bg-slate-100"
                    >
                        <svg
                            class="w-5 h-5 text-slate-400 group-hover:text-slate-600"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="1.6"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                        >
                            <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
                            <circle cx="12" cy="7" r="4" />
                        </svg>
                        <span>Profile</span>
                    </a> --}}
                    
                    <!-- Logout Link -->
                    <a
                        href="{{ route('logout') }}"
                        class="flex items-center gap-3 px-3 py-2 transition-colors rounded-lg group text-slate-700 hover:bg-slate-100"
                        onclick="event.preventDefault(); document.getElementById('logout-form').submit();"
                    >
                        <svg
                            class="w-5 h-5 text-slate-400 group-hover:text-slate-600"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="1.6"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                        >
                            <path d="M9 21h6" />
                            <path d="M12 17v4" />
                            <path d="M3 10v3a9 9 0 0 0 18 0v-3" />
                            <path
                                d="M21 10V7a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v3"
                            />
                        </svg>
                        <span>Logout</span>
                    </a>
                    <form id="logout-form" action="{{ route('logout') }}" method="POST" class="hidden">
                        @csrf
                    </form>
                </div>
                </div>
            </nav>


            <!-- Main Content Area -->
            <div id="content" class="flex-1">
                <!-- Topbar -->
                <header
                    class="sticky top-0 z-30 border-b bg-white/70 backdrop-blur border-slate-200"
                >
                    <div
                        class="flex items-center justify-between h-16 px-4 sm:px-6"
                    >
                        <div class="flex items-center gap-3">
                            <!-- Mobile menu toggle -->
                            <button
                                id="menuBtn"
                                class="inline-flex items-center justify-center w-10 h-10 transition-colors border rounded-lg lg:hidden border-slate-300 text-slate-700 hover:bg-slate-100"
                                aria-label="Open menu"
                            >
                                <svg
                                    class="w-5 h-5"
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    stroke-width="1.6"
                                    stroke-linecap="round"
                                    stroke-linejoin="round"
                                >
                                    <line x1="3" y1="12" x2="21" y2="12" />
                                    <line x1="3" y1="6" x2="21" y2="6" />
                                    <line x1="3" y1="18" x2="21" y2="18" />
                                </svg>
                            </button>
                            <div class="hidden sm:block lg:block">
                                <h1
                                    class="text-lg sm:text-xl font-semibold tracking-tight text-slate-900"
                                >
                                    TEENZ FEST 25
                                </h1>
                            </div>
                            <button
                                id="collapseBtn"
                                class="items-center justify-center hidden w-10 h-10 transition-colors border rounded-lg lg:inline-flex border-slate-300 text-slate-700 hover:bg-slate-100"
                                aria-label="Collapse sidebar"
                            >
                                <svg
                                    class="w-5 h-5"
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    stroke-width="1.6"
                                    stroke-linecap="round"
                                    stroke-linejoin="round"
                                >
                                    <polyline points="15 18 9 12 15 6" />
                                </svg>
                            </button>
                        </div>
                        <div class="flex items-center gap-2 sm:gap-3">
                            <!-- Date Range -->
                            <label class="sr-only" for="dateRange"
                                >Date range</label
                            >
                            <select
                                id="dateRange"
                                class="h-10 px-2 sm:px-3 text-xs sm:text-sm bg-white border rounded-lg theme-select border-slate-300 shadow-soft focus:outline-none focus:ring-2 focus:ring-brand-500"
                            >
                                <option>Last 7 Days</option>
                                <option selected>Last 30 Days</option>
                                <option>Last 90 Days</option>
                                <option>Year to Date</option>
                            </select>
                            <!-- Search - Hidden on very small screens -->
                            <div class="relative hidden sm:block">
                                <svg
                                    class="absolute w-5 h-5 -translate-y-1/2 left-3 top-1/2 text-slate-400"
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    stroke-width="1.6"
                                    stroke-linecap="round"
                                    stroke-linejoin="round"
                                >
                                    <circle cx="11" cy="11" r="8" />
                                    <path d="M21 21l-4.3-4.3" />
                                </svg>
                                <input
                                    type="text"
                                    placeholder="Search"
                                    class="w-32 sm:w-40 md:w-64 h-10 pl-10 pr-3 text-sm bg-white border rounded-lg border-slate-300 shadow-soft focus:outline-none focus:ring-2 focus:ring-brand-500"
                                />
                            </div>
                            <!-- Export -->
                            <button
                                style="display: none;"
                                id="exportBtn"
                                class="inline-flex items-center h-10 gap-2 px-2 sm:px-4 text-white transition rounded-lg bg-gradient-to-r from-brand-600 to-secondary-500 shadow-soft hover:brightness-105 active:brightness-95"
                            >
                                <svg
                                    class="w-5 h-5"
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    stroke-width="1.6"
                                    stroke-linecap="round"
                                    stroke-linejoin="round"
                                >
                                    <path
                                        d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"
                                    />
                                    <path d="M17 8l-5-5-5 5" />
                                    <path d="M12 3v12" />
                                </svg>
                                <span class="hidden sm:inline"
                                    >Export Reports</span
                                >
                            </button>
                        </div>
                    </div>
                </header>

                <!-- Content -->
                <main class="px-4 py-6 space-y-6 sm:px-6">
                    <!-- KPI Cards -->
                    @can('view-metrics')
                    <section
                        id="kpis-section"
                        aria-labelledby="kpis"
                        class="grid grid-cols-1 gap-4 md:grid-cols-3"
                    >
                        <h2 id="kpis" class="sr-only">Key metrics</h2>
                        
                        <!-- Total Revenue Card -->
                        <div
                            class="kpi-card kpi-card-positive"
                            data-kpi-card="total_revenue"
                        >
                            <div class="kpi-card-header">
                                <div>
                                    <div class="kpi-card-label">Total Revenue</div>
                                    <div class="kpi-card-change {{ $ticketStats['total_revenue_direction'] ?? 'neutral' }}">{{ $ticketStats['total_revenue_change'] ?? '--' }}</div>
                                </div>
                            </div>
                            <div class="kpi-card-body">
                                <div class="kpi-card-value">
                                    <span class="counter" data-key="total_revenue" data-target="{{ (float)($ticketStats['total_revenue'] ?? 0) }}" data-prefix="KSH " data-decimals="2">0</span>
                                </div>
                                <div class="kpi-card-icon {{ $ticketStats['total_revenue_direction'] ?? 'neutral' }}">
                                    @if(($ticketStats['total_revenue_direction'] ?? 'neutral') === 'positive')
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                            <polyline points="18 15 12 9 6 15" />
                                        </svg>
                                    @elseif(($ticketStats['total_revenue_direction'] ?? 'neutral') === 'negative')
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                            <polyline points="6 9 12 15 18 9" />
                                        </svg>
                                    @else
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                            <line x1="5" y1="12" x2="19" y2="12" />
                                        </svg>
                                    @endif
                                </div>
                            </div>
                        </div>
                        
                        <!-- Today's Sales Card -->
                        <div
                            class="kpi-card kpi-card-neutral"
                            data-kpi-card="today_sales"
                        >
                            <div class="kpi-card-header">
                                <div>
                                    <div class="kpi-card-label">Today's Sales</div>
                                    <div class="kpi-card-change {{ $ticketStats['today_sales_direction'] ?? 'neutral' }}">{{ $ticketStats['today_sales_change'] ?? '--' }}</div>
                                </div>
                            </div>
                            <div class="kpi-card-body">
                                <div class="kpi-card-value">
                                    <span class="counter" data-key="today_sales" data-target="{{ (int)($ticketStats['today_sales'] ?? 0) }}" data-decimals="0">0</span>
                                </div>
                                <div class="kpi-card-icon {{ $ticketStats['today_sales_direction'] ?? 'neutral' }}">
                                    @if(($ticketStats['today_sales_direction'] ?? 'neutral') === 'positive')
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                            <polyline points="18 15 12 9 6 15" />
                                        </svg>
                                    @elseif(($ticketStats['today_sales_direction'] ?? 'neutral') === 'negative')
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                            <polyline points="6 9 12 15 18 9" />
                                        </svg>
                                    @else
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                            <line x1="5" y1="12" x2="19" y2="12" />
                                        </svg>
                                    @endif
                                </div>
                            </div>
                        </div>
                        
                        <!-- Today's Revenue Card -->
                        <div
                            class="kpi-card kpi-card-positive"
                            data-kpi-card="today_revenue"
                        >
                            <div class="kpi-card-header">
                                <div>
                                    <div class="kpi-card-label">Today's Revenue</div>
                                    <div class="kpi-card-change {{ $ticketStats['today_revenue_direction'] ?? 'neutral' }}">{{ $ticketStats['today_revenue_change'] ?? '--' }}</div>
                                </div>
                            </div>
                            <div class="kpi-card-body">
                                <div class="kpi-card-value">
                                    <span class="counter" data-key="today_revenue" data-target="{{ (float)($ticketStats['today_revenue'] ?? 0) }}" data-prefix="KSH " data-decimals="2">0</span>
                                </div>
                                <div class="kpi-card-icon {{ $ticketStats['today_revenue_direction'] ?? 'neutral' }}">
                                    @if(($ticketStats['today_revenue_direction'] ?? 'neutral') === 'positive')
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                            <polyline points="18 15 12 9 6 15" />
                                        </svg>
                                    @elseif(($ticketStats['today_revenue_direction'] ?? 'neutral') === 'negative')
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                            <polyline points="6 9 12 15 18 9" />
                                        </svg>
                                    @else
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                            <line x1="5" y1="12" x2="19" y2="12" />
                                        </svg>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </section>
                    @endcan

                    <!-- Charts and Insights -->
                    <section class="grid grid-cols-1 gap-4 xl:grid-cols-3">
                        <!-- Revenue Over Time -->
                        <div
                            class="p-5 bg-white border xl:col-span-2 rounded-xl border-slate-200 shadow-soft sm:p-6"
                        >
                            <div class="flex items-center justify-between">
                                <div>
                                    <h3
                                        class="text-sm font-medium text-slate-700"
                                    >
                                        Revenue Over Time
                                    </h3>
                                    <p class="text-xs text-slate-500">
                                        Daily, weekly, or monthly trend
                                    </p>
                                </div>
                                <div class="flex items-center gap-2">
                                    <button
                                        data-period="daily"
                                        class="h-8 px-3 text-xs bg-white border rounded-lg period-btn border-slate-300 hover:bg-slate-100"
                                    >
                                        Daily
                                    </button>
                                    <button
                                        data-period="weekly"
                                        class="h-8 px-3 text-xs bg-white border rounded-lg period-btn border-slate-300 hover:bg-slate-100"
                                    >
                                        Weekly
                                    </button>
                                    <button
                                        data-period="monthly"
                                        class="h-8 px-3 text-xs bg-white border rounded-lg period-btn border-slate-300 hover:bg-slate-100"
                                    >
                                        Monthly
                                    </button>
                                </div>
                            </div>
                            <div class="mt-4">
                                <canvas
                                    id="revenueLine"
                                    class="w-full"
                                    height="300"
                                ></canvas>
                            </div>
                            <!-- Filters row -->
                            <div class="grid items-center grid-cols-1 gap-3 mt-4">
                                <select
                                    class="w-full px-3 text-xs bg-white border rounded-lg theme-select h-9 border-slate-300 focus:outline-none focus:ring-2 focus:ring-brand-500"
                                >
                                    <option selected>All Dates</option>
                                    <option>Past Week</option>
                                    <option>Past Month</option>
                                </select>
                            </div>
                        </div>

                        <!-- Right column: Event revenue and Ticket type -->
                        <div class="space-y-4">
                            <div
                                class="p-5 bg-white border rounded-xl border-slate-200 shadow-soft sm:p-6"
                            >
                                <div class="flex items-center justify-between">
                                    <h3
                                        class="text-sm font-medium text-slate-700"
                                    >
                                        Tickets by Status
                                    </h3>
                                    <span class="text-xs text-slate-500"
                                        >Counts</span
                                    >
                                </div>
                                <div class="mt-4">
                                    <canvas
                                        id="eventBar"
                                        class="w-full"
                                        height="170"
                                    ></canvas>
                                </div>
                            </div>
                            <div
                                class="p-5 bg-white border rounded-xl border-slate-200 shadow-soft sm:p-6"
                            >
                                <div class="flex items-center justify-between">
                                    <h3
                                        class="text-sm font-medium text-slate-700"
                                    >
                                        Payment Status Distribution
                                    </h3>
                                    <span class="text-xs text-slate-500"
                                        >Overall</span
                                    >
                                </div>
                                <div
                                    class="flex items-center justify-center mt-4"
                                >
                                    <canvas
                                        id="ticketPie"
                                        class="w-full"
                                        height="160"
                                    ></canvas>
                                </div>
                            </div>
                        </div>
                    </section>

                    <!-- Recent Transactions (Enhanced Data Table) -->
                    <section
                        aria-labelledby="transactions"
                        class="p-5 bg-white border rounded-xl border-slate-200 shadow-soft sm:p-6"
                        id="transactions-section"
                    >
                        <div class="flex items-center justify-between">
                            <h2
                                id="transactions"
                                class="text-sm font-medium text-slate-700"
                            >
                                Recent Transactions
                            </h2>
                            <div class="flex items-center gap-2">
                                <button
                                    id="dt-export-csv"
                                    class="h-8 px-3 text-xs bg-white border rounded-lg border-slate-300 hover:bg-slate-100"
                                >
                                    Export CSV
                                </button>
                                <button
                                    id="dt-export-xls"
                                    class="h-8 px-3 text-xs bg-white border rounded-lg border-slate-300 hover:bg-slate-100"
                                >
                                    Export Excel
                                </button>
                                <button
                                    id="dt-export-pdf"
                                    class="h-8 px-3 text-xs bg-white border rounded-lg border-slate-300 hover:bg-slate-100"
                                >
                                    Export PDF
                                </button>
                            </div>
                        </div>

                        <!-- Toolbar -->
                        <div class="grid grid-cols-1 gap-2 mt-3 lg:grid-cols-12">
                            <div class="lg:col-span-4">
                                <label class="sr-only" for="dt-search"
                                    >Search</label
                                >
                                <div class="relative">
                                    <svg
                                        class="absolute w-5 h-5 -translate-y-1/2 left-3 top-1/2 text-slate-400"
                                        viewBox="0 0 24 24"
                                        fill="none"
                                        stroke="currentColor"
                                        stroke-width="1.6"
                                        stroke-linecap="round"
                                        stroke-linejoin="round"
                                    >
                                        <circle cx="11" cy="11" r="8" />
                                        <path d="M21 21l-4.3-4.3" />
                                    </svg>
                                    <input
                                        id="dt-search"
                                        type="text"
                                        placeholder="Search all columns"
                                        class="w-full pl-10 pr-3 text-xs bg-white border rounded-lg h-9 border-slate-300 focus:outline-none focus:ring-2 focus:ring-brand-500"
                                    />
                                </div>
                            </div>
                            <div class="lg:col-span-1">
                                <label class="sr-only" for="dt-page-size"
                                    >Per Page</label
                                >
                                <select
                                    id="dt-page-size"
                                    class="w-full px-2 text-xs bg-white border rounded-lg theme-select h-9 border-slate-300 focus:outline-none focus:ring-2 focus:ring-brand-500"
                                >
                                    <option>10</option>
                                    <option selected>25</option>
                                    <option>50</option>
                                    <option>100</option>
                                </select>
                            </div>
                            <div class="lg:col-span-2">
                                <label class="sr-only" for="dt-status-filter"
                                    >Status</label
                                >
                                <select
                                    id="dt-status-filter"
                                    class="w-full px-2 text-xs bg-white border rounded-lg theme-select h-9 border-slate-300 focus:outline-none focus:ring-2 focus:ring-brand-500"
                                >
                                    <option selected>All Status</option>
                                    <option>Paid</option>
                                    <option>Pending</option>
                                    <option>Failed</option>
                                </select>
                            </div>
                            <div class="lg:col-span-2">
                                <label class="sr-only" for="dt-school-filter"
                                    >School</label
                                >
                                <select
                                    id="dt-school-filter"
                                    class="w-full px-2 text-xs bg-white border rounded-lg theme-select h-9 border-slate-300 focus:outline-none focus:ring-2 focus:ring-brand-500"
                                >
                                    <option selected>All Schools</option>
                                </select>
                            </div>
                            
                            <!--
                            <div class="lg:col-span-3">
                                <label class="sr-only" for="dt-columns">Columns</label>
                                <select id="dt-columns" multiple class="w-full px-2 text-xs bg-white border rounded-lg theme-select h-9 border-slate-300 focus:outline-none focus:ring-2 focus:ring-brand-500" size="6">
                                    <option value="id" selected>Transaction ID</option>
                                    <option value="event" selected>Event</option>
                                    <option value="date" selected>Date</option>
                                    <option value="ticketType" selected>Ticket Type</option>
                                    <option value="paymentMethod" selected>Payment Method</option>
                                    <option value="amount" selected>Amount</option>
                                </select>
                                <div id="dt-columns-chips" class="flex flex-wrap gap-1 mt-1"></div>
                            </div>
                            -->
                            <div class="flex items-center gap-2 lg:col-span-1">
                                <button
                                    id="dt-clear"
                                    class="px-3 text-xs bg-white border rounded-lg h-9 border-slate-300 hover:bg-slate-100"
                                >
                                    Clear
                                </button>
                                <button
                                    id="dt-reload"
                                    class="px-3 text-xs text-white rounded-lg h-9 bg-gradient-to-r from-brand-600 to-secondary-500 shadow-soft hover:brightness-105"
                                >
                                    Reload
                                </button>
                            </div>
                        </div>

                        <div class="mt-3 overflow-x-auto" aria-live="polite">
                            <table
                                id="transactions-table"
                                class="min-w-full text-sm"
                                role="grid"
                                aria-rowcount="0"
                                aria-colcount="12"
                            >
                                <thead>
                                    <tr
                                        class="text-left border-b text-slate-500 border-slate-200"
                                    >
                                        <th class="w-6 py-2 pr-4">
                                            <input
                                                id="dt-select-all"
                                                type="checkbox"
                                                class="w-4 h-4 rounded border-slate-300"
                                                aria-label="Select all rows"
                                            />
                                        </th>
                                        <th class="py-2 pr-4">
                                            <button
                                                class="dt-sort"
                                                data-key="id"
                                            >
                                                ID
                                            </button>
                                        </th>
                                        <th class="py-2 pr-4">
                                            <button
                                                class="dt-sort"
                                                data-key="reference"
                                            >
                                                Reference
                                            </button>
                                        </th>
                                        <th class="py-2 pr-4">
                                            <button
                                                class="dt-sort"
                                                data-key="customer"
                                            >
                                                Customer
                                            </button>
                                        </th>
                                        <th class="py-2 pr-4">
                                            <button
                                                class="dt-sort"
                                                data-key="contact"
                                            >
                                                Contact
                                            </button>
                                        </th>
                                        <th class="py-2 pr-4">
                                            <button
                                                class="dt-sort"
                                                data-key="school"
                                            >
                                                School
                                            </button>
                                        </th>
                                        <th class="py-2 pr-4">
                                            <button
                                                class="dt-sort"
                                                data-key="qty"
                                            >
                                                Qty
                                            </button>
                                        </th>
                                        <th class="py-2 pr-4">
                                            <button
                                                class="dt-sort"
                                                data-key="amount"
                                            >
                                                Amount
                                            </button>
                                        </th>
                                        <th class="py-2 pr-4">
                                            <button
                                                class="dt-sort"
                                                data-key="status"
                                            >
                                                Status
                                            </button>
                                        </th>
                                        
                                        <th class="py-2 pr-4">
                                            <button
                                                class="dt-sort"
                                                data-key="paymentDate"
                                            >
                                                Payment Date
                                            </button>
                                        </th>
                                        <th class="py-2 pr-4">
                                            <button
                                                class="dt-sort"
                                                data-key="created"
                                                aria-sort="descending"
                                            >
                                                Created
                                            </button>
                                        </th>
                                    </tr>
                                </thead>
                                <tbody
                                    id="transactions-tbody"
                                    class="divide-y divide-slate-200"
                                ></tbody>
                            </table>

                            <!-- Mobile Card-Based Table View -->
                            <div id="mobile-table-cards" class="mobile-table-cards hidden">
                                <!-- Cards will be dynamically generated here -->
                            </div>
                        </div>

                        <!-- Pagination -->
                        <div
                            class="flex items-center justify-between mt-3"
                            id="dt-pagination"
                        >
                            <div class="text-xs text-slate-500" id="dt-status">
                                Loading…
                            </div>
                            <div class="flex items-center gap-2">
                                <button
                                    id="dt-prev"
                                    class="h-8 px-3 text-xs bg-white border rounded-lg border-slate-300 hover:bg-slate-100"
                                    aria-label="Previous page"
                                >
                                    Prev
                                </button>
                                <span
                                    id="dt-page"
                                    class="text-xs text-slate-700"
                                    >1 / 1</span
                                >
                                <button
                                    id="dt-next"
                                    class="h-8 px-3 text-xs bg-white border rounded-lg border-slate-300 hover:bg-slate-100"
                                    aria-label="Next page"
                                >
                                    Next
                                </button>
                            </div>
                        </div>
                    </section>
                </main>
            </div>
        </div>

        <div id="kpiOverlay" class="fixed inset-0 z-[100] hidden">
            <div id="kpiOverlayBackdrop" class="absolute inset-0 bg-slate-900/50"></div>
            <div class="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-[94vw] max-w-md sm:left-auto sm:top-auto sm:right-6 sm:bottom-6 sm:translate-x-0 sm:translate-y-0 sm:w-[92vw] sm:max-w-sm bg-white rounded-xl border border-slate-200 shadow-soft p-5 sm:p-6">
                <div class="flex items-center justify-between">
                    <h3 id="kpiOverlayTitle" class="text-sm font-medium text-slate-700"></h3>
                    <button id="kpiOverlayClose" class="w-8 h-8 border rounded-lg border-slate-300 text-slate-700">×</button>
                </div>
                <div class="mt-2 text-5xl font-semibold tracking-tight sm:text-4xl text-slate-900">
                    <span id="kpiOverlayCounter" class="counter" data-decimals="0" data-mode="step">0</span>
                </div>
            </div>
        </div>

        <!--
      Interaction logic: mobile menu toggle, chart initialization, export action.
      - Vanilla JS for minimal footprint.
    -->
        @php
            $paceRows = [];
            foreach ($tickets as $ticket) {
                $paceRows[] = [
                    'id' => $ticket->id,
                    'reference' => $ticket->reference,
                    'customer' => trim(($ticket->first_name ?? '') . ' ' . ($ticket->last_name ?? '')),
                    'contact' => trim(($ticket->phone ?? '') . (($ticket->email) ? ' | ' . $ticket->email : '')),
                    'school' => $ticket->school ?? '',
                    'qty' => (int)($ticket->quantity ?? 0),
                    'amount' => (float)($ticket->amount ?? 0),
                    'status' => $ticket->payment_status === 'completed' ? 'Paid' : ($ticket->payment_status === 'pending' ? 'Pending' : 'Failed'),
                    'stkStatus' => $ticket->stk_status ?? '',
                    'receipt' => $ticket->mpesa_receipt_number ?? '',
                    'paymentDate' => $ticket->payment_date ? ((is_string($ticket->payment_date) ? \Carbon\Carbon::parse($ticket->payment_date) : $ticket->payment_date)->format('Y-m-d H:i')) : '—',
                    'created' => $ticket->created_at ? $ticket->created_at->format('Y-m-d H:i') : '',
                ];
            }
        @endphp
        <script>
            window.paceData = @json($paceRows);
        </script>
        <script>
            window.addEventListener("load", function () {
                const prefersReduced = window.matchMedia(
                    "(prefers-reduced-motion: reduce)"
                ).matches;

                // Mobile sidebar toggle
                const menuBtn = document.getElementById("menuBtn");
                const sidebar = document.getElementById("sidebar");
                const content = document.getElementById("content");
                const backdrop = document.getElementById("sidebar-backdrop");

                const isLG = () =>
                    window.matchMedia("(min-width: 1024px)").matches;
                function setContentShift(shown) {
                    if (isLG()) {
                        content.style.marginLeft = shown ? "18rem" : "";
                    } else {
                        content.style.marginLeft = "";
                    }
                }

                function toggleSidebar(show) {
                    sidebar.classList.toggle("-translate-x-full", !show);
                    if (backdrop) {
                        backdrop.classList.toggle("active", show && !isLG());
                    }
                    setContentShift(show);
                }

                if (menuBtn) {
                    menuBtn.addEventListener("click", () => {
                        const hidden =
                            sidebar.classList.contains("-translate-x-full");
                        toggleSidebar(hidden);
                    });
                }

                if (backdrop) {
                    backdrop.addEventListener("click", () => {
                        toggleSidebar(false);
                    });
                }

                const collapseBtn = document.getElementById("collapseBtn");
                if (collapseBtn) {
                    collapseBtn.addEventListener("click", () => {
                        const hidden =
                            sidebar.classList.contains("-translate-x-full");
                        toggleSidebar(hidden);
                    });
                }

                // Export action (simple print for demo)
                const exportBtn = document.getElementById("exportBtn");
                if (exportBtn) {
                    exportBtn.addEventListener("click", () => window.print());
                }

                // Chart helpers
                const brand = {
                    primary: "#E30613",
                    accent: "#F5B300",
                    slate: "#94a3b8",
                };

                // height sync removed; left chart uses fixed height for simplicity

                const lineCtx = document
                    .getElementById("revenueLine")
                    .getContext("2d");
                const barCtx = document
                    .getElementById("eventBar")
                    .getContext("2d");
                const pieCtx = document
                    .getElementById("ticketPie")
                    .getContext("2d");

                let stats = {
                    total_tickets: {{ (int)($ticketStats['total_tickets'] ?? 0) }},
                    total_paid: {{ (int)($ticketStats['total_paid'] ?? 0) }},
                    total_pending: {{ (int)($ticketStats['total_pending'] ?? 0) }},
                    total_failed: {{ (int)($ticketStats['total_failed'] ?? 0) }},
                };

                async function loadRevenue(period) {
                    try {
                        const res = await fetch(`/api/revenue-series?period=${period}`, { headers: { 'Accept': 'application/json' } });
                        if (!res.ok) return;
                        const d = await res.json();
                        revenueLine.data.labels = Array.isArray(d.labels) ? d.labels : [];
                        revenueLine.data.datasets[0].data = Array.isArray(d.values) ? d.values : [];
                        revenueLine.update();
                    } catch {}
                }

                const baseOpts = {
                    responsive: true,
                    maintainAspectRatio: false,
                    animation: prefersReduced
                        ? false
                        : { duration: 700, easing: "easeOutQuart" },
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            enabled: true,
                            backgroundColor: "rgba(15,23,42,0.9)",
                            padding: 10,
                            titleColor: "#fff",
                            bodyColor: "#fff",
                            borderColor: "#334155",
                            borderWidth: 1,
                        },
                    },
                    scales: {
                        x: {
                            grid: { color: "rgba(148,163,184,0.25)" },
                            ticks: { color: "#475569" },
                        },
                        y: {
                            grid: { color: "rgba(148,163,184,0.2)" },
                            ticks: { color: "#475569" },
                        },
                    },
                };

                // Line chart
                let currentPeriod = "daily";
                let lineData = { labels: [], values: [] };
                const revenueLine = new Chart(lineCtx, {
                    type: "line",
                    data: {
                        labels: lineData.labels,
                        datasets: [
                            {
                                label: "Revenue",
                                data: lineData.values,
                                borderColor: brand.primary,
                                backgroundColor: "rgba(227,6,19,0.15)",
                                tension: 0.35,
                                fill: true,
                                pointRadius: 0,
                                pointHoverRadius: 4,
                            },
                        ],
                    },
                    options: {
                        ...baseOpts,
                        scales: {
                            ...baseOpts.scales,
                            y: { ...baseOpts.scales.y, beginAtZero: true },
                        },
                    },
                });

                // Period buttons
                document.querySelectorAll(".period-btn").forEach((btn) => {
                    btn.addEventListener("click", async () => {
                        currentPeriod = btn.dataset.period;
                        await loadRevenue(currentPeriod);
                        document
                            .querySelectorAll(".period-btn")
                            .forEach((b) =>
                                b.classList.remove(
                                    "bg-brand-50",
                                    "text-brand-700"
                                )
                            );
                        btn.classList.add("bg-brand-50", "text-brand-700");
                    });
                });
                loadRevenue(currentPeriod);

                // Bar chart (horizontal)
                const valueLabelPlugin = {
                    id: "valueLabel",
                    afterDatasetsDraw(chart) {
                        const { ctx, scales } = chart;
                        const ds = chart.data.datasets[0];
                        const meta = chart.getDatasetMeta(0);
                        ctx.save();
                        ctx.fillStyle = "#334155";
                        ctx.font = "12px Inter, sans-serif";
                        meta.data.forEach((el, i) => {
                            const val = ds.data[i];
                            const x = scales.x.getPixelForValue(val) + 8;
                            const y = el.y + 4;
                            const maxX = chart.chartArea.right - 4;
                            ctx.fillText(
                                Number(val).toLocaleString(),
                                Math.min(x, maxX),
                                y
                            );
                        });
                        ctx.restore();
                    },
                };

                const eventBar = new Chart(barCtx, {
                    type: "bar",
                    data: {
                        labels: [
                            "Total Tickets",
                            "Paid Tickets",
                            "Pending",
                            "Failed",
                        ],
                        datasets: [
                            {
                                data: [
                                    stats.total_tickets,
                                    stats.total_paid,
                                    stats.total_pending,
                                    stats.total_failed,
                                ],
                                backgroundColor: [
                                    "#FB7185",
                                    brand.accent,
                                    brand.slate,
                                    "#7A0810",
                                ],
                                borderRadius: 8,
                            },
                        ],
                    },
                    options: {
                        ...baseOpts,
                        indexAxis: "y",
                        scales: {
                            x: {
                                ...baseOpts.scales.x,
                                beginAtZero: true,
                                ticks: {
                                    color: "#475569",
                                    callback: (v) => Number(v).toLocaleString(),
                                },
                            },
                            y: { ...baseOpts.scales.y },
                        },
                    },
                    plugins: [valueLabelPlugin],
                });
                window.eventBar = eventBar;

                // Doughnut chart
                const pieLabelPlugin = {
                    id: "pieLabel",
                    afterDatasetsDraw(chart) {
                        const ds = chart.data.datasets[0];
                        const meta = chart.getDatasetMeta(0);
                        const colors = ds.backgroundColor;
                        const ctx = chart.ctx;
                        function luminance(hex) {
                            const m =
                                /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(
                                    hex
                                );
                            if (!m) return 0;
                            const r = parseInt(m[1], 16) / 255,
                                g = parseInt(m[2], 16) / 255,
                                b = parseInt(m[3], 16) / 255;
                            return 0.2126 * r + 0.7152 * g + 0.0722 * b;
                        }
                        ctx.save();
                        ctx.textAlign = "center";
                        ctx.textBaseline = "middle";
                        ctx.font = "12px Inter, sans-serif";
                        meta.data.forEach((arc, i) => {
                            const val = ds.data[i];
                            const color = Array.isArray(colors)
                                ? colors[i]
                                : "#334155";
                            const lum = luminance(color);
                            ctx.fillStyle = lum > 0.6 ? "#1f2937" : "#ffffff";
                            const cx = arc.x,
                                cy = arc.y;
                            const mid = (arc.startAngle + arc.endAngle) / 2;
                            const r =
                                arc.innerRadius +
                                (arc.outerRadius - arc.innerRadius) * 0.6;
                            ctx.fillText(
                                String(val),
                                cx + Math.cos(mid) * r,
                                cy + Math.sin(mid) * r
                            );
                        });
                        ctx.restore();
                    },
                };
                const ticketPie = new Chart(pieCtx, {
                    type: "doughnut",
                    data: {
                        labels: ["Completed", "Pending", "Failed"],
                        datasets: [
                            {
                                data: [
                                    stats.total_paid,
                                    stats.total_pending,
                                    stats.total_failed,
                                ],
                                backgroundColor: [
                                    "#22c55e",
                                    "#F5B300",
                                    "#B00020",
                                ],
                                borderWidth: 0,
                            },
                        ],
                    },
                    options: {
                        ...baseOpts,
                        cutout: "65%",
                        plugins: {
                            ...baseOpts.plugins,
                            legend: {
                                position: "bottom",
                                labels: { color: "#334155", boxWidth: 12 },
                            },
                        },
                    },
                    plugins: [pieLabelPlugin],
                });
                window.ticketPie = ticketPie;
                window.addEventListener("resize", () => {
                    const shown =
                        !sidebar.classList.contains("-translate-x-full");
                    setContentShift(shown);
                    // Hide backdrop on desktop
                    if (isLG() && backdrop) {
                        backdrop.classList.remove("active");
                    }
                });
                // no dynamic height sync; content uses fixed chart height

                // DataTable implementation: sorting, paging, filtering, selection, export
                (function initDataTable() {
                    const table = document.getElementById("transactions-table");
                    if (!table) return;
                    const tbody = document.getElementById("transactions-tbody");
                    const search = document.getElementById("dt-search");
                    const pageSizeSel = document.getElementById("dt-page-size");
                    const statusEl = document.getElementById("dt-status");
                    const pageEl = document.getElementById("dt-page");
                    const prevBtn = document.getElementById("dt-prev");
                    const nextBtn = document.getElementById("dt-next");
                    const selectAll = document.getElementById("dt-select-all");
                    const clearBtn = document.getElementById("dt-clear");
                    const reloadBtn = document.getElementById("dt-reload");
                    const exportCSVBtn =
                        document.getElementById("dt-export-csv");
                    const exportXLSBtn =
                        document.getElementById("dt-export-xls");
                    const exportPDFBtn =
                        document.getElementById("dt-export-pdf");
                    const columnsSel = document.getElementById("dt-columns");
                    const statusFilter =
                        document.getElementById("dt-status-filter");
                    const schoolFilter =
                        document.getElementById("dt-school-filter");
                    

                    const columns = [
                        { key: "id", label: "ID", visible: true, width: 64 },
                        {
                            key: "reference",
                            label: "Reference",
                            visible: true,
                            width: 220,
                        },
                        {
                            key: "customer",
                            label: "Customer",
                            visible: true,
                            width: 200,
                        },
                        {
                            key: "contact",
                            label: "Contact",
                            visible: true,
                            width: 220,
                        },
                        {
                            key: "school",
                            label: "School",
                            visible: true,
                            width: 200,
                        },
                        { key: "qty", label: "Qty", visible: true, width: 80 },
                        {
                            key: "amount",
                            label: "Amount",
                            visible: true,
                            width: 120,
                        },
                        {
                            key: "status",
                            label: "Status",
                            visible: true,
                            width: 120,
                        },
                        
                        {
                            key: "paymentDate",
                            label: "Payment Date",
                            visible: true,
                            width: 160,
                        },
                        {
                            key: "created",
                            label: "Created",
                            visible: true,
                            width: 160,
                        },
                    ];

                    let data = [];
                    let filtered = [];
                    let pageIndex = 0;
                    let pageSize = parseInt(pageSizeSel.value, 10) || 25;
                    let sortKey = "created";
                    let sortDir = "desc";

                    function apiUrl() {
                        return "/api/transactions";
                    }

                    async function loadData() {
                        statusEl.textContent = "Loading…";
                        try {
                            const demo = [
                                {
                                    id: 1,
                                    reference: "PACE-TRX-0001",
                                    customer: "Misheck Muiru",
                                    contact: "0117929791",
                                    school: "Kapsabet Boys",
                                    qty: 2,
                                    amount: 649,
                                    status: "Pending",
                                    stkStatus: "Launched",
                                    paymentDate: "—",
                                    created: "2025-11-27 17:04",
                                },
                                {
                                    id: 2,
                                    reference: "PACE-TRX-0002",
                                    customer: "Joan lesley Isibaki",
                                    contact: "lesleyisibaki@gmail.com",
                                    school: "OL-Kalou",
                                    qty: 1,
                                    amount: 649,
                                    status: "Pending",
                                    stkStatus: "Launched",
                                    paymentDate: "—",
                                    created: "2025-11-27 17:04",
                                },
                                {
                                    id: 3,
                                    reference: "PACE-TRX-0003",
                                    customer: "Keysha Kocha",
                                    contact: "angelothadi949@gmail.com",
                                    school: "St Georges",
                                    qty: 1,
                                    amount: 649,
                                    status: "Paid",
                                    stkStatus: "TRX123MEDZZ",
                                    paymentDate: "2025-11-27 17:01",
                                    created: "2025-11-27 17:01",
                                },
                                {
                                    id: 4,
                                    reference: "PACE-TRX-0004",
                                    customer: "Bridget Kemunto",
                                    contact: "eunsiondukabe@gmail.com",
                                    school: "Mount Carmel Girls",
                                    qty: 1,
                                    amount: 2500,
                                    status: "Paid",
                                    stkStatus: "TRX8891EDZC",
                                    paymentDate: "2025-11-27 16:58",
                                    created: "2025-11-27 16:58",
                                },
                            ];
                            let resData = window.paceData || demo;
                            data = Array.isArray(resData) ? resData : demo;
                            fillFilterOptions();
                            applyFilterSort();
                        } finally {
                            statusEl.textContent = "";
                        }
                    }

                    function fillFilterOptions() {
                        function setOptions(sel, firstLabel, values) {
                            if (!sel) return;
                            const uniq = Array.from(
                                new Set(values.filter(Boolean))
                            ).sort();
                            sel.innerHTML =
                                `<option selected>${firstLabel}</option>` +
                                uniq
                                    .map((v) => `<option>${v}</option>`)
                                    .join("");
                        }
                        setOptions(
                            schoolFilter,
                            "All Schools",
                            data.map((d) => String(d.school))
                        );
                        
                    }

                    function applyFilterSort() {
                        const q = (search.value || "").toLowerCase();
                        const sVal = statusFilter
                            ? statusFilter.value
                            : "All Status";
                        const schVal = schoolFilter
                            ? schoolFilter.value
                            : "All Schools";
                        
                        filtered = data.filter((row) => {
                            const matchesText = Object.keys(row).some((k) =>
                                String(row[k]).toLowerCase().includes(q)
                            );
                            const okStatus =
                                !statusFilter ||
                                sVal === "All Status" ||
                                String(row.status).toLowerCase() ===
                                    sVal.toLowerCase();
                            const okSchool =
                                !schoolFilter ||
                                schVal === "All Schools" ||
                                String(row.school).toLowerCase() ===
                                    schVal.toLowerCase();
                            return matchesText && okStatus && okSchool;
                        });
                        filtered.sort((a, b) => {
                            const av = a[sortKey],
                                bv = b[sortKey];
                            if (av == null && bv == null) return 0;
                            const cmp = av > bv ? 1 : av < bv ? -1 : 0;
                            return sortDir === "asc" ? cmp : -cmp;
                        });
                        pageIndex = 0;
                        document
                            .querySelectorAll(".dt-sort")
                            .forEach((el) => el.removeAttribute("aria-sort"));
                        const active = document.querySelector(
                            `.dt-sort[data-key="${sortKey}"]`
                        );
                        if (active)
                            active.setAttribute(
                                "aria-sort",
                                sortDir === "asc" ? "ascending" : "descending"
                            );
                        render();
                    }

                    function render() {
                        const start = pageIndex * pageSize;
                        const end = start + pageSize;
                        const pageRows = filtered.slice(start, end);
                        tbody.innerHTML = "";
                        
                        // Render desktop table
                        for (const row of pageRows) {
                            const tr = document.createElement("tr");
                            tr.className = "hover:bg-slate-50";
                            tr.setAttribute("tabindex", "0");
                            tr.setAttribute("aria-expanded", "false");
                            const selTd = document.createElement("td");
                            selTd.className = "py-2 pr-4";
                            selTd.innerHTML =
                                '<input type="checkbox" class="w-4 h-4 rounded border-slate-300" aria-label="Select row">';
                            tr.appendChild(selTd);
                            columns.forEach((col) => {
                                if (!col.visible) return;
                                const td = document.createElement("td");
                                td.className = "py-2 pr-4";
                                td.style.maxWidth = (col.width || 160) + "px";
                                if (col.key === "status") {
                                    const status = String(row.status);
                                    let cls = "inline-flex items-center px-2 py-0.5 rounded-full text-xs border";
                                    if (status === "Paid") cls += " bg-emerald-50 text-emerald-700 border-emerald-200";
                                    else if (status === "Pending") cls += " bg-amber-50 text-amber-700 border-amber-200";
                                    else cls += " bg-rose-50 text-rose-700 border-rose-200";
                                    const pill = document.createElement("span");
                                    pill.className = cls;
                                    pill.textContent = status;
                                    td.appendChild(pill);
                                    if (status === "Paid") {
                                        const code = row.receipt || row.trans_id || "";
                                        if (code) {
                                            const small = document.createElement("span");
                                            small.className = "ml-2 text-xs text-slate-500";
                                            small.textContent = code;
                                            td.appendChild(small);
                                        }
                                    }
                                } else {
                                    let value = row[col.key];
                                    if (col.key === "amount") value = `KSH ${Number(value).toFixed(2)}`;
                                    if (col.key === "qty") value = Number(value).toLocaleString();
                                    td.textContent = value;
                                }
                                tr.appendChild(td);
                            });
                            tbody.appendChild(tr);
                        }

                        // Render mobile cards
                        const mobileCards = document.getElementById("mobile-table-cards");
                        if (mobileCards) {
                            mobileCards.innerHTML = "";
                            pageRows.forEach((row) => {
                                const card = document.createElement("div");
                                card.className = "mobile-table-card";
                                
                                const status = String(row.status);
                                let statusCls = "inline-flex items-center px-2 py-1 rounded-full text-xs font-medium border";
                                if (status === "Paid") statusCls += " bg-emerald-50 text-emerald-700 border-emerald-200";
                                else if (status === "Pending") statusCls += " bg-amber-50 text-amber-700 border-amber-200";
                                else statusCls += " bg-rose-50 text-rose-700 border-rose-200";
                                
                                card.innerHTML = `
                                    <div class="mobile-card-header">
                                        <div>
                                            <div class="mobile-card-title">${row.customer || 'N/A'}</div>
                                            <div class="mobile-card-subtitle">${row.reference || ''}</div>
                                        </div>
                                        <span class="${statusCls}">${status}</span>
                                    </div>
                                    <div class="mobile-card-row">
                                        <span class="mobile-card-label">Amount</span>
                                        <span class="mobile-card-value font-semibold text-brand-600">KSH ${Number(row.amount).toFixed(2)}</span>
                                    </div>
                                    <div class="mobile-card-row">
                                        <span class="mobile-card-label">School</span>
                                        <span class="mobile-card-value">${row.school || 'N/A'}</span>
                                    </div>
                                    <div class="mobile-card-row">
                                        <span class="mobile-card-label">Quantity</span>
                                        <span class="mobile-card-value">${row.qty}</span>
                                    </div>
                                    <div class="mobile-card-details">
                                        <div class="mobile-card-row">
                                            <span class="mobile-card-label">Contact</span>
                                            <span class="mobile-card-value">${row.contact || 'N/A'}</span>
                                        </div>
                                        <div class="mobile-card-row">
                                            <span class="mobile-card-label">Payment Date</span>
                                            <span class="mobile-card-value">${row.paymentDate || '—'}</span>
                                        </div>
                                        <div class="mobile-card-row">
                                            <span class="mobile-card-label">Created</span>
                                            <span class="mobile-card-value">${row.created || '—'}</span>
                                        </div>
                                    </div>
                                    <div class="mobile-expand-toggle">
                                        <span class="toggle-text">Show Details</span>
                                        <svg class="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                                        </svg>
                                    </div>
                                `;
                                
                                // Add expand/collapse functionality
                                const toggle = card.querySelector(".mobile-expand-toggle");
                                const details = card.querySelector(".mobile-card-details");
                                const toggleText = toggle.querySelector(".toggle-text");
                                const toggleIcon = toggle.querySelector("svg");
                                
                                toggle.addEventListener("click", () => {
                                    const isExpanded = details.classList.contains("expanded");
                                    details.classList.toggle("expanded");
                                    toggleText.textContent = isExpanded ? "Show Details" : "Hide Details";
                                    toggleIcon.style.transform = isExpanded ? "" : "rotate(180deg)";
                                });
                                
                                mobileCards.appendChild(card);
                            });
                        }

                        const totalPages = Math.max(
                            1,
                            Math.ceil(filtered.length / pageSize)
                        );
                        pageEl.textContent = `${pageIndex + 1} / ${totalPages}`;
                        prevBtn.disabled = pageIndex <= 0;
                        nextBtn.disabled = pageIndex >= totalPages - 1;
                        table.setAttribute(
                            "aria-rowcount",
                            String(filtered.length)
                        );
                    }

                    document.querySelectorAll(".dt-sort").forEach((btn) => {
                        btn.addEventListener("click", () => {
                            const key = btn.dataset.key;
                            if (sortKey === key)
                                sortDir = sortDir === "asc" ? "desc" : "asc";
                            else {
                                sortKey = key;
                                sortDir = "asc";
                            }
                            applyFilterSort();
                        });
                    });

                    prevBtn.addEventListener("click", () => {
                        if (pageIndex > 0) {
                            pageIndex--;
                            render();
                        }
                    });
                    nextBtn.addEventListener("click", () => {
                        const totalPages = Math.max(
                            1,
                            Math.ceil(filtered.length / pageSize)
                        );
                        if (pageIndex < totalPages - 1) {
                            pageIndex++;
                            render();
                        }
                    });
                    pageSizeSel.addEventListener("change", () => {
                        pageSize = parseInt(pageSizeSel.value, 10) || 25;
                        pageIndex = 0;
                        render();
                    });

                    selectAll.addEventListener("change", () => {
                        tbody
                            .querySelectorAll('input[type="checkbox"]')
                            .forEach((cb) => {
                                cb.checked = selectAll.checked;
                            });
                    });
                    search.addEventListener("input", () => applyFilterSort());
                    clearBtn.addEventListener("click", () => {
                        search.value = "";
                        if (statusFilter) statusFilter.value = "All Status";
                        if (schoolFilter) schoolFilter.value = "All Schools";
                        
                        applyFilterSort();
                    });
                    reloadBtn.addEventListener("click", () => loadData());
                    if (statusFilter)
                        statusFilter.addEventListener("change", applyFilterSort);
                    if (schoolFilter)
                        schoolFilter.addEventListener("change", applyFilterSort);
                    

                    function updateColumnChips() {
                        const chips =
                            document.getElementById("dt-columns-chips");
                        if (!chips || !columnsSel) return;
                        chips.innerHTML = "";
                        Array.from(columnsSel.selectedOptions).forEach(
                            (opt) => {
                                const span = document.createElement("span");
                                span.className =
                                    "inline-flex items-center px-2 py-0.5 rounded-full text-xs bg-brand-50 text-brand-700 border border-brand-200";
                                span.textContent = opt.textContent.trim();
                                chips.appendChild(span);
                            }
                        );
                    }

                    if (columnsSel) {
                        columnsSel.addEventListener("change", () => {
                            columns.forEach((c) => (c.visible = false));
                            Array.from(columnsSel.selectedOptions).forEach(
                                (opt) => {
                                    const c = columns.find(
                                        (x) => x.key === opt.value
                                    );
                                    if (c) c.visible = true;
                                }
                            );
                            render();
                            updateColumnChips();
                        });
                    }

                    function toCSV(rows) {
                        const visibleCols = columns.filter((c) => c.visible);
                        const header = [
                            "Selected",
                            ...visibleCols.map((c) => c.label),
                        ].join(",");
                        const lines = [header];
                        rows.forEach((r) => {
                            lines.push(
                                ["", ...visibleCols.map((c) => r[c.key])].join(
                                    ","
                                )
                            );
                        });
                        return lines.join("\n");
                    }
                    exportCSVBtn.addEventListener("click", () => {
                        const csv = toCSV(filtered);
                        const blob = new Blob([csv], { type: "text/csv" });
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement("a");
                        a.href = url;
                        a.download = "transactions.csv";
                        a.click();
                        URL.revokeObjectURL(url);
                    });
                    exportXLSBtn.addEventListener("click", () => {
                        const csv = toCSV(filtered);
                        const blob = new Blob([csv], {
                            type: "application/vnd.ms-excel",
                        });
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement("a");
                        a.href = url;
                        a.download = "transactions.xls";
                        a.click();
                        URL.revokeObjectURL(url);
                    });
                    exportPDFBtn.addEventListener("click", () =>
                        window.print()
                    );

                    const container = document.querySelector(
                        "#transactions-section .overflow-x-auto"
                    );
                    if (container)
                        container.addEventListener("scroll", () => {}, {
                            passive: true,
                        });

                    table.setAttribute("role", "grid");
                    table.addEventListener("keydown", (e) => {
                        if (e.key === "ArrowDown") {
                            const f = tbody.querySelector("tr:focus");
                            const n = f
                                ? f.nextElementSibling
                                : tbody.firstElementChild;
                            n && n.focus();
                        }
                        if (e.key === "ArrowUp") {
                            const f = tbody.querySelector("tr:focus");
                            const p = f ? f.previousElementSibling : null;
                            p && p.focus();
                        }
                    });

                    updateColumnChips();
                    if (columnsSel) updateColumnChips();
                    loadData();
                })();

                (function initCounters() {
                    const els = Array.from(document.querySelectorAll('.counter'));
                    if (!els.length) return;
                    function format(n, decimals, prefix) {
                        return (prefix || '') + Number(n).toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
                    }
                    const animate = (el, fromValue) => {
                        const target = parseFloat(el.getAttribute('data-target') || '0') || 0;
                        const decimals = parseInt(el.getAttribute('data-decimals') || '0', 10) || 0;
                        const prefix = el.getAttribute('data-prefix') || '';
                        const mode = el.getAttribute('data-mode') || 'smooth';
                        const duration = prefersReduced ? 0 : 1200;
                        const baseText = el.textContent || '0';
                        const baseNumeric = parseFloat(baseText.replace(prefix, '').replace(/,/g, '')) || 0;
                        const base = typeof fromValue === 'number' ? fromValue : baseNumeric;
                        if (!duration) {
                            el.textContent = format(target, decimals, prefix);
                            return;
                        }
                        const start = performance.now();
                        const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
                        function tick(now) {
                            const elapsed = now - start;
                            const progress = Math.min(1, elapsed / duration);
                            const eased = easeOutCubic(progress);
                            let value;
                            if (mode === 'step' && decimals === 0) {
                                const delta = target - base;
                                const frames = 60;
                                const stepSize = Math.max(1, Math.round(Math.abs(delta) / frames)) * Math.sign(delta);
                                const raw = base + delta * eased;
                                const stepsCount = Math.round((raw - base) / stepSize);
                                value = base + stepsCount * stepSize;
                                if ((delta > 0 && value > target) || (delta < 0 && value < target)) value = target;
                            } else {
                                value = base + (target - base) * eased;
                            }
                            el.textContent = format(value, decimals, prefix);
                            if (progress < 1) requestAnimationFrame(tick);
                            else el.textContent = format(target, decimals, prefix);
                        }
                        requestAnimationFrame(tick);
                    };
                    const observer = new IntersectionObserver((entries, ob) => {
                        entries.forEach((e) => {
                            if (e.isIntersecting) {
                                animate(e.target);
                                ob.unobserve(e.target);
                            }
                        });
                    }, { threshold: 0.4 });
                    els.forEach((el) => observer.observe(el));
                    window.paceAnimate = animate;

                    // Dynamic font size adjustment for mobile KPI cards
                    function adjustKPIFontSize() {
                        if (window.innerWidth > 640) return; // Only on mobile
                        
                        document.querySelectorAll('.kpi-card-value').forEach((valueEl) => {
                            const text = valueEl.textContent || '';
                            const length = text.length;
                            
                            // Reset to default
                            valueEl.style.fontSize = '';
                            
                            // Adjust based on text length for better fit
                            if (length > 15) {
                                valueEl.style.fontSize = '1rem';
                            } else if (length > 12) {
                                valueEl.style.fontSize = '1.125rem';
                            }
                        });
                    }

                    // Adjust after animations and on resize
                    setTimeout(adjustKPIFontSize, 1300);
                    window.addEventListener('resize', adjustKPIFontSize);
                })();

                (function pollStats() {
                    const counters = Array.from(document.querySelectorAll('.counter'));
                    function updateCountersFromStats(s) {
                        counters.forEach((el) => {
                            const key = el.getAttribute('data-key');
                            if (!key || !(key in s)) return;
                            const decimals = parseInt(el.getAttribute('data-decimals') || '0', 10) || 0;
                            const prefix = el.getAttribute('data-prefix') || '';
                            const currentText = el.textContent || '0';
                            const numeric = parseFloat(currentText.replace(prefix, '').replace(/,/g, '')) || 0;
                            el.setAttribute('data-target', String(s[key]));
                            const last = parseFloat(el.getAttribute('data-last') || 'NaN');
                            const next = Number(s[key]);
                            if (last !== next) {
                                el.setAttribute('data-last', String(next));
                                const animateFrom = isNaN(last) ? numeric : last;
                                if (window.paceAnimate) {
                                    window.paceAnimate(el, animateFrom);
                                } else {
                                    el.textContent = String(next);
                                }
                            }
                        });
                    }
                    async function fetchStats() {
                        try {
                            const res = await fetch('/api/ticket-stats', { headers: { 'Accept': 'application/json' } });
                            if (!res.ok) return;
                            const s = await res.json();
                            stats = { ...stats, ...s };
                            // Update charts
                            if (window.eventBar) {
                                window.eventBar.data.datasets[0].data = [
                                    stats.total_tickets,
                                    stats.total_paid,
                                    stats.total_pending,
                                    stats.total_failed,
                                ];
                                window.eventBar.update();
                            }
                            if (window.ticketPie) {
                                window.ticketPie.data.datasets[0].data = [
                                    stats.total_paid,
                                    stats.total_pending,
                                    stats.total_failed,
                                ];
                                window.ticketPie.update();
                            }
                            updateCountersFromStats(stats);
                        } catch (e) {}
                    }
                    fetchStats();
                    window.paceFetchStats = fetchStats;
                    let timer = setInterval(() => {
                        if (document.visibilityState === 'visible') fetchStats();
                    }, 5000);
                    document.addEventListener('visibilitychange', () => {
                        if (document.visibilityState !== 'visible') return;
                        fetchStats();
                    });
                })();

                (function overlayControls() {
                    const overlay = document.getElementById('kpiOverlay');
                    const titleEl = document.getElementById('kpiOverlayTitle');
                    const counterEl = document.getElementById('kpiOverlayCounter');
                    const closeBtn = document.getElementById('kpiOverlayClose');
                    const cardEls = Array.from(document.querySelectorAll('[data-kpi-card]'));
                    const labels = {
                        total_revenue: 'Total Revenue',
                        today_sales: "Today's Sales",
                        today_revenue: "Today's Revenue",
                    };
                    async function openFor(key) {
                        titleEl.textContent = labels[key] || key;
                        counterEl.setAttribute('data-key', key);
                        const decimals = key.includes('revenue') ? 2 : 0;
                        const prefix = key.includes('revenue') ? 'KSH ' : '';
                        counterEl.setAttribute('data-decimals', String(decimals));
                        if (prefix) counterEl.setAttribute('data-prefix', prefix); else counterEl.removeAttribute('data-prefix');
                        const val = Number(stats[key] || 0);
                        counterEl.setAttribute('data-target', String(val));
                        overlay.classList.remove('hidden');
                        if (window.paceFetchStats) await window.paceFetchStats();
                        if (window.paceAnimate) window.paceAnimate(counterEl, 0);
                    }
                    cardEls.forEach((el) => {
                        el.addEventListener('click', () => {
                            const key = el.getAttribute('data-kpi-card');
                            openFor(key);
                        });
                    });
                    closeBtn.addEventListener('click', () => {
                        overlay.classList.add('hidden');
                    });
                    const backdrop = document.getElementById('kpiOverlayBackdrop');
                    if (backdrop) backdrop.addEventListener('click', () => overlay.classList.add('hidden'));
                    overlay.addEventListener('click', (e) => {
                        if (e.target === overlay) overlay.classList.add('hidden');
                    });
                })();
            });
        </script>
    </body>
</html>
