@extends('layouts.app')

@section('title', 'Checkout - ' . \App\Models\Setting::get('site_name', 'KiyoKart'))

@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="row g-3 address-options">
                        @foreach($addresses as $address)
                            <label class="address-option col-12 col-md-6 col-lg-4 mb-0">
                                <input type="radio" name="address_id" value="{{ $address->id }}" 
                                       {{ $address->is_default ? 'checked' : '' }} required>
                                <div class="address-card">
                                    <div class="address-header">
                                        <div class="d-flex align-items-center gap-2">
                                            <strong>{{ $address->name }}</strong>
                                            @if($address->is_default)
                                                <span class="badge-default">Default</span>
                                            @endif
                                        </div>
                                        <button
                                            type="button"
                                            class="btn btn-sm btn-outline-secondary js-edit-address"
                                            data-address-id="{{ $address->id }}"
                                            aria-label="Edit address"
                                            title="Edit address">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                    </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" novalidate>
                        @csrf
                        <input type="hidden" name="_method" id="addressFormMethod" value="PUT" disabled>
                        <input type="hidden" id="addressFormUpdateUrlBase" value="{{ url('/checkout/address') }}">
                        <div class="form-row">
                            <div class="form-group">
                                <label>Name *</label>
                                <input type="text" name="name" class="form-control-modern" required maxlength="50" autocomplete="name">
                                <div class="invalid-feedback d-block js-field-error" data-error-for="name"></div>
                            </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="[5-9]\d{9}" required inputmode="numeric" autocomplete="tel-national">
                                </div>
                                <div class="invalid-feedback d-block js-field-error" data-error-for="mobile"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>Address Line 1 *</label>
                            <input type="text" name="line1" class="form-control-modern" required maxlength="100" autocomplete="address-line1">
                            <div class="invalid-feedback d-block js-field-error" data-error-for="line1"></div>
                        </div>
                        <div class="form-group">
                            <label>Address Line 2</label>
                            <input type="text" name="line2" class="form-control-modern" maxlength="100" autocomplete="address-line2">
                            <div class="invalid-feedback d-block js-field-error" data-error-for="line2"></div>
                        </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 class="invalid-feedback d-block js-field-error" data-error-for="country_id"></div>
                            </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 class="invalid-feedback d-block js-field-error" data-error-for="state_id"></div>
                            </div>
                            <div class="form-group col-md-4">
                                <label>City *</label>
                                <select name="city_id" id="citySelect" class="form-control-modern" required data-city-select data-selected-city="{{ old('city_id') }}" disabled onchange="onCityChange();">
                                    <option value="">Select city</option>
                                </select>
                                <div class="invalid-feedback d-block js-field-error" data-error-for="city_id"></div>
                                <div class="d-none mt-2" data-city-custom-wrap>
                                    <label class="small d-block mb-1">Enter your city *</label>
                                    <input type="text" name="city_custom" class="form-control-modern" maxlength="100" autocomplete="address-level2" data-city-custom value="{{ old('city_custom') }}">
                                    <div class="invalid-feedback d-block js-field-error" data-error-for="city_custom"></div>
                                </div>
                            </div>
                            <div class="col-12 mt-1">
                                @include('partials.address-city-help')
                            </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 inputmode="numeric" pattern="[1-9]\d{5}" autocomplete="postal-code">
                                <div class="invalid-feedback d-block js-field-error" data-error-for="pin"></div>
                            </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>
                        
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn-primary-modern" id="addressSubmitBtn">Save Address</button>
                            <button type="button" class="btn btn-outline-secondary" id="cancelEditAddressBtn" style="display:none;">Cancel</button>
                        </div>
                    </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)
                            @php
                                $effectiveShippingPrice = $method->calculateCharge($cart->totals['subtotal'] ?? 0);
                            @endphp
                            <label class="shipping-option">
                                <input type="radio" name="shipping_method" value="{{ $method->code }}" 
                                       {{ $index === 0 ? 'checked' : '' }} 
                                       data-price="{{ $method->price }}"
                                       data-cart-value="{{ $method->cart_value ?? '' }}">
                                <div class="shipping-card">
                                    <div class="shipping-header">
                                        <strong>{{ $method->name }}</strong>
                                        <span class="shipping-price">
                                            @if($effectiveShippingPrice == 0 && $method->price > 0)
                                                <span class="text-muted text-decoration-line-through">₹{{ number_format($method->price, 2) }}</span> FREE
                                            @elseif($effectiveShippingPrice == 0)
                                                FREE
                                            @else
                                                ₹{{ number_format($effectiveShippingPrice, 2) }}
                                            @endif
                                        </span>
                                    </div>
                                    <p class="shipping-desc">
                                        {{ $method->description ?? $method->estimated_days }}
                                        @if($method->cart_value)
                                            <br><small class="text-muted">Free on orders over ₹{{ number_format($method->cart_value, 2) }}</small>
                                        @endif
                                    </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="small" 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 -->
                @php
                    $defaultMethod = isset($shippingMethods) ? $shippingMethods->first() : null;
                    $checkoutSubtotal = $cart->totals['subtotal'] ?? 0;
                    $checkoutShipping = $defaultMethod ? $defaultMethod->calculateCharge($checkoutSubtotal) : ($cart->totals['shipping'] ?? 0);
                    $checkoutShippingOriginalPrice = $defaultMethod ? (float) $defaultMethod->price : 0;
                @endphp
                <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">
                            @if($checkoutShipping == 0 && $checkoutShippingOriginalPrice > 0)
                                <span class="text-muted text-decoration-line-through">₹{{ number_format($checkoutShippingOriginalPrice, 2) }}</span> FREE
                            @elseif($checkoutShipping == 0)
                                FREE
                            @else
                                ₹{{ number_format($checkoutShipping, 2) }}
                            @endif
                        </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

