<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Pesanan Masuk - Glow Beauty</title>

    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">

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

    <style>
        * {
            font-family: 'Poppins', 'Inter', sans-serif;
        }

        .nav-link {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 14px;
            border-radius: 10px;
            font-size: 0.875rem;
            font-weight: 500;
            transition: all 0.2s ease;
        }

        .nav-link:hover {
            background-color: #fef2f8;
            color: #ec489a;
        }

        .active-nav {
            background-color: #fef2f8;
            color: #ec489a;
            border: 1px solid #fbcfe8;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 14px;
            border-radius: 10px;
            font-size: 0.875rem;
            font-weight: 600;
        }

        .hover-scale {
            transition: transform 0.2s ease;
        }

        .hover-scale:hover {
            transform: scale(1.02);
        }

        .shopee-shadow {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05), 0 4px 12px rgba(244, 114, 182, 0.1);
        }

        .status-badge {
            transition: all 0.2s ease;
        }

        .status-badge:hover {
            transform: scale(1.05);
        }

        .action-btn {
            transition: all 0.2s ease;
        }

        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        /* FILTER BUTTON STYLES */
        .filter-btn {
            transition: all 0.2s ease;
            cursor: pointer;
            display: inline-flex !important;
            visibility: visible !important;
            opacity: 1 !important;
        }

        .filter-btn:hover {
            transform: translateY(-2px);
            filter: brightness(0.95);
        }

        .filter-btn.active {
            border: 2px solid #f472b6;
            box-shadow: 0 0 0 2px rgba(244, 114, 182, 0.3);
        }

        .filter-btn[data-status="all"] {
            background-color: #f472b6 !important;
            color: white !important;
        }

        .filter-btn[data-status="pending"] {
            background-color: #fef3c7 !important;
            color: #b45309 !important;
        }

        .filter-btn[data-status="dibayar"],
        .filter-btn[data-status="diproses"] {
            background-color: #dbeafe !important;
            color: #1e40af !important;
        }

        .filter-btn[data-status="dikirim"] {
            background-color: #f3e8ff !important;
            color: #6b21a8 !important;
        }

        .filter-btn[data-status="selesai"] {
            background-color: #d1fae5 !important;
            color: #065f46 !important;
        }

        .filter-btn[data-status="dibatalkan"] {
            background-color: #fee2e2 !important;
            color: #b91c1c !important;
        }

        /* Chat button animation */
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        
        .chat-badge {
            animation: pulse 2s infinite;
        }

        /* Toast animation */
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        
        @keyframes slideOut {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(100%);
                opacity: 0;
            }
        }
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-2px); }
            75% { transform: translateX(2px); }
        }

        .animate-shake {
            animation: shake 0.5s ease-in-out infinite;
        }

        /* Atau efek ring/bell */
        @keyframes ring {
            0% { transform: rotate(0); }
            25% { transform: rotate(15deg); }
            75% { transform: rotate(-15deg); }
            100% { transform: rotate(0); }
        }

        .animate-ring {
            animation: ring 0.5s ease-in-out infinite;
            transform-origin: top center;
        }
        
        .bg-gradient-pink {
            background: linear-gradient(135deg, #fdf2f8 0%, #fff1f3 100%);
        }
        
        .border-pink-light {
            border-color: #fbcfe8;
        }
    </style>
</head>

<body class="bg-gradient-pink font-sans antialiased">

    <!-- NAVBAR -->
    <nav class="bg-white/95 backdrop-blur-md border-b border-pink-light shadow-sm sticky top-0 z-50 w-full">
        <div class="px-4 sm:px-6 lg:px-8 py-3">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between">

                <div class="flex items-center gap-3 mb-3 md:mb-0">
                    <div
                        class="w-10 h-10 bg-gradient-to-br from-pink-400 to-pink-500 rounded-lg flex items-center justify-center shadow-md">
                        <span class="text-white font-bold text-lg">✨</span>
                    </div>
                    <div>
                        <h1 class="font-bold text-lg text-gray-800">Glow Beauty</h1>
                        <p class="text-xs text-pink-400">Manajemen Pesanan Masuk</p>
                    </div>
                </div>

                <div class="flex flex-wrap items-center gap-1">

                    @php
                        // Badge Pesanan Masuk
                        $pendingPesananCount = \App\Models\Pesanan::where('status', 'pending')
                            ->whereHas('detail', function($q) {
                                $q->whereHas('produk', function($q2) {
                                    $q2->where('user_id', auth()->id());
                                });
                            })
                            ->count();

                        // Badge Restok
                        $restokCount = \App\Models\Produk::where('user_id', auth()->id())
                            ->where('stok', '<', 5)
                            ->count();

                        // Badge Chat
                        $unreadChatCount = 0;
                        $chats = \App\Models\Chat::where('penjual_id', auth()->id())->get();
                        foreach ($chats as $chatItem) {
                            $unreadChatCount += \App\Models\ChatMessage::where('chat_id', $chatItem->id)
                                ->where('sender_id', $chatItem->user_id)
                                ->where('is_read', false)
                                ->count();
                        }
                    @endphp

                    <a href="{{ route('dashboard') }}" class="flex items-center gap-2 px-4 py-2 rounded-lg
                        {{ request()->routeIs('dashboard') ? 'bg-pink-100 text-pink-600' : 'text-gray-600 hover:bg-pink-50 hover:text-pink-600' }}
                        transition">
                        <i class="fas fa-home"></i> Dashboard
                    </a>

                    <a href="{{ route('kategori.index') }}"
                        class="px-4 py-2 rounded-lg {{ request()->routeIs('kategori.*') ? 'bg-pink-500 text-white shadow' : 'text-gray-600 hover:bg-pink-50 hover:text-pink-600' }} transition">
                        <i class="fas fa-tags mr-2"></i>Kategori
                    </a>

                    <a href="{{ route('produk.index') }}" class="flex items-center gap-2 px-4 py-2 rounded-lg
                        {{ request()->routeIs('produk.*') ? 'bg-pink-100 text-pink-600' : 'text-gray-600 hover:bg-pink-50 hover:text-pink-600' }}
                        transition">
                        <i class="fas fa-store"></i> Produk
                    </a>

                    {{-- Pesanan Masuk --}}
                    <a href="{{ route('pesanan.masuk.index') }}" class="flex items-center gap-2 px-4 py-2 rounded-lg
                        {{ request()->routeIs('pesanan.masuk.*') ? 'bg-pink-100 text-pink-600' : 'text-gray-600 hover:bg-pink-50 hover:text-pink-600' }}
                        transition">
                        <i class="fas fa-truck"></i> Pesanan Masuk
                        @if($pendingPesananCount > 0)
                            <span class="bg-red-500 text-white text-xs font-bold px-1.5 py-0.5 rounded-full min-w-[18px] text-center">
                                {{ $pendingPesananCount > 99 ? '99+' : $pendingPesananCount }}
                            </span>
                        @endif
                    </a>

                    <a href="{{ route('restok.index') }}" class="flex items-center gap-2 px-4 py-2 rounded-lg {{ request()->routeIs('restok.*') ? 'bg-pink-500 text-white shadow' : 'text-gray-600 hover:bg-pink-50 hover:text-pink-600' }} transition">
                        <i class="fas fa-boxes"></i>Restok
                        @if($restokCount > 0)<span class="bg-red-500 text-white text-xs font-bold px-1.5 py-0.5 rounded-full min-w-[18px] text-center notification-badge animate-pulse">{{ $restokCount > 99 ? '99+' : $restokCount }}</span>@endif
                    </a>
                    <a href="{{ route('chat.index') }}" class="flex items-center gap-2 px-4 py-2 rounded-lg {{ request()->routeIs('chat.*') ? 'bg-pink-500 text-white shadow' : 'text-gray-600 hover:bg-pink-50 hover:text-pink-600' }} transition">
                        <i class="fas fa-comments"></i>Chat
                        @if($unreadChatCount > 0)<span class="bg-red-500 text-white text-xs font-bold px-1.5 py-0.5 rounded-full min-w-[18px] text-center notification-badge animate-pulse">{{ $unreadChatCount > 99 ? '99+' : $unreadChatCount }}</span>@endif
                    </a>

                    <a href="{{ route('user.index') }}"
                        class="px-4 py-2 rounded-lg {{ request()->routeIs('user.*') ? 'bg-pink-500 text-white shadow' : 'text-gray-600 hover:bg-pink-50 hover:text-pink-600' }} transition">
                        <i class="fas fa-users mr-2"></i>User
                    </a>

                </div>

                <!-- USER DROPDOWN -->
                <div class="relative" id="userDropdown">
                    <button onclick="toggleDropdown()"
                        class="flex items-center gap-3 px-3 py-2 hover:bg-pink-50 rounded-xl transition-all duration-200 border border-transparent hover:border-pink-200 group">
                        <div
                            class="w-9 h-9 bg-gradient-to-br from-pink-400 to-pink-500 rounded-full flex items-center justify-center text-white font-semibold shadow-md">
                            {{ substr(Auth::user()->name, 0, 1) }}
                        </div>
                        <div class="hidden md:block text-left">
                            <p class="text-sm font-medium text-gray-700 group-hover:text-pink-600">
                                {{ Auth::user()->name }}
                            </p>
                            <p class="text-xs text-gray-500">
                                @if(Auth::user()->role == 'penjual') <i class="fas fa-store mr-1 text-pink-500"></i>
                                    Penjual
                                @elseif(Auth::user()->role == 'admin') <i
                                    class="fas fa-shield-alt mr-1 text-purple-500"></i> Admin
                                @else Customer @endif
                            </p>
                        </div>
                        <i class="fas fa-chevron-down text-sm text-gray-400 group-hover:text-pink-600 transition-transform duration-200"
                            id="dropdownIcon"></i>
                    </button>

                    <div id="dropdownMenu"
                        class="hidden absolute right-0 mt-2 w-64 bg-white rounded-xl shadow-xl border border-gray-100 py-2 z-50">
                        <div class="px-4 py-4 border-b border-gray-100">
                            <div class="flex items-center gap-3">
                                <div
                                    class="w-12 h-12 bg-gradient-to-br from-pink-400 to-pink-500 rounded-full flex items-center justify-center text-white font-bold text-xl shadow-md">
                                    {{ substr(Auth::user()->name, 0, 1) }}
                                </div>
                                <div>
                                    <p class="font-semibold text-gray-800">{{ Auth::user()->name }}</p>
                                    <p class="text-sm text-gray-500">{{ Auth::user()->email }}</p>
                                    <span class="inline-block mt-1 px-2 py-0.5 rounded-full text-xs font-medium
                                        @if(Auth::user()->role == 'penjual') bg-pink-100 text-pink-600
                                        @elseif(Auth::user()->role == 'admin') bg-purple-100 text-purple-600
                                        @else bg-pink-100 text-pink-600 @endif">
                                        @if(Auth::user()->role == 'penjual') <i class="fas fa-store mr-1"></i> Penjual
                                        @elseif(Auth::user()->role == 'admin') <i class="fas fa-shield-alt mr-1"></i>
                                            Admin
                                        @else <i class="fas fa-user mr-1"></i> Customer @endif
                                    </span>
                                </div>
                            </div>
                        </div>

                        <a href="{{ route('profile.edit') }}"
                            class="flex items-center gap-3 px-4 py-3 hover:bg-pink-50 text-gray-700 transition group">
                            <div
                                class="w-8 h-8 bg-gray-100 rounded-lg flex items-center justify-center group-hover:bg-pink-100">
                                <i class="fas fa-user text-gray-500 group-hover:text-pink-600"></i>
                            </div>
                            <div>
                                <p class="font-medium">Profil Saya</p>
                                <p class="text-xs text-gray-500">Lihat dan edit profil</p>
                            </div>
                        </a>

                        @if(Auth::user()->role == 'admin')
                            <a href="{{ route('user.index') }}"
                                class="flex items-center gap-3 px-4 py-3 hover:bg-pink-50 text-gray-700 transition group">
                                <div
                                    class="w-8 h-8 bg-gray-100 rounded-lg flex items-center justify-center group-hover:bg-pink-100">
                                    <i class="fas fa-users text-gray-500 group-hover:text-pink-600"></i>
                                </div>
                                <div>
                                    <p class="font-medium">Kelola User</p>
                                    <p class="text-xs text-gray-500">Atur pengguna</p>
                                </div>
                            </a>
                            <a href="{{ route('kategori.index') }}"
                                class="flex items-center gap-3 px-4 py-3 hover:bg-pink-50 text-gray-700 transition group">
                                <div
                                    class="w-8 h-8 bg-gray-100 rounded-lg flex items-center justify-center group-hover:bg-pink-100">
                                    <i class="fas fa-tags text-gray-500 group-hover:text-pink-600"></i>
                                </div>
                                <div>
                                    <p class="font-medium">Kelola Kategori</p>
                                    <p class="text-xs text-gray-500">Atur kategori produk skincare</p>
                                </div>
                            </a>
                        @endif

                        <div class="border-t border-gray-100 mt-1 pt-1">
                            <form method="POST" action="{{ route('logout') }}">
                                @csrf
                                <button type="submit"
                                    class="w-full flex items-center gap-3 px-4 py-3 hover:bg-red-50 text-red-600 transition group">
                                    <div
                                        class="w-8 h-8 bg-red-50 rounded-lg flex items-center justify-center group-hover:bg-red-100">
                                        <i class="fas fa-sign-out-alt text-red-500"></i>
                                    </div>
                                    <div class="text-left">
                                        <p class="font-medium">Keluar</p>
                                        <p class="text-xs text-red-400">Akhiri sesi</p>
                                    </div>
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </nav>

    <!-- CONTAINER UTAMA -->
    <div class="w-full px-4 sm:px-6 lg:px-8 py-6 min-h-screen">

        <!-- HEADER PESANAN MASUK -->
        <div class="relative mb-8 bg-gradient-to-r from-pink-400 via-pink-500 to-pink-600 rounded-2xl p-6 text-white shadow-lg overflow-hidden w-full">
            <div class="absolute top-0 right-0 w-64 h-64 opacity-10">
                <i class="fas fa-truck text-8xl absolute top-10 right-10"></i>
                <i class="fas fa-clipboard-list text-7xl absolute bottom-0 right-32"></i>
                <i class="fas fa-box-open text-6xl absolute top-20 right-48"></i>
            </div>
            <div class="relative flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div>
                    <div class="flex items-center gap-3 mb-2">
                        <div class="w-12 h-12 bg-white/20 backdrop-blur-sm rounded-xl flex items-center justify-center">
                            <i class="fas fa-truck text-white text-xl"></i>
                        </div>
                        <h2 class="text-2xl font-bold text-white flex items-center gap-2">
                            Pesanan Masuk
                        </h2>
                     </div>
                    <p class="text-pink-100">Kelola pesanan skincare dari pembeli dengan mudah</p>
                    <div class="flex flex-wrap items-center gap-3 mt-3">
                        <span class="bg-white/20 backdrop-blur-sm px-3 py-1.5 rounded-lg text-sm flex items-center gap-2">
                            <i class="fas fa-clock"></i> Menunggu Konfirmasi: <span class="font-bold">{{ $pesananMenunggu ?? 0 }}</span>
                        </span>
                        <span class="bg-white/20 backdrop-blur-sm px-3 py-1.5 rounded-lg text-sm flex items-center gap-2">
                            <i class="fas fa-check-circle"></i> Diproses: <span class="font-bold">{{ $pesananDiproses ?? 0 }}</span>
                        </span>
                        <span class="bg-white/20 backdrop-blur-sm px-3 py-1.5 rounded-lg text-sm flex items-center gap-2">
                            <i class="fas fa-truck"></i> Dikirim: <span class="font-bold">{{ $pesananDikirim ?? 0 }}</span>
                        </span>
                        <span class="bg-white/20 backdrop-blur-sm px-3 py-1.5 rounded-lg text-sm flex items-center gap-2">
                            <i class="fas fa-check-double"></i> Selesai: <span class="font-bold">{{ $pesananSelesai ?? 0 }}</span>
                        </span>
                        <span class="bg-white/20 backdrop-blur-sm px-3 py-1.5 rounded-lg text-sm flex items-center gap-2">
                            <i class="fas fa-times-circle"></i> Dibatalkan: <span class="font-bold">{{ $pesananDibatalkan ?? 0 }}</span>
                        </span>
                    </div>
                </div>
                <div class="flex-shrink-0 flex items-center gap-3">
                    <a href="{{ route('produk.index') }}"
                        class="inline-flex items-center gap-2 border-2 border-white/30 text-white bg-white/20 backdrop-blur-sm px-5 py-2.5 rounded-xl font-semibold hover:bg-white/30 transition-all action-btn">
                        <i class="fas fa-box"></i> Kelola Produk Skincare
                    </a>
                </div>
            </div>
        </div>

        <!-- FILTER STATUS -->
        <div class="bg-white rounded-xl shadow-md border border-pink-100 p-4 w-full mb-6">
            <div class="flex items-center justify-center gap-2 flex-wrap">
                <span class="text-sm font-medium text-gray-700 mr-2 flex items-center gap-1 whitespace-nowrap">
                    <i class="fas fa-filter text-pink-500"></i> Filter Status:
                </span>
                <button
                    class="filter-btn px-4 py-2 text-sm rounded-lg font-medium flex items-center gap-1 active whitespace-nowrap"
                    data-status="all">
                    <i class="fas fa-list"></i> Semua
                </button>
                <button
                    class="filter-btn px-4 py-2 text-sm rounded-lg font-medium flex items-center gap-1 whitespace-nowrap"
                    data-status="pending">
                    <i class="fas fa-clock"></i> Pending
                </button>
                <button
                    class="filter-btn px-4 py-2 text-sm rounded-lg font-medium flex items-center gap-1 whitespace-nowrap"
                    data-status="dibayar">
                    <i class="fas fa-credit-card"></i> Dibayar
                </button>
                <button
                    class="filter-btn px-4 py-2 text-sm rounded-lg font-medium flex items-center gap-1 whitespace-nowrap"
                    data-status="diproses">
                    <i class="fas fa-box-open"></i> Diproses (Dikemas)
                </button>
                <button
                    class="filter-btn px-4 py-2 text-sm rounded-lg font-medium flex items-center gap-1 whitespace-nowrap"
                    data-status="dikirim">
                    <i class="fas fa-truck"></i> Dikirim
                </button>
                <button
                    class="filter-btn px-4 py-2 text-sm rounded-lg font-medium flex items-center gap-1 whitespace-nowrap"
                    data-status="selesai">
                    <i class="fas fa-check-circle"></i> Selesai
                </button>
                <button
                    class="filter-btn px-4 py-2 text-sm rounded-lg font-medium flex items-center gap-1 whitespace-nowrap"
                    data-status="dibatalkan">
                    <i class="fas fa-times-circle"></i> Dibatalkan
                </button>
            </div>
        </div>

        <!-- TOAST NOTIFICATION - POJOK KANAN BAWAH (HIJAU) -->
        @if(session('success'))
        <div id="toast-success"
            class="fixed bottom-6 right-6 z-50 flex items-center gap-3 bg-white border border-green-200 shadow-2xl rounded-2xl px-5 py-4 max-w-sm w-full"
            style="animation: slideInRight 0.4s ease;">
            <div class="w-10 h-10 bg-green-500 rounded-xl flex items-center justify-center flex-shrink-0">
                <i class="fas fa-check-circle text-white text-lg"></i>
            </div>
            <div class="flex-1 min-w-0">
                <p class="font-semibold text-gray-800 text-sm">Berhasil!</p>
                <p class="text-gray-500 text-xs mt-0.5 truncate">{{ session('success') }}</p>
            </div>
            <button onclick="closeSuccessToast()" class="text-gray-400 hover:text-gray-600 flex-shrink-0 ml-1">
                <i class="fas fa-times text-xs"></i>
            </button>
            <!-- Progress bar -->
            <div class="absolute bottom-0 left-0 h-1 bg-green-500 rounded-b-2xl" id="successToastProgress"
                style="width: 100%; transition: width 5s linear;"></div>
        </div>

        <style>
        @keyframes slideInRight {
            from { opacity: 0; transform: translateX(100px); }
            to   { opacity: 1; transform: translateX(0); }
        }
        @keyframes slideOutRight {
            from { opacity: 1; transform: translateX(0); }
            to   { opacity: 0; transform: translateX(100px); }
        }
        </style>

        <script>
            // Jalankan progress bar
            setTimeout(() => {
                const bar = document.getElementById('successToastProgress');
                if (bar) bar.style.width = '0%';
            }, 100);

            // Auto-hide setelah 5 detik
            setTimeout(() => closeSuccessToast(), 5100);

            function closeSuccessToast() {
                const toast = document.getElementById('toast-success');
                if (toast) {
                    toast.style.animation = 'slideOutRight 0.3s ease forwards';
                    setTimeout(() => toast.remove(), 300);
                }
            }
        </script>
        @endif

        @if(session('error'))
            <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6 rounded-lg shadow-sm w-full"
                role="alert">
                <div class="flex items-center">
                    <i class="fas fa-exclamation-circle mr-2"></i>
                    <p>{{ session('error') }}</p>
                </div>
            </div>
        @endif

        <!-- CARDS PESANAN -->
        @forelse($pesanan as $pesananItem)
            @php
                $totalProdukSaya = 0;
                $produkSaya = $pesananItem->detail->filter(function ($detail) {
                    return $detail->produk && $detail->produk->user_id == auth()->id();
                });

                foreach ($produkSaya as $detail) {
                    $totalProdukSaya += $detail->subtotal;
                }

                // Tentukan status display berdasarkan kurir assignment
                $statusDisplay = $pesananItem->status;
                $statusLabel = strtoupper($pesananItem->status);
                $additionalLabel = '';
                
                if($pesananItem->kurirAssignment) {
                    $assignment = $pesananItem->kurirAssignment;
                    
                    if($assignment->status == 'ditugaskan') {
                        $statusDisplay = 'diproses';
                        $statusLabel = 'DIPROSES';
                        $additionalLabel = '(DIKEMAS)';
                    } elseif(in_array($assignment->status, ['dijemput', 'diantar'])) {
                        $statusDisplay = 'dikirim';
                        $statusLabel = 'DIKIRIM';
                        $additionalLabel = '';
                    } elseif($assignment->status == 'selesai') {
                        $statusDisplay = 'selesai';
                        $statusLabel = 'SELESAI';
                        $additionalLabel = '';
                    }
                }

                $statusColor = match ($statusDisplay) {
                    'pending' => 'bg-yellow-100 text-yellow-700 border-yellow-200',
                    'dibayar' => 'bg-blue-100 text-blue-700 border-blue-200',
                    'diproses' => 'bg-pink-100 text-pink-700 border-pink-200',
                    'dikirim' => 'bg-purple-100 text-purple-700 border-purple-200',
                    'selesai' => 'bg-green-100 text-green-700 border-green-200',
                    'dibatalkan' => 'bg-red-100 text-red-700 border-red-200',
                    default => 'bg-gray-100 text-gray-700 border-gray-200'
                };

                $statusIcon = match ($statusDisplay) {
                    'pending' => 'fa-clock',
                    'dibayar' => 'fa-credit-card',
                    'diproses' => 'fa-box-open',
                    'dikirim' => 'fa-truck',
                    'selesai' => 'fa-check-circle',
                    'dibatalkan' => 'fa-times-circle',
                    default => 'fa-circle'
                };

                $kodeTampil = $pesananItem->kode_pesanan;
                if (strpos($pesananItem->kode_pesanan, 'BATAL:') === 0) {
                    $kodeTampil = 'PSN-' . substr($pesananItem->kode_pesanan, 6, 8);
                }

                // CEK CHAT DAN PESAN BELUM DIBACA
                $chat = \App\Models\Chat::where('pesanan_id', $pesananItem->id)->first();
                $unreadChatMessages = 0;
                
                if ($chat) {
                    // Untuk penjual: pesan dari pembeli (user_id) yang belum dibaca
                    $unreadChatMessages = \App\Models\ChatMessage::where('chat_id', $chat->id)
                        ->where('sender_id', $chat->user_id)
                        ->where('is_read', false)
                        ->count();
                }

                // CEK APAKAH INVOICE SUDAH PERNAH DIKIRIM - HANYA DARI DATABASE
                $invoiceSent = false;
                if(isset($pesananItem->invoice_sent_at) && $pesananItem->invoice_sent_at) {
                    $invoiceSent = true;
                }
            @endphp

            <div class="bg-white rounded-2xl mb-6 border-l-4 border-pink-500 shopee-shadow hover-scale transition-all duration-300 overflow-hidden w-full"
                data-status="{{ $statusDisplay }}">

                <!-- HEADER PESANAN -->
                <div
                    class="flex flex-wrap justify-between items-center p-5 bg-gradient-to-r from-pink-50 to-white border-b border-pink-100">
                    <div class="flex items-center gap-3">
                        <span
                            class="status-badge px-4 py-1.5 {{ $statusColor }} rounded-full text-sm font-medium flex items-center gap-1 border">
                            <i class="fas {{ $statusIcon }}"></i>
                            {{ $statusLabel }}
                            @if($additionalLabel)
                                <span class="text-xs bg-white/30 px-2 py-0.5 rounded-full">{{ $additionalLabel }}</span>
                            @endif
                        </span>
                        @if($pesananItem->kurirAssignment && in_array($pesananItem->kurirAssignment->status, ['dijemput', 'diantar']))
                            <span class="text-xs bg-purple-100 text-purple-700 px-2 py-1 rounded-full flex items-center gap-1">
                                <i class="fas fa-check-circle"></i> Kurir sudah menjemput
                            </span>
                        @endif
                        
                        <!-- CHAT BADGE DI HEADER -->
                        @if($chat && $unreadChatMessages > 0)
                            <span class="text-xs bg-red-100 text-red-700 px-2 py-1 rounded-full flex items-center gap-1">
                                <i class="fas fa-comment"></i> {{ $unreadChatMessages }} pesan baru
                            </span>
                        @endif

                        <!-- BADGE INVOICE TERKIRIM -->
                        @if($invoiceSent)
                            <span class="text-xs bg-green-100 text-green-700 px-2 py-1 rounded-full flex items-center gap-1">
                                <i class="fas fa-file-invoice"></i> Invoice Terkirim
                            </span>
                        @endif
                    </div>
<div class="flex items-center gap-2 flex-wrap">
    <span class="text-xs font-mono font-medium text-gray-600 bg-white px-3 py-1.5 rounded-full shadow-sm">
        {{ $kodeTampil }}
    </span>
    <span class="text-xs text-gray-400 bg-white px-3 py-1.5 rounded-full shadow-sm flex items-center gap-1.5">
        <i class="fas fa-calendar-alt text-pink-400"></i> {{ $pesananItem->created_at->format('d M Y') }}
    </span>
    <span class="text-xs text-gray-400 bg-white px-3 py-1.5 rounded-full shadow-sm flex items-center gap-1.5">
        <i class="fas fa-clock text-pink-400"></i> {{ $pesananItem->created_at->format('H:i') }} WIB
    </span>
    <span class="text-xs text-gray-400 bg-white px-3 py-1.5 rounded-full shadow-sm flex items-center gap-1.5">
        <i class="fas fa-history text-pink-400"></i> {{ $pesananItem->created_at->diffForHumans() }}
    </span>
</div>
                </div>

                <!-- INFO PEMBELI & ALAMAT -->
                <div class="grid md:grid-cols-2 gap-4 p-5 bg-gray-50/50">
                    <div class="flex items-start gap-3 bg-white p-3 rounded-xl shadow-sm">
                        <div class="bg-pink-100 p-2 rounded-lg">
                            <i class="fas fa-user text-pink-500"></i>
                        </div>
                        <div>
                            <p class="text-xs text-gray-400">Nama Pembeli</p>
                            <p class="font-semibold text-gray-800">{{ $pesananItem->user->name }}</p>
                            <p class="text-xs text-gray-400 mt-1">
                                <i class="far fa-envelope mr-1"></i> {{ $pesananItem->user->email }}
                            </p>
                        </div>
                    </div>

<div class="flex items-start gap-3 bg-white p-3 rounded-xl shadow-sm">
    <div class="bg-pink-100 p-2 rounded-lg">
        <i class="fas fa-map-marker-alt text-pink-500"></i>
    </div>
    <div class="flex-1">
        <p class="text-xs text-gray-400">Alamat Pengiriman</p>
        @php
            $alamatLengkap = $pesananItem->alamat->alamat_lengkap ?? 'Alamat tidak tersedia';
            $uniqueIdAlamat = 'alamat_pesanan_' . ($pesananItem->id ?? rand(1, 9999));

            // Ambil 7 kata pertama
            $kata = explode(' ', $alamatLengkap);
            $tujuhKataPertama = array_slice($kata, 0, 7);
            $previewText = implode(' ', $tujuhKataPertama);

            // Cek apakah alamat memiliki lebih dari 7 kata
            $isLongAlamat = count($kata) > 7 && $alamatLengkap !== 'Alamat tidak tersedia';
        @endphp

        <div class="mt-1">
            @if($alamatLengkap !== 'Alamat tidak tersedia')
                {{-- Versi pendek (7 kata pertama dengan ellipsis) --}}
                <div id="alamat-pendek-{{ $uniqueIdAlamat }}" class="{{ $isLongAlamat ? '' : 'hidden' }}">
                    <p class="text-sm text-gray-700 leading-relaxed">{{ $previewText }}...</p>
                </div>
                {{-- Versi lengkap --}}
                <div id="alamat-lengkap-{{ $uniqueIdAlamat }}" class="{{ $isLongAlamat ? 'hidden' : '' }}">
                    <p class="text-sm text-gray-700 leading-relaxed">{{ $alamatLengkap }}</p>
                </div>
                @if($isLongAlamat)
                <button onclick="toggleAlamatPesanan('{{ $uniqueIdAlamat }}', this)"
                        class="mt-1 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
            @else
                <p class="text-sm text-gray-400 leading-relaxed">{{ $alamatLengkap }}</p>
            @endif
        </div>

        <p class="text-xs text-gray-400 mt-2 flex items-center gap-1">
            <i class="fas fa-phone-alt text-pink-400 text-[10px]"></i>
            {{ $pesananItem->alamat->no_hp ?? '-' }}
        </p>
    </div>
</div>

<script>
function toggleAlamatPesanan(id, btn) {
    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) {
        pendekEl.classList.remove('hidden');
        lengkapEl.classList.add('hidden');
        if (iconEl) {
            iconEl.classList.remove('fa-chevron-up');
            iconEl.classList.add('fa-chevron-down');
        }
        if (btnText) btnText.textContent = 'Baca selengkapnya';
    } else {
        pendekEl.classList.add('hidden');
        lengkapEl.classList.remove('hidden');
        if (iconEl) {
            iconEl.classList.remove('fa-chevron-down');
            iconEl.classList.add('fa-chevron-up');
        }
        if (btnText) btnText.textContent = 'Sembunyikan';
    }
}
</script>
                </div>

                <!-- INFO KURIR (TAMBAHAN) -->
                @if($pesananItem->kurirAssignment && $pesananItem->kurir)
                <div class="px-5 py-2 bg-pink-50/50 border-b border-pink-100 flex flex-wrap items-center gap-4 text-xs">
                    <span class="flex items-center gap-1">
                        <i class="fas fa-truck text-pink-500"></i>
                        Kurir: <span class="font-medium">{{ $pesananItem->kurir->name }}</span>
                    </span>
                    <span class="flex items-center gap-1">
                        <i class="fas fa-phone-alt text-pink-500"></i>
                        {{ $pesananItem->kurir->no_hp }}
                    </span>
                    @if($pesananItem->kurirAssignment->status == 'ditugaskan')
                        <span class="flex items-center gap-1 text-blue-600">
                            <i class="fas fa-clock"></i> Menunggu dijemput
                        </span>
                    @elseif($pesananItem->kurirAssignment->status == 'dijemput')
                        <span class="flex items-center gap-1 text-yellow-600">
                            <i class="fas fa-box"></i> Sudah dijemput
                        </span>
                    @elseif($pesananItem->kurirAssignment->status == 'diantar')
                        <span class="flex items-center gap-1 text-purple-600">
                            <i class="fas fa-truck"></i> Sedang diantar
                        </span>
                    @elseif($pesananItem->kurirAssignment->status == 'selesai')
                        <span class="flex items-center gap-1 text-green-600">
                            <i class="fas fa-check-circle"></i> Selesai
                        </span>
                    @endif
                </div>
                @endif

                <!-- PRODUK YANG DIPESAN -->
                <div class="p-5">
                    <div class="flex items-center gap-3 mb-4">
                        <div class="bg-pink-500 p-1.5 rounded-lg">
                            <i class="fas fa-shopping-bag text-white text-sm"></i>
                        </div>
                        <span class="font-semibold text-gray-700">Produk Dipesan:</span>
                        <span class="bg-pink-100 text-pink-600 text-xs px-3 py-1 rounded-full ml-auto">
                            {{ $produkSaya->count() }} produk skincare dari toko Anda
                        </span>
                    </div>

                    <!-- TABLE PRODUK -->
                    <div class="overflow-x-auto rounded-xl border border-pink-100">
                        <table class="w-full text-sm">
                            <thead class="bg-gradient-to-r from-pink-400 to-pink-500 text-white">
                                <tr>
                                    <th class="p-3 text-left font-medium rounded-tl-xl">Produk</th>
                                    <th class="p-3 text-right font-medium">Harga</th>
                                    <th class="p-3 text-center font-medium">Jumlah</th>
                                    <th class="p-3 text-right font-medium rounded-tr-xl">Subtotal</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-pink-100">
                                @forelse($produkSaya as $detail)
                                    @php
                                        $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);
                                                    $warnaFoto = strtolower(trim($parts[0]));
                                                    if ($warnaFoto === $warnaDipesan) {
                                                        $fotoTampil = $parts[1];
                                                        break;
                                                    }
                                                }
                                            }
                                            if (!$fotoTampil) {
                                                $first = $allPhotos[0];
                                                $fotoTampil = str_contains($first, ':') ? explode(':', $first)[1] : $first;
                                            }
                                        }
                                    @endphp
                                    <tr class="hover:bg-pink-50/50 transition-colors">
                                        <td class="p-3">
                                            <div class="flex items-center gap-3">
                                                <div
                                                    class="w-12 h-12 bg-gradient-to-br from-pink-100 to-pink-200 rounded-lg flex items-center justify-center shadow-sm overflow-hidden">
                                                    @if($fotoTampil)
                                                        <img src="{{ asset('storage/' . $fotoTampil) }}"
                                                            alt="{{ $detail->produk->nama_produk }}"
                                                            class="w-full h-full object-cover"
                                                            onerror="this.style.display='none'; this.parentElement.innerHTML='<i class=\'fas fa-image text-pink-300 text-xl\'></i>'">
                                                    @else
                                                        <i class="fas fa-image text-pink-300 text-xl"></i>
                                                    @endif
                                                </div>
                                                <div>
                                                    <p class="font-medium text-gray-800">{{ $detail->produk->nama_produk }}</p>
                                                    @if($detail->warna || $detail->ukuran)
                                                        <p class="text-xs text-gray-400">
                                                            @if($detail->warna) Warna: {{ $detail->warna }} @endif
                                                            @if($detail->ukuran) {{ $detail->warna ? '|' : '' }} Ukuran:
                                                            {{ $detail->ukuran }} @endif
                                                        </p>
                                                    @endif
                                                </div>
                                            </div>
                                         </td>
                                        <td class="p-3 text-right font-medium text-gray-700">
                                            Rp {{ number_format($detail->harga, 0, ',', '.') }}
                                         </td>
                                        <td class="p-3 text-center">
                                            <span
                                                class="px-3 py-1 bg-pink-100 text-pink-700 rounded-full text-xs font-medium">
                                                {{ $detail->qty }}x
                                            </span>
                                         </td>
                                        <td class="p-3 text-right font-semibold text-pink-600">
                                            Rp {{ number_format($detail->subtotal, 0, ',', '.') }}
                                         </td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="4" class="text-center p-8 text-gray-400">
                                            <div class="flex flex-col items-center">
                                                <div class="bg-pink-50 p-4 rounded-full mb-3">
                                                    <i class="fas fa-box-open text-pink-300 text-3xl"></i>
                                                </div>
                                                <p class="font-medium text-gray-500">Tidak ada produk skincare milik Anda di pesanan ini
                                                </p>
                                            </div>
                                         </td>
                                    </tr>
                                @endforelse

                                @if($produkSaya->count() > 0)
                                    <tr class="bg-pink-50/70">
                                        <td colspan="3" class="p-3 text-right font-semibold text-gray-700">Total Produk Anda:
                                         </td>
                                        <td class="p-3 text-right font-bold text-pink-600 text-lg">
                                            Rp {{ number_format($totalProdukSaya, 0, ',', '.') }}
                                         </td>
                                    </tr>
                                @endif
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- ACTION BUTTONS -->
                @if($produkSaya->count() > 0)
                    <div class="p-5 bg-gradient-to-r from-pink-50 to-white border-t border-pink-100 flex flex-wrap justify-between items-center">
                        <div class="flex items-center gap-4">
                            <div class="flex items-center gap-1 text-sm text-gray-500">
                                <i class="far fa-sticky-note text-pink-400"></i>
                                <span>Total Pesanan: Rp {{ number_format($pesananItem->total_harga, 0, ',', '.') }}</span>
                            </div>
                        </div>
                        <div class="flex gap-2 flex-wrap">

                            <a href="{{ route('pesanan.masuk.detail', $pesananItem->id) }}"
                                class="px-5 py-2.5 border-2 border-blue-500 text-blue-500 rounded-xl hover:bg-blue-50 transition-all duration-300 text-sm font-semibold flex items-center gap-2 action-btn">
                                <i class="fas fa-search"></i> Detail
                            </a>

                            {{-- Tombol Kirim Invoice - HANYA UNTUK STATUS DIIZINKAN --}}
                            @if(in_array($pesananItem->status, ['dibayar', 'diproses', 'dikirim']))
                                <button type="button"
                                        onclick="kirimInvoice({{ $pesananItem->id }}, this)"
                                        class="px-5 py-2.5 border-2 {{ $invoiceSent ? 'border-green-500 text-green-600 bg-green-50 cursor-not-allowed' : 'border-pink-500 text-pink-500 hover:bg-pink-50' }} rounded-xl transition-all duration-300 text-sm font-semibold flex items-center gap-2 action-btn kirim-invoice-btn"
                                        data-pesanan-id="{{ $pesananItem->id }}"
                                        data-invoice-sent="{{ $invoiceSent ? 'true' : 'false' }}"
                                        {{ $invoiceSent ? 'disabled' : '' }}>
                                    @if($invoiceSent)
                                        <i class="fas fa-check-circle"></i> Invoice Terkirim
                                    @else
                                        <i class="fas fa-file-invoice"></i> Kirim Invoice
                                    @endif
                                </button>
                            @endif

                            @if($pesananItem->status === 'dibayar')
                                <a href="{{ route('pesanan.masuk.pilih-kurir', $pesananItem->id) }}"
                                    class="px-5 py-2.5 bg-gradient-to-r from-pink-400 to-pink-500 text-white rounded-xl hover:from-pink-500 hover:to-pink-600 transition-all duration-300 text-sm font-semibold flex items-center gap-2 shadow-md action-btn">
                                    <i class="fas fa-truck"></i> Kirim Pesanan
                                </a>
                            @endif


                            <!-- BUTTON CHAT -->
                            @if($pesananItem->status != 'dibatalkan')
                                @if($chat)
                                    <a href="{{ route('chat.show', $chat->id) }}" 
                                    class="px-5 py-2.5 bg-gradient-to-r from-green-500 to-green-600 text-white rounded-xl hover:from-green-600 hover:to-green-700 transition-all duration-300 text-sm font-semibold flex items-center gap-2 shadow-md action-btn relative">
                                        <i class="fas fa-comments"></i> Chat
                                        @if($unreadChatMessages > 0)
                                            <span class="absolute -top-2 -right-2 bg-red-500 text-white text-xs px-1.5 py-0.5 rounded-full chat-badge">
                                                {{ $unreadChatMessages }}
                                            </span>
                                        @endif
                                    </a>
                                @else
                                    <button type="button"
                                            onclick="createChat({{ $pesananItem->id }})"
                                            class="px-5 py-2.5 bg-gradient-to-r from-green-500 to-green-600 text-white rounded-xl hover:from-green-600 hover:to-green-700 transition-all duration-300 text-sm font-semibold flex items-center gap-2 shadow-md action-btn">
                                        <i class="fas fa-comments"></i> Mulai Chat
                                    </button>
                                @endif
                            @endif
                        </div>
                    </div>
                @endif

                <!-- INFORMASI TAMBAHAN -->
     <div class="px-5 py-3 bg-gray-50/50 text-xs text-gray-400 border-t border-pink-100 flex flex-wrap gap-3">
    <span class="flex items-center gap-1">
        <i class="far fa-credit-card text-pink-400"></i>
        Pembayaran:
        <span class="font-semibold text-gray-600">
            @if($pesananItem->pembayaran)
                {{ $pesananItem->pembayaran->metode ?? 'Transfer' }}
            @else
                Belum dibayar
            @endif
        </span>
    </span>
    @if($pesananItem->pembayaran && $pesananItem->pembayaran->tanggal_bayar)
        <span class="text-gray-300">|</span>
        <span class="flex items-center gap-1"><i class="fas fa-calendar-alt text-pink-400"></i> {{ $pesananItem->pembayaran->tanggal_bayar->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> {{ $pesananItem->pembayaran->tanggal_bayar->format('H:i') }} WIB</span>
        <span class="text-gray-300">|</span>
        <span class="flex items-center gap-1"><i class="fas fa-history text-pink-400"></i> {{ $pesananItem->pembayaran->tanggal_bayar->diffForHumans() }}</span>
    @endif
</div>
            </div>

        @empty
            <div class="bg-white p-12 text-center rounded-2xl border-l-4 border-pink-500 shadow-lg w-full">
                <div class="flex justify-center mb-6">
                    <div class="bg-gradient-to-br from-pink-100 to-pink-200 p-6 rounded-full">
                        <i class="fas fa-shopping-bag text-pink-400 text-5xl"></i>
                    </div>
                </div>
                <h3 class="text-xl font-bold text-gray-700 mb-2">Belum Ada Pesanan Masuk</h3>
                <p class="text-sm text-gray-400 max-w-md mx-auto mb-6">
                    Tenang, pesanan skincare dari pembeli akan muncul di sini.
                    Pastikan toko Anda selalu aktif dan produk skincare tersedia!
                </p>
                <a href="{{ route('produk.index') }}"
                    class="px-6 py-3 bg-gradient-to-r from-pink-400 to-pink-500 text-white rounded-xl hover:from-pink-500 hover:to-pink-600 transition-all duration-300 font-medium shadow-md inline-flex items-center gap-2">
                    <i class="fas fa-box"></i> Kelola Produk Skincare
                </a>
            </div>
        @endforelse
    </div>

<script>
// Gabungkan semua fungsi dalam satu script
(function() {
    // Fungsi untuk mengirim invoice
    window.kirimInvoice = function(pesananId, buttonElement) {
        // Validasi: cek apakah invoice sudah terkirim dari database
        if (buttonElement.disabled) {
            showToast('Invoice sudah pernah dikirim untuk pesanan ini', 'warning');
            return;
        }

        // Validasi status dari data attribute
        const invoiceSentAttr = buttonElement.getAttribute('data-invoice-sent');
        if (invoiceSentAttr === 'true') {
            showToast('Invoice sudah pernah dikirim', 'warning');
            return;
        }

        // Tanya konfirmasi
        if (!confirm('Kirim invoice ke email pembeli?')) {
            return;
        }

        // Simpan HTML asli untuk referensi
        const originalHtml = buttonElement.innerHTML;
        const btn = buttonElement;

        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Mengirim...';

        // Gunakan URL manual
        fetch('/pesanan-masuk/' + pesananId + '/kirim-invoice', {
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            method: 'POST'
        })
        .then(res => {
            if (!res.ok) {
                return res.json().then(data => {
                    throw new Error(data.message || 'Network response was not ok');
                });
            }
            return res.json();
        })
        .then(data => {
            if (data.success) {
                // Tampilkan toast sukses
                showToast(data.message || 'Invoice berhasil dikirim', 'success');
                
                // Ubah tampilan tombol menjadi "Invoice Terkirim"
                btn.innerHTML = '<i class="fas fa-check-circle"></i> Invoice Terkirim';
                btn.classList.remove('border-pink-500', 'text-pink-500', 'hover:bg-pink-50');
                btn.classList.add('border-green-500', 'text-green-600', 'bg-green-50', 'cursor-not-allowed');
                
                // Nonaktifkan tombol agar tidak bisa diklik lagi
                btn.disabled = true;
                btn.onclick = null;
                btn.setAttribute('data-invoice-sent', 'true');
                
                // Tambahkan badge invoice terkirim di header
                const card = btn.closest('.bg-white.rounded-2xl');
                if (card) {
                    const headerDiv = card.querySelector('.flex.flex-wrap.justify-between.items-center.p-5');
                    if (headerDiv) {
                        const badgeContainer = headerDiv.querySelector('.flex.items-center.gap-3');
                        if (badgeContainer && !badgeContainer.querySelector('.bg-green-100')) {
                            const badge = document.createElement('span');
                            badge.className = 'text-xs bg-green-100 text-green-700 px-2 py-1 rounded-full flex items-center gap-1';
                            badge.innerHTML = '<i class="fas fa-file-invoice"></i> Invoice Terkirim';
                            badgeContainer.appendChild(badge);
                        }
                    }
                }
                
                // Refresh halaman setelah 2 detik untuk memastikan data terupdate
                setTimeout(() => {
                    location.reload();
                }, 2000);
            } else {
                // Kembalikan ke tampilan awal jika gagal
                btn.disabled = false;
                btn.innerHTML = originalHtml;
                showToast(data.message || 'Gagal mengirim invoice', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            btn.disabled = false;
            btn.innerHTML = originalHtml;
            showToast(error.message || 'Terjadi kesalahan. Coba lagi.', 'error');
        });
    };

    // Fungsi showToast
    window.showToast = function(message, type) {
        let toastContainer = document.getElementById('toast-container');
        
        if (!toastContainer) {
            toastContainer = document.createElement('div');
            toastContainer.id = 'toast-container';
            toastContainer.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 9999;
            `;
            document.body.appendChild(toastContainer);
        }
        
        const toast = document.createElement('div');
        toast.style.cssText = `
            background: ${type === 'success' ? '#10b981' : '#ef4444'};
            color: white;
            padding: 12px 24px;
            border-radius: 8px;
            margin-bottom: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            gap: 8px;
            animation: slideIn 0.3s ease;
            font-weight: 500;
        `;
        
        toast.innerHTML = `
            <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i>
            ${message}
        `;
        
        toastContainer.appendChild(toast);
        
        setTimeout(() => {
            toast.style.animation = 'slideOut 0.3s ease';
            setTimeout(() => {
                toast.remove();
            }, 300);
        }, 3000);
    };

    // Fungsi toggle dropdown
    window.toggleDropdown = function() {
        const menu = document.getElementById('dropdownMenu');
        const icon = document.getElementById('dropdownIcon');
        if (menu && icon) {
            menu.classList.toggle('hidden');
            icon.style.transform = menu.classList.contains('hidden') ? 'rotate(0deg)' : 'rotate(180deg)';
        }
    };

    // Fungsi untuk membuat chat baru
    window.createChat = function(pesananId) {
        fetch('{{ route("chat.create-or-get") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify({ pesanan_id: pesananId })
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                window.location.href = data.redirect_url;
            } else {
                showToast(data.message || 'Gagal membuat chat', 'error');
            }
        })
        .catch(err => {
            console.error('Error:', err);
            showToast('Terjadi kesalahan saat membuat chat', 'error');
        });
    };

    // Fungsi refresh unread chat
    window.refreshUnreadChat = function() {
        fetch('{{ route("chat.unread-count") }}')
            .then(res => res.json())
            .then(data => {
                const chatBadge = document.querySelector('a[href*="chat.index"] .bg-red-500');
                if (chatBadge) {
                    if (data.unread_count > 0) {
                        chatBadge.textContent = data.unread_count > 99 ? '99+' : data.unread_count;
                        chatBadge.classList.remove('hidden');
                    } else {
                        chatBadge.classList.add('hidden');
                    }
                }
            })
            .catch(err => console.error('Error refreshing chat:', err));
    };

    // Event listeners yang digabung dalam satu DOMContentLoaded
    document.addEventListener('DOMContentLoaded', function() {
        // Filter status
        const filterButtons = document.querySelectorAll('.filter-btn');
        const cards = document.querySelectorAll('[data-status]');

        function filterCards(status) {
            cards.forEach(card => {
                const cardStatus = card.dataset.status;
                if (status === 'all') {
                    card.style.display = 'block';
                } else if (status === 'dibayar' && (cardStatus === 'dibayar' || cardStatus === 'diproses')) {
                    card.style.display = 'block';
                } else if (cardStatus === status) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
        }

        filterButtons.forEach(btn => {
            btn.addEventListener('click', function() {
                filterButtons.forEach(b => b.classList.remove('active', 'bg-pink-500', 'text-white'));
                this.classList.add('active');
                
                // Tambahkan styling active
                if (this.dataset.status === 'all') {
                    this.classList.add('bg-pink-500', 'text-white');
                }
                
                filterCards(this.dataset.status);
            });
            
            // Set active class untuk tombol "Semua" secara default
            if (btn.dataset.status === 'all') {
                btn.classList.add('active', 'bg-pink-500', 'text-white');
            }
        });

        // Auto hide alerts
        setTimeout(() => {
            document.querySelectorAll('[role="alert"]').forEach(el => {
                el.style.transition = 'opacity 0.5s';
                el.style.opacity = '0';
                setTimeout(() => el.remove(), 500);
            });
        }, 5000);

        // Set default filter ke "Semua"
        filterCards('all');
    });

    // Event listener untuk dropdown (di luar DOMContentLoaded karena perlu menangkap klik di mana saja)
    document.addEventListener('click', function(e) {
        const dropdown = document.getElementById('userDropdown');
        const menu = document.getElementById('dropdownMenu');
        const icon = document.getElementById('dropdownIcon');
        
        if (dropdown && !dropdown.contains(e.target)) {
            if (menu) menu.classList.add('hidden');
            if (icon) icon.style.transform = 'rotate(0deg)';
        }
    });

    // Auto refresh unread chat count every 30 seconds
    setInterval(refreshUnreadChat, 30000);
})();
</script>

</body>

</html>