{{-- ===================================================== --}}
{{-- OWNER DASHBOARD — Boss Command Center (Final Replace) --}}
{{-- File: resources/views/pages/dashboard/partials/owner.blade.php --}}
{{-- Data source: DashboardController@getOwnerDashboard() --}}
{{-- ===================================================== --}}

<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">

@php
    $stats = $stats ?? [];

    $revenueToday     = (float) data_get($stats, 'revenue_today', 0);
    $revenueMonth     = (float) data_get($stats, 'revenue_month', 0);
    $ordersToday      = (int)   data_get($stats, 'orders_today', 0);
    $ordersMonth      = (int)   data_get($stats, 'orders_month', 0);
    $completedToday   = (int)   data_get($stats, 'completed_today', 0);
    $completedMonth   = (int)   data_get($stats, 'completed_month', 0);
    $readyForPickup   = (int)   data_get($stats, 'ready_for_pickup', 0);
    $receivablesTotal = (float) data_get($stats, 'receivables_total', 0);

    $dailyRevenue = $daily_revenue ?? collect();

    $fmtRp = fn($n) => 'Rp ' . number_format((float)$n, 0, ',', '.');

    $monthLabel = now()->translatedFormat('F Y');
    $todayLabel = now()->translatedFormat('d F Y');

    $pickupLevel = $readyForPickup >= 15 ? 'high' : ($readyForPickup >= 5 ? 'mid' : 'low');
    $piutangLevel = $receivablesTotal >= 5000000 ? 'high' : ($receivablesTotal >= 1000000 ? 'mid' : 'low');

    $headline = "Boss Mode aktif • Data terupdate " . now()->format('H:i') . " • Fokus: ";
    if ($pickupLevel === 'high') $headline .= "banyak order siap diambil.";
    elseif ($piutangLevel === 'high') $headline .= "piutang perlu dipantau.";
    else $headline .= "ritme operasional stabil.";

    $safeRoute = function($name, $params = []) {
        try { return route($name, $params); } catch (\Throwable $e) { return '#'; }
    };

    $links = [
        'Laporan Omset'        => $safeRoute('reports.sales'),
        'Rincian Pendapatan'   => $safeRoute('reports.revenue'),
        'Piutang Penjualan'    => $safeRoute('reports.receivables'),
        'Hutang Pembelian'     => $safeRoute('reports.purchase-debt'),
        'Buku Besar'           => $safeRoute('reports.cash-ledger'),
        'Log Transaksi'        => $safeRoute('reports.transactions'),
        'Data Keuangan'        => $safeRoute('finance.index'),
        'Laporan Kas'          => $safeRoute('finance.cash'),
        'Setoran'              => $safeRoute('finance.deposits.index'),
        'Orders'               => $safeRoute('orders.index'),
        'Kasir (Tagihan)'      => $safeRoute('kasir.index'),
        'Kasir (Riwayat)'      => $safeRoute('kasir.history'),
        'Stok'                 => $safeRoute('stock.index'),
        'Produk'               => $safeRoute('products.items.index'),
        'Pembelian'            => $safeRoute('purchases.index'),
        'Pengeluaran'          => $safeRoute('expenses.index'),
    ];

    $ctaDisabledClass = fn($url) => $url === '#' ? 'pointer-events-none opacity-50' : '';

    $today = \Carbon\Carbon::today();
    $overdueOrders = collect();
    $dueSoonOrders = collect();

    if (class_exists(\App\Models\Order::class)) {
        $baseDueQuery = \App\Models\Order::query()
            ->whereNotNull('due_date');

        if (method_exists($baseDueQuery->getModel(), 'notCancelled')) {
            $baseDueQuery->notCancelled();
        }

        if (method_exists($baseDueQuery->getModel(), 'withReceivables')) {
            $baseDueQuery->withReceivables();
        }

        $overdueOrders = (clone $baseDueQuery)
    ->whereDate('created_at', '<=', $today->copy()->subDays(30))
    ->orderBy('created_at')
    ->limit(5)
    ->get();

        $dueSoonOrders = (clone $baseDueQuery)
            ->whereDate('due_date', '>=', $today)
            ->whereDate('due_date', '<=', $today->copy()->addDays(3))
            ->orderBy('due_date')
            ->limit(5)
            ->get();
    }

    $overdueCount = $overdueOrders->count();
    $dueSoonCount = $dueSoonOrders->count();
@endphp

