@extends('layouts.kurir_sidebar')

@section('title', 'Laporan Harian')

@push('styles')
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<style>
    .laporan-page, .laporan-page * { font-family: 'Inter', 'Plus Jakarta Sans', system-ui, sans-serif !important; }

    /* Animations */
    @keyframes fadeIn { from { opacity:0; transform:translateY(16px); } to { opacity:1; transform:translateY(0); } }
    @keyframes countUp { from { opacity:0; transform:scale(0.92); } to { opacity:1; transform:scale(1); } }
    @keyframes barRise { from { height:0 !important; } }
    @keyframes pulse-dot { 0%,100%{opacity:.5;transform:scale(1);} 50%{opacity:1;transform:scale(1.15);} }
    @keyframes float { 0%,100%{transform:translateY(0);} 50%{transform:translateY(-5px);} }
    @keyframes shimmer { 0%{background-position:-200% center;} 100%{background-position:200% center;} }

    .fade-1 { animation: fadeIn .45s cubic-bezier(.22,1,.36,1) both; }
    .fade-2 { animation: fadeIn .45s cubic-bezier(.22,1,.36,1) .06s both; }
    .fade-3 { animation: fadeIn .45s cubic-bezier(.22,1,.36,1) .12s both; }
    .fade-4 { animation: fadeIn .45s cubic-bezier(.22,1,.36,1) .18s both; }
    .fade-5 { animation: fadeIn .45s cubic-bezier(.22,1,.36,1) .24s both; }
    .count-anim { animation: countUp .5s cubic-bezier(.22,1,.36,1) .15s both; }

    /* Stat Cards */
    .stat-card {
        position: relative;
        overflow: hidden;
        transition: transform .2s ease, box-shadow .2s ease;
    }
    .stat-card:hover { transform: translateY(-3px); }
    .stat-card .shimmer-overlay {
        position: absolute; inset: 0;
        background: linear-gradient(105deg, transparent 40%, rgba(255,255,255,.1) 50%, transparent 60%);
        background-size: 200% 100%;
        animation: shimmer 3.5s ease infinite;
        pointer-events: none;
    }

    /* Bar chart */
    .bar-fill-anim { animation: barRise .7s cubic-bezier(.22,1,.36,1) both; }

    /* Smooth form inputs */
    .form-input-custom {
        transition: border-color .15s, box-shadow .15s, background .15s;
    }
    .form-input-custom:focus {
        border-color: #6366f1;
        box-shadow: 0 0 0 3px rgba(99,102,241,.1);
        background: #fff;
    }

    /* Tile radio styles */
    .tile-option:has(input:checked) .tile-box {
        border-color: #6366f1;
        background: #eef2ff;
        box-shadow: 0 0 0 3px rgba(99,102,241,.12);
    }
</style>
@endpush

@section('content')

@php
    use Carbon\Carbon;
    $maxBar      = $riwayat7Hari->max('total') ?: 1;
    $badgeCls    = [
        'Bongkar'=>'bg-sky-50 text-sky-700 border border-sky-200',
        'Bensin'=>'bg-amber-50 text-amber-700 border border-amber-200',
        'Lain-lain'=>'bg-violet-50 text-violet-700 border border-violet-200',
    ];
    $iconMap     = ['Bongkar'=>'truck','Bensin'=>'fuel','Lain-lain'=>'tag'];
    $mobIconBg   = ['Bongkar'=>'bg-sky-50','Bensin'=>'bg-amber-50','Lain-lain'=>'bg-violet-50'];
    $mobIconClr  = ['Bongkar'=>'text-sky-500','Bensin'=>'text-amber-500','Lain-lain'=>'text-violet-500'];
    $isPositive  = $totalBersih >= 0;
@endphp


