<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Detail Pesanan - Glow Beauty</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>

    @if($pesanan->status == 'pending')
        @php $isProduction = config('services.midtrans.is_production'); @endphp
        @if($isProduction)
            <script src="https://app.midtrans.com/snap/snap.js" data-client-key="{{ config('services.midtrans.client_key') }}"></script>
        @else
            <script src="https://app.sandbox.midtrans.com/snap/snap.js" data-client-key="{{ config('services.midtrans.client_key') }}"></script>
        @endif
    @endif

    <meta name="csrf-token" content="{{ csrf_token() }}">

    <style>
        * { font-family: 'Poppins', 'Plus Jakarta Sans', sans-serif; }
        body { background: linear-gradient(135deg, #fdf2f8 0%, #fff1f3 100%); }

        .card { background: #fff; border-radius: 16px; border: 1px solid #fbcfe8; overflow: hidden; }
        .card-header { padding: 14px 20px; border-bottom: 1px solid #fef2f8; display: flex; align-items: center; gap: 10px; }
        .card-icon { width: 34px; height: 34px; border-radius: 10px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
        .card-title { font-size: 13.5px; font-weight: 700; color: #1f1f1f; }
        .card-subtitle { font-size: 11.5px; color: #9ca3af; margin-top: 1px; }

        .status-header { background: linear-gradient(135deg, #f472b6 0%, #ec489a 100%); border-radius: 16px; overflow: hidden; position: relative; margin-bottom: 20px; }
        .status-header::before { content:''; position:absolute; top:-40px; right:-40px; width:160px; height:160px; background:rgba(255,255,255,0.07); border-radius:50%; }
        .status-header::after  { content:''; position:absolute; bottom:-25px; left:50px; width:100px; height:100px; background:rgba(255,255,255,0.05); border-radius:50%; }

        .info-row { display:flex; justify-content:space-between; align-items:center; padding:10px 20px; font-size:13px; gap:12px; }
        .info-row:not(:last-child) { border-bottom: 1px solid #fef2f8; }
        .info-row-label { color:#a0aec0; display:flex; align-items:center; gap:8px; white-space:nowrap; flex-shrink:0; }
        .info-row-label i { width:13px; text-align:center; }
        .info-row-value { font-weight:600; color:#1f1f1f; text-align:right; }

        .sidebar { position: sticky; top: 24px; }

        .product-row { display:flex; align-items:center; gap:12px; padding:12px 20px; }
        .product-row:not(:last-child) { border-bottom: 1px solid #fef2f8; }

        .badge { display:inline-flex; align-items:center; gap:3px; padding:2px 9px; border-radius:20px; font-size:11px; font-weight:600; }

        .navbar { background:#fff; border-bottom:1px solid #fbcfe8; position:sticky; top:0; z-index:50; }

        @keyframes fadeUp { from{opacity:0;transform:translateY(10px)} to{opacity:1;transform:translateY(0)} }
        .fu  { animation: fadeUp 0.35s ease both; }
        .fu1 { animation-delay:.05s } .fu2 { animation-delay:.1s } .fu3 { animation-delay:.15s }
        .fu4 { animation-delay:.2s  } .fu5 { animation-delay:.25s }

        .modal { display:none; position:fixed; z-index:9999; left:0; top:0; width:100%; height:100%; background:rgba(0,0,0,0.88); }
        .modal-img { display:block; max-width:90%; max-height:90%; position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); border-radius:12px; }
        .close-modal { position:absolute; top:18px; right:22px; color:#fff; width:40px; height:40px; display:flex; align-items:center; justify-content:center; background:rgba(255,255,255,0.15); border-radius:50%; cursor:pointer; transition:.2s; z-index:10000; font-size:18px; }
        .close-modal:hover { background:rgba(255,255,255,0.25); }
        .zoom-bar { position:absolute; bottom:22px; left:50%; transform:translateX(-50%); display:flex; gap:8px; background:rgba(0,0,0,0.5); padding:7px 14px; border-radius:50px; z-index:10000; }
        .zoom-btn { background:none; border:none; color:white; font-size:16px; cursor:pointer; width:32px; height:32px; display:flex; align-items:center; justify-content:center; border-radius:50%; transition:.2s; }
        .zoom-btn:hover { background:rgba(255,255,255,0.2); }
        .zoom-lbl { color:white; font-size:12px; min-width:44px; text-align:center; display:flex; align-items:center; justify-content:center; }

        #trackingMap { height:300px; border-radius:12px; }
        .custom-div-icon { background:transparent; border:none; }

        .prog-bar { height:5px; border-radius:99px; background:#f3f4f6; overflow:hidden; }
        .prog-fill { height:100%; border-radius:99px; background:linear-gradient(90deg,#f472b6,#ec489a); transition:width .5s ease; }

        @keyframes spin { to{transform:rotate(360deg)} }
        .spin { animation: spin 1s linear infinite; }

        .s-pending    { background:#fef9c3; color:#854d0e; border:1px solid #fde68a; }
        .s-dibayar    { background:#dbeafe; color:#1e40af; border:1px solid #bfdbfe; }
        .s-diproses   { background:#ede9fe; color:#5b21b6; border:1px solid #c4b5fd; }
        .s-dikirim    { background:#e0e7ff; color:#3730a3; border:1px solid #a5b4fc; }
        .s-selesai    { background:#dcfce7; color:#166534; border:1px solid #86efac; }
        .s-dibatalkan { background:#fee2e2; color:#991b1b; border:1px solid #fca5a5; }

        .tl-dot { width:30px; height:30px; border-radius:50%; display:flex; align-items:center; justify-content:center; flex-shrink:0; }
        .tl-line { width:2px; background:#fbcfe8; margin:3px auto; min-height:18px; }
        .tl-line.done { background:#f472b6; }
        
        .border-pink-light { border-color: #fbcfe8; }
    </style>
</head>
<body class="min-h-screen overflow-x-hidden">
    <div class="w-full px-4 sm:px-6 lg:px-8 py-6">

{{-- STATUS HEADER --}}
<div class="relative mb-8 overflow-hidden rounded-2xl bg-gradient-to-r from-pink-400 via-pink-500 to-pink-600 shadow-xl w-full">
    {{-- Background Decorations --}}
    <div class="absolute top-0 right-0 w-64 h-64 opacity-10">
        <i class="fas fa-clipboard-list text-8xl absolute top-10 right-10"></i>
        <i class="fas fa-receipt text-7xl absolute bottom-0 right-32"></i>
        <i class="fas fa-box text-6xl absolute top-20 right-48"></i>
        <i class="fas fa-spa text-7xl absolute bottom-10 left-10"></i>
    </div>
    <div class="absolute bottom-0 left-0 w-48 h-48 bg-white opacity-5 rounded-full -ml-16 -mb-16"></div>
    
    <div class="relative z-10 p-5 sm:p-6">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            {{-- Left Section - Order Info --}}
            <div class="flex items-center gap-4">
                <div class="w-14 h-14 bg-white/20 backdrop-blur-sm rounded-2xl flex items-center justify-center border border-white/30 shadow-inner flex-shrink-0">
                    <i class="fas {{ $statusIcon }} text-white text-2xl"></i>
                </div>
                <div>
                    <div class="flex items-center gap-2 flex-wrap">
                        <h1 class="text-white font-bold text-xl md:text-2xl">Detail Pesanan Skincare</h1>
                        <span class="px-3 py-1 rounded-full text-xs font-semibold {{ $statusClass }} inline-flex items-center gap-1 border">
                            <i class="fas {{ $statusIcon }} text-[10px]"></i> 
                            {{ $statusLabel }}
                            @if($additionalLabel)
                                <span class="text-xs bg-white/30 px-1.5 py-0.5 rounded-full ml-1">{{ $additionalLabel }}</span>
                            @endif
                        </span>
                    </div>
                    <p class="text-pink-100 text-sm mt-1">
                        {{ $statusText }} · 
                        <span class="text-white font-semibold">{{ $pesanan->kode_pesanan }}</span>
                    </p>
                    @if($pesanan->kurir && $statusDisplay == 'dikirim')
                    <p class="text-pink-200 text-xs mt-1.5 flex items-center gap-1.5">
                        <i class="fas fa-truck text-xs"></i>
                        Kurir: <span class="text-white font-semibold">{{ $pesanan->kurir->name }}</span> · {{ $pesanan->kurir->no_hp }}
                    </p>
                    @endif
                </div>
            </div>
            
            {{-- Right Section - Action Buttons --}}
            <div class="flex gap-2 flex-wrap">
                @if($pesanan->status == 'pending')
                    <button onclick="openSnapPayment()" id="payBtnHeader"
                            class="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-white text-pink-600 font-semibold text-sm hover:bg-pink-50 transition-all shadow-md hover:shadow-lg transform hover:scale-105 duration-200">
                        <i class="fas fa-credit-card"></i> Bayar Sekarang
                    </button>
                @elseif($statusDisplay == 'dikirim')
                    <button onclick="openTrackingModal({{ $pesanan->id }})"
                            class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-white text-purple-600 font-semibold text-sm hover:bg-purple-50 transition-all shadow-md hover:shadow-lg">
                        <i class="fas fa-map-marked-alt"></i> Lacak
                    </button>
                @endif
            </div>
        </div>

        {{-- Estimasi Tiba Section (only for dikirim status) --}}
        @if($estimasiTiba && $statusDisplay == 'dikirim')
        <div class="mt-5 bg-white/15 backdrop-blur-sm rounded-xl p-4 border border-white/25">
            <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-clock text-white text-sm"></i>
                    </div>
                    <div>
                        <p class="text-pink-200 text-xs">Estimasi Tiba</p>
                        <p class="text-white font-bold text-base">{{ $estimasiTiba->format('d M Y') }}</p>
                        <p class="text-pink-200 text-xs">{{ $estimasiLabel }} dari pengiriman</p>
                    </div>
                </div>
                <div class="flex-1 max-w-sm">
                    <div class="flex justify-between text-pink-200 text-[10px] mb-1">
                        <span>Diproses</span>
                        <span>Dijemput</span>
                        <span>Diantar</span>
                        <span>Tiba</span>
                    </div>
                    <div class="w-full bg-white/25 rounded-full h-1.5 overflow-hidden">
                        @php 
                            $progBar = match($pesanan->kurirAssignment->status ?? '') { 
                                'dijemput' => 40,
                                'diantar' => 70,
                                'selesai' => 100,
                                default => 30 
                            }; 
                        @endphp
                        <div class="bg-white h-1.5 rounded-full transition-all duration-500" style="width: {{ $progBar }}%"></div>
                    </div>
                    <p class="text-pink-200 text-[9px] mt-1.5 text-right">*Estimasi dapat berubah tergantung kondisi</p>
                </div>
            </div>
        </div>
        @endif
    </div>
</div>

        {{-- PEMBATALAN --}}
        @if($pesanan->status === 'dibatalkan' && $pesanan->catatan)
        @php $catatanBatal = json_decode($pesanan->catatan, true); @endphp
        @if(!is_array($catatanBatal))
        <div class="card mb-5 fu fu1" style="border-color:#fca5a5">
            <div class="card-header" style="background:#fff5f5">
                <div class="card-icon" style="background:#fee2e2"><i class="fas fa-ban text-red-500 text-xs"></i></div>
                <p class="card-title text-red-700">Alasan Pembatalan</p>
            </div>
<div class="p-5">
    <p class="text-gray-700 text-sm italic">
        @php
            $catatanJson = json_decode($pesanan->catatan, true);
            $catatanTampil = null;
            if (json_last_error() === JSON_ERROR_NONE && is_array($catatanJson)) {
                $catatanTampil = $catatanJson['keterangan'] ?? $catatanJson['keterangan_diskon'] ?? null;
            } else {
                $catatanTampil = $pesanan->catatan;
            }
        @endphp
        "{{ $catatanTampil ?? $pesanan->catatan }}"
    </p>
    <div class="flex items-center gap-3 mt-3 text-xs text-gray-400">
        <span class="flex items-center gap-1">
            <i class="fas fa-calendar-alt text-pink-400"></i>
            {{ $pesanan->updated_at->format('d M Y') }}
        </span>
        <span class="text-gray-200">|</span>
        <span class="flex items-center gap-1">
            <i class="fas fa-clock text-pink-400"></i>
            {{ $pesanan->updated_at->format('H:i') }} WIB
        </span>
        <span class="text-gray-200">|</span>
        <span class="flex items-center gap-1">
            <i class="fas fa-history text-pink-400"></i>
            {{ $pesanan->updated_at->diffForHumans() }}
        </span>
    </div>
</div>
        </div>
        @endif
        @endif

        {{-- MAIN GRID --}}
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-5">

            {{-- LEFT --}}
            <div class="lg:col-span-2 space-y-5">

                {{-- INFORMASI PESANAN --}}
                @php
                    $subtotalProduk = $pesanan->detail->sum(fn($d) => $d->harga * $d->qty);
                    $diskon = 0; $keteranganDiskon = null; $subtotalSetelahDiskon = $subtotalProduk;
                    if ($pesanan->catatan) {
                        $catatanInfo = json_decode($pesanan->catatan, true);
                        if (is_array($catatanInfo) && isset($catatanInfo['diskon'])) {
                            $diskon = $catatanInfo['diskon'];
                            $keteranganDiskon = $catatanInfo['keterangan_diskon'] ?? $catatanInfo['keterangan'] ?? null;
                            $subtotalSetelahDiskon = $catatanInfo['subtotal_setelah_diskon'] ?? $subtotalProduk;
                        }
                    }
                    $ongkir = $pesanan->total_harga - $subtotalSetelahDiskon;
                @endphp
                <div class="card fu fu1">
                    <div class="card-header border-b border-pink-100 pb-3">
                        <div class="card-icon bg-pink-100"><i class="fas fa-receipt text-pink-600 text-xs"></i></div>
                        <p class="card-title">Informasi Pesanan Skincare</p>
                    </div>
                    <div>
                        <div class="info-row"><span class="info-row-label"><i class="fas fa-barcode text-pink-400"></i>Kode Pesanan</span><span class="info-row-value font-mono text-sm">{{ $pesanan->kode_pesanan }}</span></div>
                        <div class="info-row"><span class="info-row-label"><i class="fas fa-calendar text-blue-400"></i>Tanggal Pesan</span><span class="info-row-value font-medium">{{ $pesanan->created_at->format('d M Y, H:i') }}</span></div>
                        <div class="info-row"><span class="info-row-label"><i class="fas fa-user text-purple-400"></i>Pemesan</span><span class="info-row-value">{{ optional($pesanan->user)->name ?? '-' }}</span></div>
                        <div class="info-row"><span class="info-row-label"><i class="fas fa-envelope text-pink-400"></i>Email</span><span class="info-row-value text-xs">{{ optional($pesanan->user)->email ?? '-' }}</span></div>
                        <div class="info-row"><span class="info-row-label"><i class="fas fa-box text-blue-400"></i>Subtotal Produk Skincare</span><span class="info-row-value">Rp {{ number_format($subtotalProduk,0,',','.') }}</span></div>
                        @if($diskon > 0)
                        <div class="info-row" style="background:#f0fdf4">
                            <span class="info-row-label" style="color:#059669"><i class="fas fa-tag text-emerald-500"></i>Diskon</span>
                            <div class="text-right">
                                <p class="font-semibold text-emerald-600 text-sm">- Rp {{ number_format($diskon,0,',','.') }}</p>
                                @if($keteranganDiskon)<p class="text-xs text-gray-400">{{ $keteranganDiskon }}</p>@endif
                            </div>
                        </div>
                        <div class="info-row"><span class="info-row-label"><i class="fas fa-calculator text-pink-400"></i>Setelah Diskon</span><span class="info-row-value text-pink-600">Rp {{ number_format($subtotalSetelahDiskon,0,',','.') }}</span></div>
                        @endif
                        <div class="info-row">
                        
                        </div>
                    @if($pesanan->catatan)
                        @php $catatanDetail = json_decode($pesanan->catatan, true); @endphp
                        @if(is_array($catatanDetail) && !empty($catatanDetail['detail']))
                        @php
                            $d        = $catatanDetail;
                            $jarak    = $d['jarak_km'] ?? null;
                            $minJarak = $d['jarak_dihitung_km'] ?? null;
                            $berat    = $d['berat_total'] ?? null;
                            $ongkir   = $d['ongkir'] ?? null;
                            $provinsi = $d['kategori_provinsi'] ?? null;

                            // Parse biaya dari detail string
                            $biayaJarak    = $d['biaya_jarak'] ?? null;
                            $biayaProvinsi = $d['biaya_provinsi'] ?? null;
                            $biayaBerat    = $d['biaya_berat'] ?? null;
                        @endphp
                        <div class="px-5 py-3 border-t border-dashed border-pink-100 bg-pink-50/40">
                            <p class="text-xs font-semibold text-pink-600 mb-2 flex items-center gap-1">
                                <i class="fas fa-calculator text-pink-400"></i> Rincian Ongkos Kirim
                            </p>

                            {{-- 3 KARTU INFO --}}
                            <div class="grid grid-cols-1 sm:grid-cols-3 gap-2 mb-3">
                                @if($jarak)
                                <div class="flex items-start gap-2 bg-white rounded-lg px-3 py-2 border border-pink-100">
                                    <i class="fas fa-route text-pink-400 mt-0.5 text-xs"></i>
                                    <div>
                                        <p class="text-[10px] text-gray-400 font-medium">Jarak</p>
                                        <p class="text-xs font-semibold text-gray-700">{{ $jarak }} km</p>
                                        @if($minJarak && $jarak < $minJarak)
                                            <p class="text-[10px] text-pink-400">Min. dihitung {{ $minJarak }} km</p>
                                        @endif
                                    </div>
                                </div>
                                @endif
                                @if($berat)
                                <div class="flex items-start gap-2 bg-white rounded-lg px-3 py-2 border border-pink-100">
                                    <i class="fas fa-weight-hanging text-pink-400 mt-0.5 text-xs"></i>
                                    <div>
                                        <p class="text-[10px] text-gray-400 font-medium">Berat Paket Skincare</p>
                                        <p class="text-xs font-semibold text-gray-700">
                                            @if($berat >= 1000) {{ number_format($berat/1000, 1) }} kg
                                            @else {{ number_format($berat) }} gram @endif
                                        </p>
                                    </div>
                                </div>
                                @endif
                                @if($provinsi)
                                <div class="flex items-start gap-2 bg-white rounded-lg px-3 py-2 border border-pink-100">
                                    <i class="fas fa-map-marker-alt text-pink-400 mt-0.5 text-xs"></i>
                                    <div>
                                        <p class="text-[10px] text-gray-400 font-medium">Zona Pengiriman</p>
                                        <p class="text-xs font-semibold text-gray-700">
                                            @if(str_contains(strtolower($provinsi), 'sama')) Dalam Provinsi
                                            @else Luar Provinsi @endif
                                        </p>
                                    </div>
                                </div>
                                @endif
                            </div>

                            {{-- BREAKDOWN PERHITUNGAN --}}
                            @if($biayaJarak || $biayaProvinsi || $biayaBerat)
                            <div class="bg-white rounded-lg border border-pink-100 overflow-hidden mb-2">
                                <div class="px-3 py-1.5 bg-pink-50 border-b border-pink-100">
                                    <p class="text-[10px] font-semibold text-pink-600 uppercase tracking-wider">Perhitungan</p>
                                </div>
                                <div class="divide-y divide-gray-50">
                                    @if($biayaJarak)
                                    <div class="flex items-center justify-between px-3 py-2">
                                        <span class="text-xs text-gray-500 flex items-center gap-1.5">
                                            <i class="fas fa-route text-pink-300 text-[10px]"></i>
                                            Biaya Jarak
                                            <span class="text-[10px] text-gray-300">
                                                ({{ $minJarak ?? $jarak }} km)
                                            </span>
                                        </span>
                                        <span class="text-xs font-semibold text-gray-700">Rp {{ number_format($biayaJarak, 0, ',', '.') }}</span>
                                    </div>
                                    @endif
                                    @if($biayaProvinsi)
                                    <div class="flex items-center justify-between px-3 py-2">
                                        <span class="text-xs text-gray-500 flex items-center gap-1.5">
                                            <i class="fas fa-map-marker-alt text-pink-300 text-[10px]"></i>
                                            Biaya Zona
                                            <span class="text-[10px] text-gray-300">
                                                ({{ str_contains(strtolower($provinsi ?? ''), 'sama') ? 'Dalam Provinsi' : 'Luar Provinsi' }})
                                            </span>
                                        </span>
                                        <span class="text-xs font-semibold text-gray-700">Rp {{ number_format($biayaProvinsi, 0, ',', '.') }}</span>
                                    </div>
                                    @endif
                                    @if($biayaBerat)
                                    <div class="flex items-center justify-between px-3 py-2">
                                        <span class="text-xs text-gray-500 flex items-center gap-1.5">
                                            <i class="fas fa-weight-hanging text-pink-300 text-[10px]"></i>
                                            Biaya Berat
                                            <span class="text-[10px] text-gray-300">
                                                ({{ $berat >= 1000 ? number_format($berat/1000, 1).' kg' : number_format($berat).' gram' }})
                                            </span>
                                        </span>
                                        <span class="text-xs font-semibold text-gray-700">Rp {{ number_format($biayaBerat, 0, ',', '.') }}</span>
                                    </div>
                                    @endif
                                </div>
                            </div>
                            @endif

                            {{-- TOTAL ONGKIR --}}
                            @if($ongkir)
                            <div class="flex items-center justify-between px-3 py-2.5 bg-pink-500 rounded-lg">
                                <span class="text-xs text-white font-medium flex items-center gap-1.5">
                                    <i class="fas fa-truck text-pink-200"></i> Total Ongkos Kirim
                                </span>
                                <span class="text-sm font-bold text-white">Rp {{ number_format($ongkir, 0, ',', '.') }}</span>
                            </div>
                            @endif
                        </div>
                        @endif
                    @endif
                        <div class="info-row" style="background:#fff5f7">
                            <span class="font-bold text-gray-700 flex items-center gap-2 text-sm"><i class="fas fa-money-bill-wave text-pink-500"></i> Total Bayar</span>
                            <span class="font-extrabold text-pink-600 text-lg">Rp {{ number_format($pesanan->total_harga,0,',','.') }}</span>
                        </div>
                    </div>
                </div>

                {{-- PRODUK --}}
                <div class="card fu fu2">
                    <div class="card-header border-b border-pink-100 pb-3">
                        <div class="card-icon bg-blue-100"><i class="fas fa-box text-blue-600 text-xs"></i></div>
                        <div><p class="card-title">Produk Skincare Dipesan</p><p class="card-subtitle">{{ count($pesanan->detail) }} item</p></div>
                    </div>
                    @foreach($pesanan->detail as $detail)
                    @php
                        $fotoTampil = null; $warnaDipesan = strtolower(trim($detail->warna));
                        if (!empty($detail->produk->foto)) {
                            $allPhotos = explode('|', $detail->produk->foto);
                            foreach ($allPhotos as $p) { if (str_contains($p,':')) { $parts=explode(':',$p); if(strtolower(trim($parts[0]))===$warnaDipesan){$fotoTampil=$parts[1];break;} } }
                            if (!$fotoTampil) { $first=$allPhotos[0]; $fotoTampil=str_contains($first,':')?explode(':',$first)[1]:$first; }
                        }
                    @endphp
                    <div class="product-row">
                        <div class="w-13 h-13 rounded-xl border border-pink-100 overflow-hidden bg-gray-50 flex-shrink-0 cursor-pointer hover:opacity-80 transition" style="width:52px;height:52px"
                            onclick="openModal('{{ $fotoTampil ? asset('storage/'.$fotoTampil) : asset('images/no-image.png') }}')">
                            <img src="{{ $fotoTampil ? asset('storage/'.$fotoTampil) : asset('images/no-image.png') }}" class="w-full h-full object-contain p-1" onerror="this.src='/images/no-image.png'">
                        </div>
                        <div class="flex-1 min-w-0">
                            <p class="font-semibold text-gray-800 text-sm truncate">{{ $detail->nama_produk }}</p>
                            <div class="flex items-center gap-1.5 mt-1 flex-wrap">
                                @if($detail->warna)<span class="badge bg-pink-50 text-pink-700" style="border:1px solid #fbcfe8"><i class="fas fa-palette" style="font-size:9px"></i> {{ $detail->warna }}</span>@endif
                                @if($detail->ukuran)<span class="badge bg-blue-50 text-blue-700" style="border:1px solid #bfdbfe"><i class="fas fa-ruler" style="font-size:9px"></i> {{ $detail->ukuran }}</span>@endif
                                <span class="badge bg-gray-100 text-gray-600">×{{ $detail->qty }}</span>
                            </div>
                        </div>
                        <div class="text-right flex-shrink-0">
                            <p class="font-bold text-pink-600 text-sm">Rp {{ number_format($detail->subtotal,0,',','.') }}</p>
                            <p class="text-xs text-gray-400 mt-0.5">Per Item {{ number_format($detail->harga,0,',','.') }}</p>
                        </div>
                    </div>
                    @endforeach
                </div>

                {{-- KURIR --}}
                @if($pesanan->kurirAssignment && $pesanan->kurir)
                <div class="card fu fu3">
               <div class="card-header border-b border-pink-100 pb-3">
    <div class="card-icon bg-indigo-100"><i class="fas fa-truck text-indigo-600 text-xs"></i></div>
    <p class="card-title">Informasi Kurir</p>
</div>
                    <div class="p-5">
                        <table style="width:100%; border-collapse:collapse; font-size:0.8rem;">
                            <thead>
                                <tr style="border-bottom: 1.5px solid #fbcfe8;">
                                    <th style="padding:7px 10px; text-align:left; font-weight:600; color:#6b7280; text-transform:uppercase; font-size:0.7rem; letter-spacing:0.05em;">Nama Kurir</th>
                                    <th style="padding:7px 10px; text-align:left; font-weight:600; color:#6b7280; text-transform:uppercase; font-size:0.7rem; letter-spacing:0.05em;">No. HP</th>
                                    <th style="padding:7px 10px; text-align:left; font-weight:600; color:#6b7280; text-transform:uppercase; font-size:0.7rem; letter-spacing:0.05em;">Status</th>
                                    @if($pesanan->tanggal_pengiriman)
                                    <th style="padding:7px 10px; text-align:left; font-weight:600; color:#6b7280; text-transform:uppercase; font-size:0.7rem; letter-spacing:0.05em;">Dikirim Pada</th>
                                    @endif
                                    @if($estimasiTiba)
                                    <th style="padding:7px 10px; text-align:left; font-weight:600; color:#6b7280; text-transform:uppercase; font-size:0.7rem; letter-spacing:0.05em;">Estimasi Tiba</th>
                                    @endif
                                 </tr>
                            </thead>
                            <tbody>
                                <tr style="border-bottom: 1px solid #e5e7eb;">
                                    <td style="padding:8px 10px; color:#1f2937; font-weight:600;">{{ $pesanan->kurir->name }}</td>
                                    <td style="padding:8px 10px; color:#1f2937;">{{ $pesanan->kurir->no_hp }}</td>
                                    <td style="padding:8px 10px;">
                                        @php $ksc = match($pesanan->kurirAssignment->status) { 'ditugaskan'=>'bg-blue-100 text-blue-700','dijemput'=>'bg-amber-100 text-amber-700','diantar'=>'bg-purple-100 text-purple-700','selesai'=>'bg-emerald-100 text-emerald-700',default=>'bg-gray-100 text-gray-700' }; @endphp
                                        <span class="badge {{ $ksc }} text-xs">{{ strtoupper($pesanan->kurirAssignment->status) }}</span>
                                     </td>
                                @if($pesanan->tanggal_pengiriman)
                            <td style="padding:8px 10px; color:#1f2937;">
                                <div class="flex items-center gap-1.5 flex-wrap">
                                    <span class="flex items-center gap-1"><i class="fas fa-calendar-alt text-pink-400"></i> {{ $pesanan->tanggal_pengiriman->format('d M Y') }}</span>
                                    <span class="text-gray-300">|</span>
                                    <span class="flex items-center gap-1"><i class="fas fa-clock text-pink-400"></i> {{ $pesanan->tanggal_pengiriman->format('H:i') }} WIB</span>
                                    <span class="text-gray-300">|</span>
                                    <span class="flex items-center gap-1 text-gray-400"><i class="fas fa-history text-pink-400"></i> {{ $pesanan->tanggal_pengiriman->diffForHumans() }}</span>
                                </div>
                             </td>
                @endif
                @if($estimasiTiba)
                <td style="padding:8px 10px;">
                    <span class="flex items-center gap-1" style="color:#059669; font-weight:600;">
                        <i class="fas fa-calendar-alt text-pink-400"></i> {{ $estimasiTiba->format('d M Y') }}
                    </span>
                    <span style="display:block; font-size:0.7rem; color:#9ca3af; margin-top:2px;">{{ $estimasiLabel }}</span>
                 </td>
                @endif
                 \/tr>
            </tbody>
        </table>

        @if($statusDisplay == 'dikirim')
        <div class="mt-4">
            @php $progress = match($pesanan->kurirAssignment->status??'') {'dijemput'=>30,'diantar'=>70,'selesai'=>100,default=>0}; @endphp
            <div class="prog-bar"><div class="prog-fill" style="width:{{ $progress }}%"></div></div>
            <div class="flex justify-between mt-1 text-xs text-gray-400"><span>Dikirim</span><span>Dalam Perjalanan</span><span>Tiba</span></div>
        </div>
        @endif
    </div>
<\/div>
@endif

{{-- TIMELINE --}}
@if($pesanan->kurirAssignment && $pesanan->kurirAssignment->foto_bukti)
<div class="card fu fu4">
    <div class="card-header border-b border-pink-100 pb-3">
        <div class="card-icon bg-teal-100"><i class="fas fa-history text-teal-600 text-xs"></i></div>
        <p class="card-title">Timeline Pengiriman</p>
    </div>
    <div class="p-5 grid grid-cols-1 md:grid-cols-3 gap-5">
        <div class="md:col-span-2 space-y-0">

            {{-- STEP 1: Dikemas --}}
            <div class="flex gap-3">
                <div class="flex flex-col items-center">
                    <div class="tl-dot bg-emerald-100"><i class="fas fa-check text-emerald-600 text-xs"></i></div>
                    <div class="tl-line done"></div>
                </div>
                <div class="pb-4">
                    <p class="font-semibold text-gray-800 text-sm">Pesanan Skincare Dikemas</p>
                    <div class="flex items-center gap-2 mt-0.5 flex-wrap">
                        <span class="text-xs text-gray-400 flex items-center gap-1">
                            <i class="fas fa-calendar-alt text-pink-400"></i>
                            {{ $pesanan->updated_at->format('d M Y') }}
                        </span>
                        <span class="text-gray-200 text-xs">|</span>
                        <span class="text-xs text-gray-400 flex items-center gap-1">
                            <i class="fas fa-clock text-pink-400"></i>
                            {{ $pesanan->updated_at->format('H:i') }} WIB
                        </span>
                        <span class="text-gray-200 text-xs">|</span>
                        <span class="text-xs text-gray-400 flex items-center gap-1">
                            <i class="fas fa-history text-pink-400"></i>
                            {{ $pesanan->updated_at->diffForHumans() }}
                        </span>
                    </div>
                </div>
            </div>

            {{-- STEP 2: Dikirim --}}
            @if($pesanan->tanggal_pengiriman)
            <div class="flex gap-3">
                <div class="flex flex-col items-center">
                    <div class="tl-dot bg-emerald-100"><i class="fas fa-check text-emerald-600 text-xs"></i></div>
                    @if($pesanan->status == 'selesai')<div class="tl-line done"></div>@else<div class="tl-line"></div>@endif
                </div>
                <div class="pb-4">
                    <p class="font-semibold text-gray-800 text-sm">Pesanan Skincare Dikirim</p>
                    <div class="flex items-center gap-2 mt-0.5 flex-wrap">
                        <span class="text-xs text-gray-400 flex items-center gap-1">
                            <i class="fas fa-calendar-alt text-pink-400"></i>
                            {{ $pesanan->tanggal_pengiriman->format('d M Y') }}
                        </span>
                        <span class="text-gray-200 text-xs">|</span>
                        <span class="text-xs text-gray-400 flex items-center gap-1">
                            <i class="fas fa-clock text-pink-400"></i>
                            {{ $pesanan->tanggal_pengiriman->format('H:i') }} WIB
                        </span>
                        <span class="text-gray-200 text-xs">|</span>
                        <span class="text-xs text-gray-400 flex items-center gap-1">
                            <i class="fas fa-history text-pink-400"></i>
                            {{ $pesanan->tanggal_pengiriman->diffForHumans() }}
                        </span>
                    </div>
                </div>
            </div>
            @endif

            {{-- STEP 3: Diterima --}}
            @if($pesanan->status == 'selesai')
            @php
                $tglDiterima = $pesanan->tanggal_selesai
                    ?? $pesanan->kurirAssignment->tanggal_diterima
                    ?? null;
            @endphp
            <div class="flex gap-3">
                <div class="tl-dot bg-emerald-100"><i class="fas fa-flag-checkered text-emerald-600 text-xs"></i></div>
                <div>
                    <p class="font-semibold text-gray-800 text-sm">Pesanan Skincare Diterima</p>
                    @if($tglDiterima)
                    <div class="flex items-center gap-2 mt-0.5 flex-wrap">
                        <span class="text-xs text-gray-400 flex items-center gap-1">
                            <i class="fas fa-calendar-alt text-pink-400"></i>
                            {{ $tglDiterima->format('d M Y') }}
                        </span>
                        <span class="text-gray-200 text-xs">|</span>
                        <span class="text-xs text-gray-400 flex items-center gap-1">
                            <i class="fas fa-clock text-pink-400"></i>
                            {{ $tglDiterima->format('H:i') }} WIB
                        </span>
                        <span class="text-gray-200 text-xs">|</span>
                        <span class="text-xs text-gray-400 flex items-center gap-1">
                            <i class="fas fa-history text-pink-400"></i>
                            {{ $tglDiterima->diffForHumans() }}
                        </span>
                    </div>
                    @else
                        <p class="text-xs text-gray-400">-</p>
                    @endif
                </div>
            </div>
            @endif

        </div>

        {{-- BUKTI FOTO --}}
        <div>
            <div class="bg-emerald-50 rounded-xl p-3 border border-emerald-100">
                <p class="text-xs font-semibold text-emerald-700 mb-2 flex items-center gap-1">
                    <i class="fas fa-camera text-xs"></i> Bukti Pengiriman
                </p>
                <div class="relative group cursor-pointer rounded-lg overflow-hidden"
                     onclick="openModal('{{ asset('storage/'.$pesanan->kurirAssignment->foto_bukti) }}')">
                    <img src="{{ asset('storage/'.$pesanan->kurirAssignment->foto_bukti) }}"
                         class="w-full h-32 object-cover">
                    <div class="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition flex items-center justify-center">
                        <i class="fas fa-search-plus text-white text-lg"></i>
                    </div>
                </div>
                @php $tglFoto = $pesanan->kurirAssignment->tanggal_diterima ?? null; @endphp
                @if($tglFoto)
                <div class="mt-2 space-y-1 text-center">
                    <div class="flex items-center justify-center gap-2 flex-wrap">
                        <span class="text-xs text-gray-500 flex items-center gap-1">
                            <i class="fas fa-calendar-alt text-pink-400"></i> {{ $tglFoto->format('d M Y') }}
                        </span>
                        <span class="text-gray-300">|</span>
                        <span class="text-xs text-gray-500 flex items-center gap-1">
                            <i class="fas fa-clock text-pink-400"></i> {{ $tglFoto->format('H:i') }} WIB
                        </span>
                        <span class="text-gray-300">|</span>
                        <span class="text-xs text-gray-400 flex items-center gap-1">
                            <i class="fas fa-history text-pink-400"></i> {{ $tglFoto->diffForHumans() }}
                        </span>
                    </div>
                </div>
                @else
                    <p class="text-xs text-gray-400 mt-1.5 text-center">-</p>
                @endif
            </div>
        </div>

    </div>
</div>
@endif

{{-- ULASAN --}}
@if($statusDisplay == 'selesai')
<div class="card fu fu5">
    <div class="card-header border-b border-pink-100 pb-3" style="background:#fffbeb">
        <div class="card-icon bg-amber-100"><i class="fas fa-star text-amber-500 text-xs"></i></div>
        <div><p class="card-title">Ulasan Pembeli</p><p class="card-subtitle">Berikan penilaian untuk setiap produk skincare yang kamu terima</p></div>
    </div>
    <div class="p-5 space-y-3">
        @php
            $semuaUlasan = \App\Models\Ulasan::where('user_id', auth()->id())
                            ->where('pesanan_id', $pesanan->id)
                            ->get();
        @endphp
        @forelse($pesanan->detail as $index => $detail)
        @php
            // Cari ulasan berdasarkan produk_id saja
            // Produk yang sama akan berbagi ulasan yang sama
            $ulasan = $semuaUlasan->where('produk_id', $detail->produk_id)->first();

            // Proses foto produk
            $fotoTampil = null;
            if(!empty($detail->produk->foto)) {
                $allPhotos = explode('|', $detail->produk->foto);
                $warnaDipesan = strtolower(trim($detail->warna));
                foreach($allPhotos as $p) {
                    if(str_contains($p, ':')) {
                        $parts = explode(':', $p);
                        if(strtolower(trim($parts[0])) === $warnaDipesan) {
                            $fotoTampil = $parts[1];
                            break;
                        }
                    }
                }
                if(!$fotoTampil) {
                    $first = $allPhotos[0];
                    $fotoTampil = str_contains($first, ':') ? explode(':', $first)[1] : $first;
                }
            }
        @endphp
        <div class="border border-gray-100 rounded-xl p-4 hover:border-pink-200 transition">
            <div class="flex items-center gap-3 mb-3">
                <div class="w-11 h-11 rounded-xl overflow-hidden border border-gray-100 bg-gray-50 flex-shrink-0">
                    <img src="{{ $fotoTampil ? asset('storage/'.$fotoTampil) : asset('images/no-image.png') }}" 
                         class="w-full h-full object-cover" 
                         onerror="this.src='/images/no-image.png'">
                </div>
                <div class="flex-1">
                    <p class="font-semibold text-gray-800 text-sm">{{ $detail->nama_produk }}</p>
                    @if($detail->warna || $detail->ukuran)
                        <p class="text-xs text-gray-400">
                            {{ $detail->warna }}@if($detail->warna && $detail->ukuran) · @endif{{ $detail->ukuran }}
                        </p>
                    @endif
                </div>
                <div class="text-right">
                    @if($ulasan)
                        <span class="inline-flex items-center gap-1 px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs">
                            <i class="fas fa-check-circle" style="font-size: 9px"></i> Sudah diulas
                        </span>
                    @else
                        <span class="inline-flex items-center gap-1 px-2 py-1 bg-gray-100 text-gray-500 rounded-full text-xs">
                            <i class="fas fa-clock" style="font-size: 9px"></i> Belum diulas
                        </span>
                    @endif
                </div>
            </div>

            @if($ulasan)
            <div class="bg-amber-50 rounded-lg p-3 border border-amber-100">
                <div class="flex items-center gap-0.5 mb-1">
                    @for($s = 1; $s <= 5; $s++)
                        <i class="fas fa-star text-sm {{ $s <= $ulasan->bintang ? 'text-amber-400' : 'text-gray-200' }}"></i>
                    @endfor
                    <span class="ml-2 text-xs font-bold text-amber-600">{{ $ulasan->bintang }}/5</span>
                </div>
                <div class="komentar-container" id="komentar-{{ $index }}">
                    @php
                        $komentar = $ulasan->komentar ?: 'Tidak ada komentar';
                        $panjangKomentar = strlen($komentar);
                        $batasKarakter = 100;
                        $isLong = $panjangKomentar > $batasKarakter;
                    @endphp
                    <div class="komentar-teks">
                        <div class="komentar-pendek {{ $isLong ? '' : 'hidden' }}" id="pendek-{{ $index }}">
                            <p class="text-gray-700 text-sm">{{ Str::limit($komentar, $batasKarakter) }}</p>
                        </div>
                        <div class="komentar-lengkap {{ $isLong ? 'hidden' : '' }}" id="lengkap-{{ $index }}">
                            <p class="text-gray-700 text-sm">{{ $komentar }}</p>
                        </div>
                    </div>
                    @if($isLong)
                    <div class="mt-2">
                        <button onclick="toggleKomentar({{ $index }})"
                                class="text-xs text-amber-600 hover:text-amber-700 font-semibold transition flex items-center gap-1"
                                id="btn-{{ $index }}">
                            <i class="fas fa-chevron-down text-amber-500" style="font-size: 9px"></i>
                            Baca Selengkapnya
                        </button>
                    </div>
                    @endif
                </div>
                <div class="flex items-center gap-3 mt-2 text-xs text-gray-400">
                    <span class="flex items-center gap-1">
                        <i class="fas fa-calendar-alt text-pink-400"></i>
                        {{ $ulasan->created_at->translatedFormat('d M Y') }}
                    </span>
                    <span class="text-gray-200">|</span>
                    <span class="flex items-center gap-1">
                        <i class="fas fa-clock text-pink-400"></i>
                        {{ $ulasan->created_at->format('H:i') }} WIB
                    </span>
                    <span class="text-gray-200">|</span>
                    <span class="flex items-center gap-1">
                        <i class="fas fa-history text-pink-400"></i>
                        {{ $ulasan->created_at->diffForHumans() }}
                    </span>
                </div>
            </div>
            @else
            <div class="flex items-center justify-between gap-3 bg-gray-50 rounded-lg p-3">
                <p class="text-gray-400 text-sm italic">Belum ada ulasan untuk produk skincare ini</p>
                <button onclick="bukaModalUlas('{{ $pesanan->id }}','{{ $detail->produk_id }}','{{ $detail->nama_produk }}')"
                        class="px-3 py-1.5 text-xs rounded-lg bg-amber-100 text-amber-700 hover:bg-amber-200 font-semibold transition flex items-center gap-1">
                    <i class="fas fa-star text-amber-500" style="font-size:9px"></i> Beri Ulasan
                </button>
            </div>
            @endif
        </div>
        @empty
        <div class="text-center py-8">
            <i class="fas fa-box-open text-gray-300 text-4xl mb-3"></i>
            <p class="text-gray-400">Tidak ada produk skincare dalam pesanan ini</p>
        </div>
        @endforelse
    </div>
</div>
@endif

<style>
    .komentar-pendek p,
    .komentar-lengkap p {
        line-height: 1.5;
        word-wrap: break-word;
        white-space: normal;
    }
    .hidden { display: none; }
</style>

<script>
    function toggleKomentar(index) {
        const pendek = document.getElementById(`pendek-${index}`);
        const lengkap = document.getElementById(`lengkap-${index}`);
        const btn = document.getElementById(`btn-${index}`);
        if (pendek.classList.contains('hidden')) {
            pendek.classList.remove('hidden');
            lengkap.classList.add('hidden');
            btn.innerHTML = '<i class="fas fa-chevron-down text-amber-500" style="font-size: 9px"></i> Baca Selengkapnya';
        } else {
            pendek.classList.add('hidden');
            lengkap.classList.remove('hidden');
            btn.innerHTML = '<i class="fas fa-chevron-up text-amber-500" style="font-size: 9px"></i> Sembunyikan';
        }
    }
</script>

            </div>

            {{-- RIGHT SIDEBAR --}}
            <div class="lg:col-span-1">
                <div class="sidebar space-y-5">

{{-- ALAMAT --}}
<div class="card fu fu1">
    <div class="card-header border-b border-pink-100 pb-3">
        <div class="card-icon bg-pink-100"><i class="fas fa-map-marker-alt text-pink-600 text-xs"></i></div>
        <div class="flex-1"><p class="card-title">Alamat Pengiriman</p></div>
        @if(optional($pesanan->alamat)->alamat_utama)
        <span class="badge bg-pink-100 text-pink-700" style="border:1px solid #fbcfe8;font-size:10px">
            <i class="fas fa-star" style="font-size:8px"></i> Utama
        </span>
        @endif
    </div>
    @if($pesanan->alamat)
    <div class="p-4">
        <div class="border-2 border-gray-400 rounded-lg overflow-hidden">
            <table class="w-full text-sm border-collapse border-2 border-black rounded-lg overflow-hidden">
                <tbody>
                    <tr class="border-b border-black">
                        <td class="py-3 px-4 w-1/3 bg-gray-50 border-r border-black font-semibold text-gray-700 text-xs uppercase tracking-wider">Nama Penerima</td>
                        <td class="py-3 px-4 font-medium text-gray-800">{{ $pesanan->alamat->nama_penerima ?? $pesanan->user->name }}</td>
                     </tr>
                    <tr class="border-b border-black">
                        <td class="py-3 px-4 bg-gray-50 border-r border-black font-semibold text-gray-700 text-xs uppercase tracking-wider">No. Telepon</td>
                        <td class="py-3 px-4 font-medium text-gray-800">{{ $pesanan->alamat->no_hp ?? '-' }}</td>
                     </tr>
                    <tr class="border-b border-black">
                        <td class="py-3 px-4 bg-gray-50 border-r border-black font-semibold text-gray-700 text-xs uppercase tracking-wider">Alamat Lengkap</td>
                        <td class="py-3 px-4 text-gray-700">
                            @php
                                $alamatLengkap   = $pesanan->alamat->alamat_lengkap ?? '-';
                                $uniqueIdAlamat  = 'alamat_detail_' . $pesanan->id;
                                $batasKarakter   = 35; // sesuaikan jika perlu
                                $isLongAlamat    = strlen($alamatLengkap) > $batasKarakter && $alamatLengkap !== '-';
                                $alamatPendek    = $isLongAlamat
                                                    ? substr($alamatLengkap, 0, $batasKarakter) . '...'
                                                    : $alamatLengkap;
                            @endphp

                            @if($alamatLengkap !== '-')
                                <div>
                                    {{-- Versi pendek --}}
                                    <p id="alamat-pendek-{{ $uniqueIdAlamat }}"
                                       class="text-gray-700 {{ $isLongAlamat ? '' : 'hidden' }}">
                                        {{ $alamatPendek }}
                                    </p>
                                    {{-- Versi lengkap --}}
                                    <p id="alamat-lengkap-{{ $uniqueIdAlamat }}"
                                       class="text-gray-700 break-words leading-relaxed {{ $isLongAlamat ? 'hidden' : '' }}"
                                       style="word-break: break-word; overflow-wrap: break-word;">
                                        {{ $alamatLengkap }}
                                    </p>
                                    @if($isLongAlamat)
                                    <button onclick="toggleAlamatDetail('{{ $uniqueIdAlamat }}')"
                                            class="mt-2 text-xs font-semibold text-pink-500 hover:text-pink-600 flex items-center gap-1 transition-colors">
                                        <i id="icon-alamat-{{ $uniqueIdAlamat }}" class="fas fa-chevron-down text-[10px]"></i>
                                        <span id="btn-alamat-{{ $uniqueIdAlamat }}">Baca selengkapnya</span>
                                    </button>
                                    @endif
                                </div>
                            @else
                                <span class="text-gray-400">{{ $alamatLengkap }}</span>
                            @endif
                         </td>
                </tr>
                    @php
                        $prov = $pesanan->alamat->province->name ?? '-';
                        $kota = $pesanan->alamat->city->name ?? '-';
                        $kec  = $pesanan->alamat->district->name ?? '-';
                        $desa = $pesanan->alamat->village->name ?? '-';
                    @endphp
                    <tr class="border-b border-black">
                        <td class="py-3 px-4 bg-gray-50 border-r border-black font-semibold text-gray-700 text-xs uppercase tracking-wider">Provinsi</td>
                        <td class="py-3 px-4 font-medium text-gray-800 uppercase">{{ $prov }}</td>
                     </tr>
                    <tr class="border-b border-black">
                        <td class="py-3 px-4 bg-gray-50 border-r border-black font-semibold text-gray-700 text-xs uppercase tracking-wider">Kota / Kab</td>
                        <td class="py-3 px-4 font-medium text-gray-800 uppercase">{{ $kota }}</td>
                     </tr>
                    <tr class="border-b border-black">
                        <td class="py-3 px-4 bg-gray-50 border-r border-black font-semibold text-gray-700 text-xs uppercase tracking-wider">Kecamatan</td>
                        <td class="py-3 px-4 font-medium text-gray-800 uppercase">{{ $kec }}</td>
                     </tr>
                    <tr class="border-b border-black">
                        <td class="py-3 px-4 bg-gray-50 border-r border-black font-semibold text-gray-700 text-xs uppercase tracking-wider">Desa / Kel</td>
                        <td class="py-3 px-4 font-medium text-gray-800 uppercase">{{ $desa }}</td>
                     </tr>
                    @if($pesanan->alamat->kode_pos)
                    <tr class="border-b border-black">
                        <td class="py-3 px-4 bg-gray-50 border-r border-black font-semibold text-gray-700 text-xs uppercase tracking-wider">Kode Pos</td>
                        <td class="py-3 px-4 font-medium text-gray-800">{{ $pesanan->alamat->kode_pos }}</td>
                     </tr>
                    @endif
                </tbody>
             </table>
        </div>
    </div>
    @else
    <div class="p-5 text-center"><p class="text-gray-400 text-sm">Alamat tidak tersedia</p></div>
    @endif
</div>

<script>
function toggleAlamatDetail(id) {
    const pendekEl = document.getElementById(`alamat-pendek-${id}`);
    const lengkapEl = document.getElementById(`alamat-lengkap-${id}`);
    const iconEl   = document.getElementById(`icon-alamat-${id}`);
    const btnText  = document.getElementById(`btn-alamat-${id}`);

    if (!pendekEl || !lengkapEl) return;

    const isExpanded = pendekEl.classList.contains('hidden');

    if (isExpanded) {
        // Sembunyikan → tampilkan versi pendek
        pendekEl.classList.remove('hidden');
        lengkapEl.classList.add('hidden');
        iconEl?.classList.replace('fa-chevron-up', 'fa-chevron-down');
        if (btnText) btnText.textContent = 'Baca selengkapnya';
    } else {
        // Tampilkan lengkap
        pendekEl.classList.add('hidden');
        lengkapEl.classList.remove('hidden');
        iconEl?.classList.replace('fa-chevron-down', 'fa-chevron-up');
        if (btnText) btnText.textContent = 'Sembunyikan';
    }
}
</script>

{{-- PEMBAYARAN --}}
@if($statusDisplay != 'selesai' && $statusDisplay != 'dibatalkan')
    <div class="card fu fu2">
    <div class="card-header border-b border-pink-100 pb-3">
        <div class="card-icon bg-emerald-100"><i class="fas fa-credit-card text-emerald-500 text-xs"></i></div>
        <p class="card-title">Informasi Pembayaran</p>
    </div>
        @if($pesanan->pembayaran)
        <div class="p-5 space-y-3">
            <div class="flex items-center gap-3 p-3 bg-emerald-50 rounded-xl border border-emerald-100">
                <div class="w-9 h-9 bg-emerald-200 rounded-full flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-check-circle text-emerald-700 text-sm"></i>
                </div>
                <div><p class="text-xs text-emerald-600">Status</p><p class="font-bold text-emerald-700 text-sm">LUNAS</p></div>
            </div>

            <div>
                <p class="text-xs text-gray-400 mb-0.5">Metode</p>
                <p class="font-semibold text-gray-800 text-sm capitalize">{{ $pesanan->pembayaran->metode }}</p>
            </div>

            <div>
                <p class="text-xs text-gray-400 mb-1">Tanggal</p>
                <div class="flex items-center gap-2 flex-wrap">
                    <span class="flex items-center gap-1 text-sm font-semibold text-gray-800"><i class="fas fa-calendar-alt text-pink-400"></i> {{ $pesanan->pembayaran->created_at->format('d M Y') }}</span>
                    <span class="text-gray-300">|</span>
                    <span class="flex items-center gap-1 text-sm font-semibold text-gray-800"><i class="fas fa-clock text-pink-400"></i> {{ $pesanan->pembayaran->created_at->format('H:i') }} WIB</span>
                    <span class="text-gray-300">|</span>
                    <span class="flex items-center gap-1 text-xs text-gray-400"><i class="fas fa-history text-pink-400"></i> {{ $pesanan->pembayaran->created_at->diffForHumans() }}</span>
                </div>
            </div>

            @if($pesanan->pembayaran->metode != 'cod' && $pesanan->pembayaran->bukti)
            <div>
                <p class="text-xs text-gray-400 mb-1">Bukti Transfer</p>
                <div class="relative group cursor-pointer rounded-xl overflow-hidden"
                    onclick="openModal('{{ asset('storage/'.$pesanan->pembayaran->bukti) }}')">
                    <img src="{{ asset('storage/'.$pesanan->pembayaran->bukti) }}" class="w-full h-28 object-cover">
                    <div class="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition flex items-center justify-center">
                        <i class="fas fa-search-plus text-white text-lg"></i>
                    </div>
                </div>
            </div>
            @endif
        </div>
        @else
        <div class="p-5">
            <div class="bg-amber-50 rounded-xl p-4 border border-amber-100 text-center">
                <div class="w-9 h-9 bg-amber-100 rounded-full flex items-center justify-center mx-auto mb-2">
                    <i class="fas fa-exclamation text-amber-500 text-sm"></i>
                </div>
                <p class="text-sm font-semibold text-gray-700 mb-0.5">Belum Dibayar</p>
                <p class="text-xs text-gray-400 mb-3">Selesaikan pembayaran Anda</p>
                <button onclick="openSnapPayment()" id="payBtnInfo"
                        class="w-full py-2.5 rounded-xl bg-gradient-to-r from-pink-400 to-pink-500 text-white text-sm font-semibold flex items-center justify-center gap-2 shadow-md">
                    <i class="fas fa-credit-card text-xs"></i> Bayar Sekarang
                </button>
            </div>
        </div>
        @endif
    </div>
@endif

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

        {{-- BOTTOM ACTIONS --}}
        <div class="flex items-center justify-center mt-6 pt-5 border-t border-pink-100">
            <div class="flex gap-4">
                <a href="{{ route('pesanan.index') }}" 
                class="inline-flex items-center gap-2 px-6 py-3 bg-gray-500 hover:bg-gray-600 text-white rounded-xl font-semibold transition-all shadow-md hover:shadow-lg transform hover:scale-105 duration-200">
                    <i class="fas fa-arrow-left text-sm"></i> 
                    <span>Kembali Ke Pesanan</span>
                </a>
                
                @if($pesanan->status === 'dibayar' && isset($produkSayaCek) && $produkSayaCek->count() > 0)
                <a href="{{ route('pesanan.masuk.pilih-kurir', $pesanan->id) }}" 
                class="inline-flex items-center gap-2 px-6 py-3 bg-pink-500 hover:bg-pink-600 text-white rounded-xl font-semibold transition-all shadow-md hover:shadow-lg transform hover:scale-105 duration-200">
                    <i class="fas fa-truck text-sm"></i> 
                    <span>Kirim Pesanan</span>
                </a>
                @endif
            </div>
        </div>
    </div>

    @if($pesanan->status == 'pending')
    <div id="pollingIndicator" class="hidden fixed bottom-6 right-6 bg-blue-600 text-white px-4 py-3 rounded-xl shadow-xl flex items-center gap-3 z-50 text-sm">
        <i class="fas fa-circle-notch spin text-sm"></i>
        <div><p class="font-semibold text-sm">Memverifikasi...</p><p class="text-blue-200 text-xs">Diperbarui tiap 5 detik</p></div>
    </div>
    @endif

    {{-- IMAGE MODAL --}}
    <div id="imageModal" class="modal">
        <span class="close-modal" onclick="closeModal()"><i class="fas fa-times"></i></span>
        <div class="zoom-bar">
            <button class="zoom-btn" onclick="zoomOut()"><i class="fas fa-search-minus"></i></button>
            <span class="zoom-lbl" id="zoomLevel">100%</span>
            <button class="zoom-btn" onclick="zoomIn()"><i class="fas fa-search-plus"></i></button>
            <button class="zoom-btn" onclick="resetZoom()"><i class="fas fa-sync-alt"></i></button>
        </div>
        <img class="modal-img" id="modalImage">
    </div>

    {{-- MODAL ULASAN --}}
    <div id="modalUlas" class="fixed inset-0 z-[60] hidden">
        <div class="absolute inset-0 bg-black/60 backdrop-blur-sm" onclick="tutupModalUlas()"></div>
        <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-white rounded-2xl shadow-2xl w-full max-w-md mx-4 overflow-hidden">
            <div class="bg-gradient-to-r from-pink-400 to-pink-500 p-5">
                <div class="flex items-center justify-between">
                    <div><h3 class="text-white font-bold text-sm flex items-center gap-2"><i class="fas fa-star"></i> Beri Ulasan</h3><p id="modalNamaProduk" class="text-pink-100 text-xs mt-0.5"></p></div>
                    <button onclick="tutupModalUlas()" class="w-7 h-7 rounded-full bg-white/20 flex items-center justify-center hover:bg-white/30 transition text-white text-xs"><i class="fas fa-times"></i></button>
                </div>
            </div>
            <form id="formUlas" action="{{ route('ulasan.store') }}" method="POST" class="p-5">
                @csrf
                <input type="hidden" name="pesanan_id" id="inputPesananId">
                <input type="hidden" name="produk_id"  id="inputProdukId">
                <div class="mb-4 text-center">
                    <p class="text-gray-500 text-sm mb-3">Seberapa puas kamu?</p>
                    <div class="flex justify-center gap-1">
                        @for($s=1;$s<=5;$s++)
                        <button type="button" data-value="{{ $s }}" onclick="setBintang({{ $s }})" onmouseover="hoverBintang({{ $s }})" onmouseout="resetHover()"
                                class="star-btn text-4xl text-gray-200 focus:outline-none select-none">★</button>
                        @endfor
                    </div>
                    <input type="hidden" name="bintang" id="inputBintang" value="0">
                    <p id="labelBintang" class="text-xs text-pink-500 mt-1 h-4 font-medium"></p>
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Komentar <span class="text-gray-400 font-normal">(opsional)</span></label>
                    <textarea name="komentar" rows="3" placeholder="Ceritakan pengalamanmu..." class="w-full border border-gray-200 rounded-xl px-4 py-2.5 text-sm focus:ring-2 focus:ring-pink-400 outline-none resize-none"></textarea>
                </div>
                <div class="flex gap-2">
                    <button type="button" onclick="tutupModalUlas()" class="flex-1 py-2.5 rounded-xl border border-gray-200 text-gray-600 text-sm font-semibold hover:bg-gray-50 transition">Batal</button>
                    <button type="submit" id="btnKirimUlas" disabled class="flex-1 py-2.5 rounded-xl bg-gradient-to-r from-pink-400 to-pink-500 text-white text-sm font-semibold disabled:opacity-40 disabled:cursor-not-allowed">
                        <i class="fas fa-paper-plane mr-1"></i> Kirim
                    </button>
                </div>
            </form>
        </div>
    </div>

    {{-- MODAL TRACKING --}}
    <div id="trackingModal" class="fixed inset-0 z-[70] hidden">
        <div class="absolute inset-0 bg-black/70 backdrop-blur-sm" onclick="closeTrackingModal()"></div>
        <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-white rounded-2xl shadow-2xl w-full max-w-4xl mx-4 overflow-hidden max-h-[90vh] overflow-y-auto">
            <div class="bg-gradient-to-r from-pink-500 to-pink-600 p-4 flex justify-between items-center sticky top-0 z-10">
                <div class="flex items-center gap-3">
                    <i class="fas fa-map-marked-alt text-white"></i>
                    <div><h3 class="text-white font-bold text-sm">Lacak Pesanan Skincare</h3><p class="text-pink-100 text-xs">{{ $pesanan->kode_pesanan }}</p></div>
                </div>
                <button onclick="closeTrackingModal()" class="w-7 h-7 rounded-full bg-white/20 flex items-center justify-center hover:bg-white/30 transition text-white text-xs"><i class="fas fa-times"></i></button>
            </div>
            <div class="p-5">
                <div id="trackingLoading" class="text-center py-10">
                    <div class="inline-block animate-spin rounded-full h-7 w-7 border-b-2 border-pink-600 mb-3"></div>
                    <p class="text-gray-500 text-sm">Memuat peta...</p>
                </div>
                <div id="trackingMapContainer" class="hidden">
                    <div class="grid grid-cols-3 gap-3 mb-4">
                        <div class="bg-pink-50 rounded-xl p-3 border border-pink-100"><p class="text-xs text-pink-500 mb-0.5">Kurir</p><p class="font-semibold text-gray-800 text-sm">{{ $pesanan->kurir->name??'-' }}</p></div>
                        <div class="bg-pink-50 rounded-xl p-3 border border-pink-100"><p class="text-xs text-pink-500 mb-0.5">No. HP</p><p class="font-semibold text-gray-800 text-sm">{{ $pesanan->kurir->no_hp??'-' }}</p></div>
                        <div class="bg-pink-50 rounded-xl p-3 border border-pink-100"><p class="text-xs text-pink-500 mb-0.5">Estimasi</p><p class="font-semibold text-gray-800 text-sm">@if($estimasiTiba){{ $estimasiTiba->format('d M Y') }}@else-@endif</p></div>
                    </div>
                    <div class="mb-4">
                        <div class="prog-bar"><div class="prog-fill" id="trackingProgressBar" style="width:0%"></div></div>
                        <p class="text-xs text-gray-400 mt-1 text-center" id="trackingProgressText">Memuat...</p>
                    </div>
                    <div id="trackingMap" class="mb-4"></div>
                    <div class="grid grid-cols-4 gap-2 text-center">
                        <div>
                            <div class="w-9 h-9 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-1"><i class="fas fa-check text-emerald-600 text-xs"></i></div>
                            <p class="text-xs font-medium text-gray-600">Dikemas</p>
                            <p class="text-xs text-gray-400">{{ $pesanan->updated_at?$pesanan->updated_at->format('H:i'):'-' }}</p>
                        </div>
                        @foreach([['statusDijemput','tanggalDijemput','fa-box','Dijemput'],['statusDiantar','tanggalDiantar','fa-truck','Diantar'],['statusTiba','tanggalTiba','fa-flag-checkered','Tiba']] as $ts)
                        <div>
                            <div id="{{ $ts[0] }}" class="w-9 h-9 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-1"><i class="fas {{ $ts[2] }} text-gray-400 text-xs"></i></div>
                            <p class="text-xs font-medium text-gray-600">{{ $ts[3] }}</p>
                            <p class="text-xs text-gray-400" id="{{ $ts[1] }}">-</p>
                        </div>
                        @endforeach
                    </div>
                </div>
            </div>
        </div>
    </div>

   

    <script>
        function toggleDropdown(){document.getElementById("dropdownMenu").classList.toggle("hidden");}
        window.addEventListener('click',e=>{const d=document.getElementById("dropdownMenu");if(!e.target.closest('.relative#userDropdown')&&!d.classList.contains('hidden'))d.classList.add("hidden");});

        let currentZoom=1;
        function openModal(src){const m=document.getElementById('imageModal'),i=document.getElementById('modalImage');i.src=src;m.style.display='block';currentZoom=1;updateZoom();document.body.style.overflow='hidden';}
        function closeModal(){document.getElementById('imageModal').style.display='none';document.body.style.overflow='';}
        function zoomIn(){currentZoom=Math.min(currentZoom+0.25,3);updateZoom();}
        function zoomOut(){currentZoom=Math.max(currentZoom-0.25,0.5);updateZoom();}
        function resetZoom(){currentZoom=1;updateZoom();}
        function updateZoom(){const i=document.getElementById('modalImage');i.style.transform=`translate(-50%,-50%) scale(${currentZoom})`;document.getElementById('zoomLevel').textContent=Math.round(currentZoom*100)+'%';}
        document.addEventListener('keydown',e=>{if(e.key==='Escape'){closeModal();closeTrackingModal();closeResiModal();}});

        @if($pesanan->status == 'pending')
        let snapToken=null,pollingInterval=null,pollingCount=0;const MAX_POLLS=120;
        function loadSnapToken(cb){
            if(snapToken){cb(snapToken);return;}
            fetch('{{ route('pembayaran.token',$pesanan->id) }}',{headers:{'X-Requested-With':'XMLHttpRequest','Accept':'application/json','X-CSRF-TOKEN':document.querySelector('meta[name="csrf-token"]').content}})
                .then(r=>r.json()).then(d=>{if(d.snap_token){snapToken=d.snap_token;cb(snapToken);}else alert('Gagal: '+(d.error||'Unknown'));})
                .catch(()=>alert('Gagal memuat pembayaran.'));
        }
        function openSnapPayment(){
            loadSnapToken(token=>snap.pay(token,{
                onSuccess:()=>startPolling(),onPending:()=>startPolling(),
                onError:()=>alert('Pembayaran gagal. Coba lagi.'),onClose:()=>startPolling()
            }));
        }
        function startPolling(){if(pollingInterval)return;pollingCount=0;const ind=document.getElementById('pollingIndicator');if(ind)ind.classList.remove('hidden');pollingInterval=setInterval(checkPaymentStatus,5000);}
        function stopPolling(){clearInterval(pollingInterval);pollingInterval=null;}
        function checkPaymentStatus(){
            if(++pollingCount>MAX_POLLS){stopPolling();return;}
            fetch('{{ route('pembayaran.check',$pesanan->id) }}',{headers:{'X-Requested-With':'XMLHttpRequest','Accept':'application/json'}})
                .then(r=>r.json()).then(d=>{if(d.status==='paid'||d.status==='failed'||d.pesanan==='dibatalkan'){stopPolling();window.location.reload();}})
                .catch(err=>console.error(err));
        }
        @endif

        const labelMap={1:'😞 Sangat Tidak Puas',2:'😕 Tidak Puas',3:'😐 Cukup',4:'😊 Puas',5:'🤩 Sangat Puas!'};
        let bintangTerpilih=0;
        function bukaModalUlas(pesananId,produkId,namaProduk){
            document.getElementById('inputPesananId').value=pesananId;document.getElementById('inputProdukId').value=produkId;
            document.getElementById('modalNamaProduk').textContent=namaProduk;bintangTerpilih=0;
            document.getElementById('inputBintang').value=0;document.getElementById('labelBintang').textContent='';
            document.getElementById('btnKirimUlas').disabled=true;document.querySelector('#formUlas textarea').value='';
            renderBintang(0);document.getElementById('modalUlas').classList.remove('hidden');document.body.style.overflow='hidden';
        }
        function tutupModalUlas(){document.getElementById('modalUlas').classList.add('hidden');document.body.style.overflow='';}
        function setBintang(n){bintangTerpilih=n;document.getElementById('inputBintang').value=n;document.getElementById('labelBintang').textContent=labelMap[n]||'';document.getElementById('btnKirimUlas').disabled=false;renderBintang(n);}
        function hoverBintang(n){renderBintang(n);}
        function resetHover(){renderBintang(bintangTerpilih);}
        function renderBintang(aktif){document.querySelectorAll('.star-btn').forEach(btn=>{const v=parseInt(btn.dataset.value);btn.classList.toggle('text-amber-400',v<=aktif);btn.classList.toggle('text-gray-200',v>aktif);});}

        function cetakResi(){
            document.getElementById('resiModal').classList.remove('hidden');
            document.body.style.overflow = 'hidden';
        }
        function closeResiModal(){
            document.getElementById('resiModal').classList.add('hidden');
            document.body.style.overflow = '';
        }

        function printResi(){
            const iframe = document.getElementById('resiIframe');
            iframe.contentWindow.focus();
            iframe.contentWindow.print();
        }
        

        let trackingMap=null,kurirMarker=null,trackingInterval=null,rutePoints=[];
        function openTrackingModal(pesananId){
            document.getElementById('trackingModal').classList.remove('hidden');document.body.style.overflow='hidden';
            document.getElementById('trackingLoading').classList.remove('hidden');document.getElementById('trackingMapContainer').classList.add('hidden');
            setTimeout(()=>{initTrackingMap(pesananId);startTrackingPolling(pesananId);},500);
        }
        function closeTrackingModal(){
            document.getElementById('trackingModal').classList.add('hidden');document.body.style.overflow='';
            if(trackingInterval){clearInterval(trackingInterval);trackingInterval=null;}
            if(trackingMap){trackingMap.remove();trackingMap=null;}
        }
        async function getRoute(lat1,lng1,lat2,lng2){
            try{const r=await fetch(`https://router.project-osrm.org/route/v1/driving/${lng1},${lat1};${lng2},${lat2}?alternatives=false&geometries=geojson&overview=full`);const d=await r.json();if(d.code==='Ok'&&d.routes?.length>0)return d.routes[0].geometry.coordinates.map(c=>[c[1],c[0]]);}catch(e){console.error(e);}return null;
        }
        async function initTrackingMap(pesananId){
            if(trackingMap){trackingMap.remove();trackingMap=null;}
            try{
                const[tokoRes,tujuanRes]=await Promise.all([fetch(`/api/tracking/toko/${pesananId}`),fetch(`/api/tracking/tujuan/${pesananId}`)]);
                const tokoData=await tokoRes.json(),tujuanData=await tujuanRes.json();
                if(!tokoData.success)throw new Error(tokoData.error||'Gagal data toko');
                if(!tujuanData.success)throw new Error(tujuanData.error||'Gagal data tujuan');
                let tokoCoords={lat:-6.3948,lng:106.8226},tujuanCoords={lat:-6.4025,lng:106.7942};
                try{const gT=await(await fetch(`/api/geocode?address=${encodeURIComponent(tokoData.alamat)}`)).json();if(gT.success)tokoCoords={lat:parseFloat(gT.lat),lng:parseFloat(gT.lng)};}catch(e){}
                try{const gU=await(await fetch(`/api/geocode?address=${encodeURIComponent(tujuanData.alamat)}`)).json();if(gU.success)tujuanCoords={lat:parseFloat(gU.lat),lng:parseFloat(gU.lng)};}catch(e){}
                const routePoints=await getRoute(tokoCoords.lat,tokoCoords.lng,tujuanCoords.lat,tujuanCoords.lng);
                document.getElementById('trackingLoading').classList.add('hidden');document.getElementById('trackingMapContainer').classList.remove('hidden');
                trackingMap=L.map('trackingMap').setView([(tokoCoords.lat+tujuanCoords.lat)/2,(tokoCoords.lng+tujuanCoords.lng)/2],12);
                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{attribution:'© OpenStreetMap'}).addTo(trackingMap);
                const tokoIcon=L.divIcon({className:'custom-div-icon',html:'<div style="background:#f472b6;width:22px;height:22px;border-radius:50%;border:2px solid white;box-shadow:0 2px 5px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center"><i class="fas fa-store text-white" style="font-size:8px"></i></div>',iconSize:[22,22],popupAnchor:[0,-11]});
                L.marker([tokoCoords.lat,tokoCoords.lng],{icon:tokoIcon}).addTo(trackingMap).bindPopup(`<b>🏪 ${tokoData.nama_toko}</b><small style="display:block;color:#666;margin-top:3px">${tokoData.alamat}</small>`);
                const tujuanIcon=L.divIcon({className:'custom-div-icon',html:'<div style="background:#22c55e;width:22px;height:22px;border-radius:50%;border:2px solid white;box-shadow:0 2px 5px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center"><i class="fas fa-flag text-white" style="font-size:8px"></i></div>',iconSize:[22,22],popupAnchor:[0,-11]});
                L.marker([tujuanCoords.lat,tujuanCoords.lng],{icon:tujuanIcon}).addTo(trackingMap).bindPopup(`<b>📦 ${tujuanData.nama_penerima}</b><small style="display:block;color:#666;margin-top:3px">${tujuanData.alamat}</small>`);
                const lines=routePoints||[[tokoCoords.lat,tokoCoords.lng],[tujuanCoords.lat,tujuanCoords.lng]];
                rutePoints=lines;
                L.polyline(lines,{color:'#a78bfa',weight:5,opacity:0.8,lineCap:'round'}).addTo(trackingMap);
                trackingMap.fitBounds(L.latLngBounds(lines),{padding:[40,40]});
                await updateTrackingStatus(pesananId);
            }catch(error){document.getElementById('trackingLoading').innerHTML=`<div class="text-center py-8"><i class="fas fa-exclamation-triangle text-red-500 text-2xl mb-3"></i><p class="text-red-600 text-sm">Gagal memuat: ${error.message}</p></div>`;}
        }
        async function updateTrackingStatus(pesananId){
            try{
                const data=await(await fetch(`/api/tracking/kurir/${pesananId}`)).json();
                if(!data.success)return;
                const prog=data.progress||0;
                document.getElementById('trackingProgressBar').style.width=prog+'%';
                document.getElementById('trackingProgressText').textContent=data.message||'';
                ['statusDijemput','statusDiantar','statusTiba'].forEach(id=>document.getElementById(id).className='w-9 h-9 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-1');
                if(['dijemput','diantar','selesai'].includes(data.status)){document.getElementById('statusDijemput').className='w-9 h-9 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-1';document.getElementById('statusDijemput').innerHTML='<i class="fas fa-box text-emerald-600 text-xs"></i>';}
                if(['diantar','selesai'].includes(data.status)){document.getElementById('statusDiantar').className='w-9 h-9 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-1';document.getElementById('statusDiantar').innerHTML='<i class="fas fa-truck text-purple-600 text-xs"></i>';}
                if(data.status==='selesai'){document.getElementById('statusTiba').className='w-9 h-9 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-1';document.getElementById('statusTiba').innerHTML='<i class="fas fa-flag-checkered text-emerald-600 text-xs"></i>';}
                if(trackingMap&&rutePoints.length>0){
                    const idx=Math.floor((prog/100)*(rutePoints.length-1));
                    const pos=rutePoints[Math.min(idx,rutePoints.length-1)];
                    const kurirIcon=L.divIcon({className:'custom-div-icon',html:'<div style="background:#8b5cf6;width:26px;height:26px;border-radius:50%;border:2px solid white;box-shadow:0 2px 5px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center"><i class="fas fa-motorcycle text-white" style="font-size:10px"></i></div>',iconSize:[26,26],popupAnchor:[0,-13]});
                    if(kurirMarker)kurirMarker.setLatLng(pos);
                    else kurirMarker=L.marker(pos,{icon:kurirIcon}).addTo(trackingMap).bindPopup(`<b>🚚 ${data.kurir?.nama??''}</b>`);
                }
            }catch(e){console.error(e);}
        }
        function startTrackingPolling(pesananId){if(trackingInterval)clearInterval(trackingInterval);trackingInterval=setInterval(()=>updateTrackingStatus(pesananId),5000);}
    </script>
</body>
</html>