<style>
    .boss-owner-wrap{
        font-family:'Poppins',sans-serif;
        background:
            radial-gradient(1000px 380px at 12% 0%, rgba(99,102,241,.16), transparent 62%),
            radial-gradient(950px 340px at 88% 8%, rgba(16,185,129,.14), transparent 62%),
            radial-gradient(900px 360px at 50% 115%, rgba(244,63,94,.12), transparent 62%);
        border-radius: 16px;
    }
    .boss-glass{
        background: rgba(255,255,255,.74);
        backdrop-filter: blur(12px);
        -webkit-backdrop-filter: blur(12px);
        border: 1px solid rgba(17,24,39,.10);
    }
    .dark .boss-glass{
        background: rgba(255,255,255,.04);
        border: 1px solid rgba(255,255,255,.08);
    }
    .boss-neo{
        position:relative;
        overflow:hidden;
        border-radius: 16px;
    }
    .boss-neo:before{
        content:"";
        position:absolute;
        inset:-2px;
        background: linear-gradient(90deg, rgba(99,102,241,.42), rgba(16,185,129,.36), rgba(244,63,94,.34));
        filter: blur(16px);
        opacity:.55;
        z-index:0;
    }
    .boss-neo > *{ position:relative; z-index:1; }

    .boss-chip{
        display:inline-flex; align-items:center; gap:8px;
        border-radius:999px; padding:7px 10px;
        font-size:12px; font-weight:700;
        border:1px solid rgba(17,24,39,.10);
        background: rgba(255,255,255,.75);
        color:#111827;
        white-space:nowrap;
    }
    .dark .boss-chip{
        border:1px solid rgba(255,255,255,.10);
        background: rgba(255,255,255,.05);
        color: rgba(255,255,255,.86);
    }

    .boss-action{
        display:flex; align-items:center; gap:12px;
        border-radius:14px;
        padding:12px 14px;
        border: 1px solid rgba(17,24,39,.08);
        background: rgba(255,255,255,.60);
        transition: .15s ease;
    }
    .boss-action:hover{
        transform: translateY(-1px);
        box-shadow: 0 12px 26px rgba(0,0,0,.10);
        background: rgba(255,255,255,.82);
    }
    .dark .boss-action{
        border: 1px solid rgba(255,255,255,.08);
        background: rgba(255,255,255,.03);
    }
    .dark .boss-action:hover{
        background: rgba(255,255,255,.05);
        box-shadow: 0 12px 26px rgba(0,0,0,.25);
    }

    .boss-pill{
        border-radius: 999px;
        padding: 8px 12px;
        font-size: 12px;
        font-weight: 700;
        border: 1px solid rgba(17,24,39,.10);
        background: rgba(255,255,255,.65);
    }
    .dark .boss-pill{
        border: 1px solid rgba(255,255,255,.10);
        background: rgba(255,255,255,.05);
    }

    .boss-kpi-note details summary{
        cursor:pointer;
        user-select:none;
        list-style:none;
    }
    .boss-kpi-note details summary::-webkit-details-marker{ display:none; }

    .due-card{
        border-radius: 16px;
        padding: 14px;
        border: 1px solid rgba(17,24,39,.08);
        background: rgba(255,255,255,.60);
    }
    .dark .due-card{
        background: rgba(255,255,255,.03);
        border: 1px solid rgba(255,255,255,.08);
    }
    .due-badge{
        display:inline-flex;
        align-items:center;
        border-radius:999px;
        padding:4px 8px;
        font-size:10px;
        font-weight:700;
        white-space:nowrap;
    }
    .due-badge.overdue{
        background: rgba(239,68,68,.12);
        color:#dc2626;
    }
    .due-badge.soon{
        background: rgba(245,158,11,.14);
        color:#d97706;
    }

    .floating-due-popup{
        position: fixed;
        right: 18px;
        bottom: 18px;
        width: min(390px, calc(100vw - 24px));
        z-index: 60;
        border-radius: 18px;
        border: 1px solid rgba(239,68,68,.25);
        background: rgba(255,255,255,.96);
        box-shadow: 0 20px 60px rgba(0,0,0,.18);
        overflow: hidden;
    }
    .dark .floating-due-popup{
        background: rgba(17,24,39,.96);
        border: 1px solid rgba(239,68,68,.18);
        box-shadow: 0 20px 60px rgba(0,0,0,.45);
    }
    .floating-due-header{
        display:flex;
        align-items:center;
        justify-content:space-between;
        gap:12px;
        padding:12px 14px;
        background: linear-gradient(135deg, rgba(239,68,68,.12), rgba(245,158,11,.10));
        border-bottom: 1px solid rgba(17,24,39,.08);
    }
    .dark .floating-due-header{
        border-bottom: 1px solid rgba(255,255,255,.08);
    }
    .floating-due-body{
        padding:12px 14px;
        max-height: 260px;
        overflow-y:auto;
    }
    .due-item{
        display:flex;
        align-items:flex-start;
        justify-content:space-between;
        gap:12px;
        padding:10px 0;
        border-bottom:1px dashed rgba(17,24,39,.10);
    }
    .dark .due-item{
        border-bottom:1px dashed rgba(255,255,255,.08);
    }
    .due-item:last-child{
        border-bottom:none;
        padding-bottom:0;
    }

    @keyframes bossScroll { 0%{ transform:translateX(0);} 100%{ transform:translateX(-100%);} }
    @keyframes popupIn {
        from { opacity:0; transform: translateY(16px) scale(.98); }
        to { opacity:1; transform: translateY(0) scale(1); }
    }
    .popup-show { animation: popupIn .25s ease; }
