@extends('layouts.app')

@section('title', 'Checkout - ' . \App\Models\Setting::get('site_name', 'KiyoKart'))

@php
    $gaBeginCheckoutItems = $cart->items->map(function ($item) {
        return [
            'item_id' => (string) (($item->product->sku ?? null) ?: $item->product_id),
            'item_name' => (string) ($item->product->name ?? 'Product'),
            'price' => (float) $item->price_at_add,
            'quantity' => (int) $item->qty,
        ];
    })->values()->all();

    $gaBeginCheckoutPayload = [
        'currency' => 'INR',
        'value' => (float) ($cart->totals['total'] ?? 0),
        'items' => $gaBeginCheckoutItems,
    ];
@endphp

@section('content')
<div class="checkout-page">
    <div class="checkout-container">
        <!-- Left Column: Checkout Form -->
        <div class="checkout-main">
            @php
                $user = auth()->user();
                $nameEmpty = empty($user->name);
                $emailEmpty = empty($user->email);
                $phoneEmpty = empty($user->mobile);
                $showCustomerInfo = $nameEmpty && $emailEmpty && $phoneEmpty;
            @endphp

            @if($showCustomerInfo)
            <!-- Customer Details Section -->
            <div class="checkout-section">
                <h2 class="section-title">Customer Information</h2>
                
                <div class="form-group">
                    <label for="customer_name">Full Name *</label>
                    <input type="text" id="customer_name" name="name" class="form-control-modern" 
                           value="{{ auth()->user()->name }}" required>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="customer_email">Email Address *</label>
                        <input type="email" id="customer_email" name="email" class="form-control-modern" 
                               value="{{ auth()->user()->email ?? '' }}" required>
                    </div>
                    <div class="form-group">
                        <label for="customer_phone">Phone Number *</label>
                        <div class="input-group">
                            <span class="input-group-text">+91</span>
                            <input type="tel" id="customer_phone" name="mobile" class="form-control-modern" 
                                   value="{{ auth()->user()->mobile }}" placeholder="9876543210" maxlength="10" pattern="[6-9]\d{9}" required>
                        </div>
                    </div>
                </div>
            </div>
            @endif

            <!-- Delivery Address Section -->
            <div class="checkout-section">
                <h2 class="section-title">Delivery Address</h2>
                
                @if($addresses->count())
                    <div class="address-options">
                        @foreach($addresses as $address)
                            <label class="address-option">
                                <input type="radio" name="address_id" value="{{ $address->id }}" 
                                       {{ $address->is_default ? 'checked' : '' }} required>
                                <div class="address-card">
                                    <div class="address-header">
                                        <strong>{{ $address->name }}</strong>
                                        @if($address->is_default)
                                            <span class="badge-default">Default</span>
                                        @endif
                                    </div>
                                    <div class="address-details">
                                        <p>{{ $address->full_address }}</p>
                                        <p class="text-muted">{{ $address->mobile }}</p>
                                    </div>
                                </div>
                            </label>
                        @endforeach
                    </div>
                @endif

                <!-- Add New Address -->
                <button type="button" class="btn-add-address" data-bs-toggle="collapse" data-bs-target="#newAddressForm">
                    <i class="bi bi-plus-circle"></i> Add New Address
                </button>

                <div class="collapse mt-3" id="newAddressForm">
                    <form action="{{ route('checkout.address.store') }}" method="POST" class="address-form">
                        @csrf
                        <div class="form-row">
                            <div class="form-group">
                                <label>Name *</label>
                                <input type="text" name="name" class="form-control-modern" required>
                            </div>
                            <div class="form-group">
                                <label>Mobile *</label>
                                <div class="input-group">
                                    <span class="input-group-text">+91</span>
                                    <input type="text" name="mobile" class="form-control" 
                                           placeholder="9876543210" maxlength="10" pattern="[6-9]\d{9}" required>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>Address Line 1 *</label>
                            <input type="text" name="line1" class="form-control-modern" required>
                        </div>
                        <div class="form-group">
                            <label>Address Line 2</label>
                            <input type="text" name="line2" class="form-control-modern">
                        </div>
                        <div class="row">
                            <div class="form-group col-md-4">
                                <label>Country *</label>
                                <select name="country_id" id="countrySelect" class="form-control-modern" required data-selected-country="{{ old('country_id') }}" onchange="onCountryChange(this.value);">
                                    <option value="">Select country</option>
                                </select>
                            </div>
                            <div class="form-group col-md-4">
                                <label>State *</label>
                                <select name="state_id" id="stateSelect" class="form-control-modern" required data-selected-state="{{ old('state_id') }}" disabled onchange="onStateChange(this.value);">
                                    <option value="">Select state</option>
                                </select>
                            </div>
                            <div class="form-group col-md-4">
                                <label>City *</label>
                                <select name="city_id" id="citySelect" class="form-control-modern" required data-selected-city="{{ old('city_id') }}" disabled onchange="onCityChange(this.value);">
                                    <option value="">Select city</option>
                                </select>
                            </div>
                        </div>
                        <input type="hidden" name="state" id="stateNameInput" value="{{ old('state') }}">
                        <input type="hidden" name="city" id="cityNameInput" value="{{ old('city') }}">
                        <div class="form-row">
                            <div class="form-group">
                                <label>PIN Code *</label>
                                <input type="text" name="pin" class="form-control-modern" maxlength="6" required>
                            </div>
                            <div class="form-group form-check-modern">
                                <input type="checkbox" name="is_default" id="isDefault" value="1">
                                <label for="isDefault" class="pt-2">Set as default address</label>
                            </div>
                        </div>
                        
                        <button type="submit" class="btn-primary-modern">Save Address</button>
                    </form>
                </div>
            </div>

            <!-- Shipping Options -->
            <div class="checkout-section">
                <h2 class="section-title">Shipping Method</h2>
                @if(isset($shippingMethods) && $shippingMethods->count() > 0)
                    <div class="shipping-options">
                        @foreach($shippingMethods as $index => $method)
                            <label class="shipping-option">
                                <input type="radio" name="shipping_method" value="{{ $method->code }}" 
                                       {{ $index === 0 ? 'checked' : '' }} 
                                       data-price="{{ $method->price }}">
                                <div class="shipping-card">
                                    <div class="shipping-header">
                                        <strong>{{ $method->name }}</strong>
                                        <span class="shipping-price">
                                            @if($method->price == 0)
                                                FREE
                                            @else
                                                ₹{{ number_format($method->price, 2) }}
                                            @endif
                                        </span>
                                    </div>
                                    <p class="shipping-desc">
                                        {{ $method->description ?? $method->estimated_days }}
                                    </p>
                                </div>
                            </label>
                        @endforeach
                    </div>
                @else
                    <div class="alert alert-warning">
                        <i class="bi bi-exclamation-triangle"></i> No shipping methods available. Please contact support.
                    </div>
                @endif
            </div>

            <!-- Payment Section -->
            <div class="checkout-section">
                <h2 class="section-title">Payment</h2>
                <p class="section-subtitle">All transactions are secure and encrypted.</p>
                
                <div class="payment-methods">
                    @if($razorpayEnabled)
                        <label class="payment-method">
                            <input type="radio" name="payment_method" value="razorpay" checked>
                            <div class="payment-card">
                                <div class="payment-card-header">
                                    <div class="payment-header">
                                        <strong>Full Payment - Razorpay</strong>
                                        <div class="payment-logos">
                                            <img src="{{ asset('images/visa.webp') }}" alt="Visa" height="20">
                                            <img src="{{ asset('images/mastercard-logo.svg') }}" alt="Mastercard" height="18">
                                            <img src="{{ asset('images/google_pay_logo.png') }}" alt="Google Pay" height="18">
                                            <span class="more-options">+10</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="payment-card-content">
                                    <div class="payment-redirect-illustration">
                                        <svg width="120" height="80" viewBox="0 0 120 80" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <!-- Browser window -->
                                            <rect x="10" y="15" width="70" height="50" rx="4" stroke="#333" stroke-width="2" fill="white"/>
                                            <rect x="10" y="15" width="70" height="20" rx="4" fill="#f0f0f0"/>
                                            <circle cx="18" cy="25" r="3" fill="#ff5f57"/>
                                            <circle cx="28" cy="25" r="3" fill="#ffbd2e"/>
                                            <circle cx="38" cy="25" r="3" fill="#28ca42"/>
                                            <line x1="45" y1="25" x2="75" y2="25" stroke="#ccc" stroke-width="1"/>
                                            <!-- Arrow pointing right -->
                                            <path d="M85 40 L105 40 M100 35 L105 40 L100 45" stroke="#333" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                    </div>
                                    <p class="payment-redirect-message">After clicking "Pay now", you will be redirected to Razorpay payment gateway to complete your purchase securely.</p>
                                </div>
                            </div>
                        </label>
                    @endif
                    @if($codEnabled)
                        <label class="payment-method">
                            <input type="radio" name="payment_method" value="cod">
                            <div class="payment-card">
                                <div class="payment-card-header">
                                    <div class="payment-header">
                                        <strong>Cash on Delivery</strong>
                                    </div>
                                </div>
                                <div class="payment-card-content">
                                    <p class="payment-redirect-message text-start">Pay when you receive your order</p>
                                </div>
                            </div>
                        </label>
                    @endif
                    @if(!$razorpayEnabled && !$codEnabled)
                        <div class="alert alert-danger">
                            <i class="bi bi-exclamation-triangle"></i> No payment methods are enabled. Please contact support.
                        </div>
                    @endif
                </div>
            </div>
        </div>

        <!-- Right Column: Order Summary -->
        <div class="checkout-sidebar">
            <div class="order-summary-card">
                <h3 class="summary-title">Order Summary</h3>
                
                <!-- Products List -->
                <div class="products-list">
                    @foreach($cart->items as $item)
                        <div class="product-item">
                            <div class="product-image-checkout">
                                @if($item->product && ($item->product->image_path || $item->product->image))
                                    <x-product-image :product="$item->product" context="listing" alt="{{ $item->product->name }}" onerror="this.onerror=null; this.outerHTML='<div class=&quot;product-placeholder-checkout&quot;><i class=&quot;bi bi-image&quot;></i></div>';" />
                                @else
                                    <div class="product-placeholder-checkout">
                                        <i class="bi bi-image"></i>
                                    </div>
                                @endif
                            </div>
                            <div class="product-details">
                                <h4 class="product-name">{{ $item->product->name }}</h4>
                                <p class="product-meta">Qty: {{ $item->qty }} × ₹{{ number_format($item->price_at_add, 2) }}</p>
                            </div>
                            <div class="product-price">
                                ₹{{ number_format($item->qty * $item->price_at_add, 2) }}
                            </div>
                        </div>
                    @endforeach
                </div>

                <!-- Discount Code -->
                <div class="checkout-section" style="padding-top: 1rem; border-top: 2px solid var(--border-color);">
                    <h3 class="section-title" style="font-size: 1rem; margin-bottom: 0.625rem;">Discount Code</h3>
                    <div class="coupon-section">
                        <div class="coupon-input-group">
                            <input type="text" id="coupon_code" class="form-control-modern" 
                                   placeholder="Enter coupon code" value="{{ $cart->coupon->code ?? '' }}">
                            <button type="button" id="apply-coupon" class="btn-apply-coupon">Apply</button>
                        </div>
                        <div id="coupon-message" class="coupon-message"></div>
                    </div>
                </div>

                <!-- Order Totals -->
                <div class="order-totals">
                    <div class="total-row">
                        <span>Subtotal</span>
                        <span id="subtotal-display">₹{{ number_format($cart->totals['subtotal'] ?? 0, 2) }}</span>
                    </div>
                    <div class="total-row" id="discount-row" style="display: none;">
                        <span class="text-success">Discount</span>
                        <span class="text-success" id="discount-display">-₹0.00</span>
                    </div>
                    <div class="total-row">
                        <span>Shipping</span>
                        <span id="shipping-display">₹{{ number_format($cart->totals['shipping'] ?? 0, 2) }}</span>
                    </div>
                    <div class="total-row total-final">
                        <span>Total</span>
                        <span id="total-display">₹{{ number_format($cart->totals['total'] ?? 0, 2) }}</span>
                    </div>
                </div>

                <!-- Place Order Button -->
                <button id="place-order-btn" class="btn-place-order">
                    <span>Place Order</span>
                    <i class="bi bi-arrow-right"></i>
                </button>

                <p class="security-note">
                    <i class="bi bi-shield-check"></i> Secure checkout. Your payment information is encrypted.
                </p>
            </div>
        </div>
    </div>
