<x-app-layout>
    <x-slot name="header">
        <style>
            .dash-header-title {
                font-family: 'Inter', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
                font-weight: 500;
                font-size: 1.5rem;
                letter-spacing: -0.01em;
                color: #0f0f0f;
            }
        </style>
        <h2 class="dash-header-title">Keranjang Belanja</h2>
    </x-slot>

    <style>
        /* Font system biasa */
        .cart-wrap,
        .cart-wrap * {
            font-family: 'Inter', system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, sans-serif;
        }

        .cart-inner {
            max-width: 1400px;
            margin: 0 auto;
            padding: 40px 32px;
        }

        /* ── ALERT ── */
        .cart-alert {
            padding: 14px 24px;
            margin-bottom: 32px;
            font-size: 0.8rem;
            border-radius: 8px;
            background: #fff;
            border: 1px solid #e5e5e5;
            border-left-width: 3px;
            border-left-style: solid;
        }

        .cart-alert-success {
            border-left-color: #f97316;
            color: #0f0f0f;
            background: #fff7ed;
        }

        .cart-alert-error {
            border-left-color: #ef4444;
            color: #ef4444;
            background: #fef2f2;
        }

        /* ── EMPTY STATE ── */
        .cart-empty {
            background: #fff;
            border: 1px solid #e5e5e5;
            border-radius: 12px;
            padding: 80px 32px;
            text-align: center;
        }

        .cart-empty-title {
            font-size: 1.3rem;
            font-weight: 500;
            color: #999;
            margin-bottom: 12px;
        }

        .cart-empty-desc {
            font-size: 0.85rem;
            font-weight: 400;
            color: #bbb;
            margin-bottom: 28px;
        }

        .cart-empty-btn {
            display: inline-block;
            background: #f97316;
            color: #fff;
            font-size: 0.7rem;
            font-weight: 500;
            letter-spacing: 0.05em;
            text-transform: uppercase;
            text-decoration: none;
            padding: 12px 28px;
            border-radius: 8px;
            transition: background 0.2s;
        }

        .cart-empty-btn:hover { background: #ea580c; }

        /* ── CART LAYOUT ── */
        .cart-layout {
            display: flex;
            flex-direction: column;
            gap: 32px;
        }

        @media (min-width: 768px) {
            .cart-layout {
                flex-direction: row;
                align-items: flex-start;
            }
            .cart-items {
                flex: 2;
            }
            .cart-summary {
                flex: 1;
                position: sticky;
                top: 24px;
            }
        }

        /* ── SELECT ALL BAR ── */
        .cart-select-all {
            background: #fff;
            border: 1px solid #e5e5e5;
            border-radius: 10px;
            padding: 14px 20px;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .cart-checkbox {
            width: 18px;
            height: 18px;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            accent-color: #f97316;
        }

        .cart-checkbox-label {
            font-size: 0.75rem;
            font-weight: 500;
            letter-spacing: 0.03em;
            text-transform: uppercase;
            color: #888;
            cursor: pointer;
        }

        /* ── CART ITEM CARD ── */
        .cart-item {
            background: #fff;
            border: 1px solid #e5e5e5;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 12px;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 16px;
            transition: all 0.2s;
        }

        .cart-item:hover {
            box-shadow: 0 2px 8px rgba(0,0,0,0.04);
            border-color: #f97316;
        }

        .cart-item-checkbox {
            flex-shrink: 0;
        }

        .cart-item-image {
            flex-shrink: 0;
            width: 80px;
            height: 80px;
            border-radius: 8px;
            object-fit: cover;
            border: 1px solid #e5e5e5;
        }

        .cart-item-info {
            flex: 1;
            min-width: 150px;
        }

        .cart-item-name {
            font-size: 0.9rem;
            font-weight: 500;
            color: #1a1a1a;
            margin-bottom: 4px;
        }

        .cart-item-variant {
            font-size: 0.7rem;
            color: #888;
            margin-bottom: 6px;
        }

        .cart-item-price {
            font-size: 0.8rem;
            font-weight: 500;
            color: #f97316;
        }

        .cart-item-quantity {
            flex-shrink: 0;
            display: flex;
            align-items: center;
            border: 1px solid #e5e5e5;
            border-radius: 8px;
            overflow: hidden;
        }

        .cart-qty-btn {
            width: 34px;
            height: 34px;
            background: #fafafa;
            border: none;
            font-size: 1.1rem;
            font-weight: 500;
            cursor: pointer;
            color: #666;
            transition: all 0.2s;
        }

        .cart-qty-btn:hover {
            background: #f97316;
            color: #fff;
        }

        .cart-qty-input {
            width: 52px;
            height: 34px;
            text-align: center;
            border: none;
            border-left: 1px solid #e5e5e5;
            border-right: 1px solid #e5e5e5;
            font-size: 0.8rem;
        }

        .cart-qty-input:focus {
            outline: none;
        }

        .cart-item-subtotal {
            flex-shrink: 0;
            min-width: 110px;
            text-align: right;
        }

        .cart-item-subtotal-value {
            font-size: 0.9rem;
            font-weight: 600;
            color: #f97316;
        }

        .cart-item-delete {
            flex-shrink: 0;
        }

        .cart-delete-btn {
            background: none;
            border: none;
            font-size: 0.7rem;
            font-weight: 500;
            letter-spacing: 0.05em;
            text-transform: uppercase;
            color: #bbb;
            cursor: pointer;
            padding: 0;
            padding-bottom: 2px;
            border-bottom: 1px solid transparent;
            transition: color 0.2s, border-color 0.2s;
        }

        .cart-delete-btn:hover {
            color: #ef4444;
            border-bottom-color: #ef4444;
        }

        /* ── CONTINUE SHOPPING ── */
        .cart-continue {
            background: #fff;
            border: 1px solid #e5e5e5;
            border-radius: 10px;
            padding: 14px 20px;
            margin-top: 12px;
        }

        .cart-continue-link {
            font-size: 0.7rem;
            font-weight: 500;
            letter-spacing: 0.05em;
            text-transform: uppercase;
            color: #888;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: color 0.2s;
        }

        .cart-continue-link:hover {
            color: #f97316;
        }

        /* ── SUMMARY CARD ── */
        .cart-summary-card {
            background: #fff;
            border: 1px solid #e5e5e5;
            border-radius: 12px;
            padding: 28px;
        }

        .cart-summary-title {
            font-size: 1.1rem;
            font-weight: 500;
            color: #0f0f0f;
            padding-bottom: 16px;
            border-bottom: 2px solid #f97316;
            margin-bottom: 20px;
        }

        .cart-summary-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 14px;
            font-size: 0.8rem;
            color: #666;
        }

        .cart-summary-row.total {
            border-top: 1px solid #e5e5e5;
            padding-top: 18px;
            margin-top: 10px;
            margin-bottom: 0;
        }

        .cart-summary-label {
            font-size: 0.7rem;
            font-weight: 500;
            letter-spacing: 0.05em;
            text-transform: uppercase;
            color: #999;
        }

        .cart-summary-value {
            font-weight: 500;
            color: #1a1a1a;
        }

        .cart-summary-value.total {
            font-size: 1.2rem;
            font-weight: 600;
            color: #f97316;
        }

        .cart-checkout-btn {
            width: 100%;
            background: #f97316;
            color: #fff;
            font-size: 0.7rem;
            font-weight: 500;
            letter-spacing: 0.08em;
            text-transform: uppercase;
            padding: 14px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: background 0.2s;
            margin-top: 24px;
        }

        .cart-checkout-btn:hover:not(:disabled) {
            background: #ea580c;
        }

        .cart-checkout-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .cart-summary-note {
            font-size: 0.65rem;
            color: #aaa;
            text-align: center;
            margin-top: 18px;
            line-height: 1.5;
        }

        .cart-login-link {
            display: block;
            width: 100%;
            background: #fff7ed;
            color: #f97316;
            font-size: 0.7rem;
            font-weight: 500;
            letter-spacing: 0.08em;
            text-transform: uppercase;
            text-align: center;
            padding: 14px 20px;
            border: 1px solid #f97316;
            border-radius: 8px;
            text-decoration: none;
            transition: all 0.2s;
            margin-top: 24px;
        }

        .cart-login-link:hover {
            background: #f97316;
            color: #fff;
            border-color: #f97316;
        }
    </style>

    <div class="cart-wrap">
        <div class="cart-inner">

            {{-- Alert Messages --}}
            @if(session('success'))
                <div class="cart-alert cart-alert-success">{{ session('success') }}</div>
            @endif
            @if(session('error'))
                <div class="cart-alert cart-alert-error">{{ session('error') }}</div>
            @endif

            {{-- Keranjang Kosong --}}
            @if(!$cart || $cart->items->isEmpty())
                <div class="cart-empty">
                    <div class="cart-empty-title">Keranjang Anda kosong</div>
                    <div class="cart-empty-desc">Sepertinya Anda belum menambahkan item apa pun</div>
                    <a href="{{ route('products.index') }}" class="cart-empty-btn">Mulai Belanja</a>
                </div>

            @else
                <div id="cart-wrapper">
                    <div class="cart-layout">

                        {{-- KIRI: Daftar Item --}}
                        <div class="cart-items">

                            {{-- Header Pilih Semua --}}
                            <div class="cart-select-all">
                                <input type="checkbox" id="check-all" class="cart-checkbox">
                                <label for="check-all" class="cart-checkbox-label">Pilih Semua</label>
                            </div>

                            {{-- Daftar Item --}}
                            @foreach($cart->items as $item)
                                <div class="cart-item"
                                    data-item-id="{{ $item->id }}"
                                    data-item-price="{{ $item->price }}"
                                    data-item-qty="{{ $item->quantity }}">

                                    {{-- Checkbox --}}
                                    <div class="cart-item-checkbox">
                                        <input type="checkbox"
                                            class="item-checkbox cart-checkbox"
                                            value="{{ $item->id }}"
                                            data-price="{{ $item->price * $item->quantity }}">
                                    </div>

                                    {{-- Gambar --}}
                                    @php
                                        $cartImgPath = null;
                                        if ($item->variant && $item->variant->image) {
                                            $cartImgPath = $item->variant->image->image_path;
                                        } elseif ($item->product->images && $item->product->images->count() > 0) {
                                            $cover = $item->product->images->firstWhere('is_primary', true) ?? $item->product->images->first();
                                            $cartImgPath = $cover->image_path;
                                        }
                                    @endphp
                                    @if($cartImgPath)
                                        <img class="cart-item-image"
                                            src="{{ asset('storage/' . $cartImgPath) }}"
                                            alt="{{ $item->product->name }}">
                                    @else
                                        <img class="cart-item-image"
                                            src="https://via.placeholder.com/150" alt="No Image">
                                    @endif

                                    {{-- Info Produk --}}
                                    <div class="cart-item-info">
                                        <div class="cart-item-name">{{ $item->product->name }}</div>
                                        @if($item->variant)
                                            <div class="cart-item-variant">
                                                {{ $item->variant->size ?? '' }} / {{ $item->variant->color ?? '' }}
                                            </div>
                                        @endif
                                        <div class="cart-item-price">Rp {{ number_format($item->price, 0, ',', '.') }}</div>
                                    </div>

                                    {{-- Qty Update --}}
                                    <div class="cart-item-quantity">
                                        <button type="button" onclick="adjustQty(this, -1, '{{ $item->id }}')"
                                            class="cart-qty-btn">−</button>
                                        <input type="number" id="qty-{{ $item->id }}"
                                            value="{{ $item->quantity }}" min="1"
                                            max="{{ $item->variant ? $item->variant->stock : ($item->product->variants->first()->stock ?? 999) }}"
                                            class="cart-qty-input qty-input"
                                            data-item-id="{{ $item->id }}"
                                            onchange="updateQuantity(this)">
                                        <button type="button" onclick="adjustQty(this, 1, '{{ $item->id }}')"
                                            class="cart-qty-btn">+</button>
                                    </div>

                                    {{-- Subtotal Item --}}
                                    <div class="cart-item-subtotal">
                                        <div class="cart-item-subtotal-value" id="subtotal-{{ $item->id }}">
                                            Rp {{ number_format($item->price * $item->quantity, 0, ',', '.') }}
                                        </div>
                                    </div>

                                    {{-- Hapus --}}
                                    <div class="cart-item-delete">
                                        <form action="{{ route('cart.destroy', $item->id) }}" method="POST"
                                            onsubmit="return confirm('Yakin ingin menghapus item ini?')">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit" class="cart-delete-btn">Hapus</button>
                                        </form>
                                    </div>
                                </div>
                            @endforeach

                            {{-- Kembali Belanja --}}
                            <div class="cart-continue">
                                <a href="{{ route('products.index') }}" class="cart-continue-link">
                                ← Lanjut Belanja
                                </a>
                            </div>
                        </div>

                        {{-- KANAN: Ringkasan Pesanan --}}
                        <div class="cart-summary">
                            <div class="cart-summary-card">
                                <h3 class="cart-summary-title">Ringkasan Pesanan</h3>

                                <div class="cart-summary-row">
                                    <span class="cart-summary-label">Item Dipilih</span>
                                    <span id="summary-count" class="cart-summary-value">0 item</span>
                                </div>

                                <div class="cart-summary-row">
                                    <span class="cart-summary-label">Subtotal</span>
                                    <span id="summary-subtotal" class="cart-summary-value">Rp 0</span>
                                </div>

                                <div class="cart-summary-row total">
                                    <span class="cart-summary-label">Total</span>
                                    <span id="summary-total" class="cart-summary-value total">Rp 0</span>
                                </div>

                                @auth
                                    <button type="button" id="btn-checkout"
                                        onclick="submitCheckout()"
                                        disabled
                                        class="cart-checkout-btn">
                                        Checkout (<span id="btn-count">0</span>)
                                    </button>
                                @else
                                    <a href="{{ route('login') }}" class="cart-login-link">
                                        Login untuk Checkout
                                    </a>
                                @endauth

                                <div class="cart-summary-note">
                                    Pilih item yang ingin di-checkout.<br>Ongkir dihitung saat checkout.
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            @endif
        </div>
    </div>

    <script>
        // =============================================
        // LOGIKA CHECKBOX & SUMMARY
        // =============================================
        const checkAll        = document.getElementById('check-all');
        const btnCheckout     = document.getElementById('btn-checkout');
        const btnCount        = document.getElementById('btn-count');
        const summaryCount    = document.getElementById('summary-count');
        const summarySubtotal = document.getElementById('summary-subtotal');
        const summaryTotal    = document.getElementById('summary-total');

        function getChecked() {
            return document.querySelectorAll('.item-checkbox:checked');
        }

        function formatRupiah(num) {
            return 'Rp ' + num.toLocaleString('id-ID');
        }

        function updateSummary() {
            const checked = getChecked();
            let total = 0;

            checked.forEach(cb => {
                const row   = cb.closest('[data-item-id]');
                const price = parseInt(row.dataset.itemPrice);
                const qty   = parseInt(row.querySelector('.qty-input').value);
                total += price * qty;
            });

            const count = checked.length;

            summaryCount.textContent    = count + ' item';
            summarySubtotal.textContent = formatRupiah(total);
            summaryTotal.textContent    = formatRupiah(total);

            if (btnCount) btnCount.textContent = count;
            if (btnCheckout) btnCheckout.disabled = count === 0;

            const allBoxes = document.querySelectorAll('.item-checkbox');
            if (checkAll) {
                checkAll.checked       = allBoxes.length > 0 && count === allBoxes.length;
                checkAll.indeterminate = count > 0 && count < allBoxes.length;
            }
        }

        if (checkAll) {
            checkAll.addEventListener('change', function () {
                document.querySelectorAll('.item-checkbox').forEach(cb => {
                    cb.checked = this.checked;
                });
                updateSummary();
            });
        }

        document.querySelectorAll('.item-checkbox').forEach(cb => {
            cb.addEventListener('change', updateSummary);
        });

        // =============================================
        // UPDATE QUANTITY VIA AJAX
        // =============================================
        function adjustQty(btn, delta, itemId) {
            const input = document.getElementById('qty-' + itemId);
            if (!input) return;
            
            const min = parseInt(input.min) || 1;
            const max = parseInt(input.max) || 999;
            let val = parseInt(input.value) + delta;

            if (val < min) val = min;
            if (val > max) val = max;

            input.value = val;
            updateQuantity(input);
        }

        function updateQuantity(input) {
            const itemId = input.dataset.itemId;
            const qty = parseInt(input.value);
            
            fetch(`/cart/${itemId}`, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify({ quantity: qty })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const subtotalEl = document.getElementById('subtotal-' + itemId);
                    if (subtotalEl) subtotalEl.textContent = data.item_subtotal;
                    
                    const row = document.querySelector(`[data-item-id="${itemId}"]`);
                    if (row) {
                        row.dataset.itemQty = qty;
                    }
                    
                    updateSummary();
                } else {
                    alert(data.message);
                    location.reload();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                location.reload();
            });
        }

        // =============================================
        // SUBMIT CHECKOUT - HANYA ITEM YANG DIPILIH
        // =============================================
        function submitCheckout() {
            const checked = getChecked();
            if (checked.length === 0) {
                alert('Pilih minimal 1 produk untuk di-checkout!');
                return;
            }

            const form = document.createElement('form');
            form.method = 'GET';
            form.action = '{{ route('checkout.index') }}';
            
            const csrf = document.createElement('input');
            csrf.type = 'hidden';
            csrf.name = '_token';
            csrf.value = '{{ csrf_token() }}';
            form.appendChild(csrf);
            
            checked.forEach(cb => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'selected_items[]';
                input.value = cb.value;
                form.appendChild(input);
            });
            
            document.body.appendChild(form);
            form.submit();
        }

        // Inisialisasi awal
        updateSummary();
    </script>
</x-app-layout>