<!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>Category Management - Ryll Store</title>
    <link rel="icon" type="image/webp" href="{{ asset('images/ryll.webp') }}">

    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <style>
        .font-orbitron {
            font-family: 'Orbitron', sans-serif;
        }

        [x-cloak] {
            display: none !important;
        }
        
        /* ✅ Smooth hover effects */
        .category-card {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        .category-card:hover {
            transform: translateY(-4px);
        }

        /* ✅ Scrollbar styling */
        .modal-body::-webkit-scrollbar {
            width: 8px;
        }

        .modal-body::-webkit-scrollbar-track {
            background: rgb(17 24 39);
            border-radius: 4px;
        }

        .modal-body::-webkit-scrollbar-thumb {
            background: rgb(6 182 212);
            border-radius: 4px;
        }

        .modal-body::-webkit-scrollbar-thumb:hover {
            background: rgb(8 145 178);
        }
    </style>
</head>

<body class="bg-gray-950 text-white" x-data="categoryManager()">

    <!-- Header -->
    <div class="bg-gray-900 border-b border-cyan-500/20 p-4 md:p-6">
        <div class="max-w-7xl mx-auto">
            <!-- NAVBAR -->
            @include('components.admin-navbar')
            <br>

            <!-- Header with Stats -->
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-6">
                <div>
                    <h1 class="text-2xl md:text-3xl font-bold text-cyan-400 font-orbitron mb-2">
                        📂 CATEGORY MANAGEMENT
                    </h1>
                    <p class="text-sm md:text-base text-gray-400">
                        Atur kategori produk jeung upload gambar logo
                    </p>
                </div>
                
                <button @click="openModal('create')" 
                    class="w-full md:w-auto px-6 py-3 bg-gradient-to-r from-cyan-500 to-blue-600 rounded-lg font-bold hover:scale-105 transition shadow-lg shadow-cyan-500/20 text-sm md:text-base">
                    <i class="fas fa-plus mr-2"></i> TAMBAH Category
                </button>
            </div>

            <!-- ✅ QUICK STATS -->
            <div class="grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4">
                <div class="bg-gradient-to-br from-cyan-500/10 to-blue-500/10 border border-cyan-500/30 rounded-xl p-4">
                    <div class="flex items-center gap-3">
                        <div class="w-12 h-12 bg-cyan-500/20 rounded-lg flex items-center justify-center">
                            <i class="fas fa-folder text-cyan-400 text-xl"></i>
                        </div>
                        <div>
                            <p class="text-2xl font-black text-white">{{ $categories->count() }}</p>
                            <p class="text-xs text-gray-400">Total Categories</p>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-green-500/10 to-emerald-500/10 border border-green-500/30 rounded-xl p-4">
                    <div class="flex items-center gap-3">
                        <div class="w-12 h-12 bg-green-500/20 rounded-lg flex items-center justify-center">
                            <i class="fas fa-check-circle text-green-400 text-xl"></i>
                        </div>
                        <div>
                            <p class="text-2xl font-black text-white">{{ $categories->where('is_active', 1)->count() }}</p>
                            <p class="text-xs text-gray-400">Active</p>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-orange-500/10 to-red-500/10 border border-orange-500/30 rounded-xl p-4">
                    <div class="flex items-center gap-3">
                        <div class="w-12 h-12 bg-orange-500/20 rounded-lg flex items-center justify-center">
                            <i class="fas fa-fire text-orange-400 text-xl"></i>
                        </div>
                        <div>
                            <p class="text-2xl font-black text-white">{{ $categories->where('is_popular', 1)->count() }}</p>
                            <p class="text-xs text-gray-400">Popular</p>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-purple-500/10 to-pink-500/10 border border-purple-500/30 rounded-xl p-4">
                    <div class="flex items-center gap-3">
                        <div class="w-12 h-12 bg-purple-500/20 rounded-lg flex items-center justify-center">
                            <i class="fas fa-box text-purple-400 text-xl"></i>
                        </div>
                        <div>
                            <p class="text-2xl font-black text-white">{{ $categories->sum('product_count') }}</p>
                            <p class="text-xs text-gray-400">Total Products</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Categories Grid -->
    <div class="max-w-7xl mx-auto px-4 md:px-6 py-6 md:py-8" 
         x-data="categoryFilterManager()"
         x-init="allCategories = {{ Js::from($categories->map(function($c) {
            return [
                'id' => $c->id,
                'name' => $c->name,
                'slug' => $c->slug,
                'brand_code' => $c->brand_code,
                'category_type' => $c->category_type,
                'input_type' => $c->input_type,
                'description' => $c->description,
                'image' => $c->image,
                'icon' => $c->icon,
                'sort_order' => $c->sort_order,
                'product_count' => $c->product_count,
                'is_active' => $c->is_active,
                'is_popular' => $c->is_popular,
                'status' => $c->is_active
            ];
        })) }}">
        
        <!-- ✅ SEARCH & SORT BAR -->
        <div class="bg-gray-900/50 backdrop-blur-sm border border-gray-800 rounded-xl p-4 mb-6">
            <div class="flex flex-col md:flex-row gap-4">
                <!-- Search Input -->
                <div class="flex-1">
                    <div class="relative">
                        <i class="fas fa-search absolute left-4 top-1/2 -translate-y-1/2 text-gray-500"></i>
                        <input type="text" 
                            x-model="searchQuery"
                            placeholder="Search categories, brand code, or description..."
                            class="w-full pl-12 pr-10 py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
                        <button @click="searchQuery = ''" 
                            x-show="searchQuery"
                            class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-white">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
                
                <!-- Sort Dropdown -->
                <div class="w-full md:w-64">
                    <select x-model="sortBy"
                        class="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
                        <option value="name">📝 Sort by Name (A-Z)</option>
                        <option value="products">📦 Sort by Products (Most)</option>
                        <option value="sort_order">🔢 Sort by Order</option>
                        <option value="newest">⏰ Sort by Newest</option>
                    </select>
                </div>
            </div>
            
            <!-- Results Counter -->
            <div class="mt-3 flex items-center justify-between text-sm">
                <p class="text-gray-400">
                    <span x-text="filteredCategories.length"></span> 
                    <span x-text="filteredCategories.length === 1 ? 'category' : 'categories'"></span> found
                </p>
                <button @click="searchQuery = ''; activeFilter = 'all'; sortBy = 'name'" 
                    x-show="searchQuery || activeFilter !== 'all' || sortBy !== 'name'"
                    class="text-cyan-400 hover:text-cyan-300 transition font-bold">
                    <i class="fas fa-redo mr-1"></i> Reset Filters
                </button>
            </div>
        </div>
        
        <!-- ✅ FILTER TABS -->
        <div class="flex flex-wrap gap-2 mb-6">
            <button @click="activeFilter = 'all'" 
                :class="activeFilter === 'all' ? 'bg-cyan-500 text-white' : 'bg-gray-800 text-gray-400 hover:bg-gray-700'"
                class="px-4 py-2 rounded-lg font-bold text-sm transition">
                <i class="fas fa-th mr-2"></i>All ({{ $categories->count() }})
            </button>
            <button @click="activeFilter = 'game'" 
                :class="activeFilter === 'game' ? 'bg-cyan-500 text-white' : 'bg-gray-800 text-gray-400 hover:bg-gray-700'"
                class="px-4 py-2 rounded-lg font-bold text-sm transition">
                🎮 Games ({{ $categories->where('category_type', 'game')->count() }})
            </button>
            <button @click="activeFilter = 'voucher'" 
                :class="activeFilter === 'voucher' ? 'bg-cyan-500 text-white' : 'bg-gray-800 text-gray-400 hover:bg-gray-700'"
                class="px-4 py-2 rounded-lg font-bold text-sm transition">
                🎫 Vouchers ({{ $categories->where('category_type', 'voucher')->count() }})
            </button>
            <button @click="activeFilter = 'pulsa'" 
                :class="activeFilter === 'pulsa' ? 'bg-cyan-500 text-white' : 'bg-gray-800 text-gray-400 hover:bg-gray-700'"
                class="px-4 py-2 rounded-lg font-bold text-sm transition">
                📱 Pulsa ({{ $categories->where('category_type', 'pulsa')->count() }})
            </button>
        </div>

        <!-- Categories Grid -->
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 md:gap-6">
            <template x-for="category in filteredCategories" :key="category.id">
                <div class="category-card bg-gray-900 rounded-xl md:rounded-2xl border border-gray-800 overflow-hidden hover:border-cyan-500/50 transition group"
                    x-transition:enter="transition ease-out duration-200"
                    x-transition:enter-start="opacity-0 scale-95"
                    x-transition:enter-end="opacity-100 scale-100">
                    
                    <!-- Category Image -->
                    <div class="aspect-video bg-gradient-to-br from-gray-800 to-gray-900 relative overflow-hidden">
                        <template x-if="category.image">
                            <img :src="`{{ asset('storage/') }}/${category.image}`" 
                                 :alt="category.name"
                                 class="w-full h-full object-cover group-hover:scale-110 transition duration-500">
                        </template>
                        <template x-if="!category.image">
                            <div class="w-full h-full flex items-center justify-center">
                                <i :class="category.icon || 'fas fa-tag'" class="text-4xl md:text-6xl text-gray-700 group-hover:text-cyan-500 transition"></i>
                            </div>
                        </template>

                        <!-- ✅ STATUS & BADGES (Top Right) -->
                        <div class="absolute top-2 md:top-3 right-2 md:right-3 flex flex-col items-end gap-2">
                            <!-- Status Badge (Clickable) -->
                            <button @click="toggleStatus(category.id)"
                                class="px-2 md:px-3 py-1 rounded-full text-[10px] md:text-xs font-bold transition shadow-lg backdrop-blur-md hover:scale-110"
                                :class="categories.find(c => c.id === category.id)?.status ? 
                                    'bg-green-500/20 text-green-400 border border-green-500/30 hover:bg-green-500/30' : 
                                    'bg-red-500/20 text-red-400 border border-red-500/30 hover:bg-red-500/30'">
                                <i class="fas fa-circle text-[6px] mr-1 animate-pulse" 
                                   :class="categories.find(c => c.id === category.id)?.status ? 'text-green-400' : 'text-red-400'"></i>
                                <span x-text="categories.find(c => c.id === category.id)?.status ? 'Active' : 'Inactive'"></span>
                            </button>

                            <!-- Popular Badge -->
                            <template x-if="category.is_popular">
                                <div class="flex items-center gap-1.5 px-2 md:px-3 py-1 rounded-full text-[10px] md:text-xs font-black bg-gradient-to-r from-orange-500 to-red-500 text-white shadow-[0_0_20px_rgba(249,115,22,0.6)] border border-orange-300">
                                    <i class="fas fa-fire-alt animate-bounce"></i>
                                    <span>POPULER</span>
                                </div>
                            </template>
                        </div>

                        <!-- ✅ PRODUCT COUNT BADGE (Bottom Left) -->
                        <div class="absolute bottom-2 left-2 px-3 py-1 bg-black/60 backdrop-blur-md rounded-lg border border-cyan-500/30">
                            <div class="flex items-center gap-2 text-xs font-bold text-cyan-400">
                                <i class="fas fa-box-open"></i>
                                <span x-text="category.product_count + ' Products'"></span>
                            </div>
                        </div>
                    </div>

                    <!-- Category Info -->
                    <div class="p-4 md:p-6">
                        <div class="flex items-start justify-between mb-3">
                            <div class="flex-1 min-w-0">
                                <h3 class="text-lg md:text-xl font-bold text-white mb-2 truncate group-hover:text-cyan-400 transition" x-text="category.name"></h3>
                                
                                <!-- ✅ CATEGORY BADGES -->
                                <div class="flex flex-wrap gap-2 mb-2">
                                    <template x-if="category.brand_code">
                                        <span class="inline-flex items-center gap-1 px-2 py-1 bg-blue-500/20 text-blue-400 rounded text-[10px] md:text-xs font-bold border border-blue-500/30">
                                            <i class="fas fa-code text-[8px]"></i>
                                            <span x-text="category.brand_code"></span>
                                        </span>
                                    </template>
                                    
                                    <!-- Category Type Badge -->
                                    <span class="inline-flex items-center gap-1 px-2 py-1 rounded text-[10px] md:text-xs font-bold"
                                          :class="{
                                              'bg-purple-500/20 text-purple-400 border border-purple-500/30': category.category_type === 'game',
                                              'bg-pink-500/20 text-pink-400 border border-pink-500/30': category.category_type === 'voucher',
                                              'bg-green-500/20 text-green-400 border border-green-500/30': category.category_type === 'pulsa',
                                              'bg-gray-500/20 text-gray-400 border border-gray-500/30': !['game', 'voucher', 'pulsa'].includes(category.category_type)
                                          }">
                                        <span x-text="category.category_type === 'game' ? '🎮' : 
                                                     category.category_type === 'voucher' ? '🎫' : 
                                                     category.category_type === 'pulsa' ? '📱' : 
                                                     category.category_type === 'ewallet' ? '💳' : '📦'"></span>
                                        <span x-text="category.category_type.charAt(0).toUpperCase() + category.category_type.slice(1)"></span>
                                    </span>
                                </div>
                            </div>
                        </div>

                        <template x-if="category.description">
                            <p class="text-xs md:text-sm text-gray-400 mb-4 line-clamp-2" x-text="category.description"></p>
                        </template>

                        <!-- ✅ STATS GRID -->
                        <div class="grid grid-cols-2 gap-2 mb-4">
                            <div class="bg-cyan-500/10 border border-cyan-500/30 rounded-lg p-2">
                                <div class="flex items-center gap-2">
                                    <i class="fas fa-sort text-cyan-400 text-sm"></i>
                                    <div>
                                        <p class="text-xs text-gray-500">Sort Order</p>
                                        <p class="text-sm font-bold text-cyan-400" x-text="category.sort_order"></p>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="bg-purple-500/10 border border-purple-500/30 rounded-lg p-2">
                                <div class="flex items-center gap-2">
                                    <i class="fas fa-keyboard text-purple-400 text-sm"></i>
                                    <div>
                                        <p class="text-xs text-gray-500">Input Type</p>
                                        <p class="text-[10px] md:text-xs font-bold text-purple-400"
                                           x-text="category.input_type === 'user-id' ? '👤 ID' : 
                                                  category.input_type === 'user-id-zone' ? '🎮 ID+Zone' : 
                                                  category.input_type === 'email' ? '📧 Email' : 
                                                  category.input_type === 'phone' ? '📱 Phone' : 
                                                  category.input_type === 'voucher' ? '🎫 Voucher' : 
                                                  category.input_type"></p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Actions -->
                        <div class="flex gap-2">
                            <button @click="editCategory(category.id)"
                                class="flex-1 px-3 md:px-4 py-2.5 bg-blue-500/20 text-blue-400 rounded-lg hover:bg-blue-500 hover:text-white transition text-xs md:text-sm font-bold border border-blue-500/30 hover:border-blue-500">
                                <i class="fas fa-edit mr-1 md:mr-2"></i>Edit
                            </button>
                            <button @click="deleteCategory(category.id, category.product_count)"
                                class="flex-1 px-3 md:px-4 py-2.5 bg-red-500/20 text-red-400 rounded-lg hover:bg-red-500 hover:text-white transition text-xs md:text-sm font-bold border border-red-500/30 hover:border-red-500"
                                :class="category.product_count > 0 ? 'opacity-50 cursor-not-allowed' : ''"
                                :disabled="category.product_count > 0"
                                :title="category.product_count > 0 ? 'Cannot delete category with products' : ''">
                                <i class="fas fa-trash mr-1 md:mr-2"></i>Delete
                            </button>
                        </div>
                    </div>
                </div>
            </template>
        </div>

        <!-- ✅ NO RESULTS STATE -->
        <div x-show="filteredCategories.length === 0" 
             x-transition
             class="text-center py-12 md:py-16">
            <div class="inline-block p-6 bg-gray-800/50 rounded-full mb-4">
                <i class="fas fa-search text-5xl md:text-6xl text-gray-700"></i>
            </div>
            <h3 class="text-lg md:text-xl font-bold text-gray-500 mb-2">No Categories Found</h3>
            <p class="text-sm text-gray-600 mb-6">Try adjusting your search or filters</p>
            <button @click="searchQuery = ''; activeFilter = 'all'" 
                class="px-6 py-3 bg-cyan-500 text-white rounded-lg font-bold hover:bg-cyan-600 transition">
                <i class="fas fa-redo mr-2"></i>Clear Filters
            </button>
        </div>
    </div>

    <!-- ✅ MODAL -->
    <div x-show="showModal" x-cloak
        class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
        @click.self="closeModal()"
        x-transition:enter="transition ease-out duration-300"
        x-transition:enter-start="opacity-0"
        x-transition:enter-end="opacity-100"
        x-transition:leave="transition ease-in duration-200"
        x-transition:leave-start="opacity-100"
        x-transition:leave-end="opacity-0">
        
        <div class="bg-gray-900 rounded-2xl border border-cyan-500/20 w-full max-w-2xl max-h-[90vh] overflow-hidden shadow-2xl"
            @click.stop
            x-transition:enter="transition ease-out duration-300"
            x-transition:enter-start="opacity-0 scale-90"
            x-transition:enter-end="opacity-100 scale-100"
            x-transition:leave="transition ease-in duration-200"
            x-transition:leave-start="opacity-100 scale-100"
            x-transition:leave-end="opacity-0 scale-90">
            
            <!-- Modal Header -->
            <div class="p-4 md:p-6 border-b border-gray-800 bg-gradient-to-r from-cyan-500/10 to-blue-500/10">
                <div class="flex items-center justify-between">
                    <h2 class="text-xl md:text-2xl font-bold text-cyan-400 font-orbitron"
                        x-text="modalMode === 'create' ? '➕ Tambah Category Baru' : '✏️ Edit Category'"></h2>
                    <button @click="closeModal()" 
                        class="w-10 h-10 rounded-full hover:bg-gray-800 transition flex items-center justify-center text-gray-400 hover:text-white">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
            </div>

            <!-- Modal Body -->
            <form @submit.prevent="submitForm()" class="modal-body overflow-y-auto" style="max-height: calc(90vh - 180px);">
                <div class="p-4 md:p-6 space-y-4">

                    <!-- Category Name -->
                    <div>
                        <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">
                            <i class="fas fa-tag mr-1 text-cyan-400"></i> Category Name *
                        </label>
                        <input type="text" x-model="form.name" required
                            class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50"
                            placeholder="e.g. Mobile Legends">
                    </div>

                    <!-- Brand Code -->
                    <div>
                        <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">
                            <i class="fas fa-code mr-1 text-blue-400"></i> Brand Code (untuk sync API)
                        </label>
                        <input type="text" x-model="form.brand_code"
                            class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50"
                            placeholder="e.g. mobile-legends">
                        <p class="text-xs text-gray-500 mt-1">
                            <i class="fas fa-info-circle mr-1"></i>
                            Dipaké pikeun matching produk tina API
                        </p>
                    </div>

                    <!-- Category Type -->
                    <div>
                        <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">
                            <i class="fas fa-layer-group mr-1 text-purple-400"></i> Category Type *
                        </label>
                        <select x-model="form.category_type" required
                            class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
                            <option value="">Select Type</option>
                            <option value="game">🎮 Game</option>
                            <option value="ewallet">💳 E-Wallet</option>
                            <option value="pulsa">📱 Pulsa/PPOB</option>
                            <option value="voucher">🎟️ Voucher</option>
                            <option value="streaming">📺 Streaming</option>
                            <option value="subscription">💎 Subscription</option>
                        </select>
                    </div>

                    <!-- Input Type -->
                    <div>
                        <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">
                            <i class="fas fa-keyboard mr-1 text-green-400"></i> Input Type *
                        </label>
                        <select x-model="form.input_type" required
                            class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
                            <option value="">Select Input Type</option>
                            <option value="user-id">👤 User ID (Game tanpa Zone)</option>
                            <option value="user-id-zone">🎮 User ID + Zone (Mobile Legends, dll)</option>
                            <option value="email">📧 Email (Streaming, Subscription)</option>
                            <option value="phone">📱 Phone Number (Pulsa, E-Wallet)</option>
                            <option value="username">👨 Username</option>
                            <option value="voucher">🎫 Voucher (Ga Perlu Input)</option>
                        </select>
                        <p class="text-xs text-gray-500 mt-1">
                            <i class="fas fa-lightbulb mr-1"></i>
                            Tentukan tipe data yang dibutuhkeun user
                        </p>
                    </div>

                    <!-- Description -->
                    <div>
                        <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">
                            <i class="fas fa-align-left mr-1 text-yellow-400"></i> Description
                        </label>
                        <textarea x-model="form.description" rows="3"
                            class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50 resize-none"
                            placeholder="Deskripsi singkat kategori..."></textarea>
                    </div>

                    <!-- Icon & Sort Order -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">
                                <i class="fas fa-icons mr-1 text-pink-400"></i> Icon Class
                            </label>
                            <input type="text" x-model="form.icon"
                                class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50"
                                placeholder="fas fa-gamepad">
                            <p class="text-xs text-gray-500 mt-1">FontAwesome class</p>
                        </div>
                        <div>
                            <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">
                                <i class="fas fa-sort-numeric-down mr-1 text-orange-400"></i> Sort Order
                            </label>
                            <input type="number" x-model="form.sort_order" min="0"
                                class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50"
                                placeholder="0">
                        </div>
                    </div>

                    <!-- Popular Status -->
                    <div class="p-4 bg-gradient-to-r from-red-500/10 to-orange-500/10 border border-red-500/30 rounded-xl">
                        <label class="flex items-start gap-3 cursor-pointer group">
                            <input type="checkbox" 
                                x-model="form.is_popular"
                                class="w-5 h-5 rounded bg-gray-800 border-gray-700 text-red-500 focus:ring-red-500 focus:ring-offset-0 cursor-pointer mt-0.5">
                            <div class="flex-1">
                                <div class="flex items-center gap-2 mb-1">
                                    <i class="fas fa-fire text-red-500 text-lg animate-pulse"></i>
                                    <span class="font-bold text-white group-hover:text-red-400 transition">
                                        Tampilkan di "POPULER SEKARANG"
                                    </span>
                                </div>
                                <p class="text-xs text-gray-400">
                                    Kategori ini akan muncul di section populer di homepage (maksimal 6 kategori)
                                </p>
                            </div>
                        </label>
                    </div>

                    <!-- Image Upload -->
                    <div>
                        <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">
                            <i class="fas fa-image mr-1 text-indigo-400"></i> Category Image/Logo
                        </label>
                        <input type="file" @change="handleImageUpload($event)" accept="image/*"
                            class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none 
                            file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:bg-cyan-500 file:text-white file:cursor-pointer hover:file:bg-cyan-600 file:text-xs file:font-bold">
                        <p class="text-xs text-gray-500 mt-1">
                            <i class="fas fa-info-circle mr-1"></i>
                            Max 2MB. Recommended: 300x300px
                        </p>
                    </div>

                    <!-- Modal Footer -->
                    <div class="flex gap-3 pt-4 border-t border-gray-800">
                        <button type="button" @click="closeModal()"
                            class="flex-1 px-4 md:px-6 py-2 md:py-3 bg-gray-800 text-gray-400 rounded-lg font-bold hover:bg-gray-700 transition text-sm">
                            <i class="fas fa-times mr-2"></i>Cancel
                        </button>
                        <button type="submit"
                            class="flex-1 px-4 md:px-6 py-2 md:py-3 bg-gradient-to-r from-cyan-500 to-blue-600 rounded-lg font-bold hover:scale-105 transition shadow-lg shadow-cyan-500/20 text-sm"
                            :disabled="loading"
                            :class="loading ? 'opacity-50 cursor-not-allowed' : ''">
                            <span x-show="!loading">
                                <i :class="modalMode === 'create' ? 'fas fa-plus' : 'fas fa-save'" class="mr-2"></i>
                                <span x-text="modalMode === 'create' ? 'Create Category' : 'Update Category'"></span>
                            </span>
                            <span x-show="loading" class="flex items-center justify-center gap-2">
                                <i class="fas fa-spinner fa-spin"></i>
                                Processing...
                            </span>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <script>
        function categoryFilterManager() {
            return {
                activeFilter: 'all',
                searchQuery: '',
                sortBy: 'name',
                allCategories: [],
                
                get filteredCategories() {
                    let cats = [...this.allCategories];
                    
                    if (this.activeFilter !== 'all') {
                        cats = cats.filter(c => c.category_type === this.activeFilter);
                    }
                    
                    if (this.searchQuery.trim()) {
                        const query = this.searchQuery.toLowerCase();
                        cats = cats.filter(c => 
                            c.name.toLowerCase().includes(query) ||
                            (c.brand_code && c.brand_code.toLowerCase().includes(query)) ||
                            (c.description && c.description.toLowerCase().includes(query))
                        );
                    }
                    
                    cats.sort((a, b) => {
                        if (this.sortBy === 'name') {
                            return a.name.localeCompare(b.name);
                        } else if (this.sortBy === 'products') {
                            return b.product_count - a.product_count;
                        } else if (this.sortBy === 'sort_order') {
                            return a.sort_order - b.sort_order;
                        } else if (this.sortBy === 'newest') {
                            return b.id - a.id;
                        }
                        return 0;
                    });
                    
                    return cats;
                }
            }
        }
        
        function categoryManager() {
            return {
                showModal: false,
                modalMode: 'create',
                loading: false,
                categories: @json($categories).map(function(c) {
                    return Object.assign({}, c, { status: c.is_active });
                }),
                form: {
                    id: null,
                    name: '',
                    brand_code: '',
                    category_type: '',
                    input_type: 'user-id',
                    description: '',
                    icon: 'fas fa-tag',
                    sort_order: 0,
                    is_popular: false,
                    image: null
                },

                openModal(mode, categoryId = null) {
                    this.modalMode = mode;
                    this.showModal = true;

                    if (mode === 'create') {
                        this.resetForm();
                    }
                },

                closeModal() {
                    this.showModal = false;
                    this.resetForm();
                },

                resetForm() {
                    this.form = {
                        id: null,
                        name: '',
                        brand_code: '',
                        category_type: '',
                        input_type: 'user-id',
                        description: '',
                        icon: 'fas fa-tag',
                        sort_order: 0,
                        is_popular: false,
                        image: null
                    };
                },

                handleImageUpload(event) {
                    this.form.image = event.target.files[0];
                },

                async editCategory(id) {
                    try {
                        const response = await fetch(`/account/categories/${id}`);
                        const data = await response.json();

                        if (data.success) {
                            this.form = {
                                id: data.data.id,
                                name: data.data.name,
                                brand_code: data.data.brand_code || '',
                                category_type: data.data.category_type,
                                input_type: data.data.input_type || 'user-id',
                                description: data.data.description || '',
                                icon: data.data.icon || 'fas fa-tag',
                                sort_order: data.data.sort_order,
                                is_popular: Boolean(Number(data.data.is_popular)),
                                image: null
                            };
                            this.openModal('edit');
                        }
                    } catch (error) {
                        console.error('Edit error:', error);
                        alert('Error loading category data');
                    }
                },

                async submitForm() {
                    this.loading = true;

                    const formData = new FormData();
                    
                    formData.append('name', this.form.name);
                    formData.append('brand_code', this.form.brand_code || '');
                    formData.append('category_type', this.form.category_type);
                    formData.append('input_type', this.form.input_type || 'user-id');
                    formData.append('description', this.form.description || '');
                    formData.append('icon', this.form.icon || 'fas fa-tag');
                    formData.append('sort_order', this.form.sort_order || 0);
                    formData.append('is_popular', this.form.is_popular ? 1 : 0);

                    if (this.form.image) {
                        formData.append('image', this.form.image);
                    }

                    const url = this.modalMode === 'create' ?
                        '/account/categories' :
                        `/account/categories/${this.form.id}`;

                    if (this.modalMode === 'edit') {
                        formData.append('_method', 'PUT');
                    }

                    try {
                        const response = await fetch(url, {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                                'Accept': 'application/json'
                            },
                            body: formData
                        });

                        const contentType = response.headers.get("content-type");
                        if (!contentType || !contentType.includes("application/json")) {
                            const textError = await response.text();
                            console.error('Server returned non-JSON:', textError);
                            throw new Error('Server error (cek tab Network untuk detail)');
                        }

                        const data = await response.json();

                        if (data.success) {
                            alert(data.message);
                            window.location.reload();
                        } else {
                            let errorMsg = data.message || 'Terjadi kesalahan pada server';
                            if (data.errors) {
                                errorMsg = Object.values(data.errors).flat().join('\n');
                            }
                            alert('Error:\n' + errorMsg);
                            console.error('Submit error details:', data);
                        }
                    } catch (error) {
                        console.error('Submit exception:', error);
                        alert('Gagal mengirim data: ' + error.message);
                    } finally {
                        this.loading = false;
                    }
                },

                async deleteCategory(id, productCount) {
                    if (productCount > 0) {
                        alert(`❌ Cannot delete category with ${productCount} products!\n\nDelete products first.`);
                        return;
                    }

                    if (!confirm('⚠️ Are you sure you want to delete this category?\n\nThis action cannot be undone.')) {
                        return;
                    }

                    try {
                        const response = await fetch(`/account/categories/${id}`, {
                            method: 'DELETE',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                                'Content-Type': 'application/json'
                            }
                        });

                        const data = await response.json();

                        if (data.success) {
                            alert('✅ ' + data.message);
                            window.location.reload();
                        } else {
                            alert('❌ Error: ' + data.message);
                        }
                    } catch (error) {
                        alert('❌ Error deleting category');
                    }
                },

                async toggleStatus(id) {
                    try {
                        const response = await fetch(`/account/categories/${id}/toggle-status`, {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                                'Content-Type': 'application/json'
                            }
                        });

                        const data = await response.json();

                        if (data.success) {
                            const category = this.categories.find(c => c.id === id);
                            if (category) {
                                category.status = data.status;
                            }
                        }
                    } catch (error) {
                        alert('❌ Error updating status');
                    }
                }
            }
        }
    </script>
</body>

</html>