</div>

<!-- Order Confirmation Modal -->
<div class="modal fade mt-5" id="orderConfirmationModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content confirmation-modal">
            <div class="confirmation-content">
                <div class="confirmation-icon">
                    <i class="bi bi-check-circle-fill"></i>
                </div>
                <h2>Order Placed Successfully!</h2>
                <p class="confirmation-message">Thank you for your purchase. Your order has been confirmed.</p>
                <div class="order-id-display">
                    <span class="order-id-label">Order ID:</span>
                    <span class="order-id-value" id="confirmed-order-id">#12345</span>
                </div>
                <div class="confirmation-actions">
                    <a href="{{ route('customer.orders.index') }}" class="btn-view-orders">View My Orders</a>
                    <a href="{{ route('home') }}" class="btn-continue-shopping">Continue Shopping</a>
                </div>
            </div>
        </div>
    </div>
</div>

@push('styles')
<link rel="stylesheet" href="{{ asset('css/homepage.css') }}">
@endpush

@push('scripts')
{{-- GA4: Track checkout start (begin_checkout) once when checkout loads. --}}
<x-analytics.ga-events eventName="begin_checkout" :eventData="$gaBeginCheckoutPayload" />

<script>
// Remove legacy root-scoped POS service worker that can block Razorpay on checkout.
(function cleanupLegacyPosServiceWorker() {
    if (!('serviceWorker' in navigator) || !window.sessionStorage) {
        return;
    }

    const flag = 'legacy-pos-sw-cleaned';
    if (sessionStorage.getItem(flag) === '1') {
        return;
    }

    navigator.serviceWorker.getRegistrations().then((registrations) => {
        const staleRegistration = registrations.find((registration) => {
            const scriptUrl = registration.active?.scriptURL
                || registration.waiting?.scriptURL
                || registration.installing?.scriptURL
                || '';
            return scriptUrl.includes('/sw-pos.js') && registration.scope.endsWith('/');
        });

        if (!staleRegistration) {
            return;
        }

        staleRegistration.unregister().then((removed) => {
            if (!removed) {
                return;
            }
            sessionStorage.setItem(flag, '1');
            window.location.reload();
        });
    }).catch(() => {
        // Ignore cleanup errors; checkout should still continue normally.
    });
})();
</script>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
// User data from server (for fallback when form fields don't exist)
const razorpayFallbackEmail = 'chellojumounika@gmail.com';

