@extends('layouts.app')

@section('title', 'Shopping Cart - ' . config('app.name'))

@section('content')
<div class="bg-gray-50 min-h-screen">

    {{-- Hero --}}
    <div class="relative bg-gradient-to-br from-emerald-700 via-emerald-600 to-emerald-500 overflow-hidden">
        <div class="absolute inset-0 opacity-10">
            <div class="absolute -top-20 -right-20 w-72 h-72 bg-white rounded-full blur-3xl"></div>
            <div class="absolute -bottom-20 -left-20 w-96 h-96 bg-emerald-300 rounded-full blur-3xl"></div>
        </div>
        <div class="container mx-auto px-4 sm:px-6 lg:px-8 py-12 sm:py-16 relative">
            <div class="flex items-center gap-4">
                <div class="w-14 h-14 bg-white/15 backdrop-blur-sm rounded-2xl flex items-center justify-center shrink-0">
                    <svg class="w-7 h-7 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 100 4 2 2 0 000-4z"/></svg>
                </div>
                <div>
                    <h1 class="text-2xl sm:text-3xl lg:text-4xl font-bold text-white">Shopping Cart</h1>
                    <p class="text-emerald-100 text-sm sm:text-base">{{ count($cartItems) > 0 ? count($cartItems) . ' item' . (count($cartItems) !== 1 ? 's' : '') . ' in your cart' : 'Your cart is empty' }}</p>
                </div>
            </div>
        </div>
        <div class="absolute bottom-0 left-0 right-0">
            <svg viewBox="0 0 1440 60" fill="none" class="w-full h-auto">
                <path d="M0 60V30C240 0 480 0 720 30C960 60 1200 60 1440 30V60H0Z" fill="#f9fafb"/>
            </svg>
        </div>
    </div>

    <div class="container mx-auto px-4 sm:px-6 lg:px-8 py-8 sm:py-10">
        @if(count($cartItems) > 0)
            <div class="grid lg:grid-cols-3 gap-6 lg:gap-8">

                {{-- Cart Items Column --}}
                <div class="lg:col-span-2 space-y-4">
                    @foreach($cartItems as $id => $item)
                        <div class="cart-item bg-white rounded-2xl shadow-sm border border-gray-100 p-4 sm:p-5 transition-all hover:shadow-md" data-id="{{ $id }}" role="listitem">
                            <div class="flex gap-4 sm:gap-5">
                                {{-- Image --}}
                                <div class="w-20 h-20 sm:w-24 sm:h-24 rounded-xl overflow-hidden bg-gray-100 shrink-0">
                                    <img src="{{ asset('storage/' . $item['image']) }}"
                                         alt="{{ $item['name'] }}"
                                         class="w-full h-full object-cover"
                                         loading="lazy">
                                </div>
                                {{-- Details --}}
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-start justify-between gap-2">
                                        <h3 class="text-sm sm:text-base font-semibold text-gray-900 truncate">{{ $item['name'] }}</h3>
                                        <button onclick="removeFromCart({{ $id }})" class="remove-btn p-1.5 rounded-lg text-gray-300 hover:text-red-500 hover:bg-red-50 transition-all shrink-0" aria-label="Remove item">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                                        </button>
                                    </div>
                                    <div class="mt-1 text-sm text-emerald-600 font-medium" data-price="{{ $item['price'] }}">${{ number_format($item['price'], 2) }}</div>
                                    {{-- Controls row --}}
                                    <div class="mt-3 flex items-center justify-between gap-3">
                                        <div class="quantity-selector inline-flex items-center bg-gray-50 rounded-xl border border-gray-200 overflow-hidden">
                                            <button onclick="updateQuantity({{ $id }}, 'decrease')" class="qty-btn w-9 h-9 flex items-center justify-center text-gray-500 hover:text-emerald-600 hover:bg-emerald-50 transition-colors" aria-label="Decrease quantity">
                                                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 12H4"/></svg>
                                            </button>
                                            <input type="number" value="{{ $item['quantity'] }}" min="1" readonly class="w-10 text-center text-sm font-semibold bg-transparent border-0 text-gray-800 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none">
                                            <button onclick="updateQuantity({{ $id }}, 'increase')" class="qty-btn w-9 h-9 flex items-center justify-center text-gray-500 hover:text-emerald-600 hover:bg-emerald-50 transition-colors" aria-label="Increase quantity">
                                                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                                            </button>
                                        </div>
                                        <div class="item-subtotal text-sm sm:text-base font-bold text-gray-900">${{ number_format($item['price'] * $item['quantity'], 2) }}</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endforeach

                    {{-- Cart Actions --}}
                    <div class="flex flex-wrap items-center justify-between gap-3 pt-2">
                        <button onclick="emptyCart()" class="inline-flex items-center gap-2 px-4 py-2.5 text-sm font-medium text-red-600 bg-white border border-red-200 rounded-xl hover:bg-red-50 hover:border-red-300 transition-all shadow-sm">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                            Empty Cart
                        </button>
                        <a href="{{ route('categories.index') }}" class="inline-flex items-center gap-2 px-4 py-2.5 text-sm font-medium text-emerald-700 bg-emerald-50 border border-emerald-200 rounded-xl hover:bg-emerald-100 transition-all shadow-sm">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"/></svg>
                            Continue Shopping
                        </a>
                    </div>
                </div>

                {{-- Order Summary --}}
                <div class="lg:col-span-1">
                    <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 sm:p-6 lg:sticky lg:top-24">
                        <h2 class="text-lg font-bold text-gray-900 flex items-center gap-2 mb-5">
                            <svg class="w-5 h-5 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/></svg>
                            Order Summary
                        </h2>
                        <div class="flex items-center justify-between py-2.5">
                            <span class="text-sm text-gray-600">Subtotal</span>
                            <span class="cart-subtotal text-sm font-semibold text-gray-900">${{ number_format($subtotal, 2) }}</span>
                        </div>
                        <div class="flex items-center justify-between py-2.5 border-t border-gray-100">
                            <span class="text-sm text-gray-600">Shipping</span>
                            <span class="text-sm font-semibold text-emerald-600">Free</span>
                        </div>
                        <div class="my-3 border-t-2 border-dashed border-gray-100"></div>
                        <div class="flex items-center justify-between py-2">
                            <span class="text-base font-bold text-gray-900">Total</span>
                            <span class="cart-total text-lg font-bold text-emerald-600">${{ number_format($total, 2) }}</span>
                        </div>
                        <p class="text-xs text-gray-400 mt-2 flex items-center gap-1.5">
                            <svg class="w-3.5 h-3.5 text-emerald-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/></svg>
                            Secure checkout — your info is protected
                        </p>
                        <div class="mt-5 space-y-3">
                            @auth
                                <a href="{{ route('checkout') }}"
                                   class="flex items-center justify-center gap-2 w-full px-6 py-3.5 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-semibold rounded-xl transition-all shadow-sm hover:shadow-md active:scale-[0.98]">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/></svg>
                                    Proceed to Secure Checkout
                                </a>
                            @else
                                <a href="{{ route('checkout.guest') }}"
                                   class="flex items-center justify-center gap-2 w-full px-6 py-3.5 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-semibold rounded-xl transition-all shadow-sm hover:shadow-md active:scale-[0.98]">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/></svg>
                                    Checkout as Guest
                                </a>
                                <div class="relative">
                                    <div class="absolute inset-0 flex items-center">
                                        <div class="w-full border-t border-gray-200"></div>
                                    </div>
                                    <div class="relative flex justify-center text-xs">
                                        <span class="bg-white px-3 text-gray-400">or</span>
                                    </div>
                                </div>
                                <a href="{{ route('login') }}"
                                   class="flex items-center justify-center gap-2 w-full px-5 py-3 text-sm font-medium text-emerald-700 bg-emerald-50 border border-emerald-200 rounded-xl hover:bg-emerald-100 transition-all active:scale-[0.98]">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"/></svg>
                                    Login to Checkout
                                </a>
                            @endauth
                        </div>
                        <div class="mt-5 pt-4 border-t border-gray-100">
                            <p class="text-xs text-gray-400 text-center mb-3">We accept</p>
                            <div class="flex justify-center gap-4 text-gray-300">
                                <span class="w-10 h-7 bg-gray-100 rounded flex items-center justify-center text-[9px] font-bold text-gray-500">VISA</span>
                                <span class="w-10 h-7 bg-gray-100 rounded flex items-center justify-center text-[9px] font-bold text-gray-500">MC</span>
                                <span class="w-10 h-7 bg-gray-100 rounded flex items-center justify-center text-[9px] font-bold text-gray-500">AMEX</span>
                                <span class="w-10 h-7 bg-gray-100 rounded flex items-center justify-center text-[9px] font-bold text-gray-500">PP</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        @else
            {{-- Empty state --}}
            <div class="max-w-md mx-auto text-center py-12 sm:py-16">
                <div class="w-24 h-24 sm:w-28 sm:h-28 mx-auto mb-6 bg-gray-100 rounded-full flex items-center justify-center">
                    <svg class="w-12 h-12 sm:w-14 sm:h-14 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 100 4 2 2 0 000-4z"/></svg>
                </div>
                <h2 class="text-xl sm:text-2xl font-bold text-gray-900 mb-2">Your cart is empty</h2>
                <p class="text-sm text-gray-500 mb-6 max-w-xs mx-auto">Looks like you haven't added anything yet. Browse our products and find something you love.</p>
                <a href="{{ route('categories.index') }}"
                   class="inline-flex items-center gap-2 px-6 py-3 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-semibold rounded-xl transition-all shadow-sm hover:shadow-md active:scale-[0.98]">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"/></svg>
                    Start Shopping
                </a>
            </div>
        @endif
    </div>
