{{-- Ganti 'layouts.app' dengan nama file master layout Anda jika berbeda --}}
@extends('layouts.app')

@section('title', 'Space Casual Store - apparel second')

@section('content')
    <style>
        /* CSS Khusus Halaman Kategori Produk */
        .category-section {
            padding: 20px 0 80px 0;
            background-color: #ffffff;
        }

        /* Breadcrumb & Header */
        .breadcrumb-text {
            font-size: 14px;
            color: #6b7280;
            margin-bottom: 10px;
        }

        .breadcrumb-text a {
            color: #1f2937;
            text-decoration: none;
            font-weight: 500;
        }

        .page-title {
            font-size: 32px;
            font-weight: bold;
            color: #111827;
        }

        /* SIDEBAR FILTER */
        .filter-sidebar {
            background-color: #F0F1EC;
            padding: 24px 24px 125px 24px;
            border-radius: 16px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.03);
        }

        .filter-title {
            font-size: 16px;
            font-weight: 700;
            color: #000000;
            margin-bottom: 16px;
        }

        /* Range Slider Styling */
        .price-range {
            -webkit-appearance: none;
            width: 100%;
            height: 6px;
            background: linear-gradient(to right, #2D9CDB 100%, #000000 100%);
            border-radius: 6px;
            outline: none;
            margin-bottom: 12px;
        }

        .price-range::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            background: #2D9CDB;
            cursor: pointer;
        }

        .price-labels {
            display: flex;
            justify-content: space-between;
            font-size: 12px;
            font-weight: 600;
            color: #0F1C2E;
            margin-bottom: 20px;
        }

        .btn-apply {
            background-color: #0F1C2E;
            color: #FFFFFF;
            width: 100%;
            padding: 12px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 32px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 10px rgba(15, 28, 46, 0.25);
        }

        .btn-apply:hover {
            background-color: #000000;
            transform: translateY(-1px);
        }

        /* Size Buttons Grid */
        .size-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 12px;
        }

        .size-btn {
            background-color: #FFFFFF;
            border: none;
            padding: 10px 0;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 700;
            color: #000000;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s ease;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        }

        .size-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
            color: #2D9CDB;
        }

        .size-btn.active {
            background-color: #2D9CDB;
            color: #FFFFFF;
            transform: translateY(0);
            box-shadow: 0 2px 6px rgba(45, 156, 219, 0.4);
        }

        /* Product Cards */
        .product-card {
            background: #ffffff;
            border: 1px solid #e5e7eb;
            border-radius: 12px;
            overflow: hidden;
            transition: box-shadow 0.3s ease;
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        .product-card:hover {
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        }

        .product-img-wrap {
            position: relative;
            background-color: #f3f4f6;
            width: 100%;
            aspect-ratio: 1 / 1;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 24px;
            border-bottom: 1px solid #f3f4f6;
            overflow: hidden;
        }

        .product-img-wrap img {
            width: 100%;
            height: 100%;
            object-fit: contain;
            mix-blend-mode: multiply;
            transition: transform 0.3s ease;
        }

        .product-badge {
            position: absolute;
            top: 12px;
            left: 12px;
            padding: 4px 12px;
            border-radius: 999px;
            font-size: 11px;
            font-weight: 700;
            color: white;
            letter-spacing: 0.5px;
        }

        .badge-new {
            background-color: #27AE60;
        }

        .badge-second {
            background-color: #6C757D;
        }

        .product-body {
            padding: 16px;
            display: flex;
            flex-direction: column;
            flex-grow: 1;
        }

        .product-name {
            font-size: 16px;
            font-weight: 700;
            color: #111827;
            margin-bottom: 4px;
            line-height: 1.4;
        }

        .product-cat {
            font-size: 12px;
            color: #6b7280;
            margin-bottom: 8px;
        }

        .product-price {
            font-size: 16px;
            font-weight: 700;
            color: #FF7A00;
            margin-bottom: 16px;
        }

        .product-actions {
            display: flex;
            gap: 8px;
            margin-top: auto;
        }

        .btn-keranjang,
        .btn-detail {
            flex: 1;
            padding: 8px 0;
            border-radius: 6px;
            font-size: 12px;
            font-weight: 600;
            text-align: center;
            text-decoration: none;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            transition: all 0.2s;
        }

        .btn-keranjang {
            background-color: #2D9CDB;
            color: white;
            border: 1px solid #2D9CDB;
        }

        .btn-keranjang:hover {
            background-color: #0284c7;
            border-color: #0284c7;
            color: white;
        }

        .btn-detail {
            background-color: white;
            color: #374151;
            border: 1px solid #e5e7eb;
        }

        .btn-detail:hover {
            background-color: #f9fafb;
            color: #111827;
            border-color: #d1d5db;
        }

        /* --- EMPTY STATE --- */
        .empty-state-container {
            text-align: center;
            padding: 100px 20px;
            background-color: #ffffff;
            border-radius: 12px;
            border: 1px solid #e5e7eb;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.02);
        }

        .empty-icon {
            font-size: 64px;
            color: #d1d5db;
            margin-bottom: 20px;
            display: inline-block;
        }

        .empty-title {
            font-size: 20px;
            font-weight: 700;
            color: #111827;
            margin-bottom: 8px;
        }

        .empty-desc {
            font-size: 14px;
            color: #6b7280;
            margin-bottom: 28px;
            max-width: 400px;
            margin-left: auto;
            margin-right: auto;
            line-height: 1.6;
        }

        .btn-reset {
            background-color: #ffffff;
            color: #111827;
            border: 1px solid #111827;
            padding: 10px 28px;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-reset:hover {
            background-color: #111827;
            color: #ffffff;
        }

        /* ==========================================
               MODAL KERANJANG BELANJA (DETAIL PRODUK)
               ========================================== */
        .cart-modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(0, 0, 0, 0.4);
            z-index: 9998;
            opacity: 0;
            visibility: hidden;
            display: flex;
            align-items: flex-end;
            justify-content: center;
            transition: opacity 0.3s ease;
        }

        .cart-modal-content {
            background: #ffffff;
            width: 100%;
            max-width: 100%;
            border-radius: 0px;
            padding: 90px 10% 40px 10%;
            position: relative;
            transform: translateY(100%);
            transition: transform 0.4s ease-out;
            max-height: 90vh;
            overflow-y: auto;
        }

        .cart-modal-overlay.show {
            opacity: 1;
            visibility: visible;
        }

        .cart-modal-overlay.show .cart-modal-content {
            transform: translateY(0);
        }

        .cart-modal-title {
            position: absolute;
            top: 32px;
            left: 3%;
            font-weight: 800;
            color: #0F1C2E;
            margin: 0;
            font-size: 24px;
            line-height: 1;
        }

        .btn-close-modal {
            position: absolute;
            top: 24px;
            right: 3%;
            background-color: #FF0000;
            color: white;
            border: none;
            border-radius: 6px;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            padding: 0;
        }

        .btn-close-modal i {
            font-size: 20px;
            line-height: 0;
        }

        /* Kotak Abu-abu Detail Produk */
        .cart-grey-box {
            background-color: #E6E8EB;
            border-radius: 12px;
            padding: 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 20px;
        }

        .cart-product-left {
            display: flex;
            align-items: center;
            gap: 24px;
        }

        .cart-img-wrapper {
            background: #ffffff;
            border-radius: 8px;
            width: 140px;
            height: 140px;
            padding: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .cart-img-wrapper img {
            border-radius: 8px;
            width: 140px;
            height: 140px;
            object-fit: contain;
        }

        .cart-modal-name {
            font-size: 20px;
            font-weight: 800;
            color: #000000;
            margin-bottom: 4px;
        }

        .cart-modal-price {
            font-size: 18px;
            font-weight: 800;
            color: #F59E0B;
        }

        .cart-size-label {
            font-size: 14px;
            color: #6B7280;
            margin-bottom: 12px;
        }

        /* GRID UKURAN (4 KOLOM) */
        .cart-modal-sizes {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 12px;
            width: 300px;
        }

        .cart-modal-size-btn {
            background-color: #ffffff;
            border: none;
            border-radius: 6px;
            padding: 10px 0;
            font-size: 14px;
            font-weight: 700;
            color: #000000;
            cursor: pointer;
            text-align: center;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            transition: all 0.2s;
        }

        .cart-modal-size-btn.selected {
            background-color: #2D9CDB;
            color: white;
        }

        /* Quantity Selector & Peringatan Stok */
        .cart-qty-wrapper {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 12px;
            margin: 32px 0 24px 0;
            position: relative;
        }

        .btn-qty {
            background: #ffffff;
            border: 1px solid #D1D5DB;
            border-radius: 6px;
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 16px;
            color: #374151;
        }

        .input-qty {
            width: 36px;
            text-align: center;
            border: none;
            background: transparent;
            font-weight: 700;
            font-size: 16px;
            color: #000;
            pointer-events: none;
        }

        .qty-warning {
            color: #FF0000;
            font-size: 13px;
            font-weight: 600;
            margin-left: 12px;
            position: absolute;
            left: 55%;
            white-space: nowrap;
        }

        .btn-submit-cart {
            background-color: #38bdf8;
            color: #ffffff;
            border: none;
            border-radius: 8px;
            width: 100%;
            padding: 14px;
            font-size: 16px;
            font-weight: 700;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: all 0.3s;
        }

        .btn-submit-cart:hover {
            background-color: #0284c7;
        }

        /* ==========================================
               POP-UP KERANJANG SUKSES (HIJAU)
               ========================================== */
        .cart-popup-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(0, 0, 0, 0.4);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }

        .cart-popup-overlay.show {
            opacity: 1;
            visibility: visible;
        }

        .cart-popup-content {
            background-color: #2CA759;
            width: 400px;
            max-width: 90%;
            height: 300px;
            border-radius: 16px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: #ffffff;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
            transform: scale(0.8);
            transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        }

        .cart-popup-overlay.show .cart-popup-content {
            transform: scale(1);
        }

        .cart-popup-icon {
            font-size: 110px;
            margin-bottom: 20px;
            line-height: 1;
        }

        .cart-popup-icon i::before {
            font-weight: bold !important;
        }

        .cart-popup-text {
            font-size: 18px;
            font-weight: 700;
            text-align: center;
            padding: 0 20px;
            letter-spacing: 0.5px;
        }

        /* ==========================================
                   MEDIA QUERIES (UNTUK RESPONSIVE HP)
                   ========================================== */
        @media (max-width: 768px) {
            .page-title {
                font-size: 24px;
                margin-bottom: 12px;
            }

            .filter-sidebar {
                margin-bottom: 24px;
            }

            .product-img-wrap {
                padding: 16px;
            }

            .product-body {
                padding: 12px;
            }

            .product-name {
                font-size: 14px;
            }

            .product-price {
                font-size: 14px;
            }

            .product-actions {
                flex-direction: column;
                gap: 6px;
            }

            .btn-keranjang,
            .btn-detail {
                width: 100%;
                padding: 6px 0;
                font-size: 11px;
            }

            /* Modal Keranjang Responsif HP */
            .cart-modal-title {
                left: 16px;
                font-size: 20px;
            }

            .btn-close-modal {
                right: 16px;
            }

            .cart-modal-content {
                padding: 80px 16px 24px 16px;
            }

            .cart-grey-box {
                flex-direction: column;
                align-items: flex-start;
            }

            .cart-modal-sizes {
                width: 100%;
            }

            .qty-warning {
                position: static;
                margin-left: 8px;
            }
        }
    </style>

    <section class="category-section">
        <div class="container">
            {{-- Header & Breadcrumb --}}
            <div class="row mb-4 align-items-end">
                <div class="col-md-8">
                    <div class="breadcrumb-text">
                        <a href="/">Beranda</a> / Apparel Second
                    </div>
                    <h1 class="page-title">Apparel Second</h1>
                </div>
                <div class="col-md-4 text-md-end mt-3 mt-md-0">
                    <select id="sortFilter" class="form-select form-select-sm d-inline-block w-auto"
                        style="min-width: 150px;">
                        <option value="terbaru">Terbaru </option>
                        <option value="termahal">Harga: Tinggi ke Rendah</option>
                        <option value="termurah">Harga: Rendah ke Tinggi</option>
                    </select>
                </div>
            </div>

            <div class="row">
                {{-- Sidebar Kiri - Filter --}}
                <div class="col-12 col-lg-3 col-md-4 mb-4">
                    <div class="filter-sidebar">
                        <div class="filter-title">Filter Harga</div>
                        <input type="range" id="priceRange" class="price-range" min="0" max="4000000" value="4000000"
                            step="50000">
                        <div class="price-labels">
                            <span>Rp 0</span>
                            <span id="maxPriceLabel">Rp 4.000.000</span>
                        </div>
                        <button id="btnApplyPrice" class="btn-apply">Terapkan</button>

                        <div class="filter-title">Ukuran</div>
                        <div class="size-grid">
                            <button class="size-btn" data-size="xs">Xs</button>
                            <button class="size-btn" data-size="s">S</button>
                            <button class="size-btn" data-size="m">M</button>
                            <button class="size-btn" data-size="l">L</button>
                            <button class="size-btn" data-size="xl">Xl</button>
                            <button class="size-btn" data-size="xxl">Xxl</button>
                            <button class="size-btn" data-size="3xl">3xl</button>
                            <button class="size-btn" data-size="14">14</button>
                        </div>
                    </div>
                </div>

                {{-- Konten Kanan - Grid Produk --}}
                <div class="col-12 col-lg-9 col-md-8">

                    {{-- 1. PESAN JIKA BERHASIL MENEMUKAN PRODUK --}}
                    @if(request()->filled('q') && count($products) > 0)
                        <div class="alert alert-info d-flex justify-content-between align-items-center mb-4 shadow-sm border-0"
                            style="background-color: #e3f2fd; color: #0F1C2E; border-radius: 8px;">
                            <div>
                                <i class="bi bi-check-circle-fill me-2"></i> Berhasil menampilkan produk untuk:
                                <strong>"{{ request('q') }}"</strong>
                            </div>
                            <a href="{{ url()->current() }}" class="btn btn-sm btn-danger fw-bold text-white px-3">
                                <i class="bi bi-x-lg me-1"></i> Reset
                            </a>
                        </div>
                    @endif

                    <div class="row" id="product-container">
                        @foreach($products as $index => $product)
                            @php
                                $cleanPrice = (int) str_replace('.', '', $product['price']);
                                $sizesString = strtolower(implode(',', $product['sizes'] ?? []));
                            @endphp

                            <div class="col-6 col-md-6 col-lg-4 mb-4 product-item" data-price="{{ $cleanPrice }}"
                                data-index="{{ $index }}" data-sizes="{{ $sizesString }}"
                                data-stock="{{ $product['stock'] ?? 1 }}">

                                <div class="product-card">
                                    <div class="product-img-wrap">
                                        @php
                                            $gambarUtama = is_array($product['image']) ? $product['image'][0] : $product['image'];
                                        @endphp

                                        <img src="{{ asset('images/' . $gambarUtama) }}" alt="{{ $product['name'] }}"
                                            loading="lazy"
                                            onerror="this.src='https://placehold.co/300x300/F3F4F6/9CA3AF?text=Img'">

                                        <span class="product-badge {{ $product['badge_class'] ?? 'badge-new' }}">
                                            {{ $product['status'] ?? 'NEW' }}
                                        </span>
                                    </div>
                                    <div class="product-body">
                                        <div class="product-name">{{ $product['name'] }}</div>
                                        <div class="product-cat">{{ $product['category'] }} •
                                            {{ ucfirst(strtolower($product['status'])) }}
                                        </div>
                                        <div class="product-price">Rp. {{ $product['price'] }}</div>

                                        <div class="product-actions">
                                            <a href="#" class="btn-keranjang">
                                                <i class="bi bi-cart2"></i> Keranjang
                                            </a>
                                            @php
                                                $slugKategori = Str::slug($product['category']);
                                            @endphp

                                            <a href="{{ url('/beranda/' . $slugKategori . '/' . $product['name']) }}"
                                                class="btn-detail">
                                                <i class="bi bi-eye"></i> Detail
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>

                    {{-- 2. PESAN JIKA PRODUK TIDAK DITEMUKAN (SEARCH KOSONG) --}}
                    <div id="empty-state" class="empty-state-container"
                        style="{{ count($products) == 0 ? 'display: block;' : 'display: none;' }}">
                        <i class="bi bi-search empty-icon"></i>
                        <h4 class="empty-title">Produk Tidak Ditemukan</h4>
                        <p class="empty-desc">
                            @if(request()->filled('q'))
                                Maaf, kami tidak dapat menemukan produk dengan kata kunci <strong>"{{ request('q') }}"</strong>.
                            @else
                                Maaf, kami tidak dapat menemukan produk yang sesuai dengan rentang harga atau ukuran yang Anda
                                pilih.
                            @endif
                        </p>
                        <a href="{{ url()->current() }}" class="btn-reset text-decoration-none d-inline-block">
                            <i class="bi bi-arrow-counterclockwise"></i> Reset Filter
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </section>

    {{-- HTML MODAL KERANJANG BELANJA (DETAIL) --}}
    <div id="cartModalOverlay" class="cart-modal-overlay">
        <div class="cart-modal-content">

            <h4 class="cart-modal-title">Keranjang Belanja</h4>
            <button id="closeCartModal" class="btn-close-modal">
                <i class="bi bi-x-lg"></i>
            </button>

            <div class="cart-grey-box">
                <div class="cart-product-left">
                    <div class="cart-img-wrapper">
                        <img id="modalImg" src="" alt="Product">
                    </div>
                    <div class="cart-text-wrapper">
                        <div id="modalTitle" class="cart-modal-name">Nama Produk</div>
                        <div id="modalPrice" class="cart-modal-price">Rp. 0</div>
                    </div>
                </div>
                <div class="cart-product-right">
                    <div class="cart-size-label">Ukuran:</div>
                    <div id="modalSizes" class="cart-modal-sizes">
                        {{-- Tombol ukuran di-generate otomatis --}}
                    </div>
                </div>
            </div>

            <div class="cart-qty-wrapper">
                <button id="qtyMinus" class="btn-qty"><i class="bi bi-dash"></i></button>
                <input id="qtyInput" type="text" value="1" readonly class="input-qty">
                <button id="qtyPlus" class="btn-qty"><i class="bi bi-plus"></i></button>
                <span id="qtyWarning" class="qty-warning" style="display: none;">Stok maksimum tercapai!</span>
            </div>

            <button class="btn-submit-cart">
                <i class="bi bi-cart2"></i> Keranjang
            </button>
        </div>
    </div>

    {{-- POP-UP KERANJANG SUKSES (HIJAU) --}}
    <div id="cartPopup" class="cart-popup-overlay">
        <div class="cart-popup-content">
            <div class="cart-popup-icon">
                <i class="bi bi-check-circle"></i>
            </div>
            <div class="cart-popup-text">Produk Ditambahkan Ke Keranjang!</div>
        </div>
    </div>

    {{-- POP-UP PERINGATAN (ORANYE) --}}
    <div id="warningPopup" class="cart-popup-overlay">
        <div class="cart-popup-content" style="background-color: #ffffff;"> 
            <div class="cart-popup-icon" style="color: #FF7A00;">
                <i class="bi bi-exclamation-triangle"></i>
            </div>
            <div class="cart-popup-text" style="color: #000000;" id="warningPopupText">Silakan pilih ukuran terlebih dahulu!</div>
        </div>
    </div>

    {{-- SCRIPT JAVASCRIPT GABUNGAN --}}
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const sortFilter = document.getElementById('sortFilter');
            const productContainer = document.getElementById('product-container');
            const sizeButtons = document.querySelectorAll('.size-btn');

            // Elemen Filter Harga
            const priceRange = document.getElementById('priceRange');
            const maxPriceLabel = document.getElementById('maxPriceLabel');
            const btnApplyPrice = document.getElementById('btnApplyPrice');

            // Elemen Empty State
            const emptyState = document.getElementById('empty-state');
            const btnResetFilter = document.getElementById('btnResetFilter');

            // Ambil semua elemen produk 
            let productsArray = Array.from(productContainer ? productContainer.getElementsByClassName('product-item') : []);
            let activeSize = null;
            let currentMaxPrice = priceRange ? parseInt(priceRange.value) : 4000000;

            // --- 1. EVENT LISTENER FILTER UKURAN ---
            sizeButtons.forEach(button => {
                button.addEventListener('click', function () {
                    const selectedSize = this.getAttribute('data-size');
                    if (activeSize === selectedSize) {
                        activeSize = null;
                        this.classList.remove('active');
                    } else {
                        sizeButtons.forEach(btn => btn.classList.remove('active'));
                        activeSize = selectedSize;
                        this.classList.add('active');
                    }
                    applyFiltersAndSort();
                });
            });

            // --- 2. EVENT LISTENER SORTING HARGA ---
            if (sortFilter) {
                sortFilter.addEventListener('change', applyFiltersAndSort);
            }

            // --- 3. EVENT LISTENER RANGE SLIDER HARGA ---
            if (priceRange) {
                priceRange.addEventListener('input', function () {
                    let value = parseInt(this.value);
                    if (maxPriceLabel) maxPriceLabel.innerHTML = 'Rp ' + value.toLocaleString('id-ID');
                    let max = 4000000;
                    let percentage = (value / max) * 100;
                    this.style.background = `linear-gradient(to right, #2D9CDB ${percentage}%, #000000 ${percentage}%)`;
                });
            }

            if (btnApplyPrice) {
                btnApplyPrice.addEventListener('click', function () {
                    currentMaxPrice = parseInt(priceRange.value);
                    applyFiltersAndSort();
                });
            }

            // --- 4. RESET FILTER BUTTON ---
            if (btnResetFilter) {
                btnResetFilter.addEventListener('click', function () {
                    if (priceRange) {
                        priceRange.value = 4000000;
                        priceRange.style.background = `linear-gradient(to right, #2D9CDB 100%, #000000 100%)`;
                    }
                    currentMaxPrice = 4000000;
                    if (maxPriceLabel) maxPriceLabel.innerHTML = 'Rp 4.000.000';
                    activeSize = null;
                    sizeButtons.forEach(btn => btn.classList.remove('active'));
                    if (sortFilter) sortFilter.value = 'terbaru';
                    applyFiltersAndSort();
                });
            }

            // --- 5. FUNGSI UTAMA ---
            function applyFiltersAndSort() {
                if (!productContainer) return;

                const sortValue = sortFilter ? sortFilter.value : 'terbaru';
                let visibleProductCount = 0;

                productsArray.sort(function (a, b) {
                    let priceA = parseInt(a.getAttribute('data-price'));
                    let priceB = parseInt(b.getAttribute('data-price'));
                    let indexA = parseInt(a.getAttribute('data-index'));
                    let indexB = parseInt(b.getAttribute('data-index'));

                    if (sortValue === 'termurah') return priceA - priceB;
                    if (sortValue === 'termahal') return priceB - priceA;
                    return indexA - indexB;
                });

                productsArray.forEach(function (product) {
                    productContainer.appendChild(product);

                    const productPrice = parseInt(product.getAttribute('data-price'));
                    const sizesAttr = product.getAttribute('data-sizes');
                    const productSizes = sizesAttr ? sizesAttr.split(',') : [];

                    const isSizeMatch = !activeSize || productSizes.includes(activeSize);
                    const isPriceMatch = productPrice <= currentMaxPrice;

                    if (isSizeMatch && isPriceMatch) {
                        product.style.display = 'block';
                        visibleProductCount++;
                    } else {
                        product.style.display = 'none';
                    }
                });

                if (emptyState) {
                    if (visibleProductCount === 0) {
                        emptyState.style.display = 'block';
                    } else {
                        emptyState.style.display = 'none';
                    }
                }
            }

            // --- 6. EVENT LISTENER MODAL KERANJANG BELANJA (DETAIL) ---
            const cartButtons = document.querySelectorAll('.btn-keranjang');
            const cartModalOverlay = document.getElementById('cartModalOverlay');
            const closeCartModal = document.getElementById('closeCartModal');

            const modalImg = document.getElementById('modalImg');
            const modalTitle = document.getElementById('modalTitle');
            const modalPrice = document.getElementById('modalPrice');
            const modalSizes = document.getElementById('modalSizes');
            const qtyInput = document.getElementById('qtyInput');
            const qtyMinus = document.getElementById('qtyMinus');
            const qtyPlus = document.getElementById('qtyPlus');
            const qtyWarning = document.getElementById('qtyWarning');

            let currentMaxStock = 1;

            cartButtons.forEach(button => {
                button.addEventListener('click', e => e.preventDefault());

                button.addEventListener('mouseup', function (e) {
                    e.preventDefault();

                    const productCard = this.closest('.product-item') || this.closest('.product-card'); // Support 2 layout
                    const name = productCard.querySelector('.product-name').innerText;
                    const price = productCard.querySelector('.product-price').innerText;
                    const imgSrc = productCard.querySelector('img').src;
                    const sizesData = productCard.getAttribute('data-sizes') || this.getAttribute('data-sizes');
                    const stockData = productCard.getAttribute('data-stock') || this.getAttribute('data-stock');

                    currentMaxStock = stockData ? parseInt(stockData) : 10;

                    modalTitle.innerText = name;
                    modalPrice.innerText = price;
                    modalImg.src = imgSrc;

                    // DIMULAI DARI 0
                    qtyInput.value = 0;
                    qtyWarning.style.display = 'none';

                    modalSizes.innerHTML = '';
                    
                    // Parsing array string dari JSON (untuk welcome blade) atau koma (untuk halaman kategori)
                    let sizesArray = [];
                    if (sizesData && sizesData.trim() !== '') {
                        try {
                            sizesArray = JSON.parse(sizesData); // Coba parse JSON dulu
                        } catch (e) {
                            sizesArray = sizesData.split(','); // Kalau gagal, split koma
                        }
                    }

                    if (sizesArray && sizesArray.length > 0) {
                        sizesArray.forEach(size => {
                            const formattedSize = size.charAt(0).toUpperCase() + size.slice(1);
                            const sizeBtn = document.createElement('button');
                            sizeBtn.className = 'cart-modal-size-btn';
                            sizeBtn.innerText = formattedSize;

                            sizeBtn.addEventListener('click', function () {
                                document.querySelectorAll('.cart-modal-size-btn').forEach(b => b.classList.remove('selected'));
                                this.classList.add('selected');
                            });

                            modalSizes.appendChild(sizeBtn);
                        });
                    } else {
                        modalSizes.innerHTML = '<span class="text-muted" style="font-size: 14px;">Satu Ukuran</span>';
                    }

                    setTimeout(() => {
                        if (cartModalOverlay) cartModalOverlay.classList.add('show');
                    }, 1);
                });
            });

            // Tutup Modal
            if (closeCartModal) {
                closeCartModal.addEventListener('click', () => {
                    cartModalOverlay.classList.remove('show');
                });
            }

            if (cartModalOverlay) {
                cartModalOverlay.addEventListener('click', (e) => {
                    if (e.target === cartModalOverlay) {
                        cartModalOverlay.classList.remove('show');
                    }
                });
            }

            // Qty Control (BISA MINUS SAMPAI 0)
            if (qtyMinus) {
                qtyMinus.addEventListener('click', () => {
                    let currentVal = parseInt(qtyInput.value);
                    if (currentVal > 0) {
                        qtyInput.value = currentVal - 1;
                    }
                    if (qtyWarning) qtyWarning.style.display = 'none';
                });
            }

            if (qtyPlus) {
                qtyPlus.addEventListener('click', () => {
                    let currentVal = parseInt(qtyInput.value);
                    if (currentVal < currentMaxStock) {
                        qtyInput.value = currentVal + 1;
                        if (qtyWarning) qtyWarning.style.display = 'none';
                    } else {
                        if (qtyWarning) qtyWarning.style.display = 'block';
                    }
                });
            }

            // --- 7. EVENT LISTENER SUBMIT KERANJANG ---
            const btnSubmitCart = document.querySelector('.btn-submit-cart');
            const cartPopup = document.getElementById('cartPopup');
            const warningPopup = document.getElementById('warningPopup');
            const warningPopupText = document.getElementById('warningPopupText');

            if (btnSubmitCart) {
                btnSubmitCart.addEventListener('click', function (e) {
                    e.preventDefault();

                    // === VALIDASI 1: CEK UKURAN ===
                    const checkSizeBtnExists = document.querySelector('.cart-modal-size-btn');
                    const selectedSizeBtn = document.querySelector('.cart-modal-size-btn.selected');

                    if (checkSizeBtnExists && !selectedSizeBtn) {
                        if (warningPopupText) warningPopupText.innerText = 'Silakan pilih ukuran terlebih dahulu!';
                        if (warningPopup) warningPopup.classList.add('show');
                        setTimeout(() => {
                            if (warningPopup) warningPopup.classList.remove('show');
                        }, 2500);
                        return; // Hentikan proses
                    }

                    // === VALIDASI 2: CEK JUMLAH/QTY ===
                    const qty = parseInt(document.getElementById('qtyInput').value);
                    if (qty === 0) {
                        if (warningPopupText) warningPopupText.innerText = 'Jumlah produk tidak boleh 0!';
                        if (warningPopup) warningPopup.classList.add('show');
                        setTimeout(() => {
                            if (warningPopup) warningPopup.classList.remove('show');
                        }, 2500);
                        return; // Hentikan proses
                    }

                    // 1. Ambil data dari modal detail
                    const name = document.getElementById('modalTitle').innerText;
                    const imgSrc = document.getElementById('modalImg').src;
                    const size = selectedSizeBtn ? selectedSizeBtn.innerText : 'Satu Ukuran';
                    const priceString = document.getElementById('modalPrice').innerText;
                    const cleanPrice = parseInt(priceString.replace(/[^0-9]/g, ''));

                    // 2. Buat objek produk
                    const productToCart = { name, imgSrc, size, cleanPrice, qty };

                    // 3. Simpan ke LocalStorage
                    let cart = JSON.parse(localStorage.getItem('spaceCasualCart')) || [];
                    const existingIndex = cart.findIndex(item => item.name === name && item.size === size);
                    
                    if (existingIndex !== -1) {
                        cart[existingIndex].qty += qty;
                    } else {
                        cart.push(productToCart);
                    }
                    localStorage.setItem('spaceCasualCart', JSON.stringify(cart));

                    // 4. Tutup Modal Detail Produk
                    if (cartModalOverlay) cartModalOverlay.classList.remove('show');

                    // 5. Update Badge/Keranjang Global
                    if (typeof window.renderCart === 'function') {
                        window.renderCart();
                    }

                    // 6. Munculkan Pop-up Hijau
                    if (cartPopup) cartPopup.classList.add('show');
                    setTimeout(() => {
                        if (cartPopup) cartPopup.classList.remove('show');
                    }, 2000);
                });
            }
        });
    </script>
@endsection