const userData = {
    name: '{{ auth()->user()->name ?? '' }}',
    email: '{{ auth()->user()->email ?? '' }}',
    mobile: '{{ auth()->user()->mobile ?? '' }}'
};

// Cart totals from server
const cartData = {
    subtotal: {{ $cart->totals['subtotal'] ?? 0 }},
    discount: {{ $cart->totals['discount'] ?? 0 }},
    shipping: {{ $cart->totals['shipping'] ?? 0 }},
    total: {{ $cart->totals['total'] ?? 0 }}
};

const shippingApiBase = '/api/shipping';
const countrySelect = document.getElementById('countrySelect');
const stateSelect = document.getElementById('stateSelect');
const citySelect = document.getElementById('citySelect');
const stateNameInput = document.getElementById('stateNameInput');
const cityNameInput = document.getElementById('cityNameInput');

function resetSelect(selectEl, placeholder) {
    if (!selectEl) return;
    selectEl.innerHTML = `<option value="">${placeholder}</option>`;
    selectEl.value = '';
    selectEl.disabled = true;
}

function populateSelect(selectEl, items, placeholder, selectedId = null) {
    if (!selectEl) return;
    const options = [`<option value=\"\">${placeholder}</option>`];
    items.forEach(item => {
        const selected = selectedId && Number(selectedId) === Number(item.id) ? 'selected' : '';
        options.push(`<option value=\"${item.id}\" ${selected}>${item.name}</option>`);
    });
    selectEl.innerHTML = options.join('');
    selectEl.disabled = items.length === 0;
}

