<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
  <h1 class="text-2xl font-bold text-gray-800 mb-6">Checkout</h1>

  <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
    <!-- Shipping Form -->
    <div class="lg:col-span-2">
      <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <h2 class="text-lg font-semibold text-gray-800 mb-4">Shipping Address</h2>
        <form id="checkoutForm" action="/checkout/place-order" method="POST">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div class="md:col-span-2">
              <label class="block text-sm font-medium text-gray-700 mb-1">Full Name *</label>
              <input type="text" name="shippingName" value="<%= user.name %>" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Phone *</label>
              <input type="tel" name="shippingPhone" value="<%= user.phone || '' %>" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Pincode *</label>
              <input type="text" name="shippingPincode" value="<%= user.pincode || '' %>" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
            </div>
            <div class="md:col-span-2">
              <label class="block text-sm font-medium text-gray-700 mb-1">Address *</label>
              <textarea name="shippingAddress" rows="2" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500"><%= user.address || '' %></textarea>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">City *</label>
              <input type="text" name="shippingCity" value="<%= user.city || '' %>" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">State *</label>
              <input type="text" name="shippingState" value="<%= user.state || '' %>" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
            </div>
          </div>

          <h2 class="text-lg font-semibold text-gray-800 mt-6 mb-4">Payment Method</h2>
          <div class="space-y-3">
            <label class="flex items-center gap-3 p-4 border border-gray-200 rounded-lg cursor-pointer hover:border-indigo-600">
              <input type="radio" name="paymentMethod" value="cod" checked onchange="togglePayment(this.value)">
              <div>
                <span class="font-medium text-gray-800">Cash on Delivery</span>
                <p class="text-sm text-gray-500">Pay when you receive</p>
              </div>
            </label>
            <label class="flex items-center gap-3 p-4 border border-gray-200 rounded-lg cursor-pointer hover:border-indigo-600">
              <input type="radio" name="paymentMethod" value="razorpay" onchange="togglePayment(this.value)">
              <div>
                <span class="font-medium text-gray-800">Online Payment (Razorpay)</span>
                <p class="text-sm text-gray-500">Credit/Debit Card, UPI, NetBanking</p>
              </div>
            </label>
          </div>

          <div class="mt-6">
            <input type="hidden" name="notes" value="">
            <button type="submit" id="placeOrderBtn" class="w-full bg-indigo-600 text-white py-3 rounded-lg font-medium hover:bg-indigo-700 transition text-lg">
              Place Order - ₹<%= parseFloat(totals.total).toFixed(2) %>
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Order Summary -->
    <div>
      <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 sticky top-24">
        <h3 class="font-semibold text-gray-800 mb-4">Order Summary</h3>
        <div class="space-y-3">
          <% items.forEach(function(item) { %>
            <div class="flex items-center gap-3">
              <div class="w-12 h-12 bg-gray-100 rounded-lg overflow-hidden flex-shrink-0">
                <% if (item.Product && item.Product.images && item.Product.images.length) { %>
                  <img src="<%= item.Product.images[0].imagePath %>" class="w-full h-full object-cover">
                <% } else { %>
                  <div class="w-full h-full flex items-center justify-center text-gray-400"><i class="fas fa-image"></i></div>
                <% } %>
              </div>
              <div class="flex-1 min-w-0">
                <p class="text-sm font-medium text-gray-800 truncate"><%= item.Product.name %></p>
                <p class="text-xs text-gray-500">Qty: <%= item.quantity %></p>
              </div>
              <p class="text-sm font-medium">₹<%= (parseFloat(item.unitPrice) * item.quantity).toFixed(2) %></p>
            </div>
          <% }) %>
        </div>
        <hr class="my-4">
        <div class="space-y-2 text-sm">
          <div class="flex justify-between"><span class="text-gray-500">Subtotal</span><span>₹<%= parseFloat(totals.subtotal).toFixed(2) %></span></div>
          <% if (totals.discountAmount > 0) { %>
            <div class="flex justify-between text-green-600"><span>Discount</span><span>-₹<%= parseFloat(totals.discountAmount).toFixed(2) %></span></div>
          <% } %>
          <div class="flex justify-between"><span class="text-gray-500">Shipping</span><span><%= totals.shippingAmount > 0 ? '₹' + parseFloat(totals.shippingAmount).toFixed(2) : 'FREE' %></span></div>
          <div class="flex justify-between"><span class="text-gray-500">Tax</span><span>₹<%= parseFloat(totals.taxAmount).toFixed(2) %></span></div>
          <hr>
          <div class="flex justify-between text-lg font-bold"><span>Total</span><span class="text-indigo-600">₹<%= parseFloat(totals.total).toFixed(2) %></span></div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
function togglePayment(method) {
  // Only COD submits normally; Razorpay handled via JS
}

document.getElementById('checkoutForm').addEventListener('submit', async function(e) {
  const selectedPayment = document.querySelector('input[name="paymentMethod"]:checked').value;
  
  if (selectedPayment === 'razorpay') {
    e.preventDefault();
    await processRazorpayPayment();
  }
});

async function processRazorpayPayment() {
  const form = document.getElementById('checkoutForm');
  const formData = new FormData(form);
  const shippingData = {
    shippingName: formData.get('shippingName'),
    shippingPhone: formData.get('shippingPhone'),
    shippingPincode: formData.get('shippingPincode'),
    shippingAddress: formData.get('shippingAddress'),
    shippingCity: formData.get('shippingCity'),
    shippingState: formData.get('shippingState'),
  };

  try {
    // Create Razorpay order
    const res = await fetch('/checkout/razorpay-order', { method: 'POST' });
    const data = await res.json();
    
    if (!data.success) {
      alert(data.message);
      return;
    }

    const options = {
      key: data.keyId,
      amount: data.order.amount,
      currency: data.order.currency,
      name: '<%= appName %>',
      order_id: data.order.id,
      handler: async function(response) {
        const verifyRes = await fetch('/checkout/verify-payment', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            razorpay_order_id: response.razorpay_order_id,
            razorpay_payment_id: response.razorpay_payment_id,
            razorpay_signature: response.razorpay_signature,
            shipping: JSON.stringify(shippingData),
          }),
        });
        const verifyData = await verifyRes.json();
        if (verifyData.success) {
          window.location.href = '/account/orders/' + verifyData.orderId;
        } else {
          alert('Payment verification failed: ' + verifyData.message);
        }
      },
      modal: {
        ondismiss: function() {
          console.log('Payment dismissed');
        },
      },
      prefill: {
        name: shippingData.shippingName,
        contact: shippingData.shippingPhone,
        email: '<%= user.email %>',
      },
      theme: { color: '#4f46e5' },
    };

    const rzp = new Razorpay(options);
    rzp.open();
  } catch (err) {
    alert('Error initiating payment: ' + err.message);
  }
}
</script>
<% if (typeof razorpayKeyId !== 'undefined' && razorpayKeyId && razorpayKeyId !== 'your_razorpay_key_id') { %>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<% } %>
