@extends('store.layouts.app')

@section('title', 'Cart')
@section('meta_description', 'Your cart – ' . ($store_name ?? config('app.name')))

@section('content')
<div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
    {{-- Step Indicator --}}
    <div class="mb-8 hidden md:block">
        <div class="step-indicator">
            <div class="step-item step-active">
                <div class="step-number">1</div>
                <span class="font-semibold text-gray-800">Cart</span>
            </div>
            <div class="w-16 h-0.5 bg-gray-200 mx-2"></div>
            <div class="step-item step-pending">
                <div class="step-number">2</div>
                <span class="font-semibold text-gray-500">Address</span>
            </div>
            <div class="w-16 h-0.5 bg-gray-200 mx-2"></div>
            <div class="step-item step-pending">
                <div class="step-number">3</div>
                <span class="font-semibold text-gray-500">Payment</span>
            </div>
        </div>
    </div>

    <h1 class="text-3xl font-black text-gray-900 mb-6">Shopping Cart</h1>

    @if($cart->items->isEmpty())
    <div class="card p-12 sm:p-16 text-center">
        <div class="w-24 h-24 mx-auto mb-6 rounded-full bg-gray-100 flex items-center justify-center">
            <i class="fas fa-shopping-cart text-4xl text-gray-300"></i>
        </div>
        <h2 class="text-2xl font-black text-gray-800 mb-2">Your cart is empty</h2>
        <p class="text-gray-600 mb-6">Looks like you haven't added anything to your cart yet.</p>
        <a href="{{ route('products.index') }}" class="btn-primary inline-block">
            <i class="fas fa-shopping-bag mr-2"></i> Start Shopping
        </a>
    </div>
    @else
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {{-- Cart Items --}}
        <div class="lg:col-span-2 space-y-4">
            @foreach($cart->items as $item)
            <div class="card p-4 sm:p-5 group hover:shadow-card-hover transition-all" data-item-id="{{ $item->id }}">
                <div class="flex flex-col sm:flex-row gap-4">
                    @php
                        $img = $item->product->images->sortBy('sort_order')->first();
                        $imgUrl = \App\Helpers\ImageHelper::urlOrPlaceholder($img->image_path ?? null, 'https://images.unsplash.com/photo-1542838132-92c53300491e?w=200');
                    @endphp
                    <a href="{{ route('products.show', $item->product->slug) }}" class="flex-shrink-0">
                        <img src="{{ $imgUrl }}" alt="{{ $item->product->name }}" class="w-24 h-24 sm:w-28 sm:h-28 object-cover rounded-xl shadow-sm group-hover:scale-105 transition-transform">
                    </a>
                    <div class="flex-1 min-w-0">
                        <a href="{{ route('products.show', $item->product->slug) }}" class="font-bold text-gray-900 hover:text-blinkit-green transition text-lg mb-1 block">{{ $item->product->name }}</a>
                        @if($item->variant)
                        <p class="text-sm text-gray-500 mb-2">{{ $item->variant->name }}</p>
                        @endif
                        <p class="text-blinkit-green font-black text-lg mb-3">{{ $currency_symbol }}{{ number_format($item->price, 0) }} each</p>
                        
                        <div class="flex items-center gap-3 flex-wrap">
                            <form action="{{ route('cart.update', $item) }}" method="POST" class="flex items-center gap-2" onsubmit="event.preventDefault(); updateQuantity(this, {{ $item->id }});">
                                @csrf
                                @method('PUT')
                                <button type="button" onclick="changeItemQty({{ $item->id }}, -1)" class="w-8 h-8 rounded-lg border-2 border-gray-200 hover:border-blinkit-green hover:bg-blinkit-green/5 transition flex items-center justify-center font-bold text-gray-600">
                                    <i class="fas fa-minus text-xs"></i>
                                </button>
                                <input type="number" name="quantity" value="{{ $item->quantity }}" min="1" max="99" class="w-16 text-center py-1 border-2 border-gray-200 rounded-lg font-bold" id="qty-{{ $item->id }}" readonly>
                                <button type="button" onclick="changeItemQty({{ $item->id }}, 1)" class="w-8 h-8 rounded-lg border-2 border-gray-200 hover:border-blinkit-green hover:bg-blinkit-green/5 transition flex items-center justify-center font-bold text-gray-600">
                                    <i class="fas fa-plus text-xs"></i>
                                </button>
                            </form>
                            <form action="{{ route('cart.remove', $item) }}" method="POST" class="inline" onsubmit="return confirm('Remove this item from cart?');">
                                @csrf
                                @method('DELETE')
                                <button type="submit" class="text-red-500 hover:text-red-700 text-sm font-semibold transition" title="Remove">
                                    <i class="fas fa-trash-alt mr-1"></i> Remove
                                </button>
                            </form>
                        </div>
                    </div>
                    <div class="text-right">
                        <p class="font-black text-gray-900 text-xl mb-1">{{ $currency_symbol }}{{ number_format($item->subtotal, 0) }}</p>
                        <p class="text-xs text-gray-500">{{ $item->quantity }} × {{ $currency_symbol }}{{ number_format($item->price, 0) }}</p>
                    </div>
                </div>
            </div>
            @endforeach
        </div>

        {{-- Order Summary --}}
        <div class="lg:col-span-1">
            <div class="card p-6 sticky top-24">
                <h2 class="text-xl font-black text-gray-900 mb-6">Order Summary</h2>
                
                <div class="space-y-3 mb-6">
                    <div class="flex justify-between text-gray-600">
                        <span>Subtotal ({{ $cart->items->sum('quantity') }} items)</span>
                        <span class="font-semibold">{{ $currency_symbol }}{{ number_format($cart->subtotal, 0) }}</span>
                    </div>
                    <div class="flex justify-between text-gray-600">
                        <span>Delivery Charges</span>
                        <span class="font-semibold text-green-600">FREE</span>
                    </div>
                    <div class="border-t-2 border-gray-200 pt-3 flex justify-between">
                        <span class="font-black text-lg text-gray-900">Total</span>
                        <span class="font-black text-xl text-blinkit-green">{{ $currency_symbol }}{{ number_format($cart->subtotal, 0) }}</span>
                    </div>
                </div>

                <a href="{{ route('checkout.index') }}" class="btn-primary w-full py-4 text-center block mb-3">
                    @auth('web')
                    <i class="fas fa-arrow-right mr-2"></i> Proceed to Checkout
                    @else
                    <i class="fas fa-lock mr-2"></i> Login to Checkout
                    @endauth
                </a>
                
                @guest('web')
                <p class="text-xs text-gray-500 text-center mb-4">You'll be asked to log in when you proceed</p>
                @endguest

                <form action="{{ route('cart.clear') }}" method="POST" class="text-center" onsubmit="return confirm('Clear all items from cart?');">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="text-sm text-red-600 hover:text-red-700 font-semibold transition">
                        <i class="fas fa-trash-alt mr-1"></i> Clear Cart
                    </button>
                </form>

                {{-- Trust Badges --}}
                <div class="mt-6 pt-6 border-t border-gray-200 space-y-2">
                    <div class="flex items-center gap-2 text-xs text-gray-600">
                        <i class="fas fa-shield-alt text-green-500"></i>
                        <span>Secure Payment</span>
                    </div>
                    <div class="flex items-center gap-2 text-xs text-gray-600">
                        <i class="fas fa-truck text-blue-500"></i>
                        <span>Free Delivery</span>
                    </div>
                    <div class="flex items-center gap-2 text-xs text-gray-600">
                        <i class="fas fa-undo text-orange-500"></i>
                        <span>Easy Returns</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @endif
</div>

@push('scripts')
<script>
function changeItemQty(itemId, delta) {
    const input = document.getElementById('qty-' + itemId);
    let val = parseInt(input.value) + delta;
    val = Math.max(1, Math.min(99, val));
    input.value = val;
    
    // Auto-update via AJAX
    fetch(`/cart/items/${itemId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            'Accept': 'application/json'
        },
        body: JSON.stringify({ quantity: val })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        }
    })
    .catch(error => {
        console.error('Error:', error);
        // Fallback to form submit
        const form = input.closest('form');
        if (form) {
            const formData = new FormData(form);
            formData.set('quantity', val);
            fetch(form.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                }
            }).then(() => location.reload());
        }
    });
}
</script>
@endpush
@endsection