async function fetchJson(url) {
    const response = await fetch(url, { headers: { Accept: 'application/json' } });
    if (!response.ok) {
        throw new Error('Failed to load data');
    }
    return response.json();
}

async function loadCountries() {
    if (!countrySelect) return;
    const data = await fetchJson(`${shippingApiBase}/countries`);
    const countries = data.data || [];
    let selectedCountry = countrySelect.dataset.selectedCountry || countrySelect.dataset.selected || '';
    if (!selectedCountry) {
        const india = countries.find(c => c.code === 'IN');
        selectedCountry = india ? india.id : '';
    }
    populateSelect(countrySelect, countries, 'Select country', selectedCountry);
    if (selectedCountry) {
        await loadStates(selectedCountry, stateSelect?.dataset.selectedState || stateSelect?.dataset.selected || '');
    }
}

async function loadStates(countryId, selectedStateId = '') {
    if (!stateSelect || !countryId) return;
    resetSelect(stateSelect, 'Loading states...');
    resetSelect(citySelect, 'Select city');
    const data = await fetchJson(`${shippingApiBase}/states?country_id=${countryId}`);
    const states = data.data || [];
    populateSelect(stateSelect, states, 'Select state', selectedStateId);
    stateSelect.disabled = false;
    if (selectedStateId) {
        await loadCities(selectedStateId, citySelect?.dataset.selectedCity || citySelect?.dataset.selected || '');
    }
}