</style>

<div class="boss-owner-wrap p-4 md:p-5">

    {{-- ===== Banner ===== --}}
    <div class="boss-neo mb-5">
        <div class="boss-glass px-4 py-3 flex items-center gap-3 rounded-2xl">
            <div class="flex-1 overflow-hidden whitespace-nowrap">
                <div id="boss-scroll-text"
                     class="text-sm font-semibold"
                     style="display:inline-block; padding-left:100%; animation:bossScroll 18s linear infinite; color:#0f9d58;">
                    {{ $headline }}
                </div>
            </div>

            <div class="hidden sm:flex items-center gap-2">
                <span class="boss-chip">📅 {{ $todayLabel }}</span>
                <span class="boss-chip">🗓️ {{ $monthLabel }}</span>
            </div>

            <a href="https://wa.me/628990799960" target="_blank"
               class="rounded-full px-4 py-2 text-xs font-bold text-white"
               style="background:#0f9d58;text-decoration:none;">
                💬 Bantuan
            </a>

            <button type="button"
                onclick="window.location.reload()"
                class="hidden sm:inline-flex items-center gap-2 rounded-full px-4 py-2 text-xs font-bold text-white"
                style="background:#465fff;">
                🔄 Refresh
            </button>
        </div>
    </div>

    {{-- ===== Insight Utama (real-time explanation) ===== --}}
    <div class="boss-neo mb-6">
        <div class="boss-glass rounded-2xl p-5">
            <div class="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                <div class="min-w-0">
                    <div class="flex flex-wrap items-center gap-2">
                        <h3 class="text-lg font-semibold text-gray-900 dark:text-white/90">Ringkasan Kontrol</h3>
                        <span class="boss-pill text-gray-700 dark:text-white/80">
                            Terupdate: {{ now()->format('d/m/Y H:i') }}
                        </span>
                    </div>
                    <p class="mt-2 text-sm text-gray-700 dark:text-white/70">
                        Panel ini menjelaskan <span class="font-semibold">asal angka</span> dan <span class="font-semibold">maknanya</span> untuk keputusan cepat.
                        Semua nilai di bawah dihitung langsung dari transaksi yang tersimpan di sistem (refresh untuk update terbaru).
                    </p>
                </div>

                <div class="flex flex-wrap gap-2">
                    <a href="{{ $links['Buku Besar'] }}" class="boss-chip {{ $ctaDisabledClass($links['Buku Besar']) }}">📘 Buku Besar</a>
                    <a href="{{ $links['Rincian Pendapatan'] }}" class="boss-chip {{ $ctaDisabledClass($links['Rincian Pendapatan']) }}">📈 Pendapatan</a>
                    <a href="{{ $links['Piutang Penjualan'] }}" class="boss-chip {{ $ctaDisabledClass($links['Piutang Penjualan']) }}">🧾 Piutang</a>
                    <a href="{{ $links['Kasir (Riwayat)'] }}" class="boss-chip {{ $ctaDisabledClass($links['Kasir (Riwayat)']) }}">🧾 Riwayat Bayar</a>
                </div>
            </div>

            <div class="mt-4 grid grid-cols-1 gap-3 lg:grid-cols-3">
                <div class="rounded-xl border border-gray-200 bg-white/60 p-4 dark:border-gray-800 dark:bg-white/[0.03]">
                    <div class="text-sm font-semibold text-gray-800 dark:text-white/90">✅ Pendapatan Hari Ini</div>
                    <div class="mt-1 text-2xl font-bold text-success-600 dark:text-success-400">{{ $fmtRp($revenueToday) }}</div>
                    <div class="boss-kpi-note mt-3 text-sm text-gray-700 dark:text-white/70">
                        <details>
                            <summary class="inline-flex items-center gap-2 text-xs font-semibold text-gray-600 hover:text-gray-800 dark:text-white/60 dark:hover:text-white/80">
                                Lihat asal angka
                                <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                            </summary>
                            <div class="mt-2 text-xs leading-relaxed">
                                Angka ini adalah total <b>order status Lunas</b> yang <b>dibuat hari ini</b> (berdasarkan tanggal order).
                                <br>• Jika pembayaran masih <b>cicilan</b>, belum masuk penuh.
                                <br>• Jika order dibuat kemarin tapi lunas hari ini, itu masuk sesuai aturan sistem yang sekarang (berdasarkan tanggal order).
                            </div>
                        </details>
                    </div>
                </div>

                <div class="rounded-xl border border-gray-200 bg-white/60 p-4 dark:border-gray-800 dark:bg-white/[0.03]">
                    <div class="text-sm font-semibold text-gray-800 dark:text-white/90">📊 Pendapatan Bulan Ini</div>
                    <div class="mt-1 text-2xl font-bold text-brand-600 dark:text-brand-400">{{ $fmtRp($revenueMonth) }}</div>
                    <div class="boss-kpi-note mt-3 text-sm text-gray-700 dark:text-white/70">
                        <details>
                            <summary class="inline-flex items-center gap-2 text-xs font-semibold text-gray-600 hover:text-gray-800 dark:text-white/60 dark:hover:text-white/80">
                                Lihat asal angka
                                <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                            </summary>
                            <div class="mt-2 text-xs leading-relaxed">
                                Total <b>order Lunas</b> dalam rentang <b>awal–akhir bulan ini</b> (berdasarkan tanggal order).
                                Grafik di bawah mengurai per hari (berdasarkan paid_at yang direkap).
                            </div>
                        </details>
                    </div>
                </div>

                <div class="rounded-xl border border-gray-200 bg-white/60 p-4 dark:border-gray-800 dark:bg-white/[0.03]">
                    <div class="text-sm font-semibold text-gray-800 dark:text-white/90">🧾 Total Piutang (Belum Lunas)</div>
                    <div class="mt-1 text-2xl font-bold text-orange-600 dark:text-orange-400">{{ $fmtRp($receivablesTotal) }}</div>
                    <div class="boss-kpi-note mt-3 text-sm text-gray-700 dark:text-white/70">
                        <details>
                            <summary class="inline-flex items-center gap-2 text-xs font-semibold text-gray-600 hover:text-gray-800 dark:text-white/60 dark:hover:text-white/80">
                                Lihat asal angka
                                <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                            </summary>
                            <div class="mt-2 text-xs leading-relaxed">
                                Ini akumulasi <b>sisa tagihan</b> dari order yang statusnya <b>Belum Bayar</b> atau <b>Cicilan</b>.
                                Rumus sistem: <b>(total_price - paid_amount)</b> dijumlahkan.
                                <br>• Makin besar angka ini = makin banyak uang yang masih “menggantung” di customer.
                            </div>
                        </details>

                        @if($piutangLevel === 'high')
                            <div class="mt-2 inline-flex items-center rounded-lg bg-error-50 px-2.5 py-1 text-xs font-semibold text-error-700 dark:bg-error-500/15 dark:text-error-300">
                                ⚠️ Piutang tinggi — pertimbangkan follow-up customer & cek laporan piutang.
                            </div>
                        @elseif($piutangLevel === 'mid')
                            <div class="mt-2 inline-flex items-center rounded-lg bg-warning-50 px-2.5 py-1 text-xs font-semibold text-warning-700 dark:bg-warning-500/15 dark:text-warning-200">
                                🟠 Piutang sedang — pantau rutin, terutama yang sudah lama.
                            </div>
                        @else
                            <div class="mt-2 inline-flex items-center rounded-lg bg-success-50 px-2.5 py-1 text-xs font-semibold text-success-700 dark:bg-success-500/15 dark:text-success-300">
                                ✅ Piutang terkendali — ritme pembayaran aman.
                            </div>
                        @endif
                    </div>
                </div>
            </div>

            <div class="mt-4 grid grid-cols-1 gap-3 md:grid-cols-2">
                <div class="rounded-xl border border-gray-200 bg-white/60 p-4 dark:border-gray-800 dark:bg-white/[0.03]">
                    <div class="flex items-center justify-between">
                        <div class="text-sm font-semibold text-gray-800 dark:text-white/90">📦 Operasional Hari Ini</div>
                        <span class="boss-pill text-gray-700 dark:text-white/80">Order: {{ number_format($ordersToday) }}</span>
                    </div>
                    <p class="mt-2 text-sm text-gray-700 dark:text-white/70">
                        <b>{{ number_format($completedToday) }}</b> order selesai hari ini.
                        Ini membantu membaca “kecepatan produksi” dibanding jumlah order masuk.
                    </p>
                    <div class="mt-3 flex flex-wrap gap-2 text-xs">
                        <span class="boss-chip">Masuk: {{ number_format($ordersToday) }}</span>
                        <span class="boss-chip">Selesai: {{ number_format($completedToday) }}</span>
                    </div>
                </div>

                <div class="rounded-xl border border-gray-200 bg-white/60 p-4 dark:border-gray-800 dark:bg-white/[0.03]">
                    <div class="flex items-center justify-between">
                        <div class="text-sm font-semibold text-gray-800 dark:text-white/90">🚚 Siap Diambil Customer</div>
                        <span class="boss-pill text-gray-700 dark:text-white/80">{{ number_format($readyForPickup) }} order</span>
                    </div>
                    <p class="mt-2 text-sm text-gray-700 dark:text-white/70">
                        Ini adalah order yang status produksi <b>Selesai</b>, namun status pickup masih <b>Belum Diambil</b>.
                        Idealnya angka ini dijaga rendah agar cashflow & ruang penyimpanan lebih sehat.
                    </p>

                    @if($pickupLevel === 'high')
                        <div class="mt-3 inline-flex items-center rounded-lg bg-error-50 px-2.5 py-1 text-xs font-semibold text-error-700 dark:bg-error-500/15 dark:text-error-300">
                            ⚠️ Antrian pengambilan tinggi — dorong tim untuk WA customer.
                        </div>
                    @elseif($pickupLevel === 'mid')
                        <div class="mt-3 inline-flex items-center rounded-lg bg-warning-50 px-2.5 py-1 text-xs font-semibold text-warning-700 dark:bg-warning-500/15 dark:text-warning-200">
                            🟠 Perlu monitoring — jadwalkan follow-up pengambilan.
                        </div>
                    @else
                        <div class="mt-3 inline-flex items-center rounded-lg bg-success-50 px-2.5 py-1 text-xs font-semibold text-success-700 dark:bg-success-500/15 dark:text-success-300">
                            ✅ Aman — antrian pengambilan terkendali.
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>

    {{-- ===== Jatuh Tempo Piutang ===== --}}
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <div class="boss-neo">
            <div class="boss-glass rounded-2xl p-5">
                <div class="flex items-center justify-between">
                    <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Order Lama > 30 Hari</h3>
                    <span class="boss-chip">🚨 {{ $overdueCount }} invoice</span>
                </div>

                <div class="mt-4 space-y-3">
                    @forelse($overdueOrders as $order)
                        <div class="due-card">
                            <div class="flex items-start justify-between gap-3">
                                <div>
                                    <div class="font-semibold text-gray-800 dark:text-white/90">{{ $order->invoice_number }}</div>
                                    <div class="text-xs text-gray-500 dark:text-gray-400">{{ $order->customer_name }}</div>
                                </div>
                                <span class="due-badge overdue">
                                    {{ \Carbon\Carbon::parse($order->due_date)->format('d/m/Y') }}
                                </span>
                            </div>
                            <div class="mt-2 text-sm text-error-600 dark:text-error-400">
                                Sisa: Rp {{ number_format((float) $order->getRemainingBalance(), 0, ',', '.') }}
                            </div>
                        </div>
                    @empty
                        <div class="rounded-xl border border-dashed border-gray-200 px-4 py-5 text-sm text-gray-500 dark:border-gray-700 dark:text-gray-400">
                            Belum ada piutang yang lewat jatuh tempo.
                        </div>
                    @endforelse
                </div>
            </div>
        </div>

        <div class="boss-neo">
            <div class="boss-glass rounded-2xl p-5">
                <div class="flex items-center justify-between">
                    <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Jatuh Tempo Dekat</h3>
                    <span class="boss-chip">⏰ {{ $dueSoonCount }} invoice</span>
                </div>

                <div class="mt-4 space-y-3">
                    @forelse($dueSoonOrders as $order)
                        <div class="due-card">
                            <div class="flex items-start justify-between gap-3">
                                <div>
                                    <div class="font-semibold text-gray-800 dark:text-white/90">{{ $order->invoice_number }}</div>
                                    <div class="text-xs text-gray-500 dark:text-gray-400">{{ $order->customer_name }}</div>
                                </div>
                                <span class="due-badge soon">
                                    {{ \Carbon\Carbon::parse($order->due_date)->format('d/m/Y') }}
                                </span>
                            </div>
                            <div class="mt-2 text-sm text-warning-700 dark:text-warning-400">
                                Sisa: Rp {{ number_format((float) $order->getRemainingBalance(), 0, ',', '.') }}
                            </div>
                        </div>
                    @empty
                        <div class="rounded-xl border border-dashed border-gray-200 px-4 py-5 text-sm text-gray-500 dark:border-gray-700 dark:text-gray-400">
                            Tidak ada piutang yang akan jatuh tempo dalam 3 hari.
                        </div>
                    @endforelse
                </div>
            </div>
        </div>
    </div>

    {{-- ===== KPI Cards (tetap pakai komponen existing) ===== --}}
    <div class="mb-6 grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
        <x-posgraf.stat-card
            title="Pendapatan Hari Ini"
            value="{{ $fmtRp($revenueToday) }}"
            color="success"
            icon='<svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" /></svg>'
        />
        <x-posgraf.stat-card
            title="Pendapatan Bulan Ini"
            value="{{ $fmtRp($revenueMonth) }}"
            color="brand"
            icon='<svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" /></svg>'
        />
        <x-posgraf.stat-card
            title="Order Hari Ini"
            value="{{ number_format($ordersToday) }}"
            color="blue"
            icon='<svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /></svg>'
        />
    </div>

    <div class="mb-6 grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-5">
        <x-posgraf.stat-card title="Order Bulan Ini" value="{{ number_format($ordersMonth) }}" color="brand"
            icon='<svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" /></svg>' />
        <x-posgraf.stat-card title="Selesai Hari Ini" value="{{ number_format($completedToday) }}" color="success"
            icon='<svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>' />
        <x-posgraf.stat-card title="Selesai Bulan Ini" value="{{ number_format($completedMonth) }}" color="blue"
            icon='<svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" /></svg>' />
        <x-posgraf.stat-card title="Siap Diambil" value="{{ number_format($readyForPickup) }}" color="success"
            icon='<svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" /></svg>' />
        <x-posgraf.stat-card title="Total Piutang" value="{{ $fmtRp($receivablesTotal) }}" color="orange"
            icon='<svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" /></svg>' />
    </div>

    {{-- ===== Chart + Boss Actions ===== --}}
    <div class="grid grid-cols-1 lg:grid-cols-12 gap-6 mb-6">
        <div class="lg:col-span-8">
            <x-posgraf.chart-card title="Grafik Pendapatan Bulan Ini" id="revenueChart" />
            <div class="mt-3 text-xs text-gray-600 dark:text-white/60">
                Catatan: Grafik mengambil rekap harian dari data pembayaran (paid_at) yang direkap sistem pada bulan berjalan.
            </div>
        </div>

        <div class="lg:col-span-4">
            <div class="boss-neo h-full">
                <div class="boss-glass rounded-2xl p-5 h-full">
                    <div class="flex items-center justify-between">
                        <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Akses Cepat</h3>
                        <span class="boss-chip">⚡ 1 klik</span>
                    </div>

                    <div class="mt-4 grid grid-cols-1 gap-3">
                        <a href="{{ $links['Laporan Omset'] }}" class="boss-action {{ $ctaDisabledClass($links['Laporan Omset']) }}">
                            <div class="flex size-10 items-center justify-center rounded-full bg-success-100 text-success-600 dark:bg-success-500/20 dark:text-success-400">
                                <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                            </div>
                            <div class="min-w-0">
                                <div class="font-semibold text-gray-800 dark:text-white/90">Omset Penjualan</div>
                                <div class="text-xs text-gray-500 dark:text-gray-400">Ringkasan omzet</div>
                            </div>
                        </a>

                        <a href="{{ $links['Rincian Pendapatan'] }}" class="boss-action {{ $ctaDisabledClass($links['Rincian Pendapatan']) }}">
                            <div class="flex size-10 items-center justify-center rounded-full bg-brand-100 text-brand-600 dark:bg-brand-500/20 dark:text-brand-400">
                                <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2z"/></svg>
                            </div>
                            <div class="min-w-0">
                                <div class="font-semibold text-gray-800 dark:text-white/90">Rincian Pendapatan</div>
                                <div class="text-xs text-gray-500 dark:text-gray-400">Per transaksi / produk</div>
                            </div>
                        </a>

                        <a href="{{ $links['Piutang Penjualan'] }}" class="boss-action {{ $ctaDisabledClass($links['Piutang Penjualan']) }}">
                            <div class="flex size-10 items-center justify-center rounded-full bg-warning-100 text-warning-700 dark:bg-warning-500/20 dark:text-warning-400">
                                <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2"/></svg>
                            </div>
                            <div class="min-w-0">
                                <div class="font-semibold text-gray-800 dark:text-white/90">Piutang Penjualan</div>
                                <div class="text-xs text-gray-500 dark:text-gray-400">Cetak per customer</div>
                            </div>
                        </a>

                        <a href="{{ $links['Buku Besar'] }}" class="boss-action {{ $ctaDisabledClass($links['Buku Besar']) }}">
                            <div class="flex size-10 items-center justify-center rounded-full bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-200">
                                <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2"/></svg>
                            </div>
                            <div class="min-w-0">
                                <div class="font-semibold text-gray-800 dark:text-white/90">Buku Besar</div>
                                <div class="text-xs text-gray-500 dark:text-gray-400">Debit / Kredit / Saldo</div>
                            </div>
                        </a>

                        <a href="{{ $links['Log Transaksi'] }}" class="boss-action {{ $ctaDisabledClass($links['Log Transaksi']) }}">
                            <div class="flex size-10 items-center justify-center rounded-full bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-400">
                                <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                            </div>
                            <div class="min-w-0">
                                <div class="font-semibold text-gray-800 dark:text-white/90">Log Transaksi</div>
                                <div class="text-xs text-gray-500 dark:text-gray-400">Audit / jejak</div>
                            </div>
                        </a>

                        <div class="mt-2 flex flex-wrap gap-2">
                            <a href="{{ $links['Data Keuangan'] }}" class="boss-chip {{ $ctaDisabledClass($links['Data Keuangan']) }}">💼 Data Keuangan</a>
                            <a href="{{ $links['Laporan Kas'] }}" class="boss-chip {{ $ctaDisabledClass($links['Laporan Kas']) }}">💰 Laporan Kas</a>
                            <a href="{{ $links['Setoran'] }}" class="boss-chip {{ $ctaDisabledClass($links['Setoran']) }}">🏦 Setoran</a>
                            <a href="{{ $links['Orders'] }}" class="boss-chip {{ $ctaDisabledClass($links['Orders']) }}">📦 Orders</a>
                            <a href="{{ $links['Kasir (Tagihan)'] }}" class="boss-chip {{ $ctaDisabledClass($links['Kasir (Tagihan)']) }}">🧾 Kasir</a>
                        </div>

                        <div class="mt-3 rounded-xl border border-gray-200 bg-white/60 p-4 dark:border-gray-800 dark:bg-white/[0.03]">
                            <div class="text-sm font-semibold text-gray-800 dark:text-white/90">Cara membaca cepat</div>
                            <ul class="mt-2 space-y-1 text-sm text-gray-700 dark:text-white/70">
                                <li>• Jika <b>Piutang</b> naik → cek laporan piutang & follow-up.</li>
                                <li>• Jika <b>Siap Diambil</b> naik → dorong WA customer & alur pickup.</li>
                                <li>• Jika <b>Order masuk</b> tinggi tapi <b>selesai</b> rendah → cek kapasitas produksi.</li>
                            </ul>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- ===== Footer ===== --}}
    <div class="mt-12 border-t border-gray-200 pt-6 text-center text-xs text-gray-500 dark:border-gray-800 dark:text-gray-400">
        <p>© {{ date('Y') }} <span class="font-semibold text-gray-700 dark:text-gray-300">aplikasipercetakan.com</span>. All rights reserved.</p>
    </div>
