@extends('layouts.app')

@section('title', 'Space Casual Store - Beranda')

<style>
    .cart-modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        background: rgba(0, 0, 0, 0.4);
        z-index: 9998;
        /* Lebih rendah dari success pop-up */
        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: #FF7A00;
    }

    .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;
        /* Paling atas */
        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;
    }
</style>
{{-- ================================================================
KONTEN UTAMA BERANDA
================================================================ --}}
@section('content')

    {{-- ================================================================
    HERO CAROUSEL
    ================================================================ --}}
    <div id="heroCarousel" class="carousel slide hero-carousel">

        {{-- Indicators / Dots --}}
        <div class="carousel-indicators">
            <button type="button" data-bs-target="#heroCarousel" data-bs-slide-to="0" class="active"></button>
            <button type="button" data-bs-target="#heroCarousel" data-bs-slide-to="1"></button>
            <button type="button" data-bs-target="#heroCarousel" data-bs-slide-to="2"></button>
            <button type="button" data-bs-target="#heroCarousel" data-bs-slide-to="3"></button>
        </div>

        <div class="carousel-inner">

            {{-- Slide 1 --}}
            <div class="carousel-item active">
                <img src="{{ asset('images/slide 1.png') }}" class="d-block w-100" alt="Hero 1">
                <div class="carousel-caption-custom">
                    <h2>keep it casual, keep it real</h2>
                    <p>selected footwear & apparel</p>
                </div>
            </div>

            {{-- Slide 2 --}}
            <div class="carousel-item">
                <img src="{{ asset('images/slide 2.png') }}" class="d-block w-100" alt="Hero 2">
                <div class="carousel-caption-custom caption-center">
                    <h2>keep it casual, keep it real</h2>
                    <p>selected footwear & apparel</p>
                </div>
            </div>

            {{-- Slide 3 --}}
            <div class="carousel-item">
                <img src="{{ asset('images/slide 3.png') }}" class="d-block w-100" alt="Hero 3">
                <div class="carousel-caption-custom">
                    <h2>keep it casual, keep it real</h2>
                    <p>selected footwear & apparel</p>
                </div>
            </div>

            {{-- Slide 4 --}}
            <div class="carousel-item">
                <img src="{{ asset('images/slide 4.png') }}" class="d-block w-100" alt="Hero 4">
                <div class="carousel-caption-custom caption-center">
                    <h2>keep it casual, keep it real</h2>
                    <p>selected footwear & apparel</p>
                </div>
            </div>

        </div>
    </div>


    {{-- ================================================================
    KATEGORI PRODUK
    ================================================================ --}}
    <section class="kategori-section">
        <div class="container">
            <h2 class="section-title-center">Kategori Produk</h2>

            <div class="row g-3 justify-content-center">

                {{-- Apparel New --}}
                <div class="col-6 col-md-3">
                    <div class="kategori-card">
                        <span class="badge-status badge-new">NEW</span>
                        <i class="fa-solid fa-shirt icon-wrap" style="color: #3ba1eb;"></i>
                        <h6>Apparel New</h6>
                        <p>Produk Baru Dengan Kualitas Terbaik</p>
                    </div>
                </div>

                {{-- Apparel Second --}}
                <div class="col-6 col-md-3">
                    <div class="kategori-card">
                        <span class="badge-status badge-second">SECOND</span>
                        <i class="bi bi-recycle icon-wrap" style="color: #3ba1eb;"></i>
                        <h6>Apparel Second</h6>
                        <p>Berkualitas Dengan Harga Lebih Terjangkau</p>
                    </div>
                </div>

                {{-- Footwear New --}}
                <div class="col-6 col-md-3">
                    <div class="kategori-card">
                        <span class="badge-status badge-new">NEW</span>
                        <i class="fa-solid fa-shoe-prints icon-wrap" style="color: #3ba1eb;"></i>
                        <h6>Footwear New</h6>
                        <p>Sepatu Baru Trending</p>
                    </div>
                </div>

                {{-- Footwear Second --}}
                <div class="col-6 col-md-3">
                    <div class="kategori-card">
                        <span class="badge-status badge-second">SECOND</span>
                        <i class="fa-solid fa-person-walking icon-wrap" style="color: #3ba1eb;"></i>
                        <h6>Footwear Second</h6>
                        <p>Sepatu Bekas Kualitas Premium</p>
                    </div>
                </div>

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


    {{-- ================================================================
    PRODUK TERBARU
    ================================================================ --}}
    <section class="produk-section pb-5">
        <div class="container">
            <h2 class="section-title mb-4">Produk Terbaru</h2>

            <div class="row g-3">

                @forelse($latestProducts as $product)
                    @php
                        // Amankan gambar agar tidak error jika format bukan array
                        $gambarUtama = is_array($product['image']) ? $product['image'][0] : $product['image'];
                        // Amankan data ukuran agar bisa dibaca oleh JS Modal nanti
                        $ukuranJson = isset($product['sizes']) ? json_encode($product['sizes']) : '[]';
                        $stok = $product['stock'] ?? 10;
                    @endphp

                    <div class="col-6 col-md-3 mb-4">
                        <div class="product-card">
                            <div class="product-img-wrap">
                                <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'] ?? '' }}">
                                    {{ $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">
                                    {{-- ⬇️ Tombol ini membawa data spesifik produk untuk dilempar ke Modal --}}
                                    <a href="#" class="btn-keranjang" data-name="{{ $product['name'] }}"
                                        data-price="{{ $product['price'] }}" data-image="{{ asset('images/' . $gambarUtama) }}"
                                        data-sizes="{{ $ukuranJson }}" data-stock="{{ $stok }}">
                                        <i class="bi bi-cart2"></i> Keranjang
                                    </a>

                                    @php
                                        // Kita buat slug kategori, misal 'Footwear Second' jadi 'footwear-second'
                                        $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>
                @empty
                    <div class="col-12 text-center py-5">
                        <p class="text-muted">Belum ada produk terbaru saat ini.</p>
                    </div>
                @endforelse

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

    {{-- ================================================================
    MODAL KERANJANG BELANJA (KODE ANDA)
    ================================================================ --}}
    <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 oleh JS --}}
                    </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; color: red; font-size: 12px; margin-left: 10px;">Stok maksimum tercapai!</span>
            </div>

            <button class="btn-submit-cart" style="width: 100%; border-radius: 8px;">
                <i class="bi bi-cart2"></i> Keranjang
            </button>
        </div>
    </div>

    {{-- ================================================================
    POP-UP KERANJANG SUKSES HIJAU (KODE ANDA)
    ================================================================ --}}
    <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>


    {{-- ================================================================
    SHOES TREATMENT
    ================================================================ --}}
    <section class="treatment-section">
        <div class="container">

            <div class="treatment-header">
                <h2 class="section-title mb-0">Shoes Treatment</h2>
                <a href="#" id="openMenuPopUp">Lihat Daftar Menu →</a>
            </div>

            <div id="menuModalOverlay" class="modal-menu-overlay">
                <div class="modal-menu-content">
                    <button id="closeMenuPopUp" class="modal-menu-close">&times;</button>
                    <div class="modal-menu-body">
                        <img src="{{ asset('images/daftar menu.png') }}" alt="Daftar Menu Shoes Treatment">
                    </div>
                </div>
            </div>

            <div class="row g-3">

                <div class="col-6 col-md-3">
                    <div class="treatment-card">
                        <div class="treatment-icon"><i class="bi bi-person-check-fill"></i></div>
                        <h6>Ditangani Oleh Ahli</h6>
                        <p>Berpengalaman Lebih Dari 10 Tahun Di Industri Jasa Cuci Sepatu.</p>
                    </div>
                </div>

                <div class="col-6 col-md-3">
                    <div class="treatment-card">
                        <div class="treatment-icon"><i class="bi bi-box-seam-fill"></i></div>
                        <h6>Gratis Jemput & Antar</h6>
                        <p>Layanan Antar Jemput Gratis Hingga 5 KM Dari Lokasi Kamu.</p>
                    </div>
                </div>

                <div class="col-6 col-md-3">
                    <div class="treatment-card">
                        <div class="treatment-icon"><i class="bi bi-star-fill"></i></div>
                        <h6>Peralatan Premium</h6>
                        <p>Sabun Premium Dan Sikat Khusus Yang Aman Untuk Semua Jenis Material Sepatu.</p>
                    </div>
                </div>

                <div class="col-6 col-md-3">
                    <div class="treatment-card">
                        <div class="treatment-icon"><i class="bi bi-search-heart-fill"></i></div>
                        <h6>Detail Dan Higienis</h6>
                        <p>Cuci Menyeluruh Hingga Bagian Dalam, Lengkap Dengan Penghilang Bau Dan Bakteri.</p>
                    </div>
                </div>

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