</div>

{{-- Toast container --}}
<div id="toast-container" class="fixed top-4 right-4 z-[9999] flex flex-col gap-2 pointer-events-none"></div>

<script>
(function() {
    const csrfToken = '{{ csrf_token() }}';
    const toastContainer = document.getElementById('toast-container');

    function showToast(message, type) {
        type = type || 'success';
        const bg = type === 'success' ? 'bg-emerald-600' : 'bg-red-500';
        const icon = type === 'success'
            ? '<svg class="w-5 h-5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>'
            : '<svg class="w-5 h-5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>';
        var toast = document.createElement('div');
        toast.className = 'pointer-events-auto flex items-center gap-3 px-4 py-3 rounded-xl shadow-lg text-white text-sm font-medium ' + bg + ' translate-y-[-8px] opacity-0 transition-all duration-300';
        toast.innerHTML = icon + message;
        toastContainer.appendChild(toast);
        requestAnimationFrame(function() {
            toast.classList.remove('translate-y-[-8px]', 'opacity-0');
            toast.classList.add('translate-y-0', 'opacity-100');
        });
        setTimeout(function() {
            toast.classList.remove('translate-y-0', 'opacity-100');
            toast.classList.add('translate-y-[-8px]', 'opacity-0');
            setTimeout(function() { toast.remove(); }, 300);
        }, 2500);
    }

    function updateCartBadge(count) {
        document.querySelectorAll('[data-cart-count]').forEach(function(el) {
            el.textContent = count;
            if (count === 0) el.classList.add('hidden'); else el.classList.remove('hidden');
        });
    }

    function recalcSubtotals() {
        var subtotal = 0;
        document.querySelectorAll('.cart-item').forEach(function(item) {
            var priceEl = item.querySelector('[data-price]');
            var input = item.querySelector('input[type="number"]');
            var subEl = item.querySelector('.item-subtotal');
            if (priceEl && input && subEl) {
                var price = parseFloat(priceEl.getAttribute('data-price'));
                var qty = parseInt(input.value);
                var s = price * qty;
                subEl.textContent = '$' + s.toFixed(2);
                subtotal += s;
            }
        });
        document.querySelectorAll('.cart-subtotal, .cart-total').forEach(function(el) {
            el.textContent = '$' + subtotal.toFixed(2);
        });
    }

    window.updateQuantity = function(productId, action) {
        var item = document.querySelector('.cart-item[data-id="' + productId + '"]');
        if (!item) return;
        var input = item.querySelector('input[type="number"]');
        var current = parseInt(input.value);
        var newQty = current;
        if (action === 'increase') newQty = current + 1;
        else if (action === 'decrease' && current > 1) newQty = current - 1;
        else return;

        input.value = newQty;
        recalcSubtotals();

        var btns = item.querySelectorAll('.qty-btn');
        btns.forEach(function(b) { b.disabled = true; });

        var formData = new FormData();
        formData.append('_token', csrfToken);
        formData.append('action', action);

        fetch('/cart/update/' + productId, { method: 'POST', body: formData })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) {
                    updateCartBadge(data.cartCount);
                    showToast(data.message || 'Cart updated');
                } else {
                    input.value = current;
                    recalcSubtotals();
                    showToast('Failed to update quantity', 'error');
                }
            })
            .catch(function() {
                input.value = current;
                recalcSubtotals();
                showToast('Failed to update cart', 'error');
            })
            .finally(function() {
                btns.forEach(function(b) { b.disabled = false; });
            });
    };

    window.removeFromCart = function(productId) {
        var item = document.querySelector('.cart-item[data-id="' + productId + '"]');
        if (!item) return;
        if (!confirm('Remove this item from your cart?')) return;

        item.style.transition = 'all 0.3s ease';
        item.style.transform = 'scale(0.95)';
        item.style.opacity = '0';

        var formData = new FormData();
        formData.append('_token', csrfToken);

        fetch('/cart/remove/' + productId, { method: 'DELETE', body: formData })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) {
                    updateCartBadge(data.cartCount);
                    item.remove();
                    recalcSubtotals();
                    if (document.querySelectorAll('.cart-item').length === 0) {
                        location.reload();
                    }
                    showToast('Item removed');
                } else {
                    item.style.transform = '';
                    item.style.opacity = '';
                    showToast('Failed to remove item', 'error');
                }
            })
            .catch(function() {
                item.style.transform = '';
                item.style.opacity = '';
                showToast('Failed to remove item', 'error');
            });
    };

    window.emptyCart = function() {
        if (!confirm('Are you sure you want to empty your cart? This cannot be undone.')) return;
        var formData = new FormData();
        formData.append('_token', csrfToken);
        fetch('/cart/empty', { method: 'POST', body: formData })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success) {
                    location.reload();
                } else {
                    showToast('Failed to empty cart', 'error');
                }
            })
            .catch(function() {
                showToast('Failed to empty cart', 'error');
            });
    };
})();
</script>
@endsection