</div>

@if($overdueCount > 0 || $dueSoonCount > 0)
    <div id="floatingDuePopup" class="floating-due-popup popup-show">
        <div class="floating-due-header">
            <div>
                <div class="text-sm font-bold text-gray-800 dark:text-white">Pengingat Jatuh Tempo</div>
                <div class="text-xs text-gray-500 dark:text-gray-400">
                    {{ $overdueCount }} lewat tempo • {{ $dueSoonCount }} akan jatuh tempo
                </div>
            </div>
            <button type="button" onclick="closeDuePopup()" class="rounded-full px-2 py-1 text-gray-500 hover:bg-white/70 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/10 dark:hover:text-white">
                ✕
            </button>
        </div>

        <div class="floating-due-body">
            @foreach($overdueOrders->take(3) as $order)
                <div class="due-item">
                    <div>
                        <div class="text-sm font-semibold text-gray-800 dark:text-white">{{ $order->invoice_number }}</div>
                        <div class="text-xs text-gray-500 dark:text-gray-400">{{ $order->customer_name }}</div>
                        <div class="mt-1 text-xs text-error-600 dark:text-error-400">
                            Sisa Rp {{ number_format((float) $order->getRemainingBalance(), 0, ',', '.') }}
                        </div>
                    </div>
                    <span class="due-badge overdue">
                        {{ \Carbon\Carbon::parse($order->due_date)->format('d/m/Y') }}
                    </span>
                </div>
            @endforeach

            @if($overdueCount === 0)
                @foreach($dueSoonOrders->take(3) as $order)
                    <div class="due-item">
                        <div>
                            <div class="text-sm font-semibold text-gray-800 dark:text-white">{{ $order->invoice_number }}</div>
                            <div class="text-xs text-gray-500 dark:text-gray-400">{{ $order->customer_name }}</div>
                            <div class="mt-1 text-xs text-warning-700 dark:text-warning-400">
                                Sisa Rp {{ number_format((float) $order->getRemainingBalance(), 0, ',', '.') }}
                            </div>
                        </div>
                        <span class="due-badge soon">
                            {{ \Carbon\Carbon::parse($order->due_date)->format('d/m/Y') }}
                        </span>
                    </div>
                @endforeach
            @endif

            <div class="mt-3">
                <a href="{{ $links['Piutang Penjualan'] }}" class="inline-flex items-center gap-2 rounded-lg bg-brand-500 px-3 py-2 text-xs font-semibold text-white hover:bg-brand-600 {{ $ctaDisabledClass($links['Piutang Penjualan']) }}">
                    Lihat Laporan Piutang
                </a>
            </div>
        </div>
    </div>

    <script>
        function closeDuePopup() {
            const popup = document.getElementById('floatingDuePopup');
            if (popup) popup.style.display = 'none';
        }

        setTimeout(() => {
            const popup = document.getElementById('floatingDuePopup');
            if (popup) popup.style.display = 'none';
        }, 12000);
    </script>
