

<?php $__env->startSection('content'); ?>
<div class="space-y-6 sm:space-y-8 animate-fade-in pb-8">
    <!-- Header Area -->
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white p-6 rounded-3xl shadow-[0_8px_30px_rgb(0,0,0,0.04)] border border-green-50">
        <div>
            <h1 class="text-3xl sm:text-4xl font-extrabold text-slate-800 tracking-tight flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-green-400 to-emerald-600 text-white flex items-center justify-center shadow-lg shadow-green-200">
                    <i data-lucide="layout-dashboard" class="w-5 h-5"></i>
                </div>
                Dashboard Admin
            </h1>
            <p class="text-green-600/80 text-sm font-semibold uppercase tracking-widest mt-2 ml-[52px]"><?php echo e(now()->translatedFormat('l, d F Y')); ?></p>
        </div>
        <div class="flex items-center gap-4 bg-green-50/50 px-5 py-3 rounded-2xl w-full md:w-auto">
            <div class="text-left md:text-right flex-1 md:flex-none">
                <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest leading-none">Status Koneksi</p>
                <div class="flex items-center gap-2 mt-1.5 md:justify-end">
                    <span class="relative flex h-2.5 w-2.5">
                        <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                        <span class="relative inline-flex rounded-full h-2.5 w-2.5 bg-emerald-500"></span>
                    </span>
                    <p class="text-sm font-black text-emerald-600 uppercase">SISTEM AKTIF</p>
                </div>
            </div>
            <button type="button" class="w-10 h-10 rounded-xl bg-white flex items-center justify-center border border-green-100 shadow-sm cursor-pointer hover:bg-green-50 transition-colors" onclick="window.location.reload()" aria-label="Refresh Halaman">
                <i data-lucide="refresh-cw" class="w-4 h-4 text-emerald-500"></i>
            </button>
        </div>
    </div>

    <!-- Stats Cards Grid -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
        <!-- Total Pesanan -->
        <div class="group bg-white p-6 rounded-3xl shadow-[0_8px_30px_rgb(0,0,0,0.04)] border border-slate-50 transition-all duration-300 hover:-translate-y-1 hover:shadow-xl hover:shadow-blue-100 relative overflow-hidden">
            <div class="absolute -right-6 -top-6 w-24 h-24 bg-blue-50 rounded-full transition-transform duration-500 group-hover:scale-150 group-hover:bg-blue-100/50 -z-10"></div>
            <div class="flex items-center gap-5 z-10">
                <div class="w-14 h-14 rounded-2xl bg-gradient-to-br from-blue-400 to-indigo-500 text-white flex items-center justify-center shadow-lg shadow-blue-200">
                    <i data-lucide="shopping-cart" class="w-6 h-6"></i>
                </div>
                <div>
                    <p class="text-[10px] font-black text-slate-400 uppercase tracking-[0.1em] mb-1">Total Pesanan</p>
                    <h3 class="text-3xl font-black text-slate-800"><?php echo e($totalTransaksiHariIni ?? 0); ?></h3>
                </div>
            </div>
        </div>

        <!-- Total Penjualan -->
        <div class="group relative overflow-hidden bg-gradient-to-br from-slate-900 via-slate-800 to-emerald-900 p-6 rounded-3xl shadow-[0_8px_30px_rgb(0,0,0,0.12)] border border-slate-700 transition-all duration-300 hover:-translate-y-1 hover:shadow-xl hover:shadow-emerald-900/50">
            <div class="absolute -right-10 -bottom-10 w-32 h-32 bg-emerald-500/20 blur-2xl rounded-full transition-all duration-500 group-hover:bg-emerald-400/30"></div>
            <div class="flex items-center gap-5 relative z-10">
                <div class="w-14 h-14 rounded-2xl bg-emerald-500/20 text-emerald-400 backdrop-blur-md border border-emerald-500/30 flex items-center justify-center">
                    <i data-lucide="wallet" class="w-6 h-6"></i>
                </div>
                <div>
                    <p class="text-[10px] font-black text-emerald-500 uppercase tracking-[0.1em] mb-1">Total Penjualan</p>
                    <h3 class="text-2xl font-black text-white">Rp <?php echo e(number_format($pendapatanHariIni ?? 0, 0, ',', '.')); ?></h3>
                </div>
            </div>
        </div>

        <!-- Stok Kosong -->
        <div class="group bg-white p-6 rounded-3xl shadow-[0_8px_30px_rgb(0,0,0,0.04)] border border-slate-50 transition-all duration-300 hover:-translate-y-1 hover:shadow-xl hover:shadow-amber-100">
            <div class="flex items-center justify-between mb-3">
                <p class="text-[10px] font-black text-slate-400 uppercase tracking-[0.1em]">Produk Kosong</p>
                <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-amber-400 to-orange-500 text-white flex items-center justify-center shadow-lg shadow-amber-200">
                    <i data-lucide="package-x" class="w-4 h-4"></i>
                </div>
            </div>
            <h3 class="text-3xl font-black text-slate-800">
                <?php echo e($stokKosongList->count() ?? 0); ?> 
                <span class="text-sm text-slate-400 font-bold uppercase tracking-tight">Varian</span>
            </h3>
            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($stokKosongList->count() > 0): ?>
                <div class="mt-3 flex flex-wrap gap-1.5">
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $stokKosongList; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $stok): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                        <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-lg bg-amber-50 border border-amber-200 text-[10px] font-bold text-amber-700 leading-tight">
                            <i data-lucide="package-x" class="w-2.5 h-2.5 shrink-0"></i>
                            <?php echo e($stok->nama_produk); ?>

                        </span>
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                </div>
            <?php else: ?>
                <p class="mt-3 text-[11px] text-emerald-600 font-bold flex items-center gap-1">
                    <i data-lucide="check-circle" class="w-3 h-3"></i> Semua produk tersedia
                </p>
            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
            <div class="mt-3 w-full bg-slate-100 h-1.5 rounded-full overflow-hidden">
                <div class="bg-gradient-to-r from-amber-400 to-orange-500 h-full transition-all duration-1000 ease-out" 
                     style="width: <?php echo e(min(($stokKosongList->count() ?? 0) * 20, 100)); ?>%"></div>
            </div>
        </div>


        <!-- Pesanan User Baru -->
        <a href="<?php echo e(route('admin.pesanan')); ?>" class="group relative overflow-hidden bg-gradient-to-br from-purple-600 to-fuchsia-600 p-6 rounded-3xl shadow-[0_8px_30px_rgb(0,0,0,0.12)] border border-purple-500 transition-all duration-300 hover:-translate-y-1 hover:shadow-xl hover:shadow-purple-500/30 flex items-center gap-5">
            <div class="absolute -left-6 -top-6 w-24 h-24 bg-white/10 rounded-full transition-transform duration-500 group-hover:scale-150 group-hover:bg-white/20"></div>
            <div class="w-14 h-14 z-10 rounded-2xl bg-white/20 text-white backdrop-blur-md flex items-center justify-center border border-white/30 transition-transform group-hover:scale-110 duration-300">
                <i data-lucide="smartphone" class="w-6 h-6"></i>
            </div>
            <div class="z-10">
                <p class="text-[10px] font-black text-fuchsia-100 uppercase tracking-[0.1em] mb-1">Pesanan Pengguna</p>
                <h3 class="text-3xl font-black text-white"><?php echo e($pesananUserBaru ?? 0); ?></h3>
                <p class="text-[10px] font-bold text-white/80 mt-1 flex items-center gap-1">Kelola Pesanan <i data-lucide="arrow-right" class="w-3 h-3 group-hover:translate-x-1 transition-transform"></i></p>
            </div>
        </a>
    </div>

    <!-- Peta Persebaran Pelanggan -->
    <div class="map-section-card">
        <!-- Header -->
        <div class="map-section-header">
            <div class="map-section-title-group">
                <div class="map-icon-wrap">
                    <i data-lucide="map" class="w-5 h-5"></i>
                </div>
                <div>
                    <h3 class="map-section-title">Visualisasi Persebaran Pelanggan</h3>
                    <p class="map-section-subtitle">Distribusi spasial dan analisis jangkauan depot operasional</p>
                </div>
            </div>
            <div class="map-header-actions">
                <div class="map-status-badge" id="map-status-badge">
                    <span class="map-status-dot"><span></span></span>
                    <span id="map-status-text">Memproses Lokasi...</span>
                </div>
                <button onclick="clearMapCache()" class="map-clear-btn" title="Hapus cache & geocode ulang">
                    <i data-lucide="refresh-cw" class="w-3.5 h-3.5"></i>
                    Hapus Cache
                </button>
            </div>
        </div>


        <!-- Body: Sidebar + Map -->
        <div class="map-body">
            <!-- Sidebar Zona -->
            <aside class="map-sidebar">
                <div class="map-search-container">
                    <div class="map-search-wrapper">
                        <i data-lucide="search" class="w-4 h-4 map-search-icon"></i>
                        <input type="text" id="map-search-input" placeholder="Cari nama atau kelurahan..." class="map-search-input">
                    </div>
                </div>
                <div class="map-sidebar-scroll" id="zone-lists-container">
                    <!-- Zona 1 -->
                    <div class="map-zone-group">
                        <div class="map-zone-label zone-1 cursor-pointer hover:bg-green-100/50 transition-colors" onclick="toggleZoneVisibility(1)" title="Klik untuk sembunyikan/tampilkan zona">
                            <span class="zone-dot"></span>
                            <span>Zona 1 &mdash; Lokal <small>&lt;2 km</small></span>
                            <span class="zone-count" id="count-zone-1">0</span>
                        </div>
                        <div id="list-zone-1" class="map-zone-items">
                        </div>
                    </div>
                    <!-- Zona 2 -->
                    <div class="map-zone-group">
                        <div class="map-zone-label zone-2 cursor-pointer hover:bg-blue-100/50 transition-colors" onclick="toggleZoneVisibility(2)" title="Klik untuk sembunyikan/tampilkan zona">
                            <span class="zone-dot"></span>
                            <span>Zona 2 &mdash; Sedang <small>2&ndash;5 km</small></span>
                            <span class="zone-count" id="count-zone-2">0</span>
                        </div>
                        <div id="list-zone-2" class="map-zone-items">
                        </div>
                    </div>
                    <!-- Zona 3 -->
                    <div class="map-zone-group">
                        <div class="map-zone-label zone-3 cursor-pointer hover:bg-rose-100/50 transition-colors" onclick="toggleZoneVisibility(3)" title="Klik untuk sembunyikan/tampilkan zona">
                            <span class="zone-dot"></span>
                            <span>Zona 3 &mdash; Jauh <small>&gt;5 km</small></span>
                            <span class="zone-count" id="count-zone-3">0</span>
                        </div>
                        <div id="list-zone-3" class="map-zone-items">
                        </div>
                    </div>
                </div>
            </aside>

            <!-- Peta -->
            <div class="map-canvas-wrap">
                <div id="customerMap"></div>
                
                <!-- Floating Map Controls -->
                <div class="map-floating-controls">
                    <button type="button" onclick="toggleMapStyle()" class="map-control-btn" title="Ganti Gaya Peta" aria-label="Ganti Gaya Peta">
                        <i data-lucide="layers" class="w-4 h-4"></i>
                    </button>
                    <button type="button" onclick="fitVisibleBounds()" class="map-control-btn" title="Posisikan Ulang Peta" aria-label="Posisikan Ulang Peta">
                        <i data-lucide="maximize" class="w-4 h-4"></i>
                    </button>
                </div>

                <!-- Floating Legend -->
                <div class="map-legend">
                    <div class="legend-header">Legenda Wilayah</div>
                    <div class="legend-item" onclick="map.panTo([<?php echo e(-6.2569093); ?>, <?php echo e(106.5582734); ?>], {animate:true, duration:0.6})" title="Klik untuk memfokuskan depot">
                        <span class="legend-dot" style="background:#ef4444;box-shadow:0 0 8px rgba(239,68,68,0.6)"></span>
                        <span>Depot Utama</span>
                    </div>
                    <div class="legend-item zone-1" onclick="toggleZoneVisibility(1)">
                        <span class="legend-dot" style="background:#22c55e;box-shadow:0 0 8px rgba(34, 197, 94, 0.6)"></span>
                        <span>Zona 1 (&lt; 2 km)</span>
                    </div>
                    <div class="legend-item zone-2" onclick="toggleZoneVisibility(2)">
                        <span class="legend-dot" style="background:#3b82f6;box-shadow:0 0 8px rgba(59, 130, 246, 0.6)"></span>
                        <span>Zona 2 (2 - 5 km)</span>
                    </div>
                    <div class="legend-item zone-3" onclick="toggleZoneVisibility(3)">
                        <span class="legend-dot" style="background:#f43f5e;box-shadow:0 0 8px rgba(244, 63, 94, 0.6)"></span>
                        <span>Zona 3 (&gt; 5 km)</span>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <!-- Charts Section -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 pb-2">
        <!-- Grafik Penjualan -->
        <div class="bg-white p-6 sm:p-8 rounded-[2rem] shadow-[0_8px_30px_rgb(0,0,0,0.06)] border border-slate-50">
            <div class="flex items-center gap-3 mb-8">
                <div class="w-10 h-10 rounded-xl bg-orange-50 text-orange-500 flex items-center justify-center">
                    <i data-lucide="trending-up" class="w-5 h-5"></i>
                </div>
                <div>
                    <h3 class="text-lg font-black text-slate-800">Grafik Penjualan</h3>
                    <p class="text-[10px] font-bold text-slate-400 uppercase tracking-[0.15em] mt-0.5">7 Hari Terakhir</p>
                </div>
            </div>
            <div class="relative h-[250px] sm:h-[300px]">
                <canvas id="chartPenjualan"></canvas>
            </div>
        </div>

        <!-- Grafik Kategori -->
        <div class="bg-white p-6 sm:p-8 rounded-[2rem] shadow-[0_8px_30px_rgb(0,0,0,0.06)] border border-slate-50">
            <div class="flex items-center gap-3 mb-8">
                <div class="w-10 h-10 rounded-xl bg-purple-50 text-purple-600 flex items-center justify-center">
                    <i data-lucide="pie-chart" class="w-5 h-5"></i>
                </div>
                <div>
                    <h3 class="text-lg font-black text-slate-800">Produk Keluar</h3>
                    <p class="text-[10px] font-bold text-slate-400 uppercase tracking-[0.15em] mt-0.5">Per Kategori Varian</p>
                </div>
            </div>
            <div class="relative h-[250px] sm:h-[300px]">
                <canvas id="chartKategori"></canvas>
            </div>
        </div>
    </div>

    <!-- Pesanan User Terbaru Table -->
    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($latestUserOrders->count()): ?>
    <div class="bg-white rounded-[2rem] shadow-[0_8px_30px_rgb(0,0,0,0.06)] border border-slate-50 overflow-hidden transform-gpu">
        <div class="px-6 sm:px-8 py-6 border-b border-slate-100 flex items-center justify-between bg-gradient-to-r from-slate-50/50 to-white">
            <div class="flex items-center gap-4">
                <div class="w-12 h-12 rounded-2xl bg-gradient-to-br from-indigo-500 to-purple-600 text-white flex items-center justify-center shadow-lg shadow-indigo-200">
                    <i data-lucide="bell" class="w-6 h-6"></i>
                </div>
                <div>
                    <h3 class="text-lg font-black text-slate-800 tracking-tight">Pesanan Masuk Terbaru</h3>
                    <p class="text-[10px] font-bold text-slate-500 uppercase tracking-widest mt-0.5">Aktivitas Pelanggan (App)</p>
                </div>
            </div>
            <a href="<?php echo e(route('admin.pesanan')); ?>" class="hidden sm:inline-flex items-center gap-2 text-xs font-bold text-indigo-600 uppercase tracking-widest py-2 px-4 rounded-xl hover:bg-indigo-50 transition-colors">
                Kelola Semua <i data-lucide="chevron-right" class="w-4 h-4"></i>
            </a>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full text-left whitespace-nowrap">
                <thead class="bg-slate-50/80 border-b border-slate-100 text-slate-500">
                    <tr>
                        <th class="px-6 sm:px-8 py-5 text-[10px] font-black uppercase tracking-[0.15em]">Produk</th>
                        <th class="px-6 sm:px-8 py-5 text-[10px] font-black uppercase tracking-[0.15em]">Pelanggan</th>
                        <th class="px-6 sm:px-8 py-5 text-[10px] font-black uppercase tracking-[0.15em] text-center">Status</th>
                        <th class="px-6 sm:px-8 py-5 text-[10px] font-black uppercase tracking-[0.15em] text-right">Total Transaksi</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $latestUserOrders; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $order): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                    <tr class="hover:bg-slate-50/50 transition-colors group animate-fade-in">
                        <td class="px-6 sm:px-8 py-5">
                            <div class="space-y-4">
                                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $order['items']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                    <div class="flex items-center gap-4">
                                        <?php
                                            $namaProdukLow = strtolower($item->produk->nama_produk ?? '');
                                            $imgUrl = asset('fix.jpeg'); // Default logo
                                            if (str_contains($namaProdukLow, '3kg') || str_contains($namaProdukLow, '3 kg')) {
                                                $imgUrl = asset('images/gas_3kg_elpiji.jpg');
                                            } elseif (str_contains($namaProdukLow, '12kg') || str_contains($namaProdukLow, '12 kg')) {
                                                $imgUrl = asset('images/gas_12kg_bright.jpg');
                                            } elseif (str_contains($namaProdukLow, '5.5') || str_contains($namaProdukLow, '5,5') || str_contains($namaProdukLow, '5.5kg') || str_contains($namaProdukLow, '5.5 kg')) {
                                                $imgUrl = asset('images/gas5-5.jpg');
                                            }
                                        ?>
                                        <div class="w-10 h-10 rounded-xl overflow-hidden border border-slate-100 flex items-center justify-center shrink-0 shadow-sm bg-white">
                                            <img src="<?php echo e($imgUrl); ?>" alt="Produk <?php echo e($item->produk->nama_produk ?? 'Gas'); ?>" width="40" height="40" loading="lazy" class="w-full h-full object-cover">
                                        </div>
                                        <div>
                                            <p class="font-extrabold text-slate-800 text-sm leading-snug"><?php echo e($item->produk->nama_produk ?? 'Gas Elpiji'); ?></p>
                                            <p class="text-[10px] text-slate-500 font-semibold"><?php echo e($item->qty_beli_isi); ?> Tabung × Rp <?php echo e(number_format($item->harga_satuan, 0, ',', '.')); ?></p>
                                            <p class="text-[9px] text-slate-400 font-bold tracking-widest uppercase mt-0.5"><?php echo e($order['customers_id']); ?> • <?php echo e($order['pelanggan']->name ?? 'User'); ?></p>
                                        </div>
                                    </div>
                                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                            </div>
                        </td>
                        <td class="px-6 sm:px-8 py-5 align-middle">
                            <div class="flex flex-col">
                                <span class="font-extrabold text-slate-800 text-sm"><?php echo e($order['pelanggan']->name ?? 'User '.$order['customers_id']); ?></span>
                                <span class="text-[10px] text-slate-500 font-semibold mt-0.5"><?php echo e($order['pelanggan']->phone ?? '-'); ?></span>
                            </div>
                        </td>
                        <td class="px-6 sm:px-8 py-5 text-center align-middle">
                            <?php
                                $statusConf = [
                                    'menunggu' => ['color' => 'amber', 'icon' => 'clock'],
                                    'diproses' => ['color' => 'blue', 'icon' => 'loader'],
                                    'dikirim'  => ['color' => 'orange', 'icon' => 'truck'],
                                    'selesai'  => ['color' => 'emerald', 'icon' => 'check-circle']
                                ];
                                $conf = $statusConf[$order['status']] ?? ['color' => 'slate', 'icon' => 'info'];
                            ?>
                            <span class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-<?php echo e($conf['color']); ?>-50 text-<?php echo e($conf['color']); ?>-600 text-[10px] font-black uppercase tracking-widest border border-<?php echo e($conf['color']); ?>-100/50 shadow-[0_2px_10px_rgba(0,0,0,0.02)]">
                                <i data-lucide="<?php echo e($conf['icon']); ?>" class="w-3 h-3"></i>
                                <?php echo e($order['status']); ?>

                            </span>
                        </td>
                        <td class="px-6 sm:px-8 py-5 text-right align-middle">
                            <p class="font-black text-slate-900 text-base">Rp <?php echo e(number_format($order['total_semua'], 0, ',', '.')); ?></p>
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($order['ongkir_semua'] > 0): ?>
                                <p class="text-[10px] text-emerald-600 font-bold mt-0.5">Ongkir: Rp <?php echo e(number_format($order['ongkir_semua'], 0, ',', '.')); ?></p>
                            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                            <p class="text-[10px] text-slate-400 font-semibold mt-1"><?php echo e(\Carbon\Carbon::parse($order['created_at'])->diffForHumans()); ?></p>
                        </td>
                    </tr>
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                </tbody>
            </table>
            <div class="p-4 sm:hidden border-t border-slate-100">
                <a href="<?php echo e(route('admin.pesanan')); ?>" class="block text-center w-full bg-slate-50 text-indigo-600 text-xs font-bold uppercase tracking-widest py-3 rounded-xl">Lihat Semua Pesanan</a>
            </div>
        </div>
    </div>
    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