<div class="laporan-page max-w-7xl mx-auto pb-28 lg:pb-10">

    {{-- ═══════════════════════════════════════════
         PAGE HEADER
    ═══════════════════════════════════════════ --}}
    <div class="flex flex-col sm:flex-row sm:items-end justify-between gap-4 mb-8 fade-1">
        <div>
            <p class="text-[11px] font-bold text-slate-400 uppercase tracking-[.12em] mb-2">Ringkasan Keuangan</p>
            <h1 class="text-2xl sm:text-3xl font-black text-slate-800 tracking-tight leading-none mb-2">
                Laporan Harian
            </h1>
            <div class="flex items-center gap-2.5 flex-wrap">
                <span class="inline-flex items-center gap-1.5 px-3 py-1 bg-indigo-600 text-white rounded-full text-[11px] font-bold tracking-wide shadow-lg shadow-indigo-200">
                    <span class="w-1.5 h-1.5 bg-cyan-300 rounded-full" style="animation:pulse-dot 2s ease-in-out infinite;"></span>
                    Live · Hari Ini
                </span>
                <span class="text-sm text-slate-400 font-medium">
                    {{ \Carbon\Carbon::now('Asia/Jakarta')->locale('id')->translatedFormat('l, d F Y') }}
                </span>
            </div>
        </div>
        <button id="btnAddExpense"
            class="self-start sm:self-auto inline-flex items-center gap-2 px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-sm rounded-xl shadow-lg shadow-indigo-200 hover:shadow-indigo-300 transition-all hover:-translate-y-0.5 active:scale-[.97]">
            <i data-lucide="plus-circle" class="w-4 h-4"></i>
            Catat Pengeluaran
        </button>
    </div>

    {{-- ═══════════════════════════════════════════
         STAT CARDS — 3 columns
    ═══════════════════════════════════════════ --}}
    <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 lg:gap-5 mb-7">

        {{-- 💰 Uang Masuk --}}
        <a href="{{ route('kurir.riwayat', ['tanggal' => date('Y-m-d')]) }}" class="stat-card rounded-2xl p-5 lg:p-6 text-white fade-2 group"
            style="background:linear-gradient(135deg,#0ea5e9,#1d4ed8); box-shadow:0 8px 32px rgba(59,130,246,.3);">
            <div class="shimmer-overlay rounded-2xl"></div>
            <div class="flex items-start justify-between mb-5">
                <div class="w-11 h-11 rounded-xl bg-white/20 backdrop-blur flex items-center justify-center">
                    <i data-lucide="trending-up" class="w-5 h-5 text-white"></i>
                </div>
                <span class="text-[11px] font-bold px-3 py-1 rounded-full bg-white/20 backdrop-blur tracking-wide">Pemasukan</span>
            </div>
            <p class="text-[10px] font-semibold text-white/55 uppercase tracking-[.1em] mb-1.5">Total Uang Masuk</p>
            <p class="text-2xl lg:text-[1.75rem] font-black tracking-tight leading-none count-anim">
                Rp {{ number_format($totalMasukHariIni,0,',','.') }}
            </p>
            <div class="mt-4 pt-3.5 border-t border-white/15 flex items-center justify-between">
                <div class="flex items-center gap-1.5">
                    <i data-lucide="receipt" class="w-3.5 h-3.5 text-white/40"></i>
                    <span class="text-[11px] text-white/50">Transaksi Tunai &amp; Hari Ini (Non-QRIS)</span>
                </div>
                <i data-lucide="arrow-right-circle" class="w-4 h-4 text-white/40 group-hover:text-white group-hover:translate-x-1 transition-all"></i>
            </div>
        </a>

        {{-- 💳 Biaya Operasional --}}
        <div class="stat-card rounded-2xl p-5 lg:p-6 text-white fade-3"
            style="background:linear-gradient(135deg,#fb923c,#dc2626); box-shadow:0 8px 32px rgba(249,115,22,.3);">
            <div class="shimmer-overlay rounded-2xl"></div>
            <div class="flex items-start justify-between mb-5">
                <div class="w-11 h-11 rounded-xl bg-white/20 backdrop-blur flex items-center justify-center">
                    <i data-lucide="wallet" class="w-5 h-5 text-white"></i>
                </div>
                <span class="text-[11px] font-bold px-3 py-1 rounded-full bg-white/20 backdrop-blur tracking-wide">{{ $pengeluaranHariIni->count() }} item</span>
            </div>
            <p class="text-[10px] font-semibold text-white/55 uppercase tracking-[.1em] mb-1.5">Biaya Operasional</p>
            <p class="text-2xl lg:text-[1.75rem] font-black tracking-tight leading-none count-anim">
                Rp {{ number_format($totalPengeluaran,0,',','.') }}
            </p>
            <div class="mt-4 pt-3.5 border-t border-white/15 flex items-center gap-1.5">
                <i data-lucide="fuel" class="w-3.5 h-3.5 text-white/40"></i>
                <span class="text-[11px] text-white/50">Bensin &amp; lainnya</span>
            </div>
        </div>

        {{-- 📊 Total Bersih --}}
        <div class="stat-card rounded-2xl p-5 lg:p-6 text-white fade-4"
            style="background:linear-gradient(135deg,#34d399,#059669); box-shadow:0 8px 32px rgba(16,185,129,.3);">
            <div class="shimmer-overlay rounded-2xl"></div>
            <div class="flex items-start justify-between mb-5">
                <div class="w-11 h-11 rounded-xl bg-white/20 backdrop-blur flex items-center justify-center">
                    <i data-lucide="circle-dollar-sign" class="w-5 h-5 text-white"></i>
                </div>
                @if($isPositive)
                    <span class="text-[11px] font-bold px-3 py-1 rounded-full bg-white/20 backdrop-blur tracking-wide">✓ Untung</span>
                @else
                    <span class="text-[11px] font-bold px-3 py-1 rounded-full tracking-wide" style="background:rgba(239,68,68,.45);">⚠ Rugi</span>
                @endif
            </div>
            <p class="text-[10px] font-semibold text-white/55 uppercase tracking-[.1em] mb-1.5">Total Bersih</p>
            <p class="text-2xl lg:text-[1.75rem] font-black tracking-tight leading-none count-anim">
                {{ $isPositive ? '' : '−' }}Rp {{ number_format(abs($totalBersih),0,',','.') }}
            </p>
            <div class="mt-4 pt-3.5 border-t border-white/15 flex items-center gap-1.5">
                <i data-lucide="minus-circle" class="w-3.5 h-3.5 text-white/40"></i>
                <span class="text-[11px] text-white/50">Masuk dikurangi operasional</span>
            </div>
        </div>
    </div>

    {{-- ═══════════════════════════════════════════
         MIDDLE GRID  (Left 5/12 + Right 7/12)
    ═══════════════════════════════════════════ --}}
    <div class="grid grid-cols-1 lg:grid-cols-12 gap-5 mb-5">

        {{-- ── LEFT COLUMN ─────────────────────────── --}}
        <div class="lg:col-span-5 flex flex-col gap-5">

            {{-- 🥧 Breakdown Metode Bayar --}}
            <div class="bg-white rounded-2xl border border-slate-100 shadow-sm hover:shadow-md transition-shadow fade-3">
                <div class="flex items-center justify-between px-5 py-4 border-b border-slate-50">
                    <div class="flex items-center gap-3">
                        <div class="w-9 h-9 rounded-xl bg-indigo-50 flex items-center justify-center">
                            <i data-lucide="pie-chart" class="w-4 h-4 text-indigo-500"></i>
                        </div>
                        <div>
                            <p class="text-sm font-bold text-slate-800">Metode Pembayaran</p>
                            <p class="text-[10px] text-slate-400">Distribusi hari ini</p>
                        </div>
                    </div>
                    @php $grandTotal = $breakdownMetode->sum('total') ?: 1; @endphp
                    <span class="text-xs font-bold text-slate-400">{{ $breakdownMetode->sum('jumlah') }} trx</span>
                </div>
                <div class="p-5">
                    @if($breakdownMetode->isEmpty())
                        <div class="flex flex-col items-center justify-center py-10 text-center">
                            <div class="w-16 h-16 rounded-2xl bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center shadow-inner mb-3" style="animation:float 3s ease-in-out infinite;">
                                <i data-lucide="inbox" class="w-7 h-7 text-slate-300"></i>
                            </div>
                            <p class="text-sm font-semibold text-slate-400">Belum ada transaksi hari ini</p>
                        </div>
                    @else
                    <div class="space-y-5">
                        @foreach($breakdownMetode as $m)
                        @php
                            $pct = round(($m->total / $grandTotal) * 100);
                            $cfg = [
                                'Tunai'    => ['bg-emerald-500','text-emerald-600','bg-emerald-50','banknote'],
                                'Transfer' => ['bg-blue-500','text-blue-600','bg-blue-50','building-2'],
                                'Qris'     => ['bg-violet-500','text-violet-600','bg-violet-50','qr-code'],
                            ];
                            [$barBg,$txtCls,$iconBg,$iconNm] = $cfg[$m->metode_bayar] ?? ['bg-slate-500','text-slate-600','bg-slate-50','credit-card'];
                        @endphp
                        <div>
                            <div class="flex items-center justify-between mb-2">
                                <div class="flex items-center gap-2.5">
                                    <div class="w-8 h-8 rounded-lg {{ $iconBg }} flex items-center justify-center flex-shrink-0">
                                        <i data-lucide="{{ $iconNm }}" class="w-3.5 h-3.5 {{ $txtCls }}"></i>
                                    </div>
                                    <div>
                                        <p class="text-sm font-bold text-slate-700 leading-none">{{ $m->metode_bayar }}</p>
                                        <p class="text-[10px] text-slate-400 mt-0.5">{{ $m->jumlah }} transaksi</p>
                                    </div>
                                </div>
                                <div class="text-right">
                                    <p class="text-sm font-black {{ $txtCls }} font-mono leading-none">{{ $pct }}%</p>
                                    <p class="text-[10px] text-slate-400 mt-0.5 font-mono">Rp {{ number_format($m->total,0,',','.') }}</p>
                                </div>
                            </div>
                            <div class="h-2 bg-slate-100 rounded-full overflow-hidden">
                                <div class="h-full rounded-full {{ $barBg }} transition-all duration-700" style="width:{{ $pct }}%"></div>
                            </div>
                        </div>
                        @endforeach
                    </div>
                    @endif
                </div>
            </div>

            {{-- 📝 Form Pengeluaran Multi-Row --}}
            <div class="bg-white rounded-2xl border border-slate-100 shadow-sm hover:shadow-md transition-shadow fade-4" id="panelForm">
                <div class="flex items-center justify-between px-5 py-4 border-b border-slate-50">
                    <div class="flex items-center gap-3">
                        <div class="w-9 h-9 rounded-xl bg-indigo-50 flex items-center justify-center">
                            <i data-lucide="plus-square" class="w-4 h-4 text-indigo-500"></i>
                        </div>
                        <div>
                            <p class="text-sm font-bold text-slate-800">Tambah Pengeluaran</p>
                            <p class="text-[10px] text-slate-400">Input sekaligus beberapa item</p>
                        </div>
                    </div>
                    {{-- Real-time Jakarta Clock --}}
                    <div class="text-right">
                        <p class="text-[9px] text-slate-400 uppercase tracking-wider font-semibold">Waktu Jakarta</p>
                        <p id="jakartaClock" class="text-sm font-black text-indigo-600 font-mono leading-tight tabular-nums">--:--:--</p>
                    </div>
                </div>
                <div class="p-5">
                    <form method="POST" action="{{ route('kurir.laporan.pengeluaran.store') }}" id="formPengeluaran" class="no-loader" novalidate>
                        @csrf

                        {{-- Dynamic rows container --}}
                        <div id="expenseRows" class="space-y-3 mb-4">
                            {{-- Row template will be cloned by JS --}}
                            <div class="expense-row bg-slate-50/70 border border-slate-100 rounded-xl p-4 relative group" data-row="0">
                                <div class="flex items-start gap-3">
                                    {{-- Row number --}}
                                    <div class="w-7 h-7 rounded-lg bg-indigo-100 text-indigo-600 flex items-center justify-center text-xs font-black flex-shrink-0 mt-1.5 row-number">1</div>

                                    <div class="flex-1 space-y-3">
                                        {{-- Top row: Kategori + Keterangan --}}
                                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                                            {{-- Kategori --}}
                                            <div>
                                                <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Kategori</label>
                                                <select name="items[0][kategori]"
                                                    class="form-input-custom w-full px-3 py-2 bg-white border-[1.5px] border-slate-200 rounded-lg text-sm text-slate-800 outline-none cursor-pointer">
                                                    <option value="Bensin">⛽ Bensin</option>
                                                    <option value="Lain-lain">🏷️ Lain-lain</option>
                                                </select>
                                            </div>
                                            {{-- Keterangan --}}
                                            <div>
                                                <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Keterangan</label>
                                                <input type="text" name="items[0][keterangan]"
                                                    class="form-input-custom w-full px-3 py-2 bg-white border-[1.5px] border-slate-200 rounded-lg text-sm text-slate-800 placeholder:text-slate-400 outline-none"
                                                    placeholder="Contoh: Bensin Mobil" maxlength="255" autocomplete="off">
                                            </div>
                                        </div>
                                        {{-- Bottom row: Jumlah --}}
                                        <div>
                                            <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Jumlah (Rp)</label>
                                            <div class="relative">
                                                <span class="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs font-bold pointer-events-none">Rp</span>
                                                <input type="number" name="items[0][jumlah]"
                                                    class="form-input-custom w-full pl-9 pr-3 py-2 bg-white border-[1.5px] border-slate-200 rounded-lg text-sm text-slate-800 placeholder:text-slate-400 outline-none"
                                                    placeholder="50000" min="1">
                                            </div>
                                        </div>
                                    </div>

                                    {{-- Remove button (hidden for first row) --}}
                                    <button type="button" class="btn-remove-row w-7 h-7 rounded-lg border-[1.5px] border-slate-200 bg-white text-slate-400 flex items-center justify-center flex-shrink-0 mt-1.5 transition-all hover:bg-rose-500 hover:text-white hover:border-rose-500 hover:scale-110 cursor-pointer opacity-0 group-hover:opacity-100" style="display:none;" title="Hapus baris">
                                        <i data-lucide="x" class="w-3.5 h-3.5"></i>
                                    </button>
                                </div>
                            </div>
                        </div>

                        {{-- Add Row Button --}}
                        <button type="button" id="btnAddRow"
                            class="w-full flex items-center justify-center gap-2 py-2.5 border-2 border-dashed border-slate-200 hover:border-indigo-400 text-slate-400 hover:text-indigo-500 rounded-xl transition-all text-sm font-bold mb-4 hover:bg-indigo-50/50">
                            <i data-lucide="plus" class="w-4 h-4"></i>
                            Tambah Baris Pengeluaran
                        </button>

                        {{-- Summary + Action --}}
                        <div class="flex items-center justify-between bg-slate-50 rounded-xl px-4 py-3 mb-4">
                            <div>
                                <p class="text-[10px] text-slate-400 font-bold uppercase tracking-wider">Total Estimasi</p>
                                <p id="totalEstimasi" class="text-lg font-black text-slate-800 font-mono">Rp 0</p>
                            </div>
                            <div class="text-right">
                                <p class="text-[10px] text-slate-400 font-bold uppercase tracking-wider">Jumlah Item</p>
                                <p id="itemCount" class="text-lg font-black text-indigo-600 font-mono">1</p>
                            </div>
                        </div>

                        <div class="flex gap-2">
                            <button type="submit"
                                class="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-sm rounded-xl shadow-lg shadow-indigo-200 hover:shadow-indigo-300 transition-all hover:-translate-y-0.5 active:scale-[.97]">
                                <i data-lucide="save" class="w-4 h-4"></i>
                                Simpan Semua Pengeluaran
                            </button>
                            <button type="button" id="btnResetForm"
                                class="px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-500 rounded-xl transition-colors flex items-center justify-center"
                                title="Reset form">
                                <i data-lucide="rotate-ccw" class="w-4 h-4"></i>
                            </button>
                        </div>
                    </form>
                </div>
            </div>

        </div>{{-- /LEFT --}}

        {{-- ── RIGHT COLUMN ────────────────────────── --}}
        <div class="lg:col-span-7 fade-3">
            <div class="bg-white rounded-2xl border border-slate-100 shadow-sm hover:shadow-md transition-shadow h-full flex flex-col">
                {{-- Header --}}
                <div class="flex items-center justify-between px-5 py-4 border-b border-slate-50">
                    <div class="flex items-center gap-3">
                        <div class="w-9 h-9 rounded-xl bg-emerald-50 flex items-center justify-center">
                            <i data-lucide="bar-chart-2" class="w-4 h-4 text-emerald-500"></i>
                        </div>
                        <div>
                            <p class="text-sm font-bold text-slate-800">Penjualan 7 Hari Terakhir</p>
                            <p class="text-[10px] text-slate-400">
                                Total (Non-QRIS): Rp {{ number_format($riwayat7Hari->sum('total'),0,',','.') }}
                            </p>
                        </div>
                    </div>
                    <div class="flex items-center gap-3">
                        <div class="flex items-center gap-1.5">
                            <span class="w-2.5 h-2.5 rounded bg-blue-400 inline-block"></span>
                            <span class="text-[10px] text-slate-400 font-medium">Lalu</span>
                        </div>
                        <div class="flex items-center gap-1.5">
                            <span class="w-2.5 h-2.5 rounded bg-emerald-400 inline-block"></span>
                            <span class="text-[10px] text-slate-400 font-medium">Hari ini</span>
                        </div>
                    </div>
                </div>

                {{-- Body --}}
                <div class="p-5 flex-1 flex flex-col">

                    {{-- Bar Chart --}}
                    <div class="flex items-end gap-3 sm:gap-4 mb-3" style="height:160px;">
                        @foreach($riwayat7Hari as $day)
                        @php $pct = $maxBar>0 ? round(($day['total']/$maxBar)*100) : 0; @endphp
                        <div class="flex-1 flex flex-col items-center gap-1.5 min-w-0 h-full">
                            <div class="w-full flex-1 bg-slate-50 rounded-lg relative overflow-hidden">
                                <div class="bar-fill-anim w-full absolute bottom-0 rounded-lg
                                    {{ $day['is_today']
                                        ? 'bg-gradient-to-t from-emerald-500 to-emerald-300 shadow-[0_0_10px_rgba(16,185,129,.35)]'
                                        : ($pct==0 ? 'bg-slate-200' : 'bg-gradient-to-t from-blue-500 to-blue-300') }}"
                                    style="height:{{ max($pct,3) }}%;"
                                    title="{{ $day['tanggal'] }}: Rp {{ number_format($day['total'],0,',','.') }}">
                                </div>
                            </div>
                        </div>
                        @endforeach
                    </div>

                    {{-- Day Labels --}}
                    <div class="flex gap-3 sm:gap-4 mb-5">
                        @foreach($riwayat7Hari as $day)
                        <div class="flex-1 text-center min-w-0">
                            <p class="text-[9px] sm:text-[10px] font-bold truncate
                                {{ $day['is_today'] ? 'text-emerald-600' : 'text-slate-400' }}">
                                {{ explode(', ',$day['tanggal'])[0] }}
                            </p>
                        </div>
                        @endforeach
                    </div>

                    {{-- Daily detail rows --}}
                    <div class="space-y-1.5 flex-1">
                        @foreach($riwayat7Hari as $day)
                        <a href="{{ route('kurir.riwayat', ['tanggal' => $day['tanggal_raw']]) }}" class="flex items-center justify-between px-3.5 py-2.5 rounded-xl transition-all
                            {{ $day['is_today']
                                ? 'bg-emerald-50/80 border border-emerald-100 hover:bg-emerald-100'
                                : 'hover:bg-slate-50 border border-transparent hover:border-slate-200' }} group/row">
                            <div class="flex items-center gap-2.5">
                                <span class="w-2 h-2 rounded-full flex-shrink-0
                                    {{ $day['is_today'] ? 'bg-emerald-400' : 'bg-slate-200' }}"></span>
                                <span class="text-xs font-semibold
                                    {{ $day['is_today'] ? 'text-emerald-700' : 'text-slate-600' }}">
                                    {{ $day['tanggal'] }}
                                </span>
                                @if($day['is_today'])
                                    <span class="text-[9px] font-bold bg-emerald-100 text-emerald-600 px-1.5 py-0.5 rounded-full">HARI INI</span>
                                @endif
                                <i data-lucide="external-link" class="w-2.5 h-2.5 opacity-0 group-hover/row:opacity-100 transition-opacity text-slate-400"></i>
                            </div>
                            <div class="flex items-center gap-4">
                                <span class="text-[10px] text-slate-400 font-medium">{{ $day['jumlah'] }} trx</span>
                                <span class="text-xs font-black font-mono
                                    {{ $day['is_today'] ? 'text-emerald-700' : 'text-slate-700' }}">
                                    Rp {{ number_format($day['total'],0,',','.') }}
                                </span>
                            </div>
                        </a>
                        @endforeach
                    </div>

                </div>
            </div>
        </div>{{-- /RIGHT --}}

    </div>{{-- /MIDDLE GRID --}}

    {{-- ═══════════════════════════════════════════
         PENGELUARAN TABLE
    ═══════════════════════════════════════════ --}}
    <div class="bg-white rounded-2xl border border-slate-100 shadow-sm hover:shadow-md transition-shadow fade-5">
        {{-- Header --}}
        <div class="flex items-center justify-between px-5 py-4 border-b border-slate-50">
            <div class="flex items-center gap-3">
                <div class="w-9 h-9 rounded-xl bg-red-50 flex items-center justify-center">
                    <i data-lucide="list-checks" class="w-4 h-4 text-red-500"></i>
                </div>
                <div>
                    <p class="text-sm font-bold text-slate-800">Pengeluaran Hari Ini</p>
                    <p class="text-[10px] text-slate-400">{{ $pengeluaranHariIni->count() }} item tercatat</p>
                </div>
            </div>
            <div class="text-right">
                <p class="text-[9px] text-slate-400 uppercase tracking-wider font-semibold">Total</p>
                <p class="text-lg font-black text-red-500 font-mono leading-tight">
                    Rp {{ number_format($totalPengeluaran,0,',','.') }}
                </p>
            </div>
        </div>

        @if($pengeluaranHariIni->isEmpty())
            {{-- Empty State --}}
            <div class="flex flex-col items-center justify-center py-14 px-5 text-center">
                <div class="w-[72px] h-[72px] rounded-2xl bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center shadow-inner mb-4"
                    style="animation:float 3s ease-in-out infinite;">
                    <i data-lucide="receipt" class="w-8 h-8 text-slate-300"></i>
                </div>
                <p class="text-slate-600 font-bold text-base mb-1">Belum ada pengeluaran hari ini</p>
                <p class="text-sm text-slate-400 mb-4">Klik tombol di bawah untuk menambahkan catatan pengeluaran</p>
                <button onclick="document.getElementById('btnAddExpense').click()"
                    class="inline-flex items-center gap-2 px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-sm rounded-xl shadow-lg shadow-indigo-200 transition-all hover:-translate-y-0.5 active:scale-[.97]">
                    <i data-lucide="plus" class="w-4 h-4"></i>
                    Tambah Sekarang
                </button>
            </div>
        @else

            {{-- Desktop Table --}}
            <div class="hidden md:block">
                <table class="w-full border-collapse">
                    <thead>
                        <tr>
                            <th class="px-5 py-3 text-left text-[10px] font-bold text-slate-400 uppercase tracking-[.08em] bg-slate-50/60 w-10 text-center">#</th>
                            <th class="px-5 py-3 text-left text-[10px] font-bold text-slate-400 uppercase tracking-[.08em] bg-slate-50/60">Keterangan</th>
                            <th class="px-5 py-3 text-left text-[10px] font-bold text-slate-400 uppercase tracking-[.08em] bg-slate-50/60">Kategori</th>
                            <th class="px-5 py-3 text-left text-[10px] font-bold text-slate-400 uppercase tracking-[.08em] bg-slate-50/60">Waktu</th>
                            <th class="px-5 py-3 text-right text-[10px] font-bold text-slate-400 uppercase tracking-[.08em] bg-slate-50/60">Jumlah</th>
                            <th class="px-5 py-3 text-center text-[10px] font-bold text-slate-400 uppercase tracking-[.08em] bg-slate-50/60 w-16">Hapus</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($pengeluaranHariIni as $i => $p)
                        <tr class="hover:bg-slate-50/60 transition-colors">
                            <td class="px-5 py-3.5 text-center text-xs text-slate-300 font-mono font-bold border-b border-slate-50">{{ $i+1 }}</td>
                            <td class="px-5 py-3.5 border-b border-slate-50">
                                <p class="text-sm font-semibold text-slate-700">{{ $p->keterangan }}</p>
                            </td>
                            <td class="px-5 py-3.5 border-b border-slate-50">
                                <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold {{ $badgeCls[$p->kategori] ?? 'bg-violet-50 text-violet-700 border border-violet-200' }}">
                                    <i data-lucide="{{ $iconMap[$p->kategori] ?? 'tag' }}" class="w-3 h-3"></i>
                                    {{ $p->kategori }}
                                </span>
                            </td>
                            <td class="px-5 py-3.5 text-xs text-slate-400 font-medium border-b border-slate-50">
                                {{ \Carbon\Carbon::parse($p->created_at)->timezone('Asia/Jakarta')->format('H:i') }} WIB
                            </td>
                            <td class="px-5 py-3.5 text-right border-b border-slate-50">
                                <span class="text-sm font-black text-red-500 font-mono">
                                    Rp {{ number_format($p->jumlah,0,',','.') }}
                                </span>
                            </td>
                            <td class="px-5 py-3.5 text-center border-b border-slate-50">
                                <button type="button" class="btn-hapus w-8 h-8 rounded-lg border-[1.5px] border-rose-200 bg-rose-50 text-rose-500 inline-flex items-center justify-center cursor-pointer transition-all hover:bg-rose-500 hover:text-white hover:border-rose-500 hover:scale-110 hover:shadow-lg hover:shadow-rose-200 active:scale-95"
                                    data-id="{{ $p->id }}"
                                    data-ket="{{ $p->keterangan }}"
                                    data-jumlah="Rp {{ number_format($p->jumlah,0,',','.') }}">
                                    <i data-lucide="trash-2" class="w-3.5 h-3.5"></i>
                                </button>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="4" class="px-5 py-3 text-xs font-bold text-slate-400 uppercase tracking-wider text-right bg-slate-50/60 border-t-2 border-slate-100">
                                Total Pengeluaran
                            </td>
                            <td class="px-5 py-3 text-right bg-slate-50/60 border-t-2 border-slate-100">
                                <span class="text-base font-black text-red-500 font-mono">
                                    Rp {{ number_format($totalPengeluaran,0,',','.') }}
                                </span>
                            </td>
                            <td class="bg-slate-50/60 border-t-2 border-slate-100"></td>
                        </tr>
                    </tfoot>
                </table>
            </div>

            {{-- Mobile Cards --}}
            <div class="md:hidden">
                @foreach($pengeluaranHariIni as $p)
                <div class="flex items-center gap-3.5 px-5 py-3.5 border-b border-slate-50 last:border-b-0 hover:bg-slate-50/60 transition-colors">
                    <div class="w-10 h-10 rounded-xl {{ $mobIconBg[$p->kategori] ?? 'bg-violet-50' }} flex items-center justify-center flex-shrink-0">
                        <i data-lucide="{{ $iconMap[$p->kategori] ?? 'tag' }}" class="w-4 h-4 {{ $mobIconClr[$p->kategori] ?? 'text-violet-500' }}"></i>
                    </div>
                    <div class="flex-1 min-w-0">
                        <p class="text-sm font-bold text-slate-700 truncate">{{ $p->keterangan }}</p>
                        <div class="flex items-center gap-2 mt-0.5">
                            <span class="text-[10px] text-slate-400">{{ \Carbon\Carbon::parse($p->created_at)->timezone('Asia/Jakarta')->format('H:i') }} WIB</span>
                            <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold {{ $badgeCls[$p->kategori] ?? 'bg-violet-50 text-violet-700 border border-violet-200' }}">{{ $p->kategori }}</span>
                        </div>
                    </div>
                    <div class="flex items-center gap-2.5 flex-shrink-0">
                        <span class="text-sm font-black text-red-500 font-mono">
                            Rp {{ number_format($p->jumlah,0,',','.') }}
                        </span>
                        <button type="button" class="btn-hapus w-8 h-8 rounded-lg border-[1.5px] border-rose-200 bg-rose-50 text-rose-500 inline-flex items-center justify-center cursor-pointer transition-all hover:bg-rose-500 hover:text-white hover:border-rose-500 hover:scale-110 hover:shadow-lg hover:shadow-rose-200 active:scale-95"
                            data-id="{{ $p->id }}"
                            data-ket="{{ $p->keterangan }}"
                            data-jumlah="Rp {{ number_format($p->jumlah,0,',','.') }}">
                            <i data-lucide="trash-2" class="w-3.5 h-3.5"></i>
                        </button>
                    </div>
                </div>
                @endforeach
                {{-- Mobile footer --}}
                <div class="flex items-center justify-between px-5 py-3.5 bg-slate-50 border-t border-slate-100">
                    <span class="text-xs font-bold text-slate-400 uppercase tracking-wider">Total Pengeluaran</span>
                    <span class="text-base font-black text-red-500 font-mono">
                        Rp {{ number_format($totalPengeluaran,0,',','.') }}
                    </span>
                </div>
            </div>
        @endif
    </div>