@endif

<script>
document.addEventListener('DOMContentLoaded', function () {
    const dailyRevenue = @json($daily_revenue ?? []);

    const categories = dailyRevenue.map(item => {
        const d = new Date(item.date);
        return isNaN(d.getTime()) ? item.date : d.getDate();
    });

    const data = dailyRevenue.map(item => parseInt(item.total || 0));

    const revenueChartOptions = {
        series: [{ name: "Pendapatan", data }],
        colors: ["#465fff"],
        chart: {
            fontFamily: "Outfit, sans-serif",
            type: "area",
            height: 350,
            toolbar: { show: false },
        },
        dataLabels: { enabled: false },
        stroke: { curve: 'smooth', width: 2 },
        xaxis: {
            categories,
            axisBorder: { show: false },
            axisTicks: { show: false },
            labels: { style: { colors: "#9ca3af", fontSize: "12px" } }
        },
        yaxis: {
            labels: {
                formatter: v => 'Rp ' + new Intl.NumberFormat('id-ID').format(v),
                style: { colors: "#9ca3af", fontSize: "12px" }
            },
        },
        grid: { yaxis: { lines: { show: true } }, xaxis: { lines: { show: false } } },
        fill: { type: "gradient", gradient: { shadeIntensity: 1, opacityFrom: 0.35, opacityTo: 0.05, stops: [0, 90, 100] } },
        tooltip: { theme: 'light', y: { formatter: v => "Rp " + new Intl.NumberFormat('id-ID').format(v) } }
    };

    if (document.getElementById('revenueChart') && typeof ApexCharts !== 'undefined') {
        new ApexCharts(document.getElementById('revenueChart'), revenueChartOptions).render();
    }
});
</script>