async function loadCities(stateId, selectedCityId = '') {
    if (!citySelect || !stateId) return;
    resetSelect(citySelect, 'Loading cities...');
    const data = await fetchJson(`${shippingApiBase}/cities?state_id=${stateId}`);
    const cities = data.data || [];
    populateSelect(citySelect, cities, 'Select city', selectedCityId);
    citySelect.disabled = false;
}

function syncHiddenLocationNames() {
    if (stateSelect && stateNameInput) {
        const selected = stateSelect.options[stateSelect.selectedIndex];
        stateNameInput.value = selected ? selected.textContent.trim() : '';
    }
    if (citySelect && cityNameInput) {
        const selected = citySelect.options[citySelect.selectedIndex];
        cityNameInput.value = selected ? selected.textContent.trim() : '';
    }
}

async function initAddressDropdowns() {
    if (!countrySelect) return;
    try {
        await loadCountries();
    } catch (e) {
        console.error('Failed to load location data', e);
    }
}

if (countrySelect) {
    countrySelect.addEventListener('change', async (e) => {
        resetSelect(stateSelect, 'Loading states...');
        resetSelect(citySelect, 'Select city');
        const countryId = e.target.value;
        if (countryId) {
            await loadStates(countryId);
        }
    });
}

function onCountryChange(countryId) {
    resetSelect(stateSelect, 'Loading states...');
    resetSelect(citySelect, 'Select city');
    if (countryId) {
        loadStates(countryId);
    }
    syncHiddenLocationNames();
}

function onStateChange(stateId) {
   resetSelect(citySelect, 'Loading cities...');
    // const stateId = stateId;
    if (stateId) {
     loadCities(stateId);
    }
    syncHiddenLocationNames();
}

function onCityChange(cityId) {
    syncHiddenLocationNames();
}

document.addEventListener('DOMContentLoaded', () => {
    initAddressDropdowns();
    const addressForm = document.querySelector('.address-form');
    if (addressForm) {
        addressForm.addEventListener('submit', syncHiddenLocationNames);
    }
});

// Helper function to safely get customer info (checks DOM first, then falls back to user data)
function getCustomerInfo() {
    const nameEl = document.getElementById('customer_name');
    const phoneEl = document.getElementById('customer_phone');
    const emailEl = document.getElementById('customer_email');
    const resolvedEmail = (emailEl ? emailEl.value : userData.email)?.trim() || razorpayFallbackEmail;
    
    return {
        name: nameEl ? nameEl.value : userData.name,
        contact: phoneEl ? phoneEl.value : userData.mobile,
        email: resolvedEmail
    };
}

