@extends('layouts.app')

@section('title', 'Space Casual Store - Detail Produk')

@section('content')

    {{-- ==========================================
    IMPORT GOOGLE FONT: POPPINS
    ========================================== --}}
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap"
        rel="stylesheet">

    {{-- ==========================================
    CSS KUSTOM HALAMAN DETAIL PRODUK
    ========================================== --}}
    <style>
        /* GLOBAL FONT */
        body,
        .container,
        h1,
        h2,
        h3,
        p,
        span,
        div,
        a,
        button,
        input {
            font-family: 'Poppins', sans-serif !important;
        }

        /* CONTAINER ALIGNMENT */
        .detail-container {
            margin-top: 2rem;
            margin-bottom: 3rem;
            padding-left: 70px;
        }

        /* ==========================================
                       1. BAGIAN KIRI: GAMBAR & CAROUSEL
                       ========================================== */
        .carousel-produk {
            background-color: #f0f1f3;
            /* Abu-abu terang sesuai gambar */
            border-radius: 16px;
            overflow: hidden;
            position: relative;
            padding: 0px;
            /* Jarak dari tepi ke gambar baju */
            display: flex;
            align-items: center;
            justify-content: center;
            height: 500px;
        }

        .carousel-badge {
            font-size: 0.9rem;
            font-weight: 600;
            padding: 8px 20px;
            border-radius: 50px;
            z-index: 10;
        }

        .carousel-img-produk {
            object-fit: cover;
            width: 100%;
            height: 100%;
        }

        /* Panah Hitam Tebal */
        .carousel-icon-arrow {
            background-image: none;
            width: 40px;
            /* Ukuran diubah menjadi 40px */
            height: 40px;
            /* Ukuran diubah menjadi 40px */
            display: flex;
            align-items: center;
            justify-content: center;
            color: #000;
        }

        .carousel-icon-arrow::after {
            content: '';
            display: inline-block;
            width: 18px;
            /* Sedikit diperbesar agar proporsional dengan box 40px */
            height: 18px;
            border-top: 5px solid #111;
            border-right: 5px solid #111;
        }

        .carousel-control-prev-icon::after {
            transform: rotate(-135deg);
            margin-left: 8px;
        }

        .carousel-control-next-icon::after {
            transform: rotate(45deg);
            margin-right: 8px;
        }

        /* Memisahkan prev dan next untuk mengatur left/right -20px */
        .carousel-control-prev {
            width: 50px;
            opacity: 1;
            left: -10px;
            /* Geser ke pinggir kiri */
        }

        .carousel-control-next {
            width: 50px;
            opacity: 1;
            right: -10px;
            /* Geser ke pinggir kanan */
        }

        /* ==========================================
                       2. BAGIAN KANAN: DETAIL KONTEN
                       ========================================== */
        /* Breadcrumb */
        .custom-breadcrumb {
            font-size: 14px;
            color: #4b5563;
            margin-bottom: 12px;
            font-weight: 500;
        }

        .custom-breadcrumb span.separator {
            margin: 0 6px;
            color: #9ca3af;
        }

        .custom-breadcrumb .active-page {
            color: #1f2937;
            font-weight: 600;
        }

        /* Typography Text */
        .produk-title {
            color: #1a202c;
            font-size: 32px;
            font-weight: 700;
            margin-bottom: 20px;
            letter-spacing: -0.5px;
        }

        .produk-desc-label {
            font-size: 15px;
            font-weight: 600;
            color: #1a202c;
            margin-bottom: 8px;
        }

        .produk-desc-box {
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 12px 16px;
            min-height: 80px;
            font-size: 14px;
            color: #374151;
            background-color: #ffffff;
            margin-bottom: 24px;

            /* Perbaikan: */
            max-width: 550px;
            /* Batasi lebar maksimal di layar besar */
            width: 100%;
            /* Tetap responsive mengikuti container di layar kecil */
        }

        .produk-harga {
            color: #f97316;
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 24px;
        }

        .produk-stok {
            font-size: 15px;
            font-weight: 700;
            color: #1a202c;
            margin-bottom: 16px;
        }

        /* ==========================================
                       3. PILIHAN UKURAN (BUTTONS)
                       ========================================== */
        .size-grid {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            margin-bottom: 24px;
            max-width: 320px;
            /* Membatasi agar membentuk grid 4x2 */
        }

        .size-box {
            width: 60px;
            height: 45px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 6px;
            border: 1px solid #f3f4f6;
            background-color: #ffffff;
            color: #1a202c;
            font-size: 14px;
            font-weight: 700;
            cursor: pointer;
            /* Efek Drop Shadow Persis UI */
            box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.08);
            transition: all 0.2s ease;
        }

        .size-box:hover {
            background-color: #2D9CDB !important;
            border-color: #2D9CDB !important;
            color: #ffffff
        }

        .size-box.selected {
            background-color: #2D9CDB !important;
            border-color: #2D9CDB !important;
            color: #ffffff !important;/ box-shadow: 0px 4px 8px rgba(45, 156, 219, 0.4);
        }

        /* ==========================================
                       4. BARIS AKSI (KUANTITAS & TOMBOL)
                       ========================================== */
        .action-row {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        /* Box Kuantitas */
        .qty-wrapper {
            display: flex;
            align-items: center;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            height: 42px;
            background-color: #ffffff;
        }

        .qty-btn {
            background: none;
            border: none;
            width: 35px;
            font-size: 18px;
            font-weight: 600;
            color: #4b5563;
        }

        .qty-input {
            width: 40px;
            text-align: center;
            border: none;
            font-weight: 600;
            font-size: 15px;
            pointer-events: none;
        }

        /* Tombol Keranjang */
        .btn-cart-custom {
            height: 42px;
            background-color: #ffffff;
            border: 1px solid #d1d5db;
            color: #1f2937;
            font-weight: 500;
            font-size: 13px;
            padding: 0 16px;
            border-radius: 6px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .btn-cart-custom:hover {
            background-color: #2D9CDB;
            border-color: #2D9CDB;
            color: #ffffff;
        }

        /* Tombol WA */
        .btn-wa-custom {
            height: 42px;
            background-color: #27ae60;
            border: 1px solid #27ae60;
            color: #ffffff;
            font-weight: 500;
            font-size: 13px;
            padding: 0 20px;
            border-radius: 6px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            text-decoration: none;
        }

        .btn-wa-custom:hover {
            background-color: #219653;
            border-color: #219653;
            color: #ffffff;
        }

        .qty-warning {
            color: #e53e3e;
            font-size: 0.8rem;
            margin-top: 5px;
            font-weight: 500;
        }

        /* ==========================================
        RESPONSIVE
        ========================================== */
        @media (max-width: 991px) {
            .detail-container {
                padding-left: 10px;
            }

            .carousel-produk {
                height: 400px;
            }

            .produk-title {
                font-size: 26px;
            }

            .produk-harga {
                font-size: 24px;
            }

            .action-row {
                flex-wrap: wrap;
            }
        }

        @media (max-width: 767px) {
            .detail-container {
                padding-left: 10px;
            }

            .carousel-produk {
                height: 350px;
                padding: 0px;
            }

            .carousel-badge {
                font-size: 0.8rem;
                padding: 6px 16px;
            }

            .produk-title {
                font-size: 22px;
                margin-bottom: 12px;
            }

            .produk-desc-box {
                width: 100%;
                /* Lebih ramping di layar besar */
                font-size: 14px;
                /* Teks sedikit lebih besar */
                padding: 12px 16px;
            }

            .produk-harga {
                font-size: 20px;
            }

            .action-row {
                flex-direction: column;
                align-items: stretch;
                gap: 10px;
            }

            .qty-wrapper {
                align-self: flex-start;
                width: 120px;
                justify-content: space-between;
            }
        }
    </style>

    <div class="container detail-container">
        <div class="row gx-5">

            {{-- ==========================================
            KOLOM KIRI: GAMBAR PRODUK
            ========================================== --}}
            <div class="col-md-5 mb-4">
                <div id="productImageCarousel" class="carousel slide carousel-produk" data-bs-ride="false">
                    {{-- Badge Status --}}
                    <span class="position-absolute top-0 end-0 m-3 carousel-badge text-white"
                        style="background-color: {{ (isset($product['status']) && strtoupper($product['status']) === 'NEW') ? '#27ae60' : '#6C757D' }};">
                        {{ $product['status'] ?? 'NEW' }}
                    </span>

                    <div class="carousel-inner w-100 h-100 text-center">
                        @php $images = is_array($product['image']) ? $product['image'] : [$product['image']]; @endphp

                        {{-- Data source untuk JS --}}
                        <img id="modalImgSource" src="{{ asset('images/' . $images[0]) }}" style="display:none;">

                        @foreach($images as $index => $img)
                            <div class="carousel-item w-100 h-100 {{ $index == 0 ? 'active' : '' }}">
                                <img src="{{ asset('images/' . $img) }}" class="carousel-img-produk"
                                    alt="{{ $product['name'] }}"
                                    onerror="this.src='https://placehold.co/400x500/F0F1F3/111?text=Image'">
                            </div>
                        @endforeach
                    </div>

                    @if(count($images) > 1)
                        <button class="carousel-control-prev" type="button" data-bs-target="#productImageCarousel"
                            data-bs-slide="prev">
                            <span class="carousel-control-prev-icon carousel-icon-arrow"></span>
                        </button>
                        <button class="carousel-control-next" type="button" data-bs-target="#productImageCarousel"
                            data-bs-slide="next">
                            <span class="carousel-control-next-icon carousel-icon-arrow"></span>
                        </button>
                    @endif
                </div>
            </div>

            {{-- ==========================================
            KOLOM KANAN: DETAIL KONTEN
            ========================================== --}}
            <div class="col-md-7 pt-2">

                {{-- Custom Breadcrumb --}}
                <div class="custom-breadcrumb">
                    <span>Beranda</span>
                    <span class="separator">/</span>
                    <span>{{ $product['category'] ?? 'Apparel New' }}</span>
                    <span class="separator">/</span>
                    <span class="active-page">{{ $product['name'] }}</span>
                </div>

                {{-- Judul --}}
                <h1 id="modalTitleSource" class="produk-title">{{ $product['name'] }}</h1>

                {{-- Deskripsi --}}
                <p class="produk-desc-label">Deskripsi:</p>
                <div class="produk-desc-box">
                    @if(isset($product['status']) && strtoupper($product['status']) === 'NEW')
                        100% Original
                    @else
                        Tidak ada minus
                    @endif
                </div>

                {{-- Harga --}}
                @php
                    $rawPrice = preg_replace('/[^0-9]/', '', $product['price']);
                    $formattedPrice = number_format((float) $rawPrice, 0, ',', '.');
                @endphp
                <h2 id="modalPriceSource" class="produk-harga">Rp. {{ $formattedPrice }}</h2>

                {{-- Pilihan Ukuran --}}
                <div class="size-grid" id="size-options">
                    @if(isset($product['sizes']) && is_array($product['sizes']))
                        @foreach($product['sizes'] as $size)
                            <button type="button" class="size-box cart-modal-size-btn">
                                {{ ucfirst($size) }}
                            </button>
                        @endforeach
                    @else
                        <span class="text-muted">Ukuran tidak tersedia</span>
                    @endif
                </div>

                {{-- Stok --}}
                <p class="produk-stok">
                    Stok : <span id="max-stock">{{ $product['stock'] ?? 0 }}</span> Pcs
                </p>

                {{-- Baris Aksi (Kuantitas, Keranjang, WA) --}}
                <div>
                    <div class="action-row">

                        {{-- Kuantitas --}}
                        <div class="qty-wrapper">
                            <button class="qty-btn" type="button" id="qtyMinusDetail">-</button>
                            <input type="text" class="qty-input" id="qtyInputDetail" value="0" readonly>
                            <button class="qty-btn" type="button" id="qtyPlusDetail">+</button>
                        </div>

                        {{-- Tombol Keranjang --}}
                        <button type="button" class="btn-cart-custom btn-submit-cart-detail">
                            Tambahkan Ke Keranjang
                        </button>

                        {{-- Tombol WhatsApp --}}
                        <a href="https://wa.me/6281315595087?text={{ urlencode('Halo min, saya minat dengan produk ' . $product['name']) }}"
                            target="_blank" class="btn-wa-custom">
                            <i class="bi bi-whatsapp"></i> Minat? Hubungi Kami
                        </a>

                    </div>
                    {{-- Warning Stok (Membungkus di luar agar tidak merusak flex baris) --}}
                    <span id="qtyWarning" class="qty-warning" style="display: none;">Stok maksimum tercapai!</span>
                </div>

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

    {{-- ==========================================
    POP-UP OVERLAYS
    ========================================== --}}
    <style>
        .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: #27ae60;
            width: 400px;
            max-width: 90%;
            height: 250px;
            border-radius: 16px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: #ffffff;
            transform: scale(0.8);
            transition: transform 0.3s;
        }

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

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

        .cart-popup-text {
            font-size: 18px;
            font-weight: 600;
            text-align: center;
        }

        .cart-popup-content.warning {
            background-color: #ffffff;
            color: #000;
            border: 2px solid #FF7A00;
        }

        .cart-popup-icon.warning {
            color: #FF7A00;
        }
    </style>

    <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>

    <div id="warningPopup" class="cart-popup-overlay">
        <div class="cart-popup-content warning">
            <div class="cart-popup-icon warning"><i class="bi bi-exclamation-triangle"></i></div>
            <div class="cart-popup-text" id="warningPopupText">Silakan pilih ukuran!</div>
        </div>
    </div>

    {{-- ==========================================
    JAVASCRIPT LOGIKA
    ========================================== --}}
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const qtyInput = document.getElementById('qtyInputDetail');
            const qtyMinus = document.getElementById('qtyMinusDetail');
            const qtyPlus = document.getElementById('qtyPlusDetail');
            const qtyWarning = document.getElementById('qtyWarning');
            const maxStock = parseInt(document.getElementById('max-stock').innerText) || 0;
            const sizeBtns = document.querySelectorAll('.cart-modal-size-btn');
            const btnSubmit = document.querySelector('.btn-submit-cart-detail');
            const warningPopup = document.getElementById('warningPopup');
            const warningPopupText = document.getElementById('warningPopupText');
            const cartPopup = document.getElementById('cartPopup');

            // 1. LOGIKA PLUS MINUS STOK
            qtyMinus.addEventListener('click', () => {
                let val = parseInt(qtyInput.value);
                if (val > 0) {
                    qtyInput.value = val - 1;
                    qtyWarning.style.display = 'none';
                }
            });

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

            // 2. LOGIKA PILIH UKURAN (Toggle)
            sizeBtns.forEach(btn => {
                btn.addEventListener('click', function () {
                    if (this.classList.contains('selected')) {
                        this.classList.remove('selected');
                    } else {
                        sizeBtns.forEach(b => b.classList.remove('selected'));
                        this.classList.add('selected');
                    }
                });
            });

            // 3. LOGIKA SUBMIT KERANJANG
            btnSubmit.addEventListener('click', function (e) {
                e.preventDefault();

                const selectedSizeBtn = document.querySelector('.cart-modal-size-btn.selected');
                if (!selectedSizeBtn && sizeBtns.length > 0) {
                    warningPopupText.innerText = 'Silakan pilih ukuran terlebih dahulu!';
                    warningPopup.classList.add('show');
                    setTimeout(() => warningPopup.classList.remove('show'), 2000);
                    return;
                }

                const qty = parseInt(qtyInput.value);
                if (qty <= 0) {
                    warningPopupText.innerText = 'Jumlah produk tidak boleh 0!';
                    warningPopup.classList.add('show');
                    setTimeout(() => warningPopup.classList.remove('show'), 2000);
                    return;
                }

                const name = document.getElementById('modalTitleSource').innerText;
                const imgSrc = document.getElementById('modalImgSource').src;
                const size = selectedSizeBtn ? selectedSizeBtn.innerText.trim() : 'Satu Ukuran';
                const priceText = document.getElementById('modalPriceSource').innerText;
                const cleanPrice = parseInt(priceText.replace(/[^0-9]/g, ''));

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

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

                if (typeof window.renderCart === 'function') {
                    window.renderCart();
                }

                cartPopup.classList.add('show');
                setTimeout(() => cartPopup.classList.remove('show'), 2000);
            });
        });
    </script>

@endsection