</div>{{-- /laporan-page --}}

{{-- Hidden delete form --}}
<form id="deleteForm" method="POST" action="" class="no-loader hidden">
    @csrf
    @method('DELETE')
</form>

@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    if (typeof lucide !== 'undefined') lucide.createIcons();

    // ══════════════════════════════════════════════════════════
    //  REAL-TIME JAKARTA CLOCK (Asia/Jakarta = WIB UTC+7)
    // ══════════════════════════════════════════════════════════
    const clockEl = document.getElementById('jakartaClock');
    function updateClock() {
        const now = new Date();
        const jakartaTime = new Intl.DateTimeFormat('id-ID', {
            timeZone: 'Asia/Jakarta',
            hour: '2-digit', minute: '2-digit', second: '2-digit',
            hour12: false
        }).format(now);
        if (clockEl) clockEl.textContent = jakartaTime + ' WIB';
    }
    updateClock();
    setInterval(updateClock, 1000);

    // ══════════════════════════════════════════════════════════
    //  MULTI-ROW EXPENSE FORM
    // ══════════════════════════════════════════════════════════
    let rowIndex = 0;
    const rowsContainer = document.getElementById('expenseRows');
    const btnAddRow     = document.getElementById('btnAddRow');
    const totalEstEl    = document.getElementById('totalEstimasi');
    const itemCountEl   = document.getElementById('itemCount');

    function formatRp(n) {
        return 'Rp ' + Number(n || 0).toLocaleString('id-ID');
    }

    function updateSummary() {
        const rows = rowsContainer.querySelectorAll('.expense-row');
        let total = 0;
        rows.forEach(row => {
            const inp = row.querySelector('input[type=number]');
            total += parseFloat(inp?.value || 0);
        });
        totalEstEl.textContent = formatRp(total);
        itemCountEl.textContent = rows.length;
        // Update row numbers
        rows.forEach((row, i) => {
            row.querySelector('.row-number').textContent = i + 1;
            // Show/hide remove button
            const removeBtn = row.querySelector('.btn-remove-row');
            removeBtn.style.display = rows.length > 1 ? '' : 'none';
        });
        // Re-index names
        rows.forEach((row, i) => {
            row.dataset.row = i;
            row.querySelectorAll('select, input').forEach(el => {
                const name = el.getAttribute('name');
                if (name) el.setAttribute('name', name.replace(/items\[\d+\]/, `items[${i}]`));
            });
        });
    }

    // Add new row
    btnAddRow?.addEventListener('click', function() {
        rowIndex++;
        const firstRow = rowsContainer.querySelector('.expense-row');
        const newRow = firstRow.cloneNode(true);
        // Clear values
        newRow.querySelectorAll('input').forEach(inp => { inp.value = ''; });
        newRow.querySelectorAll('select').forEach(sel => { sel.selectedIndex = 0; });
        // Update names
        newRow.dataset.row = rowIndex;
        newRow.querySelectorAll('select, input').forEach(el => {
            const name = el.getAttribute('name');
            if (name) el.setAttribute('name', name.replace(/items\[\d+\]/, `items[${rowIndex}]`));
        });
        // Show remove button
        newRow.querySelector('.btn-remove-row').style.display = '';
        // Animate in
        newRow.style.opacity = '0';
        newRow.style.transform = 'translateY(10px)';
        rowsContainer.appendChild(newRow);
        // Re-init lucide icons
        if (typeof lucide !== 'undefined') lucide.createIcons();
        // Animate
        requestAnimationFrame(() => {
            newRow.style.transition = 'opacity .3s, transform .3s';
            newRow.style.opacity = '1';
            newRow.style.transform = 'translateY(0)';
        });
        // Attach events
        attachRowEvents(newRow);
        updateSummary();
        // Focus keterangan
        newRow.querySelector('input[type=text]')?.focus();
    });

    // Remove row
    function attachRowEvents(row) {
        const removeBtn = row.querySelector('.btn-remove-row');
        removeBtn?.addEventListener('click', function() {
            const rows = rowsContainer.querySelectorAll('.expense-row');
            if (rows.length <= 1) return;
            row.style.transition = 'opacity .2s, transform .2s';
            row.style.opacity = '0';
            row.style.transform = 'translateX(20px)';
            setTimeout(() => {
                row.remove();
                updateSummary();
            }, 200);
        });
        // Listen for amount changes
        row.querySelector('input[type=number]')?.addEventListener('input', updateSummary);
    }

    // Attach events to initial row
    rowsContainer.querySelectorAll('.expense-row').forEach(attachRowEvents);

    // ── Scroll to form on validation error ────────────────────
    @if($errors->any())
    document.getElementById('panelForm')?.scrollIntoView({ behavior:'smooth', block:'center' });
    @endif

    // ── "Catat Pengeluaran" header button ─────────────────────
    document.getElementById('btnAddExpense')?.addEventListener('click', () => {
        document.getElementById('panelForm')?.scrollIntoView({ behavior:'smooth', block:'center' });
        const firstInput = rowsContainer.querySelector('.expense-row input[type=text]');
        setTimeout(() => firstInput?.focus(), 420);
    });

    // ── Reset all rows ────────────────────────────────────────
    document.getElementById('btnResetForm')?.addEventListener('click', () => {
        // Remove all rows except first
        const rows = rowsContainer.querySelectorAll('.expense-row');
        rows.forEach((row, i) => { if (i > 0) row.remove(); });
        // Reset first row
        const first = rowsContainer.querySelector('.expense-row');
        first.querySelectorAll('input').forEach(inp => { inp.value = ''; });
        first.querySelectorAll('select').forEach(sel => { sel.selectedIndex = 0; });
        rowIndex = 0;
        updateSummary();
        first.querySelector('input[type=text]')?.focus();
    });

    // ── Client-side validation (multi-row) ────────────────────
    document.getElementById('formPengeluaran')?.addEventListener('submit', function (e) {
        const rows = rowsContainer.querySelectorAll('.expense-row');
        let hasError = false;
        let errorMsg = '';

        rows.forEach((row, i) => {
            if (hasError) return;
            const ket    = row.querySelector('input[type=text]')?.value.trim();
            const jumlah = parseFloat(row.querySelector('input[type=number]')?.value);

            if (!ket) {
                hasError = true;
                errorMsg = `Baris ${i+1}: Keterangan tidak boleh kosong.`;
                row.querySelector('input[type=text]')?.focus();
            } else if (!jumlah || jumlah < 1) {
                hasError = true;
                errorMsg = `Baris ${i+1}: Jumlah harus minimal Rp 1.`;
                row.querySelector('input[type=number]')?.focus();
            }
        });

        if (hasError) {
            e.preventDefault();
            Swal.fire({
                icon: 'warning',
                title: 'Data Belum Lengkap!',
                text: errorMsg,
                confirmButtonColor: '#6366f1',
                customClass: { popup:'!rounded-2xl', confirmButton:'!rounded-xl !font-bold' }
            });
            return;
        }

        // Confirmation before submit
        e.preventDefault();
        const count = rows.length;
        let total = 0;
        rows.forEach(row => {
            total += parseFloat(row.querySelector('input[type=number]')?.value || 0);
        });

        Swal.fire({
            title: 'Simpan Pengeluaran?',
            html: `
                <div style="text-align:center;margin-top:8px;">
                    <div style="background:#eef2ff;border:1px solid #c7d2fe;border-radius:14px;padding:16px;margin-bottom:12px;">
                        <p style="color:#6366f1;font-size:.75rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;margin:0 0 4px;">Total ${count} item</p>
                        <p style="font-weight:900;color:#1e293b;font-family:'Courier New',monospace;font-size:1.3rem;margin:0;">Rp ${Number(total).toLocaleString('id-ID')}</p>
                    </div>
                    <p style="color:#64748b;font-size:.85rem;margin:0;">Semua pengeluaran akan dicatat untuk <strong>hari ini</strong>.</p>
                </div>
            `,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#6366f1',
            cancelButtonColor: '#94a3b8',
            confirmButtonText: 'Ya, Simpan Semua',
            cancelButtonText: 'Batal',
            customClass: {
                popup:         '!rounded-3xl',
                confirmButton: '!rounded-xl !font-bold',
                cancelButton:  '!rounded-xl !font-bold',
                title:         '!font-black',
            }
        }).then(result => {
            if (result.isConfirmed) {
                // Show loader manually
                const loader = document.getElementById('pageLoader');
                if (loader) {
                    loader.classList.remove('opacity-0', 'pointer-events-none');
                    loader.classList.add('opacity-100');
                }
                // Actually submit the form
                e.target.submit();
            }
        });
    });

    // ── Delete confirmation via SweetAlert2 ───────────────────
    document.addEventListener('click', function (e) {
        const btn = e.target.closest('.btn-hapus');
        if (!btn) return;

        const id     = btn.dataset.id;
        const ket    = btn.dataset.ket;
        const jumlah = btn.dataset.jumlah;

        Swal.fire({
            title: 'Hapus Pengeluaran?',
            html: `
                <div style="text-align:left;margin-top:12px;">
                    <div style="background:#fef2f2;border:1px solid #fecaca;border-radius:14px;padding:14px 18px;margin-bottom:12px;">
                        <p style="font-weight:700;color:#1e293b;font-size:.9rem;margin:0 0 4px;">${ket}</p>
                        <p style="font-weight:900;color:#ef4444;font-family:'Courier New',monospace;font-size:1.05rem;margin:0;">${jumlah}</p>
                    </div>
                    <p style="color:#64748b;font-size:.85rem;margin:0;">Pengeluaran ini akan <strong>dihapus permanen</strong>.</p>
                </div>
            `,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor:  '#94a3b8',
            confirmButtonText:  'Hapus Sekarang',
            cancelButtonText:   'Batal',
            focusCancel: true,
            customClass: {
                popup:         '!rounded-3xl',
                confirmButton: '!rounded-xl !font-bold',
                cancelButton:  '!rounded-xl !font-bold',
                title:         '!font-black',
            }
        }).then(result => {
            if (result.isConfirmed) {
                const form = document.getElementById('deleteForm');
                form.action = '{{ url('kurir/laporan/pengeluaran') }}/' + id;
                // Show loader manually
                const loader = document.getElementById('pageLoader');
                if (loader) {
                    loader.classList.remove('opacity-0', 'pointer-events-none');
                    loader.classList.add('opacity-100');
                }
                form.submit();
            }
        });
    });
});
</script>
@endpush