@endsection


{{-- ================================================================
SCRIPTS KHUSUS HALAMAN BERANDA
================================================================ --}}
@push('scripts')
    <script>
        document.addEventListener("DOMContentLoaded", function () {

            // --- Hero Carousel ---
            const heroCarouselElement = document.getElementById('heroCarousel');
            if (heroCarouselElement) {
                new bootstrap.Carousel(heroCarouselElement, {
                    interval: 4000,
                    ride: 'carousel',
                    pause: false,
                    wrap: true
                });
            }

            // --- Modal Daftar Menu Shoes Treatment ---
            const modalOverlay = document.getElementById('menuModalOverlay');
            const btnOpen = document.getElementById('openMenuPopUp');
            const btnClose = document.getElementById('closeMenuPopUp');

            function openModal() {
                modalOverlay.classList.add('active');
                document.body.style.overflow = 'hidden';
            }

            function closeModal() {
                modalOverlay.classList.remove('active');
                document.body.style.overflow = '';
            }

            if (btnOpen) btnOpen.addEventListener('click', function (e) { e.preventDefault(); openModal(); });
            if (btnClose) btnClose.addEventListener('click', closeModal);

            modalOverlay.addEventListener('click', function (e) {
                if (e.target === modalOverlay) closeModal();
            });

            document.addEventListener('keydown', function (e) {
                if (e.key === 'Escape' && modalOverlay.classList.contains('active')) closeModal();
            });

        });

        // ================================================================
        // ALGORITMA KERANJANG (MODAL -> LOCALSTORAGE -> POP-UP)
        // ================================================================

        // Elemen Modal
        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');
        const btnSubmitCart = document.querySelector('.btn-submit-cart');
        const cartPopup = document.getElementById('cartPopup');

        let currentMaxStock = 10;

        // 1 & 2. TANGKAP KLIK TOMBOL & BUKA MODAL
        document.querySelectorAll('.btn-keranjang').forEach(btn => {
            btn.addEventListener('click', function (e) {
                e.preventDefault();

                // Ambil data
                const name = this.dataset.name;
                const price = this.dataset.price;
                const image = this.dataset.image;
                const sizes = JSON.parse(this.dataset.sizes);
                currentMaxStock = parseInt(this.dataset.stock) || 10;

                // Suntik ke HTML Modal
                modalTitle.innerText = name;
                modalPrice.innerText = 'Rp. ' + price;
                modalImg.src = image;
                
                // [UBAHAN] Mulai dari 0 saat modal pertama kali dibuka
                qtyInput.value = 0; 
                qtyWarning.style.display = 'none';

                // Bikin Tombol Ukuran Dinamis
                modalSizes.innerHTML = '';
                if (sizes && sizes.length > 0) {
                    sizes.forEach(size => {
                        const btnSize = document.createElement('button');
                        btnSize.className = 'cart-modal-size-btn';
                        btnSize.innerText = size.toUpperCase();
                        btnSize.onclick = function () {
                            document.querySelectorAll('.cart-modal-size-btn').forEach(b => b.classList.remove('selected'));
                            this.classList.add('selected');
                        };
                        modalSizes.appendChild(btnSize);
                    });
                } else {
                    modalSizes.innerHTML = '<span class="text-muted" style="font-size:14px;">Satu Ukuran</span>';
                }

                // Tampilkan Modal
                cartModalOverlay.classList.add('show');
            });
        });

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

        // 3. LOGIKA PLUS MINUS
        qtyMinus.addEventListener('click', () => {
            let val = parseInt(qtyInput.value);
            // [UBAHAN] Ubah menjadi > 0 agar bisa dikurangi sampai angka 0
            if (val > 0) {
                qtyInput.value = val - 1;
                qtyWarning.style.display = 'none';
            }
        });

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

        // 4, 5, 6, 7. EKSEKUSI PENYIMPANAN & POP-UP
        btnSubmitCart.addEventListener('click', function (e) {
            e.preventDefault();

            const checkSizeBtnExists = document.querySelector('.cart-modal-size-btn');
            const selectedSizeBtn = document.querySelector('.cart-modal-size-btn.selected');
            const warningPopup = document.getElementById('warningPopup'); 
            const warningPopupText = document.getElementById('warningPopupText'); // Tangkap teksnya

            // [VALIDASI 1] Cek ukuran sudah dipilih belum
            if (checkSizeBtnExists && !selectedSizeBtn) {
                if (warningPopupText) warningPopupText.innerText = 'Silakan pilih ukuran terlebih dahulu!';
                
                warningPopup.classList.add('show');
                setTimeout(() => {
                    warningPopup.classList.remove('show');
                }, 2500);

                return; // Hentikan proses simpan ke keranjang
            }

            // [VALIDASI 2] Cek Qty tidak boleh 0
            const qty = parseInt(qtyInput.value);
            if (qty === 0) {
                if (warningPopupText) warningPopupText.innerText = 'Jumlah produk tidak boleh 0!';
                
                warningPopup.classList.add('show');
                setTimeout(() => {
                    warningPopup.classList.remove('show');
                }, 2500);

                return; // Hentikan proses simpan ke keranjang
            }

            // Jika lolos validasi, Siapkan Data
            const name = modalTitle.innerText;
            const imgSrc = modalImg.src;
            const size = selectedSizeBtn ? selectedSizeBtn.innerText : 'Satu Ukuran';
            const cleanPrice = parseInt(modalPrice.innerText.replace(/[^0-9]/g, ''));

            const productToCart = { name, imgSrc, size, cleanPrice, qty };

            // 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));

            // Tutup Modal
            cartModalOverlay.classList.remove('show');

            // Update Angka di Header
            if (typeof window.renderCart === 'function') {
                window.renderCart();
            }

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