// Update totals display
function updateTotals() {
    const selectedShipping = document.querySelector('input[name="shipping_method"]:checked');
    const shipping = selectedShipping ? parseFloat(selectedShipping.dataset.price || 0) : 0;
    const discount = cartData.discount;
    const subtotal = cartData.subtotal;
    const total = subtotal - discount + shipping;
    
    document.getElementById('subtotal-display').textContent = '₹' + subtotal.toFixed(2);
    document.getElementById('shipping-display').textContent = shipping === 0 ? 'FREE' : '₹' + shipping.toFixed(2);
    
    if (discount > 0) {
        document.getElementById('discount-row').style.display = 'flex';
        document.getElementById('discount-display').textContent = '-₹' + discount.toFixed(2);
    } else {
        document.getElementById('discount-row').style.display = 'none';
    }
    
    document.getElementById('total-display').textContent = '₹' + total.toFixed(2);
    
    // Update cartData
    cartData.shipping = shipping;
    cartData.total = total;
}

// Shipping method change
document.querySelectorAll('input[name="shipping_method"]').forEach(radio => {
    radio.addEventListener('change', updateTotals);
});

// Coupon application
document.getElementById('apply-coupon').addEventListener('click', function() {
    const code = document.getElementById('coupon_code').value.trim();
    const messageDiv = document.getElementById('coupon-message');
    
    if (!code) {
        messageDiv.textContent = 'Please enter a coupon code';
        messageDiv.className = 'coupon-message error';
        return;
    }
    
    fetch('{{ route("cart.apply-coupon") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        },
        body: JSON.stringify({ code: code })
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            messageDiv.textContent = 'Coupon applied successfully!';
            messageDiv.className = 'coupon-message success';
            cartData.discount = data.discount || 0;
            updateTotals();
            setTimeout(() => location.reload(), 1000);
        } else {
            messageDiv.textContent = data.message || 'Invalid coupon code';
            messageDiv.className = 'coupon-message error';
        }
    })
    .catch(err => {
        messageDiv.textContent = 'Failed to apply coupon';
        messageDiv.className = 'coupon-message error';
    });
});

// Helpers for loading state on Place Order button
let isCheckoutLocked = false;
let isVerifyingPayment = false;

function showPlaceOrderLoading() {
    const btn = document.getElementById('place-order-btn');
    if (!btn) return;
    if (!btn.dataset.originalContent) {
        btn.dataset.originalContent = btn.innerHTML;
    }
    btn.disabled = true;
    btn.innerHTML = `
        <span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
        Processing...
    `;
}

function setPlaceOrderLoadingText(message) {
    const btn = document.getElementById('place-order-btn');
    if (!btn) return;
    btn.disabled = true;
    btn.innerHTML = `
        <span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
        ${message}
    `;
}

function restorePlaceOrderButton() {
    const btn = document.getElementById('place-order-btn');
    if (!btn) return;
    if (btn.dataset.originalContent) {
        btn.innerHTML = btn.dataset.originalContent;
    }
    btn.disabled = false;
    isCheckoutLocked = false;
    isVerifyingPayment = false;
}