<?php $__env->startPush('styles'); ?>
<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
<?php $__env->stopPush(); ?>
<style>
/* â”â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•”€ Fade-in page animation â”â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•”€ */
.animate-fade-in { animation: fadeIn 0.5s ease-out both; }
@keyframes fadeIn { from { opacity:0; transform:translateY(12px); } to { opacity:1; transform:translateY(0); } }

/* â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
   MAP SECTION â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•” Professional Design
   â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• */
.map-section-card {
    background: #ffffff;
    border-radius: 0.5rem;
    border: 1px solid #e2e8f0;
    overflow: hidden;
}

/* Header */
.map-section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 1rem;
    padding: 1rem 1.5rem;
    border-bottom: 1px solid #e2e8f0;
    background: #ffffff;
}

.map-section-title-group {
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.map-icon-wrap {
    width: 2rem;
    height: 2rem;
    flex-shrink: 0;
    border-radius: 0.25rem;
    background: #3b82f6;
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
}

.map-section-title {
    font-size: 1rem;
    font-weight: 600;
    color: #1e293b;
}

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

.map-header-actions {
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.map-status-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.375rem;
    padding: 0.25rem 0.5rem;
    background: #f0fdf4;
    border: 1px solid #dcfce7;
    border-radius: 0.25rem;
    font-size: 0.75rem;
    color: #166534;
}

.map-status-dot {
    width: 0.5rem;
    height: 0.5rem;
    border-radius: 50%;
    background: #22c55e;
}

.map-clear-btn {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    padding: 0.25rem 0.5rem;
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 0.25rem;
    font-size: 0.75rem;
    color: #64748b;
    cursor: pointer;
}

.map-clear-btn:hover {
    background: #f1f5f9;
}

/* Map Layout */
.map-body {
    display: grid;
    grid-template-columns: 320px 1fr;
    gap: 0;
    height: 500px;
}

@media (max-width: 1024px) {
    .map-body {
        grid-template-columns: 1fr;
        grid-template-rows: 240px 400px;
        height: auto;
    }
}

/* Sidebar */
.map-sidebar {
    display: flex;
    flex-direction: column;
    border-right: 1px solid #e2e8f0;
    background: #ffffff;
    overflow: hidden;
}

@media (max-width: 1024px) {
    .map-sidebar {
        border-right: none;
        border-bottom: 1px solid #e2e8f0;
    }
}

/* Sidebar Search Box */
.map-search-container {
    padding: 0.75rem;
    border-bottom: 1px solid #e2e8f0;
}

.map-search-wrapper {
    position: relative;
    display: flex;
    align-items: center;
}

.map-search-input {
    width: 100%;
    padding: 0.5rem 0.75rem 0.5rem 2rem;
    border-radius: 0.25rem;
    border: 1px solid #e2e8f0;
    font-size: 0.75rem;
    color: #334155;
}

.map-search-icon {
    position: absolute;
    left: 0.5rem;
    color: #94a3b8;
}

/* Sidebar List Scroll */
.map-sidebar-scroll {
    flex: 1;
    overflow-y: auto;
    padding: 0.75rem;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

/* Zone header badges */
.map-zone-group {
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
}

.map-zone-label {
    display: flex;
    align-items: center;
    gap: 0.375rem;
    padding: 0.375rem 0.5rem;
    border-radius: 0.25rem;
    font-size: 0.75rem;
    font-weight: 600;
    cursor: pointer;
}

.map-zone-label.disabled {
    opacity: 0.6;
    text-decoration: line-through;
    background: #f1f5f9 !important;
    color: #64748b !important;
    border-color: #e2e8f0 !important;
}

.map-zone-label small {
    font-weight: normal;
    color: inherit;
    margin-left: 0.25rem;
}

.map-zone-label .zone-count {
    margin-left: auto;
    font-size: 0.7rem;
    padding: 0 0.375rem;
    border-radius: 0.25rem;
}

.zone-dot {
    width: 0.375rem;
    height: 0.375rem;
    border-radius: 50%;
}

.zone-1 { background: #f0fdf4; color: #166534; border: 1px solid #dcfce7; }
.zone-1 .zone-dot { background: #22c55e; }
.zone-1 .zone-count { background: #dcfce7; }

.zone-2 { background: #eff6ff; color: #1e40af; border: 1px solid #dbeafe; }
.zone-2 .zone-dot { background: #3b82f6; }
.zone-2 .zone-count { background: #dbeafe; }

.zone-3 { background: #fff1f2; color: #9f1239; border: 1px solid #ffe4e6; }
.zone-3 .zone-dot { background: #f43f5e; }
.zone-3 .zone-count { background: #ffe4e6; }

.map-zone-items {
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
}

/* Customer Item Card */
.zone-customer-btn {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    width: 100%;
    text-align: left;
    padding: 0.5rem;
    border-radius: 0.25rem;
    background: #ffffff;
    border: 1px solid #e2e8f0;
    cursor: pointer;
}

.zone-customer-btn:hover, .zone-customer-btn.active {
    background: #f8fafc;
    border-color: #cbd5e1;
}

.zone-customer-distance {
    font-size: 0.7rem;
    width: 2rem;
    text-align: center;
    color: #475569;
}

.zone-customer-info {
    flex: 1;
    min-width: 0;
}

.zone-customer-name {
    font-size: 0.75rem;
    font-weight: 600;
    color: #1e293b;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.zone-customer-sub {
    font-size: 0.7rem;
    color: #64748b;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.zone-empty-note {
    font-size: 0.75rem;
    color: #64748b;
    text-align: center;
    padding: 0.5rem;
}

/* Map Canvas Container */
.map-canvas-wrap {
    position: relative;
    background: #e2e8f0;
}

#customerMap {
    width: 100%;
    height: 100%;
}

/* Map Floating Control Box (Layers & Filters) */
.map-floating-controls {
    position: absolute;
    top: 1rem;
    right: 1rem;
    z-index: 1000;
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
}

.map-control-btn {
    width: 2rem;
    height: 2rem;
    border-radius: 0.25rem;
    background: #ffffff;
    border: 1px solid #cbd5e1;
    color: #334155;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.map-control-btn:hover {
    background: #f1f5f9;
}

.map-control-btn.active {
    background: #e2e8f0;
}

/* Premium Floating Legend */
.map-legend {
    position: absolute;
    bottom: 1rem;
    left: 1rem;
    z-index: 1000;
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
    background: #ffffff;
    border: 1px solid #cbd5e1;
    border-radius: 0.25rem;
    padding: 0.5rem;
}

.legend-header {
    font-size: 0.7rem;
    font-weight: 600;
    color: #475569;
    margin-bottom: 0.25rem;
    border-bottom: 1px solid #e2e8f0;
    padding-bottom: 0.125rem;
}

.legend-item {
    display: flex;
    align-items: center;
    gap: 0.375rem;
    font-size: 0.7rem;
    color: #334155;
    cursor: pointer;
    padding: 0.125rem 0.25rem;
}

.legend-item:hover {
    background: #f1f5f9;
}

.legend-item.disabled {
    opacity: 0.5;
    text-decoration: line-through;
}

.legend-dot {
    width: 0.5rem;
    height: 0.5rem;
    border-radius: 50%;
    display: inline-block;
}

/* Connection line */
path.connection-line {
    stroke-dasharray: 4, 4;
}

/* Date Filter Group */
.map-date-filter-group {
    display: flex;
    align-items: center;
    gap: 0.25rem;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 0.375rem;
    padding: 0.2rem;
}

.map-date-filter-btn {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    padding: 0.25rem 0.625rem;
    border-radius: 0.25rem;
    font-size: 0.7rem;
    font-weight: 600;
    color: #64748b;
    background: transparent;
    border: none;
    cursor: pointer;
    transition: all 0.15s ease;
    white-space: nowrap;
}

.map-date-filter-btn:hover {
    background: #e2e8f0;
    color: #334155;
}

.map-date-filter-btn.active {
    background: #3b82f6;
    color: #ffffff;
    box-shadow: 0 1px 4px rgba(59,130,246,0.35);
}

</style>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<!-- Leaflet JS -->
<script defer src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<!-- Chart.js -->
<script defer src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
    // Fungsi hapus semua cache geocoding dari LocalStorage
    function clearMapCache() {
        const keys = Object.keys(localStorage).filter(k => k.startsWith('geo_'));
        keys.forEach(k => localStorage.removeItem(k));
        Swal.fire({
            icon: 'success',
            title: 'Cache Peta Dihapus!',
            text: `Berhasil menghapus ${keys.length} item cache. Muat ulang halaman untuk geocode ulang.`,
            confirmButtonColor: '#3b82f6'
        });
    }

    document.addEventListener('DOMContentLoaded', async function() {
        // Inisialisasi Feather / Lucide Icons jika ada logic re-render
        if(typeof lucide !== 'undefined') lucide.createIcons();

        // Koordinat Toko/Pangkalan LPG Utama
        const baseLat = -6.2569093;
        const baseLon = 106.5582734;

        // â”â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•”€ Inisialisasi Peta Leaflet â”â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•”€
        window.map = L.map('customerMap', {
            zoomControl: true
        }).setView([baseLat, baseLon], 12);
        
        // Pilihan tile CartoDB modern & clean
        const voyagerTile = L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="https://carto.com/">CARTO</a>',
            subdomains: 'abcd',
            maxZoom: 19
        });

        const positronTile = L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/light_all/{z}/{x}/{y}{r}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="https://carto.com/">CARTO</a>',
            subdomains: 'abcd',
            maxZoom: 19
        });

        voyagerTile.addTo(map);
        let activeTile = 'voyager';

        window.toggleMapStyle = function() {
            const btn = document.querySelector('.map-control-btn');
            if (activeTile === 'voyager') {
                map.removeLayer(voyagerTile);
                positronTile.addTo(map);
                activeTile = 'positron';
                if(btn) btn.classList.add('active');
            } else {
                map.removeLayer(positronTile);
                voyagerTile.addTo(map);
                activeTile = 'voyager';
                if(btn) btn.classList.remove('active');
            }
        };

        // Fungsi menghitung jarak Haversine (km) di JS
        function calculateDistance(lat1, lon1, lat2, lon2) {
            const R = 6371; // radius bumi dalam km
            const dLat = (lat2 - lat1) * Math.PI / 180;
            const dLon = (lon2 - lon1) * Math.PI / 180;
            const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                      Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
                      Math.sin(dLon / 2) * Math.sin(dLon / 2);
            const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            return R * c;
        }

        // Icon Depot â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•” merah solid dengan pulsasi
        const depotIcon = L.divIcon({
            className: '',
            html: `<div class="relative flex items-center justify-center">
                        <span class="absolute inline-flex h-12 w-12 rounded-full bg-red-400 opacity-20 animate-ping"></span>
                        <div class="map-marker-inner" style="background:linear-gradient(135deg,#ef4444,#dc2626);width:38px;height:38px;border-radius:50%;display:flex;align-items:center;justify-content:center;border:2.5px solid #fff;box-shadow:0 4px 12px rgba(239,68,68,0.45);transform:rotate(-45deg);border-bottom-left-radius:4px">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="transform:rotate(45deg)"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path><polyline points="9 22 9 12 15 12 15 22"></polyline></svg>
                        </div>
                   </div>`,
            iconSize: [38, 38],
            iconAnchor: [19, 38],
            popupAnchor: [0, -40]
        });

        // Icon pelanggan berdasarkan zona
        const zoneIcons = {
            1: L.divIcon({
                className: '',
                html: `<div class="map-marker-inner transition-all duration-300 hover:scale-115" style="background:linear-gradient(135deg,#22c55e,#10b981);width:26px;height:26px;border-radius:50%;display:flex;align-items:center;justify-content:center;border:2px solid #fff;box-shadow:0 3px 8px rgba(34,197,94,0.3);transform:rotate(-45deg);border-bottom-left-radius:3px">
                            <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="transform:rotate(45deg)"><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z"></path><circle cx="12" cy="10" r="3"></circle></svg>
                       </div>`,
                iconSize: [26, 26],
                iconAnchor: [13, 26],
                popupAnchor: [0, -28]
            }),
            2: L.divIcon({
                className: '',
                html: `<div class="map-marker-inner transition-all duration-300 hover:scale-115" style="background:linear-gradient(135deg,#3b82f6,#2563eb);width:26px;height:26px;border-radius:50%;display:flex;align-items:center;justify-content:center;border:2px solid #fff;box-shadow:0 3px 8px rgba(59,130,246,0.3);transform:rotate(-45deg);border-bottom-left-radius:3px">
                            <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="transform:rotate(45deg)"><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z"></path><circle cx="12" cy="10" r="3"></circle></svg>
                       </div>`,
                iconSize: [26, 26],
                iconAnchor: [13, 26],
                popupAnchor: [0, -28]
            }),
            3: L.divIcon({
                className: '',
                html: `<div class="map-marker-inner transition-all duration-300 hover:scale-115" style="background:linear-gradient(135deg,#f43f5e,#e11d48);width:26px;height:26px;border-radius:50%;display:flex;align-items:center;justify-content:center;border:2px solid #fff;box-shadow:0 3px 8px rgba(244,63,94,0.3);transform:rotate(-45deg);border-bottom-left-radius:3px">
                            <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="transform:rotate(45deg)"><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z"></path><circle cx="12" cy="10" r="3"></circle></svg>
                       </div>`,
                iconSize: [26, 26],
                iconAnchor: [13, 26],
                popupAnchor: [0, -28]
            })
        };

        const bounds = L.latLngBounds();

        // Tambahkan marker pangkalan utama
        const depotMarker = L.marker([baseLat, baseLon], {icon: depotIcon}).addTo(map);
        depotMarker.bindPopup(`
            <div class="bg-gradient-to-br from-slate-900 via-slate-800 to-slate-950 p-4 text-center">
                <div class="w-10 h-10 bg-white/10 rounded-full flex items-center justify-center mx-auto mb-2 border border-white/20 text-white shadow-md">
                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path><polyline points="9 22 9 12 15 12 15 22"></polyline></svg>
                </div>
                <h4 class="text-white font-extrabold text-sm">Pangkalan LPG Utama</h4>
                <p class="text-amber-400 text-[10px] font-bold mt-0.5">Pusat Distribusi Utama</p>
            </div>
            <div class="p-3 bg-white text-left text-xs font-medium text-slate-700">
                <p class="text-slate-400 font-bold uppercase tracking-wider text-[9px] mb-1">Koordinat Pusat :</p>
                <p class="font-mono bg-slate-50 p-1.5 rounded border border-slate-100 text-[10px]">${baseLat}, ${baseLon}</p>
            </div>
        `);
        bounds.extend([baseLat, baseLon]);

        // Menambahkan lingkaran jangkauan Zona Distribusi di sekitar pangkalan
        // Zona 1 (Lokal < 2km) - Hijau Transparan
        L.circle([baseLat, baseLon], {
            color: '#22c55e',
            fillColor: '#22c55e',
            fillOpacity: 0.06,
            radius: 2000,
            dashArray: '5, 8',
            weight: 1.5
        }).addTo(map);

        // Zona 2 (Sedang 2 - 5km) - Biru Transparan
        L.circle([baseLat, baseLon], {
            color: '#3b82f6',
            fillColor: '#3b82f6',
            fillOpacity: 0.03,
            radius: 5000,
            dashArray: '5, 8',
            weight: 1.5
        }).addTo(map);

        // Ambil Data Pelanggan dari PHP
        const customers = <?php echo json_encode($customersMapData ?? [], 15, 512) ?>;
        let markersCount = 0;
        const statusText = document.getElementById('map-status-text');

        // Koordinat terverifikasi untuk tiap Kecamatan di Kab. Tangerang untuk akurasi tinggi
        const kecamatanCoords = {
            'curug': [-6.2569093, 106.5582734],
            'binong': [-6.2300, 106.5800],
            'cikupa': [-6.2418, 106.5160],
            'panongan': [-6.2778, 106.5117],
            'legok': [-6.2906, 106.5367],
            'kelapa dua': [-6.2330, 106.6040],
            'cisauk': [-6.3275, 106.6417],
            'pagedangan': [-6.2981, 106.6178],
            'balaraja': [-6.1883, 106.4522],
            'jayanti': [-6.1910, 106.4020],
            'tigaraksa': [-6.2764, 106.4719],
            'jambe': [-6.3150, 106.4740],
            'cisoka': [-6.2650, 106.4172],
            'kronjo': [-6.0464, 106.4428],
            'mekar baru': [-6.0580, 106.4120],
            'mauk': [-6.0503, 106.5269],
            'kemiri': [-6.0820, 106.4760],
            'sukadiri': [-6.0680, 106.5620],
            'rajeg': [-6.1156, 106.5100],
            'sepatan': [-6.1306, 106.5778],
            'sepatan timur': [-6.1170, 106.6080],
            'pakuhaji': [-6.0594, 106.6022],
            'teluknaga': [-6.0964, 106.6739],
            'kosambi': [-6.0790, 106.6960],
            'sindang jaya': [-6.1950, 106.5050],
            'gunung kaler': [-6.0770, 106.3980],
            'sukamulya': [-6.1680, 106.4380],
            'pasar kemis': [-6.1661, 106.5342]
        };

        // Validasi koordinat: cek apakah lat/lon adalah angka valid (Indonesia secara umum)
        function isValidCoords(lt, ln) {
            return !isNaN(lt) && !isNaN(ln) && lt >= -11 && lt <= 6 && ln >= 95 && ln <= 141;
        }

        // Stable deterministic jitter generator based on customer ID/name
        function getStableJitter(name, seedIndex) {
            let hash = 0;
            const str = name + seedIndex;
            for (let i = 0; i < str.length; i++) {
                hash = str.charCodeAt(i) + ((hash << 5) - hash);
            }
            // Generate lat and lon offset between -0.010 and +0.010 (approx 1km scatter)
            const latOffset = ((Math.abs(hash) % 1000) / 1000 - 0.5) * 0.020;
            const lonOffset = ((Math.abs(hash >> 6) % 1000) / 1000 - 0.5) * 0.020;
            return [latOffset, lonOffset];
        }

        function resolveCustomerCoordinates(c, index) {
            let lat = null, lon = null;
            // method: 'gps_registration' = koordinat GPS waktu daftar (paling akurat)
            //         'gps_address'       = koordinat ditemukan di field address
            //         'kecamatan_mapping' = estimasi dari nama kecamatan
            //         'depot_fallback'    = fallback terakhir ke sekitar depot
            let resolvedMethod = 'depot_fallback';

            // ── PRIORITAS 1: titik_koordinat dari DB (GPS waktu daftar) ──────────────
            if (c.titik_koordinat && c.titik_koordinat.includes(',')) {
                const parts = c.titik_koordinat.split(',');
                const checkLat = parseFloat(parts[0].trim());
                const checkLon = parseFloat(parts[1].trim());
                if (isValidCoords(checkLat, checkLon)) {
                    lat = checkLat;
                    lon = checkLon;
                    resolvedMethod = 'gps_registration';
                }
            }

            // ── PRIORITAS 2: koordinat GPS tersembunyi di field address ──────────────
            if (!lat && c.address) {
                // Format: "Latitude: -6.123, Longitude: 106.456"
                const gpsMatch = c.address.match(/Latitude:\s*(-?\d+\.?\d*),\s*Longitude:\s*(-?\d+\.?\d*)/i);
                if (gpsMatch) {
                    const checkLat = parseFloat(gpsMatch[1]);
                    const checkLon = parseFloat(gpsMatch[2]);
                    if (isValidCoords(checkLat, checkLon)) {
                        lat = checkLat;
                        lon = checkLon;
                        resolvedMethod = 'gps_address';
                    }
                }
                // Format: Google Maps URL "q=lat,lon"
                if (!lat) {
                    const urlMatch = c.address.match(/q=(-?\d+\.?\d*),(-?\d+\.?\d*)/);
                    if (urlMatch) {
                        const checkLat = parseFloat(urlMatch[1]);
                        const checkLon = parseFloat(urlMatch[2]);
                        if (isValidCoords(checkLat, checkLon)) {
                            lat = checkLat;
                            lon = checkLon;
                            resolvedMethod = 'gps_address';
                        }
                    }
                }
            }

            // ── PRIORITAS 3: Estimasi dari nama kecamatan (kurang akurat) ───────────
            if (!lat) {
                let checkKec = null;
                if (c.kecamatan) {
                    checkKec = c.kecamatan.toLowerCase().trim();
                } else if (c.address) {
                    const addrLower = c.address.toLowerCase();
                    for (const key of Object.keys(kecamatanCoords)) {
                        if (addrLower.includes(key)) { checkKec = key; break; }
                    }
                }
                if (checkKec && kecamatanCoords[checkKec]) {
                    const base = kecamatanCoords[checkKec];
                    const jitter = getStableJitter(c.name || 'Pelanggan', index);
                    lat = base[0] + jitter[0];
                    lon = base[1] + jitter[1];
                    resolvedMethod = 'kecamatan_mapping';
                }
            }

            // ── PRIORITAS 4: Fallback ke sekitar depot ────────────────────────────────
            if (!lat) {
                const jitter = getStableJitter(c.name || 'Pelanggan', index);
                lat = baseLat + jitter[0] * 1.5;
                lon = baseLon + jitter[1] * 1.5;
                resolvedMethod = 'depot_fallback';
            }

            return { lat, lon, method: resolvedMethod };
        }

        if(customers && customers.length > 0) {
            const usedCoords = {};

            const zone1List = [];
            const zone2List = [];
            const zone3List = [];
            window.markersMap = {};

            for(let i = 0; i < customers.length; i++) {
                const customer = customers[i];
                if(!customer.address) continue;

                const { lat: resolvedLat, lon: resolvedLon, method: resolvedMethod } = resolveCustomerCoordinates(customer, i);
                let lat = resolvedLat;
                let lon = resolvedLon;

                if(lat && lon) {
                    // Proteksi Overlapping: Cek jika koordinat sama persis dengan marker lain
                    const coordKey = `${lat.toFixed(5)}_${lon.toFixed(5)}`;
                    if(usedCoords[coordKey]) {
                        // Tambahkan sedikit offset acak (sekitar 15-20 meter)
                        lat += (Math.random() - 0.5) * 0.00025;
                        lon += (Math.random() - 0.5) * 0.00025;
                    }
                    usedCoords[coordKey] = true;

                    // Hitung jarak dari Pangkalan
                    const distance = calculateDistance(baseLat, baseLon, lat, lon);
                    let zoneNum = 3;
                    let zoneName = "Zona 3 (Jauh)";
                    let zoneColorClass = "bg-rose-50 text-rose-600 border border-rose-200";
                    
                    if (distance < 2) {
                        zoneNum = 1;
                        zoneName = "Zona 1 (Lokal)";
                        zoneColorClass = "bg-green-50 text-green-600 border border-green-200";
                    } else if (distance >= 2 && distance <= 5) {
                        zoneNum = 2;
                        zoneName = "Zona 2 (Sedang)";
                        zoneColorClass = "bg-blue-50 text-blue-600 border border-blue-200";
                    }

                    // Build WA button
                    let whatsappButton = '';
                    if (customer.phone) {
                        let cleanPhone = customer.phone.replace(/[^0-9]/g, '');
                        if (cleanPhone.startsWith('0')) {
                            cleanPhone = '62' + cleanPhone.substring(1);
                        }
                        whatsappButton = `
                            <a href="https://wa.me/${cleanPhone}" target="_blank" rel="noopener noreferrer" class="flex items-center justify-center gap-1.5 w-full mt-3 py-2 px-3 bg-emerald-500 hover:bg-emerald-600 active:bg-emerald-700 text-white text-[11px] font-black uppercase tracking-wider rounded-lg transition-all shadow-md shadow-emerald-100 decoration-none no-underline border-0 select-none cursor-pointer">
                                <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path></svg>
                                WhatsApp Pelanggan
                            </a>
                        `;
                    }

                    // Badge sumber koordinat
                    const isGps = (resolvedMethod === 'gps_registration' || resolvedMethod === 'gps_address');
                    const locationBadge = isGps
                        ? `<div style="display:flex;align-items:center;gap:4px;margin-top:2px;padding:3px 6px;background:#f0fdf4;border:1px solid #bbf7d0;border-radius:4px">
                               <svg xmlns="http://www.w3.org/2000/svg" width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="#16a34a" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l2 2"/></svg>
                               <span style="font-size:9px;font-weight:700;color:#16a34a;text-transform:uppercase;letter-spacing:0.05em">📍 GPS Akurat (Saat Daftar)</span>
                           </div>`
                        : `<div style="display:flex;align-items:center;gap:4px;margin-top:2px;padding:3px 6px;background:#fefce8;border:1px solid #fde68a;border-radius:4px">
                               <svg xmlns="http://www.w3.org/2000/svg" width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="#ca8a04" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>
                               <span style="font-size:9px;font-weight:700;color:#ca8a04;text-transform:uppercase;letter-spacing:0.05em">⚠️ Estimasi Kecamatan</span>
                           </div>`;

                    // Template Popup Minimalis
                    const popupHTML = `
                        <div style="min-width:200px;max-width:250px;font-family:inherit">
                            <div style="padding:8px 10px;background:#f8fafc;border-bottom:1px solid #e2e8f0;display:flex;align-items:center;gap:7px">
                                <div style="width:26px;height:26px;border-radius:50%;background:${isGps ? '#16a34a' : '#94a3b8'};color:#fff;display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:800;flex-shrink:0">${customer.name.substring(0,2).toUpperCase()}</div>
                                <div style="min-width:0">
                                    <div style="font-size:11px;font-weight:700;color:#1e293b;white-space:nowrap;overflow:hidden;text-overflow:ellipsis" title="${customer.name}">${customer.name}</div>
                                    <div style="font-size:9px;color:#94a3b8;font-weight:600;text-transform:uppercase;letter-spacing:0.05em">${customer.created_at ? 'Daftar: ' + new Date(customer.created_at).toLocaleDateString('id-ID', {day:'2-digit',month:'short',year:'numeric'}) : 'Aktif'}</div>
                                </div>
                            </div>
                            <div style="padding:8px 10px;display:flex;flex-direction:column;gap:5px;background:#fff">
                                ${locationBadge}
                                <div style="font-size:10px;color:#64748b">${customer.address}</div>
                                <div style="height:1px;background:#f1f5f9"></div>
                                <div style="display:flex;justify-content:space-between;align-items:center">
                                    <span style="font-size:9px;color:#94a3b8;font-weight:600;text-transform:uppercase">Jarak</span>
                                    <span style="font-size:10px;font-weight:700;color:#4f46e5">${distance.toFixed(2)} km</span>
                                </div>
                                <div style="display:flex;justify-content:space-between;align-items:center">
                                    <span style="font-size:9px;color:#94a3b8;font-weight:600;text-transform:uppercase">Zona</span>
                                    <span style="font-size:9px;font-weight:700;color:#475569">${zoneName}</span>
                                </div>
                                <div style="display:flex;justify-content:space-between;align-items:center">
                                    <span style="font-size:9px;color:#94a3b8;font-weight:600;text-transform:uppercase">Gas</span>
                                    <span style="font-size:9px;font-weight:700;color:#475569">${customer.product_name ?? 'LPG 3kg'}</span>
                                </div>
                                ${whatsappButton}
                            </div>
                        </div>
                    `;

                    const marker = L.marker([lat, lon], {icon: zoneIcons[zoneNum]}).addTo(map);
                    marker.bindPopup(popupHTML);
                    marker.on('click', function(e) {
                        map.panTo(e.target.getLatLng(), {
                            animate: true,
                            duration: 0.5
                        });
                        
                        // Set active class on corresponding sidebar button
                        document.querySelectorAll('.zone-customer-btn').forEach(btn => btn.classList.remove('active'));
                        const sideBtn = document.querySelector(`[data-marker-id="${markerId}"]`);
                        if(sideBtn) {
                            sideBtn.classList.add('active');
                            sideBtn.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                        }
                    });

                    // Simpan objek marker dengan ID unik untuk diakses dari sidebar
                    const markerId = `marker_${i}`;
                    markersMap[markerId] = marker;

                    const customerItem = {
                        id: markerId,
                        name: customer.name,
                        distance: distance,
                        address: customer.address,
                        kecamatan: customer.kecamatan || 'Umum',
                        lat: lat,
                        lon: lon,
                        created_at: customer.created_at || null
                    };
                    // Simpan referensi created_at & method resolusi di marker
                    marker._createdAt = customer.created_at || null;
                    marker._locationMethod = resolvedMethod;

                    if (zoneNum === 1) {
                        zone1List.push(customerItem);
                    } else if (zoneNum === 2) {
                        zone2List.push(customerItem);
                    } else {
                        zone3List.push(customerItem);
                    }
                    
                    bounds.extend([lat, lon]);
                    markersCount++;
                }
            }

            // Garis penghubung dinamis (Polyline) saat penanda dipilih
            let activeLine = null;
            map.on('popupopen', function(e) {
                const marker = e.popup._source;
                if (marker && marker !== depotMarker && typeof marker.getLatLng === 'function') {
                    if (activeLine) {
                        map.removeLayer(activeLine);
                    }
                    const startPoint = depotMarker.getLatLng();
                    const endPoint = marker.getLatLng();
                    activeLine = L.polyline([startPoint, endPoint], {
                        color: '#6366f1', // Indigo
                        weight: 2.5,
                        opacity: 0.85,
                        className: 'connection-line'
                    }).addTo(map);
                }
            });

            map.on('popupclose', function(e) {
                if (activeLine) {
                    map.removeLayer(activeLine);
                    activeLine = null;
                }
                document.querySelectorAll('.zone-customer-btn').forEach(btn => btn.classList.remove('active'));
            });
            
            // Render dan Kelompokkan Pelanggan di Sidebar
            document.getElementById('count-zone-1').innerText = zone1List.length;
            document.getElementById('count-zone-2').innerText = zone2List.length;
            document.getElementById('count-zone-3').innerText = zone3List.length;

            const renderZoneList = (list, containerId, distBg, distColor) => {
                const container = document.getElementById(containerId);
                if (list.length === 0) {
                    container.innerHTML = `<p class="zone-empty-note">Belum ada pelanggan</p>`;
                    return;
                }
                container.innerHTML = list.map(item => `
                    <button onclick="focusOnCustomer('${item.id}', ${item.lat}, ${item.lon})" class="zone-customer-btn" data-marker-id="${item.id}">
                        <div class="zone-customer-distance" style="background:${distBg};color:${distColor}">
                            <span class="text-[9px] font-black">${item.distance.toFixed(1)}</span>
                            <span class="text-[7px] font-bold uppercase tracking-tighter opacity-80">km</span>
                        </div>
                        <div class="zone-customer-info">
                            <div class="zone-customer-name">${item.name}</div>
                            <div class="zone-customer-sub">${item.kecamatan}</div>
                        </div>
                    </button>
                `).join('');
            };

            renderZoneList(zone1List, 'list-zone-1', '#e8fdf0', '#166534');
            renderZoneList(zone2List, 'list-zone-2', '#eff6ff', '#1e40af');
            renderZoneList(zone3List, 'list-zone-3', '#fff1f2', '#9f1239');

            // Fungsi global untuk memfokuskan peta ke pelanggan dari klik sidebar
            window.focusOnCustomer = function(markerId, lat, lon) {
                const marker = markersMap[markerId];
                
                // Highlight active button
                document.querySelectorAll('.zone-customer-btn').forEach(btn => btn.classList.remove('active'));
                const activeBtn = document.querySelector(`[data-marker-id="${markerId}"]`);
                if(activeBtn) activeBtn.classList.add('active');

                if (marker) {
                    map.panTo([lat, lon], {
                        animate: true,
                        duration: 0.6
                    });
                    setTimeout(() => {
                        marker.openPopup();
                    }, 350);
                }
            };
            
            // Search Filtering
            const searchInput = document.getElementById('map-search-input');
            if (searchInput) {
                searchInput.addEventListener('input', function(e) {
                    const query = e.target.value.toLowerCase().trim();
                    filterCustomerList(query);
                });
            }

            function filterCustomerList(query) {
                let visibleCount = 0;
                
                ['list-zone-1', 'list-zone-2', 'list-zone-3'].forEach(containerId => {
                    const container = document.getElementById(containerId);
                    if (!container) return;
                    
                    const buttons = container.querySelectorAll('.zone-customer-btn');
                    let zoneVisibleCount = 0;
                    
                    buttons.forEach(btn => {
                        const name = btn.querySelector('.zone-customer-name').innerText.toLowerCase();
                        const sub = btn.querySelector('.zone-customer-sub').innerText.toLowerCase();
                        const mId = btn.getAttribute('data-marker-id');
                        const marker = markersMap[mId];
                        
                        if (name.includes(query) || sub.includes(query)) {
                            btn.style.display = 'flex';
                            zoneVisibleCount++;
                            visibleCount++;
                            
                            // Check if zone is currently enabled
                            const zoneGroup = btn.closest('.map-zone-group');
                            const zoneLabel = zoneGroup.querySelector('.map-zone-label');
                            const isZoneEnabled = !zoneLabel.classList.contains('disabled');
                            
                            if (marker && isZoneEnabled) {
                                map.addLayer(marker);
                            }
                        } else {
                            btn.style.display = 'none';
                            if (marker) {
                                map.removeLayer(marker);
                            }
                        }
                    });
                    
                    const zoneGroup = container.closest('.map-zone-group');
                    if (zoneGroup) {
                        if (zoneVisibleCount === 0 && query !== '') {
                            zoneGroup.style.display = 'none';
                        } else {
                            zoneGroup.style.display = 'block';
                        }
                    }
                });
                
                statusText.innerText = query === '' 
                    ? `Menampilkan ${markersCount} Pelanggan`
                    : `Ditemukan ${visibleCount} Pelanggan`;
            }

            // Toggle Zone Visibility
            window.toggleZoneVisibility = function(zoneNum) {
                const zoneLabel = document.querySelector(`.map-zone-label.zone-${zoneNum}`);
                const legendItem = document.querySelector(`.legend-item.zone-${zoneNum}`);
                const listContainer = document.getElementById(`list-zone-${zoneNum}`);
                
                if (!zoneLabel) return;
                
                const isHidden = zoneLabel.classList.contains('disabled');
                
                if (isHidden) {
                    zoneLabel.classList.remove('disabled');
                    if (legendItem) legendItem.classList.remove('disabled');
                    if (listContainer) listContainer.style.opacity = '1';
                    
                    const buttons = listContainer.querySelectorAll('.zone-customer-btn');
                    buttons.forEach(btn => {
                        if (btn.style.display !== 'none') {
                            const mId = btn.getAttribute('data-marker-id');
                            const marker = markersMap[mId];
                            if (marker) map.addLayer(marker);
                        }
                    });
                } else {
                    zoneLabel.classList.add('disabled');
                    if (legendItem) legendItem.classList.add('disabled');
                    if (listContainer) listContainer.style.opacity = '0.4';
                    
                    const buttons = listContainer.querySelectorAll('.zone-customer-btn');
                    buttons.forEach(btn => {
                        const mId = btn.getAttribute('data-marker-id');
                        const marker = markersMap[mId];
                        if (marker) map.removeLayer(marker);
                    });
                }
                
                fitVisibleBounds();
            };

            window.fitVisibleBounds = function() {
                const visibleBounds = L.latLngBounds();
                visibleBounds.extend([baseLat, baseLon]);
                let hasVisible = false;
                
                Object.values(markersMap).forEach(marker => {
                    if (map.hasLayer(marker)) {
                        visibleBounds.extend(marker.getLatLng());
                        hasVisible = true;
                    }
                });
                
                if (hasVisible) {
                    map.fitBounds(visibleBounds, {
                        padding: [50, 50],
                        animate: true,
                        duration: 0.8
                    });
                }
            };

            // ── Filter berdasarkan Tanggal Daftar Pelanggan ────────────────────────
            // allCustomersData: simpan semua data lengkap sebelum filter
            window._allCustomersData = {
                zone1: zone1List,
                zone2: zone2List,
                zone3: zone3List,
                totalCount: markersCount
            };

            window.filterByRegDate = function(days, clickedBtn) {
                // Update tombol aktif
                document.querySelectorAll('.map-date-filter-btn').forEach(b => b.classList.remove('active'));
                if (clickedBtn) clickedBtn.classList.add('active');

                const now = new Date();
                let filtered = 0;

                Object.entries(markersMap).forEach(([id, marker]) => {
                    const createdAt = marker._createdAt;
                    let show = true;

                    if (days !== 'all' && createdAt) {
                        const regDate = new Date(createdAt);
                        const diffMs = now - regDate;
                        const diffDays = diffMs / (1000 * 60 * 60 * 24);
                        show = diffDays <= days;
                    } else if (days !== 'all' && !createdAt) {
                        // Jika tidak ada data tanggal, sembunyikan saat filter aktif
                        show = false;
                    }

                    if (show) {
                        map.addLayer(marker);
                        filtered++;
                    } else {
                        map.removeLayer(marker);
                    }
                });

                // Update sidebar buttons visibility
                ['list-zone-1', 'list-zone-2', 'list-zone-3'].forEach(containerId => {
                    const container = document.getElementById(containerId);
                    if (!container) return;
                    let zoneVisible = 0;
                    container.querySelectorAll('.zone-customer-btn').forEach(btn => {
                        const mId = btn.getAttribute('data-marker-id');
                        const marker = markersMap[mId];
                        if (marker && map.hasLayer(marker)) {
                            btn.style.display = 'flex';
                            zoneVisible++;
                        } else {
                            btn.style.display = 'none';
                        }
                    });
                    // Update zone count badge
                    const zoneNum = containerId.split('-')[2];
                    const countEl = document.getElementById(`count-zone-${zoneNum}`);
                    if (countEl) countEl.innerText = zoneVisible;

                    // Sembunyikan group zona jika kosong dan filter aktif
                    const zoneGroup = container.closest('.map-zone-group');
                    if (zoneGroup) {
                        zoneGroup.style.display = (zoneVisible === 0 && days !== 'all') ? 'none' : 'block';
                    }
                });

                const label = days === 'all' ? 'Semua'
                    : days === 1 ? 'Hari Ini'
                    : `${days} Hari Terakhir`;
                statusText.innerText = `${filtered} Pelanggan · ${label}`;
                fitVisibleBounds();
            };

            // Initial fit bounds
            fitVisibleBounds();
            statusText.innerText = `Menampilkan ${markersCount} Pelanggan`;

        } else {
            statusText.innerText = "Belum Ada Data Lokasi";
            document.getElementById('list-zone-1').innerHTML = `<p class="zone-empty-note">Belum ada data pelanggan</p>`;
            document.getElementById('list-zone-2').innerHTML = `<p class="zone-empty-note">Belum ada data pelanggan</p>`;
            document.getElementById('list-zone-3').innerHTML = `<p class="zone-empty-note">Belum ada data pelanggan</p>`;
        }

        const chartData = <?php echo json_encode($chartPenjualan, 15, 512) ?>;
        const labels  = chartData.map(d => d.label);
        const jumlah  = chartData.map(d => d.jumlah);
        const omzet   = chartData.map(d => d.omzet);

        const ctx = document.getElementById('chartPenjualan').getContext('2d');
        const gradTrx = ctx.createLinearGradient(0, 0, 0, 300);
        gradTrx.addColorStop(0, 'rgba(16, 185, 129, 0.3)'); // Emerald green fading
        gradTrx.addColorStop(1, 'rgba(16, 185, 129, 0)');

        new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Transaksi',
                    data: jumlah,
                    borderColor: '#10b981',
                    backgroundColor: gradTrx,
                    borderWidth: 4,
                    tension: 0.4,
                    fill: true,
                    pointRadius: 6,
                    pointHoverRadius: 8,
                    pointBackgroundColor: '#fff',
                    pointBorderColor: '#10b981',
                    pointBorderWidth: 3,
                    shadowBlur: 10,
                    shadowColor: 'rgba(16, 185, 129, 0.5)'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false,
                },
                plugins: { 
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: 'rgba(15, 23, 42, 0.9)',
                        titleFont: { size: 13, weight: 'bold' },
                        padding: 12,
                        cornerRadius: 12,
                        yAlign: 'bottom'
                    }
                },
                scales: {
                    y: { 
                        beginAtZero: true, 
                        grid: { display: true, color: '#f1f5f9', drawBorder: false },
                        border: { display: false }
                    },
                    x: { 
                        grid: { display: false },
                        border: { display: false }
                    }
                }
            }
        });

        // â”â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•”€ Data Kategori (Chart.js) â”â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•”€
        const kategoriData = <?php echo json_encode($chartKategori, 15, 512) ?>;
        const daftarKategori = <?php echo json_encode($daftarKategori, 15, 512) ?>;
        const ctxK = document.getElementById('chartKategori').getContext('2d');
        
        const colors = [
            '#8b5cf6', // purple
            '#f59e0b', // amber
            '#3b82f6', // blue
            '#10b981', // emerald
            '#ec4899', // pink
        ];

        new Chart(ctxK, {
            type: 'bar',
            data: {
                labels: kategoriData.map(d => d.label),
                datasets: daftarKategori.map((kat, idx) => ({
                    label: kat,
                    data: kategoriData.map(d => d[kat] || 0),
                    backgroundColor: colors[idx % colors.length],
                    borderRadius: {topLeft: 8, topRight: 8, bottomLeft: 2, bottomRight: 2},
                    borderSkipped: false,
                    barPercentage: 0.6
                }))
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { 
                    legend: { 
                        position: 'bottom',
                        labels: { padding: 20, usePointStyle: true, pointStyle: 'circle', font: {family: 'Inter, sans-serif', weight: '600'} }
                    },
                    tooltip: {
                        backgroundColor: 'rgba(255, 255, 255, 0.95)',
                        titleColor: '#0f172a',
                        bodyColor: '#334155',
                        borderColor: '#e2e8f0',
                        borderWidth: 1,
                        padding: 12,
                        cornerRadius: 12,
                        boxPadding: 6
                    }
                },
                scales: {
                    y: { 
                        beginAtZero: true,
                        grid: { color: '#f1f5f9', drawBorder: false },
                        border: { display: false }
                    },
                    x: { 
                        stacked: false,
                        grid: { display: false },
                        border: { display: false }
                    }
                }
            }
        });
    });
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.admin_sidebar', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\LPG\resources\views/admin/dashboard.blade.php ENDPATH**/ ?>