@php
    $checkoutAddressesJson = $addresses
        ->map(function ($address) {
            return [
                'id' => $address->id,
                'name' => $address->name,
                'mobile' => preg_replace('/^\+91/', '', (string) $address->mobile),
                'line1' => $address->line1,
                'line2' => $address->line2,
                'country_id' => $address->country_id,
                'state_id' => $address->state_id,
                'city_id' => $address->city_id,
                'city' => $address->cityRelation?->name ?? $address->city,
                'pin' => $address->pin,
                'is_default' => (bool) $address->is_default,
            ];
        })
        ->keyBy('id')
        ->toArray();
@endphp
<script type="application/json" id="checkout-addresses-json">{!! json_encode($checkoutAddressesJson, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) !!}</script>
<script type="application/json" id="checkout-user-data-json">{!! json_encode([
    'name' => auth()->user()->name ?? '',
    'email' => auth()->user()->email ?? '',
    'mobile' => auth()->user()->mobile ?? '',
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) !!}</script>
<script type="application/json" id="checkout-cart-data-json">{!! json_encode([
    'subtotal' => $cart->totals['subtotal'] ?? 0,
    'discount' => $cart->totals['discount'] ?? 0,
    'shipping' => $cart->totals['shipping'] ?? 0,
    'total' => $cart->totals['total'] ?? 0,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) !!}</script>

@push('scripts')
<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="{{ asset('js/address-location.js') }}"></script>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
// User/cart data from server (JSON script tags avoid Blade-in-JS escaping issues)
const razorpayFallbackEmail = 'sudheerktonegramgold21@gmail.com';
const userData = JSON.parse(document.getElementById('checkout-user-data-json')?.textContent || '{}');
const cartData = JSON.parse(document.getElementById('checkout-cart-data-json')?.textContent || '{}');

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');
const addressForm = document.querySelector('.address-form');
const addressFormMethod = document.getElementById('addressFormMethod');
const addressFormUpdateUrlBase = document.getElementById('addressFormUpdateUrlBase');
const addressSubmitBtn = document.getElementById('addressSubmitBtn');
const cancelEditAddressBtn = document.getElementById('cancelEditAddressBtn');
const newAddressCollapseEl = document.getElementById('newAddressForm');
const newAddressCollapse = newAddressCollapseEl && window.bootstrap ? new bootstrap.Collapse(newAddressCollapseEl, { toggle: false }) : null;
const checkoutAddresses = JSON.parse(document.getElementById('checkout-addresses-json')?.textContent || '{}');

function normalizeSpaces(value) {
    return String(value ?? '').replace(/\s+/g, ' ').trim();
}

function isRepeatedSpam(value, threshold = 6) {
    const normalized = normalizeSpaces(value).toLowerCase().replace(/\s/g, '');
    if (normalized.length < threshold) {
        return false;
    }
    return /^([a-z0-9])\1+$/.test(normalized);
}

function hasAtLeastTwoWords(value) {
    return normalizeSpaces(value).split(' ').filter(Boolean).length >= 2;
}

function setFieldError(input, message) {
    if (!input || !addressForm) {
        return;
    }
    const errorEl = addressForm.querySelector(`[data-error-for="${input.name}"]`);
    input.classList.add('is-invalid');
    if (errorEl) {
        errorEl.textContent = message;
    }
}

function clearFieldError(input) {
    if (!input || !addressForm) {
        return;
    }
    const errorEl = addressForm.querySelector(`[data-error-for="${input.name}"]`);
    input.classList.remove('is-invalid');
    if (errorEl) {
        errorEl.textContent = '';
    }
}

function validateAddressField(input) {
    if (!input) {
        return true;
    }

    const field = input.name;
    const value = normalizeSpaces(input.value);
    input.value = value;
    clearFieldError(input);

    if (field === 'name') {
        if (!value) {
            setFieldError(input, 'Name is required.');
            return false;
        }
        if (value.length < 2 || value.length > 50) {
            setFieldError(input, 'Name must be between 2 and 50 characters.');
            return false;
        }
        if (!/^[A-Za-z ]+$/.test(value)) {
            setFieldError(input, 'Name can contain only letters and spaces.');
            return false;
        }
        return true;
    }

    if (field === 'mobile') {
        const digitsOnly = value.replace(/\D/g, '');
        input.value = digitsOnly;
        if (!digitsOnly) {
            setFieldError(input, 'Mobile number is required.');
            return false;
        }
        if (!/^[5-9]\d{9}$/.test(digitsOnly)) {
            setFieldError(input, 'Mobile number must be 10 digits and start with 5 to 9.');
            return false;
        }
        return true;
    }

    if (field === 'line1') {
        if (!value) {
            setFieldError(input, 'Address Line 1 is required.');
            return false;
        }
        if (value.length < 5 || value.length > 100) {
            setFieldError(input, 'Address Line 1 must be between 5 and 100 characters.');
            return false;
        }
        if (!/[A-Za-z0-9]/.test(value)) {
            setFieldError(input, 'Address Line 1 must include at least one letter or number.');
            return false;
        }
        if (!/^[A-Za-z0-9\s,.\-\/#()]+$/.test(value)) {
            setFieldError(input, 'Address Line 1 can contain only English letters, numbers, and basic punctuation.');
            return false;
        }
        if (!hasAtLeastTwoWords(value)) {
            setFieldError(input, 'Address Line 1 must contain at least 2 words.');
            return false;
        }
        if (isRepeatedSpam(value)) {
            setFieldError(input, 'Address Line 1 looks invalid. Please enter a meaningful address.');
            return false;
        }
        return true;
    }

    if (field === 'line2') {
        if (!value) {
            return true;
        }
        if (value.length > 100) {
            setFieldError(input, 'Address Line 2 cannot exceed 100 characters.');
            return false;
        }
        if (!/^[A-Za-z0-9\s,.\-\/#()]+$/.test(value)) {
            setFieldError(input, 'Address Line 2 can contain only English letters, numbers, and basic punctuation.');
            return false;
        }
        if (isRepeatedSpam(value)) {
            setFieldError(input, 'Address Line 2 looks invalid. Please enter a meaningful value.');
            return false;
        }
        return true;
    }

    if (field === 'pin') {
        const digitsOnly = value.replace(/\D/g, '');
        input.value = digitsOnly;
        if (!digitsOnly) {
            setFieldError(input, 'PIN Code is required.');
            return false;
        }
        if (!/^[1-9]\d{5}$/.test(digitsOnly)) {
            setFieldError(input, 'PIN Code must be 6 digits and cannot start with 0.');
            return false;
        }
        return true;
    }

    if (field === 'country_id') {
        if (!input.value) {
            setFieldError(input, 'Country is required.');
            return false;
        }
        return true;
    }

    if (field === 'state_id') {
        if (!input.value) {
            setFieldError(input, 'State is required.');
            return false;
        }
        return true;
    }

    if (field === 'city_id' || field === 'city_custom') {
        return AddressLocation.validateCityField(addressForm);
    }

    return true;
}

function validateAddressForm() {
    if (!addressForm) {
        return true;
    }

    const fields = ['name', 'mobile', 'line1', 'line2', 'pin', 'country_id', 'state_id', 'city_id']
        .map((fieldName) => addressForm.querySelector(`[name="${fieldName}"]`))
        .filter(Boolean);

    let firstInvalidField = null;
    let isFormValid = true;

    fields.forEach((field) => {
        const valid = validateAddressField(field);
        if (!valid) {
            isFormValid = false;
            if (!firstInvalidField) {
                firstInvalidField = field;
            }
        }
    });

    if (!isFormValid && firstInvalidField) {
        firstInvalidField.focus();
    }

    return isFormValid;
}

function setAddressFormMode(mode, addressId = null) {
    if (!addressForm) {
        return;
    }

    if (mode === 'edit' && addressId) {
        addressForm.action = `${addressFormUpdateUrlBase.value}/${addressId}`;
        if (addressFormMethod) {
            addressFormMethod.disabled = false;
        }
        if (addressSubmitBtn) {
            addressSubmitBtn.textContent = 'Update Address';
        }
        if (cancelEditAddressBtn) {
            cancelEditAddressBtn.style.display = 'inline-block';
        }
        addressForm.dataset.mode = 'edit';
        addressForm.dataset.editAddressId = String(addressId);
        return;
    }

    addressForm.action = '{{ route("checkout.address.store") }}';
    if (addressFormMethod) {
        addressFormMethod.disabled = true;
    }
    if (addressSubmitBtn) {
        addressSubmitBtn.textContent = 'Save Address';
    }
    if (cancelEditAddressBtn) {
        cancelEditAddressBtn.style.display = 'none';
    }
    addressForm.dataset.mode = 'create';
    delete addressForm.dataset.editAddressId;
}

async function populateAddressFormForEdit(address) {
    if (!addressForm || !address) {
        return;
    }

    addressForm.querySelector('[name="name"]').value = address.name || '';
    addressForm.querySelector('[name="mobile"]').value = (address.mobile || '').replace(/\D/g, '').slice(-10);
    addressForm.querySelector('[name="line1"]').value = address.line1 || '';
    addressForm.querySelector('[name="line2"]').value = address.line2 || '';
    addressForm.querySelector('[name="pin"]').value = (address.pin || '').replace(/\D/g, '');
    const isDefaultInput = addressForm.querySelector('[name="is_default"]');
    if (isDefaultInput) {
        isDefaultInput.checked = !!address.is_default;
    }

    if (countrySelect) {
        countrySelect.value = String(address.country_id || '');
        await loadStates(address.country_id, address.state_id);
    }
    if (stateSelect) {
        stateSelect.value = String(address.state_id || '');
        await loadCities(address.state_id, address.city_id, address.city || '');
    }

    syncHiddenLocationNames();
}

function clearAddressFormErrors() {
    if (!addressForm) {
        return;
    }
    addressForm.querySelectorAll('.js-field-error').forEach((el) => {
        el.textContent = '';
    });
    addressForm.querySelectorAll('.is-invalid').forEach((el) => {
        el.classList.remove('is-invalid');
    });
}

function resetAddressFormToCreateMode() {
    if (!addressForm) {
        return;
    }
    addressForm.reset();
    clearAddressFormErrors();
    setAddressFormMode('create');
    initAddressDropdowns();
}

function resetSelect(selectEl, placeholder) {
    AddressLocation.resetSelect(selectEl, placeholder);
}

function populateSelect(selectEl, items, placeholder, selectedId = null) {
    AddressLocation.populateSelect(selectEl, items, placeholder, selectedId);
}

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 = '', selectedCityName = '') {
    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;
    await AddressLocation.selectCityAfterLoad(citySelect, cities, selectedCityId, selectedCityName);
}

function syncHiddenLocationNames() {
    AddressLocation.syncHiddenLocationNames(addressForm);
}

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() {
    AddressLocation.handleCityChange(addressForm || citySelect);
}

document.addEventListener('DOMContentLoaded', async () => {
    await initAddressDropdowns();

    const cityCustomInputOnLoad = addressForm?.querySelector('[data-city-custom]');
    const oldCustomCity = cityCustomInputOnLoad?.value?.trim();
    if (oldCustomCity && stateSelect?.value && citySelect) {
        try {
            const data = await fetchJson(`${shippingApiBase}/cities?state_id=${stateSelect.value}`);
            await AddressLocation.selectCityAfterLoad(citySelect, data.data || [], '', oldCustomCity);
            syncHiddenLocationNames();
        } catch (e) {
            console.error('Failed to restore custom city', e);
        }
    }

    if (addressForm) {
        setAddressFormMode('create');

        ['name', 'mobile', 'line1', 'line2', 'pin'].forEach((fieldName) => {
            const field = addressForm.querySelector(`[name="${fieldName}"]`);
            if (!field) {
                return;
            }

            field.addEventListener('blur', () => validateAddressField(field));
            if (fieldName === 'mobile' || fieldName === 'pin') {
                field.addEventListener('input', () => {
                    field.value = field.value.replace(/\D/g, '');
                });
            }
        });

        ['country_id', 'state_id', 'city_id'].forEach((fieldName) => {
            const field = addressForm.querySelector(`[name="${fieldName}"]`);
            if (!field) {
                return;
            }
            field.addEventListener('change', () => {
                if (fieldName === 'city_id') {
                    onCityChange();
                }
                validateAddressField(field);
            });
            field.addEventListener('blur', () => validateAddressField(field));
        });

        const cityCustomInput = addressForm.querySelector('[data-city-custom]');
        if (cityCustomInput) {
            cityCustomInput.addEventListener('input', () => syncHiddenLocationNames());
            cityCustomInput.addEventListener('blur', () => AddressLocation.validateCityField(addressForm));
        }

        addressForm.addEventListener('submit', (event) => {
            AddressLocation.prepareCityForSubmit(addressForm);
            syncHiddenLocationNames();
            if (!validateAddressForm()) {
                event.preventDefault();
                AddressLocation.restoreCityFieldsAfterSubmit(addressForm);
            }
        });
    }

    if (cancelEditAddressBtn) {
        cancelEditAddressBtn.addEventListener('click', () => {
            resetAddressFormToCreateMode();
        });
    }

    document.querySelectorAll('.js-edit-address').forEach((btn) => {
        btn.addEventListener('click', async (event) => {
            event.preventDefault();
            event.stopPropagation();
            const addressId = Number(btn.dataset.addressId || 0);
            const address = checkoutAddresses[String(addressId)];
            if (!address) {
                return;
            }
            if (newAddressCollapse) {
                newAddressCollapse.show();
            } else if (newAddressCollapseEl) {
                newAddressCollapseEl.classList.add('show');
            }
            clearAddressFormErrors();
            await populateAddressFormForEdit(address);
            setAddressFormMode('edit', addressId);
            const firstInput = addressForm?.querySelector('[name="name"]');
            if (firstInput) {
                firstInput.focus();
            }
        });
    });
});

// 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
    };
}

function getShippingCharge(radio, subtotal) {
    const price = parseFloat(radio?.dataset.price || 0);
    const cartValue = parseFloat(radio?.dataset.cartValue || '');
    if (!isNaN(cartValue) && cartValue > 0 && subtotal >= cartValue) {
        return 0;
    }
    return price;
}

function formatShippingDisplay(shipping, originalPrice) {
    const price = parseFloat(originalPrice || 0);
    if (shipping === 0 && price > 0) {
        return '<span class="text-muted text-decoration-line-through">₹' + price.toFixed(2) + '</span> FREE';
    }
    if (shipping === 0) {
        return 'FREE';
    }
    return '₹' + shipping.toFixed(2);
}

// Update totals display
function updateTotals() {
    const selectedShipping = document.querySelector('input[name="shipping_method"]:checked');
    const subtotal = cartData.subtotal;
    const shipping = getShippingCharge(selectedShipping, subtotal);
    const originalPrice = selectedShipping ? selectedShipping.dataset.price : 0;
    const discount = cartData.discount;
    const total = subtotal - discount + shipping;
    
    document.getElementById('subtotal-display').textContent = '₹' + subtotal.toFixed(2);
    document.getElementById('shipping-display').innerHTML = formatShippingDisplay(shipping, originalPrice);
    
    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