// Place Order
document.getElementById('place-order-btn').addEventListener('click', function(e) {
    e.preventDefault();
    if (isCheckoutLocked) {
        return;
    }
    
    const addressId = document.querySelector('input[name="address_id"]:checked');
    if (!addressId) {
        alert('Please select a delivery address');
        return;
    }
    
    const paymentMethod = document.querySelector('input[name="payment_method"]:checked').value;
    
    // Disable button and show processing
    isCheckoutLocked = true;
    isVerifyingPayment = false;
    showPlaceOrderLoading();
    
    // Handle COD payment
    if (paymentMethod === 'cod') {
        fetch('{{ route("checkout.cod.create") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({ 
                address_id: addressId.value,
                shipping_method: document.querySelector('input[name="shipping_method"]:checked')?.value || null
            })
        })
        .then(res => res.json())
        .then(data => {
            if (data.error) {
                alert(data.error);
                restorePlaceOrderButton();
                return;
            }
            
            if (data.success) {
                document.getElementById('confirmed-order-id').textContent = '#' + data.order_id;
                const modal = new bootstrap.Modal(document.getElementById('orderConfirmationModal'));
                modal.show();
                setTimeout(() => {
                    window.location.href = data.redirect;
                }, 3000);
            } else {
                alert('Failed to create order. Please try again.');
                restorePlaceOrderButton();
            }
        })
        .catch(err => {
            console.error(err);
            alert('Failed to create order. Please try again.');
            restorePlaceOrderButton();
        });
        return;
    }
    
    // Razorpay payment
    fetch('{{ route("checkout.razorpay.create") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
            'Accept': 'application/json'
        },
        body: JSON.stringify({ 
            address_id: addressId.value,
            shipping_method: document.querySelector('input[name="shipping_method"]:checked')?.value || null
        })
    })
    .then(res => {
        const contentType = res.headers.get('content-type') || '';
        const isJson = contentType.includes('application/json');

        if (!res.ok) {
            if (isJson) {
                return res.json().then(err => {
                    throw new Error(err.error || 'Failed to create order');
                });
            }

            return res.text().then(() => {
                throw new Error('Server returned an unexpected response. Please refresh and try again.');
            });
        }

        if (!isJson) {
            return res.text().then((raw) => {
                console.error('create-razorpay-order non-JSON response', {
                    status: res.status,
                    body_preview: raw ? raw.slice(0, 400) : null
                });
                throw new Error('Unexpected server response format. Please refresh and try again.');
            });
        }

        return res.json();
    })
    .then(data => {
        if (data.error) {
            alert(data.error);
            restorePlaceOrderButton();
            return;
        }
        
        const options = {
            key: data.key,
            amount: data.amount,
            currency: data.currency,
            name: '{{ \App\Models\Setting::get("site_name", "KiyoKart") }}',
            description: 'Order Payment',
            order_id: data.razorpay_order_id,
            handler: function(response) {
                isVerifyingPayment = true;
                setPlaceOrderLoadingText('Verifying payment...');
                const verifyUrl = '{{ route("checkout.razorpay.verify") }}';
                const csrfToken = '{{ csrf_token() }}';
                let attempts = 0;
                const maxAttempts = 3;
                function doVerify() {
                    attempts++;
                    const verifyPayload = {
                        razorpay_order_id: response.razorpay_order_id,
                        razorpay_payment_id: response.razorpay_payment_id,
                        razorpay_signature: response.razorpay_signature
                    };
                    return fetch(verifyUrl, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': csrfToken,
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify(verifyPayload)
                    }).then(function(res) {
                        return res.json().then(function(result) {
                            if (!res.ok) {
                                return Promise.reject(new Error(result.error || 'Verification failed'));
                            }
                            return result;
                        });
                    });
                }
                function runVerify() {
                    doVerify()
                        .then(function(result) {
                            if (result.success) {
                                window.location.href = result.redirect || '/customer/orders';
                            } else {
                                alert(result.error || 'Payment verification failed');
                                restorePlaceOrderButton();
                            }
                        })
                        .catch(function(err) {
                            if (attempts < maxAttempts) {
                                setTimeout(runVerify, 1500);
                            } else {
                                console.error('Payment verification error:', err);
                                alert('Payment verification failed. Please try again or contact support if the amount was deducted.');
                                restorePlaceOrderButton();
                            }
                        });
                }
                runVerify();
            },
            modal: {
                ondismiss: function() {
                    if (!isVerifyingPayment) {
                        restorePlaceOrderButton();
                    }
                }
            },
            prefill: getCustomerInfo(),
            theme: { color: '#13233c' }
        };
        
        const rzp = new Razorpay(options);
        rzp.open();
    })
    .catch(err => {
        console.error(err);
        alert('Failed to create order');
        restorePlaceOrderButton();
    });
});

// Initialize
updateTotals();
</script>
@endpush
@endsection

