// cart.jsx — Cart drawer, checkout, confirmation

const CopyChip = ({ value }) => {
  const [copied, setCopied] = useState(false);
  const onCopy = () => {
    const txt = value.replace(/\s+/g,'');
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(txt);
    } else {
      const t = document.createElement('textarea');
      t.value = txt; document.body.appendChild(t); t.select();
      try { document.execCommand('copy'); } catch(e){}
      document.body.removeChild(t);
    }
    setCopied(true);
    setTimeout(()=>setCopied(false), 1500);
  };
  return (
    <button type="button" onClick={onCopy} className="copy-chip" aria-label={`Copy ${value}`}>
      <code>{value}</code>
      <span className="copy-ico">
        {copied ? (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5L20 7"/></svg>
        ) : (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>
        )}
      </span>
      <span className="copy-label">{copied ? 'Copied' : 'Copy'}</span>
    </button>
  );
};

const sendOrderToGoogleSheet = async (orderData) => {
  const url = window.SJ_DATA?.brand?.googleSheetsWebhook;
  if (!url) {
    console.warn('Google Sheets webhook URL is not configured');
    return false;
  }
  const body = JSON.stringify(orderData);
  try {
    console.log('Sending Google Sheets webhook (cors / text/plain)...', url, orderData);
    const response = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'text/plain' },
      body,
      keepalive: true,
      mode: 'cors',
    });
    if (response.ok) {
      const text = await response.text();
      console.log('Google Sheets webhook success:', text);
      try {
        const parsed = JSON.parse(text);
        if (parsed.success) return true;
      } catch (e) {
        return true;
      }
    }
    console.warn('Google Sheets webhook returned non-ok status:', response.status, response.statusText);
  } catch (err) {
    console.warn('Google Sheets webhook primary request failed. Retrying with no-cors...', err);
    try {
      await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'text/plain' },
        body,
        keepalive: true,
        mode: 'no-cors',
      });
      console.log('Google Sheets webhook sent via no-cors fallback');
      return true;
    } catch (fallbackErr) {
      console.warn('Google Sheets webhook no-cors fallback failed:', fallbackErr);
    }
    if (navigator.sendBeacon) {
      try {
        const blob = new Blob([body], { type: 'text/plain' });
        const beaconResult = navigator.sendBeacon(url, blob);
        console.log('Google Sheets beacon fallback result:', beaconResult);
        if (beaconResult) return true;
      } catch (beaconErr) {
        console.warn('Google Sheets beacon fallback failed:', beaconErr);
      }
    }
  }
  return false;
};

const CartDrawer = ({ open, onClose, cart, updateQty, removeItem, goto }) => {
  const subtotal = cart.reduce((s,it)=>s + it.price * it.qty, 0);
  return (
    <>
      <div className={`drawer-backdrop ${open?'open':''}`} onClick={onClose}></div>
      <aside className={`drawer ${open?'open':''}`} aria-hidden={!open}>
        <div className="drawer-header">
          <h3 style={{margin:0,fontFamily:'var(--font-display)',fontSize:22}}>Your cart</h3>
          <button className="icon-btn" onClick={onClose}><Icon name="close"/></button>
        </div>
        <div className="drawer-body">
          {cart.length === 0 ? (
            <div style={{textAlign:'center',padding:'48px 16px'}}>
              <div style={{fontSize:60,marginBottom:8}}>🫙</div>
              <h4 style={{margin:'0 0 6px',fontFamily:'var(--font-display)'}}>Cart is empty</h4>
              <p className="muted" style={{marginBottom:18}}>Add some achar to get started.</p>
              <button className="btn btn-primary" onClick={()=>{onClose();goto('shop');}}>Shop achar</button>
            </div>
          ) : (
            <div style={{display:'grid',gap:14}}>
              {cart.map((it,i)=>(
                <div key={i} className="cart-line">
                  <img src={it.image} alt="" loading="lazy" decoding="async"/>
                  <div className="info">
                    <div className="title">{it.name}</div>
                    <div className="meta">{it.weight}</div>
                    <div className="price">{fmt(it.price * it.qty)}</div>
                    <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
                      <div className="qty-stepper" style={{padding:2}}>
                        <button onClick={()=>updateQty(i, it.qty-1)}><Icon name="minus" size={14}/></button>
                        <span style={{minWidth:24,fontSize:14}}>{it.qty}</span>
                        <button onClick={()=>updateQty(i, it.qty+1)}><Icon name="plus" size={14}/></button>
                      </div>
                      <button onClick={()=>removeItem(i)} style={{background:'none',border:'none',color:'var(--ink-500)',fontSize:13,cursor:'pointer',textDecoration:'underline'}}>Remove</button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
        {cart.length > 0 && (
          <div className="drawer-footer">
            {(() => {
              const sub = cart.reduce((s,it)=>s + it.price * it.qty, 0);
              const below = sub < 220;
              return below ? (
                <div style={{marginBottom:10,padding:'10px 12px',background:'#fff4e6',border:'1px solid var(--saffron)',borderRadius:10,fontSize:12.5,color:'var(--saffron-dark)',textAlign:'center'}}>
                  Minimum order ₹220 · Add <strong>{fmt(220 - sub)}</strong> more
                </div>
              ) : null;
            })()}
            <div style={{display:'flex',justifyContent:'space-between',marginBottom:6,fontSize:14,color:'var(--ink-500)'}}>
              <span>Shipping</span><span style={{color:'var(--green-800)',fontWeight:600}}>FREE</span>
            </div>
            <div style={{display:'flex',justifyContent:'space-between',marginBottom:14}}>
              <span style={{fontWeight:600}}>Subtotal</span>
              <span style={{fontFamily:'var(--font-display)',fontSize:22,color:'var(--green-900)'}}>{fmt(subtotal)}</span>
            </div>
            {subtotal < 220 ? (
              <button className="btn btn-primary btn-block btn-lg" disabled style={{opacity:0.55,cursor:'not-allowed'}}>Add {fmt(220 - subtotal)} more to checkout</button>
            ) : (
              <button className="btn btn-primary btn-block btn-lg" onClick={()=>{onClose();goto('checkout');}}>Checkout · {fmt(subtotal)}</button>
            )}
            <button className="btn btn-ghost btn-block" style={{marginTop:8}} onClick={onClose}>Continue shopping</button>
          </div>
        )}
      </aside>
    </>
  );
};

const CheckoutPage = ({ cart, goto, onPlace }) => {
  const [pay, setPay] = useState('razorpay');
  const [form, setForm] = useState({
    name:'', phone:'', email:'',
    line1:'', line2:'', city:'', state:'', pin:''
  });

  useEffect(() => {
    if (window.fbq) {
      const total = cart.reduce((s, it) => s + ((it.price || 0) * (it.qty || 0)), 0);
      const ids = cart.map(it => String(it.id || it.sku || it.slug || ""));
      const count = cart.reduce((s, it) => s + (it.qty || 0), 0);
      window.fbq("track", "InitiateCheckout", {
        value: total,
        currency: "INR",
        content_ids: ids,
        content_type: "product",
        num_items: count
      });
    }
  }, []);
  const [webhookStatus, setWebhookStatus] = useState(null);
  const [payProcessing, setPayProcessing] = useState(false);
  const upd = (k) => (e) => setForm(f => ({...f, [k]: e.target.value}));
  const subtotal = cart.reduce((s,it)=>s + it.price * it.qty, 0);
  const MIN_ORDER = 220;
  const belowMin = subtotal < MIN_ORDER;
  const codFee = pay === 'cod' ? 50 : 0;
  const partialPrepay = pay === 'cod' ? 100 : 0;
  const prepaidDiscount = pay === 'razorpay' ? Math.round(subtotal * 0.05) : 0; const total = subtotal + codFee - prepaidDiscount;
  const codBalance = total - partialPrepay;

  const submitOrder = async (e) => {
    e.preventDefault();
    const orderId = 'SJ' + Date.now().toString().slice(-6);
    const lines = cart.map(it => `• ${it.name} (${it.weight}) × ${it.qty} — ${fmt(it.price * it.qty)}`).join('\n');
    let payLabel = 'Paid Online via Razorpay';
    if (pay === 'cod') {
      payLabel = `Cash on Delivery (₹50 COD fee)\n• Partial prepayment: ${fmt(partialPrepay)} (Paid Online via Razorpay)\n• Balance on delivery: ${fmt(codBalance)}`;
    }
    const msg =
`*New Order — Shudh Jain*
Order #${orderId}

*Customer*
${form.name}
${form.phone}${form.email ? `\n${form.email}` : ''}

*Shipping*
${form.line1}${form.line2 ? `, ${form.line2}` : ''}
${form.city}, ${form.state} — ${form.pin}

*Items*
${lines}

*Subtotal:* ${fmt(subtotal)}${codFee ? `\n*COD fee:* ${fmt(codFee)}` : ''}
*Total:* ${fmt(total)}

*Payment*
${payLabel}

(Sent from shudhjain.com)`;
    const orderData = {
      orderId,
      createdAt: new Date().toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' }),
      razorpayPaymentId: '',
      paymentStatus: 'pending',
      customer: {
        name: form.name,
        phone: form.phone,
        email: form.email,
      },
      shipping: {
        line1: form.line1,
        line2: form.line2,
        city: form.city,
        state: form.state,
        pin: form.pin,
      },
      payment: {
        method: pay,
        subtotal,
        codFee,
        total,
        partialPrepay,
        codBalance,
      },
      items: cart.map(it => ({ name: it.name, weight: it.weight, qty: it.qty, unitPrice: it.price, total: it.price * it.qty })),
      source: window.location.href,
    };

    if (pay === 'razorpay' || pay === 'cod') {
      if (!window.Razorpay) {
        alert("Razorpay payment gateway load nahi hua. Internet connection check karein.");
        return;
      }
      setPayProcessing(true);
      
      // 1. Send pending order details to Google Sheet immediately
      console.log('Sending pending order to Google Sheets first...');
      await sendOrderToGoogleSheet(orderData);

      const rzpAmount = pay === 'cod' ? partialPrepay : total;

      const rzpOptions = {
        key: window.SJ_DATA?.brand?.razorpayKeyId || "rzp_test_yourKeyHere",
        amount: rzpAmount * 100, // amount in paise
        currency: "INR",
        name: "Shudh Jain",
        description: pay === 'cod' ? `COD Prepayment for Order #${orderId}` : `Order #${orderId}`,
        image: "assets/logo.jpeg",
        prefill: {
          name: form.name,
          contact: form.phone,
          email: form.email || "",
        },
        notes: {
          orderId: orderId,
          address: `${form.line1}, ${form.city}, ${form.state} - ${form.pin}`,
        },
        handler: async function (response) {
          console.log('Razorpay payment success:', response);
          const paymentId = response.razorpay_payment_id;
          const statusVal = pay === 'cod' ? 'partially_paid' : 'paid';
          const orderDataPaid = {
            ...orderData,
            razorpayPaymentId: paymentId,
            paymentStatus: statusVal,
            payment: {
              ...orderData.payment,
              paymentId: paymentId,
              status: statusVal,
            }
          };
          const webhookSaved = await sendOrderToGoogleSheet(orderDataPaid);
          setWebhookStatus(webhookSaved ? 'saved' : 'failed');
          
          let paidMsg = msg;
          if (pay === 'cod') {
            paidMsg += `\n\n*Payment Details*\n• Status: PARTIALLY PAID (via Razorpay)\n• Razorpay Payment ID: ${paymentId}\n• Paid Online: ${fmt(partialPrepay)}\n• Balance on Delivery: ${fmt(codBalance)}`;
          } else {
            paidMsg += `\n\n*Payment Details*\n• Status: PAID (via Razorpay)\n• Razorpay Payment ID: ${paymentId}`;
          }

          const url = `https://wa.me/${window.SJ_DATA.brand.whatsapp}?text=${encodeURIComponent(paidMsg)}`;
          window.open(url, '_blank');
          setPayProcessing(false);
          
          if (window.fbq) {
            const __ids = cart.map(it => String(it.id || it.sku || it.slug || ""));
            const __count = cart.reduce((s, it) => s + (it.qty || 0), 0);
            window.fbq("track", "Purchase", {
              value: rzpAmount,
              currency: "INR",
              content_ids: __ids,
              content_type: "product",
              num_items: __count
            });
          }
          onPlace({ pay, total, subtotal, codFee, orderId, paymentId, ...form });
        },
        modal: {
          ondismiss: function () {
            console.log('Razorpay modal dismissed by user');
            setPayProcessing(false);
          },
          escape: true,
          confirm_close: true,
        },
        theme: {
          color: "#1f5f3d", // Brand green color
        }
      };
      console.log('Opening Razorpay with options:', { ...rzpOptions, key: '***hidden***' });
      const rzp = new window.Razorpay(rzpOptions);
      rzp.on('payment.failed', function (response) {
        console.error('Razorpay payment failed:', response.error);
        setPayProcessing(false);
        alert("Payment fail ho gaya: " + (response.error?.description || "Unknown error") + "\n\nDobara try karein.");
      });
      rzp.open();
    }
  };

  if (cart.length === 0) {
    return (
      <section className="section">
        <div className="container text-center">
          <div style={{fontSize:64,marginBottom:12}}>🫙</div>
          <h2 className="h-section">Your cart is empty</h2>
          <p className="muted" style={{marginBottom:20}}>Add a jar before you checkout.</p>
          <button className="btn btn-primary btn-lg" onClick={()=>goto('shop')}>Shop achar</button>
        </div>
      </section>
    );
  }

  const upiBlock = (amount, label) => (
    <div className="upi-block">
      <div className="upi-qr">
        <img src="assets/upi-qr.jpeg" alt="Scan to pay with any UPI app" loading="lazy" decoding="async"/>
      </div>
      <div className="upi-details">
        <div className="upi-amount">
          <span className="lab">Amount to pay</span>
          <strong>{fmt(amount)}</strong>
          {label && <span className="upi-tag">{label}</span>}
        </div>
        <div className="upi-row"><span>UPI ID</span><CopyChip value="jain.anil1967.aj@oksbi"/></div>
        <div className="upi-row"><span>Mobile (UPI)</span><CopyChip value="+91 88714 22534"/></div>
        <div className="upi-row"><span>Account holder</span><code>Anil Jain · SBI</code></div>
        <p className="upi-note">Scan QR with any UPI app — GPay, PhonePe, Paytm, BHIM. After paying, share the screenshot on WhatsApp.</p>
      </div>
    </div>
  );

  return (
    <section className="section-tight">
      <div className="container">
        <div style={{textAlign:'center',marginBottom:24}}>
          <span className="eyebrow">Almost there</span>
          <h1 className="h-section" style={{marginTop:8}}>Checkout</h1>
        </div>
        <div className="checkout-grid">
          <form onSubmit={submitOrder}>
            <div className="checkout-section">
              <h3>1. Contact</h3>
              <div className="contact-grid" style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,marginBottom:12}}>
                <div className="field"><label>Full name</label><input className="input" required value={form.name} onChange={upd('name')} maxLength={50}/></div>
                <div className="field">
                  <label>Phone (WhatsApp)</label>
                  <input className="input" required value={form.phone} onChange={(e) => {
                    const v = e.target.value.replace(/[^0-9+\s-]/g, '').slice(0, 15);
                    setForm(f => ({...f, phone: v}));
                  }} placeholder="+91 ..." maxLength={15}/>
                </div>
              </div>
              <div className="field"><label>Email (optional)</label><input className="input" type="email" value={form.email} onChange={upd('email')} maxLength={80}/></div>
            </div>

            <div className="checkout-section">
              <h3>2. Shipping address</h3>
              <div className="shipping-grid" style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:12,marginBottom:12}}>
                <div className="field">
                  <label>PIN code</label>
                  <input className="input" required value={form.pin} onChange={(e)=>{
                    const v = e.target.value.replace(/\D/g,'').slice(0,6);
                    setForm(f => ({...f, pin: v}));
                    if (v.length === 6) {
                      // 1. Resolve State offline for ALL Indian pincodes
                      const getStateByPin = (pin) => {
                        const prefix2 = pin.slice(0, 2);
                        const mapping2 = {
                          '11': 'Delhi',
                          '12': 'Haryana', '13': 'Haryana',
                          '14': 'Punjab', '15': 'Punjab', '16': 'Punjab',
                          '17': 'Himachal Pradesh',
                          '18': 'Jammu & Kashmir', '19': 'Jammu & Kashmir',
                          '20': 'Uttar Pradesh', '21': 'Uttar Pradesh', '22': 'Uttar Pradesh', '23': 'Uttar Pradesh', '24': 'Uttar Pradesh', '25': 'Uttar Pradesh', '26': 'Uttar Pradesh', '27': 'Uttar Pradesh', '28': 'Uttar Pradesh',
                          '30': 'Rajasthan', '31': 'Rajasthan', '32': 'Rajasthan', '33': 'Rajasthan', '34': 'Rajasthan',
                          '36': 'Gujarat', '37': 'Gujarat', '38': 'Gujarat', '39': 'Gujarat',
                          '40': 'Maharashtra', '41': 'Maharashtra', '42': 'Maharashtra', '43': 'Maharashtra', '44': 'Maharashtra',
                          '45': 'Madhya Pradesh', '46': 'Madhya Pradesh', '47': 'Madhya Pradesh', '48': 'Madhya Pradesh',
                          '49': 'Chhattisgarh',
                          '50': 'Telangana', '51': 'Andhra Pradesh', '52': 'Andhra Pradesh', '53': 'Andhra Pradesh',
                          '56': 'Karnataka', '57': 'Karnataka', '58': 'Karnataka', '59': 'Karnataka',
                          '60': 'Tamil Nadu', '61': 'Tamil Nadu', '62': 'Tamil Nadu', '63': 'Tamil Nadu', '64': 'Tamil Nadu',
                          '67': 'Kerala', '68': 'Kerala', '69': 'Kerala',
                          '70': 'West Bengal', '71': 'West Bengal', '72': 'West Bengal', '73': 'West Bengal', '74': 'West Bengal',
                          '75': 'Odisha', '76': 'Odisha', '77': 'Odisha',
                          '78': 'Assam',
                          '80': 'Bihar', '81': 'Bihar', '82': 'Bihar', '83': 'Bihar', '84': 'Bihar', '85': 'Bihar'
                        };
                        if (mapping2[prefix2]) return mapping2[prefix2];

                        const prefix3 = pin.slice(0, 3);
                        const mapping3 = {
                          '246': 'Uttarakhand', '247': 'Uttarakhand', '248': 'Uttarakhand', '249': 'Uttarakhand',
                          '825': 'Jharkhand', '826': 'Jharkhand', '827': 'Jharkhand', '828': 'Jharkhand', '829': 'Jharkhand', '831': 'Jharkhand', '832': 'Jharkhand', '833': 'Jharkhand', '834': 'Jharkhand', '835': 'Jharkhand', '814': 'Jharkhand', '815': 'Jharkhand', '816': 'Jharkhand',
                          '737': 'Sikkim',
                          '790': 'Arunachal Pradesh', '791': 'Arunachal Pradesh', '792': 'Arunachal Pradesh',
                          '795': 'Manipur',
                          '793': 'Meghalaya', '794': 'Meghalaya',
                          '796': 'Mizoram',
                          '797': 'Nagaland', '798': 'Nagaland',
                          '799': 'Tripura',
                          '403': 'Goa',
                          '605': 'Puducherry',
                          '682': 'Lakshadweep',
                          '744': 'Andaman & Nicobar Islands'
                        };
                        return mapping3[prefix3] || '';
                      };

                      // 2. Resolve popular cities offline for best experience
                      const getCityByPin = (pin) => {
                        const prefix3 = pin.slice(0, 3);
                        const mappingCity = {
                          '452': 'Indore', '453': 'Indore Rural',
                          '462': 'Bhopal', '474': 'Gwalior', '482': 'Jabalpur',
                          '110': 'New Delhi', '400': 'Mumbai', '411': 'Pune',
                          '560': 'Bengaluru', '380': 'Ahmedabad', '500': 'Hyderabad',
                          '700': 'Kolkata', '302': 'Jaipur', '395': 'Surat',
                          '201': 'Noida', '122': 'Gurugram', '600': 'Chennai'
                        };
                        return mappingCity[prefix3] || '';
                      };

                      const offlineState = getStateByPin(v);
                      const offlineCity = getCityByPin(v);

                      // Pre-fill State and City offline immediately
                      if (offlineState) {
                        setForm(f => ({
                          ...f,
                          state: offlineState,
                          city: offlineCity || f.city,
                          _pinLoading: true,
                          _pinErr: false
                        }));
                      } else {
                        setForm(f => ({ ...f, _pinLoading: true, _pinErr: false }));
                      }

                      // Try online enrichment (CORS/network may fail, but state is already resolved offline!)
                      fetch(`https://api.postalpincode.in/pincode/${v}`)
                        .then(r => r.json())
                        .then(d => {
                          const po = d && d[0] && d[0].PostOffice && d[0].PostOffice[0];
                          if (po) {
                            setForm(f => ({
                              ...f,
                              city: po.District || offlineCity || f.city,
                              state: po.State || offlineState || f.state,
                              _pinLoading: false,
                              _pinErr: false
                            }));
                          } else {
                            setForm(f => ({ ...f, _pinLoading: false }));
                          }
                        })
                        .catch(() => {
                          // Offline fallback is already active, just stop loading spinner silently!
                          setForm(f => ({ ...f, _pinLoading: false }));
                        });
                    }
                  }} maxLength={6} placeholder="452001" inputMode="numeric"/>
                  {form._pinLoading && <span style={{fontSize:11.5,color:'var(--ink-500)',marginTop:4}}>Looking up city…</span>}
                  {!form._pinLoading && form.city && form.pin.length===6 && <span style={{fontSize:11.5,color:'var(--green-700)',marginTop:4}}>✓ {form.city}, {form.state}</span>}
                </div>
                <div className="field"><label>City</label><input className="input" required value={form.city} onChange={upd('city')} maxLength={40}/></div>
                <div className="field"><label>State</label><input className="input" required value={form.state} onChange={upd('state')} maxLength={40}/></div>
              </div>
              <div className="field" style={{marginBottom:12}}><label>House / Flat / Building</label><input className="input" required value={form.line1} onChange={upd('line1')} maxLength={100}/></div>
              <div className="field"><label>Street / Area / Landmark</label><input className="input" required value={form.line2} onChange={upd('line2')} maxLength={100}/></div>
            </div>

            <div className="checkout-section">
              <h3>3. Payment</h3>
              <div className="pay-options">
                {[
                  { id:'razorpay', t:'Pay Online (Cards / UPI / Netbanking)', s:'Fast & Secure checkout via Razorpay', rec:true },
                  { id:'cod', t:'Cash on Delivery', s:'+ ₹50 COD charge · ₹100 partial prepayment online' },
                ].map(p=>(
                  <label key={p.id} className={`pay-option ${pay===p.id?'active':''}`}>
                    <input type="radio" name="pay" checked={pay===p.id} onChange={()=>setPay(p.id)}/>
                    <div style={{flex:1}}>
                      <div style={{display:'flex',alignItems:'center',gap:8}}>
                        <span style={{fontWeight:600}}>{p.t}</span>
                        {p.rec && <span style={{background:'var(--green-700)',color:'var(--cream-50)',fontSize:10,fontWeight:700,letterSpacing:'.1em',textTransform:'uppercase',padding:'2px 8px',borderRadius:999}}>Recommended</span>}
                      </div>
                      <div style={{fontSize:13,color:'var(--ink-500)',marginTop:2}}>{p.s}</div>
                    </div>
                  </label>
                ))}
              </div>

              {pay === 'cod' && (
                <div style={{marginTop:18}}>
                  <div className="cod-note">
                    <strong>Cash on Delivery — how it works</strong>
                    <ol>
                      <li>Pay <strong>{fmt(partialPrepay)}</strong> online now via Razorpay (UPI, Card, Netbanking) to confirm your order.</li>
                      <li>Pay the balance <strong>{fmt(codBalance)}</strong> in cash or UPI when our courier delivers.</li>
                      <li>A flat <strong>₹50 COD charge</strong> is included in your total.</li>
                    </ol>
                  </div>
                </div>
              )}
            </div>

            <div className="checkout-prepaid-note">Pay online (UPI/Card) — Save {fmt(prepaidDiscount)} on this order!</div><button className="btn btn-primary btn-block btn-lg" type="submit" style={{marginTop:12}} disabled={belowMin || payProcessing}>
              {payProcessing ? (
                <>⏳ Processing payment...</>
              ) : pay === 'razorpay' ? (
                <>Pay via Razorpay & Place Order · {fmt(total)}</>
              ) : pay === 'cod' ? (
                <>Pay Prepayment & Confirm Order · {fmt(partialPrepay)}</>
              ) : (
                <>
                  <Icon name="whatsapp" size={18}/> {belowMin ? `Add ${fmt(MIN_ORDER - subtotal)} more to checkout` : `Send order on WhatsApp · {fmt(total)}`}
                </>
              )}
            </button>

            {!belowMin && !payProcessing && (
              <button
                type="button"
                className="btn btn-ghost btn-block btn-lg"
                style={{marginTop:12, display:'flex', alignItems:'center', justifyContent:'center', gap:8, border:'1.5px solid var(--green-700)', color:'var(--green-700)'}}
                onClick={async (e) => {
                  const formEl = e.currentTarget.closest('form');
                  if (formEl && !formEl.checkValidity()) {
                    formEl.reportValidity();
                    return;
                  }
                  setPayProcessing(true);
                  const orderId = 'SJ' + Date.now().toString().slice(-6);
                  const lines = cart.map(it => `• ${it.name} (${it.weight}) × ${it.qty} — ${fmt(it.price * it.qty)}`).join('\n');
                  
                  let payLabel = 'WhatsApp / Manual order';
                  if (pay === 'cod') {
                    payLabel = `Cash on Delivery (WhatsApp Direct Order)\n• Partial prepayment: ${fmt(partialPrepay)} (To be paid manually)\n• Balance on delivery: ${fmt(codBalance)}`;
                  } else {
                    payLabel = `Online Pay (WhatsApp Direct Order)\n• Total Amount: ${fmt(total)} (To be paid manually)`;
                  }

                  const msg =
`*New Order via WhatsApp — Shudh Jain*
Order #${orderId}

*Customer*
${form.name}
${form.phone}${form.email ? `\n${form.email}` : ''}

*Shipping*
${form.line1}${form.line2 ? `, ${form.line2}` : ''}
${form.city}, ${form.state} — ${form.pin}

*Items*
${lines}

*Subtotal:* ${fmt(subtotal)}${codFee ? `\n*COD fee:* ${fmt(codFee)}` : ''}
*Total:* ${fmt(total)}

*Payment*
${payLabel}

(Sent from shudhjain.com)`;

                  const orderData = {
                    orderId,
                    createdAt: new Date().toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' }),
                    razorpayPaymentId: 'WhatsApp Manual',
                    paymentStatus: 'pending_whatsapp',
                    customer: {
                      name: form.name,
                      phone: form.phone,
                      email: form.email,
                    },
                    shipping: {
                      line1: form.line1,
                      line2: form.line2,
                      city: form.city,
                      state: form.state,
                      pin: form.pin,
                    },
                    payment: {
                      method: pay + '_whatsapp',
                      subtotal,
                      codFee,
                      total,
                      partialPrepay,
                      codBalance,
                    },
                    items: cart.map(it => ({ name: it.name, weight: it.weight, qty: it.qty, unitPrice: it.price, total: it.price * it.qty })),
                    source: window.location.href,
                  };

                  console.log('Sending direct WhatsApp order to Google Sheets...');
                  const webhookSaved = await sendOrderToGoogleSheet(orderData);
                  setWebhookStatus(webhookSaved ? 'saved' : 'failed');

                  const url = `https://wa.me/${window.SJ_DATA.brand.whatsapp}?text=${encodeURIComponent(msg)}`;
                  window.open(url, '_blank');
                  
                  setPayProcessing(false);
                  onPlace({ pay: pay + '_whatsapp', total, subtotal, codFee, orderId, ...form });
                }}
              >
                <Icon name="whatsapp" size={18}/> Send your order on WhatsApp
              </button>
            )}

            <p style={{textAlign:'center',marginTop:10,fontSize:12.5,color:'var(--ink-500)'}}>
              {pay === 'razorpay' || pay === 'cod'
                ? 'Clicking "Pay" will open the secure Razorpay payment modal.' 
                : 'Clicking will open WhatsApp with your order details pre-filled. Just hit send.'
              }
            </p>
            {webhookStatus === 'saved' && (
              <div style={{marginTop:12,padding:'12px 14px',background:'#e6ffed',border:'1px solid #7ddc91',borderRadius:10,fontSize:13.5,color:'#0f5132',textAlign:'center'}}>
                Order sent to Google Sheets successfully.
              </div>
            )}
            {webhookStatus === 'failed' && (
              <div style={{marginTop:12,padding:'12px 14px',background:'#fff1f0',border:'1px solid #f5c2c7',borderRadius:10,fontSize:13.5,color:'#842029',textAlign:'center'}}>
                Unable to send order to Google Sheets from browser. Check console or network.
              </div>
            )}
            {belowMin && (
              <div style={{marginTop:12,padding:'12px 14px',background:'#fff4e6',border:'1px solid var(--saffron)',borderRadius:10,fontSize:13.5,color:'var(--saffron-dark)',textAlign:'center'}}>
                <strong>Minimum order is {fmt(MIN_ORDER)}.</strong> Add {fmt(MIN_ORDER - subtotal)} more to your cart to continue. <a href="#" onClick={(e)=>{e.preventDefault();goto('shop');}} style={{color:'var(--saffron-dark)',textDecoration:'underline'}}>Browse products</a>
              </div>
            )}
            <p style={{textAlign:'center',marginTop:12,fontSize:13,color:'var(--ink-500)'}}>By placing this order you agree to our terms.</p>
          </form>

          <aside className="summary">
            <h4 style={{margin:'0 0 14px',fontFamily:'var(--font-display)',fontSize:20,color:'var(--green-900)'}}>Order summary</h4>
            <div style={{display:'grid',gap:12,marginBottom:14}}>
              {cart.map((it,i)=>(
                <div key={i} style={{display:'flex',gap:12}}>
                  <div style={{position:'relative',width:56,height:56,borderRadius:10,overflow:'hidden',background:'var(--cream-100)',flexShrink:0}}>
                    <img src={it.image} loading="lazy" decoding="async" style={{width:'100%',height:'100%',objectFit:'cover'}} alt=""/>
                    <span style={{position:'absolute',top:-4,right:-4,background:'var(--ink-900)',color:'var(--cream-50)',width:20,height:20,borderRadius:'50%',fontSize:11,display:'grid',placeItems:'center',fontWeight:600}}>{it.qty}</span>
                  </div>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontWeight:600,fontSize:14,lineHeight:1.2}}>{it.name}</div>
                    <div style={{fontSize:12,color:'var(--ink-500)'}}>{it.weight}</div>
                  </div>
                  <div style={{fontFamily:'var(--font-display)',color:'var(--ink-900)'}}>{fmt(it.price * it.qty)}</div>
                </div>
              ))}
            </div>
            <div className="line"><span>Subtotal</span><span>{fmt(subtotal)}</span></div>
            <div className="line"><span>Shipping</span><span style={{color:'var(--green-800)',fontWeight:600}}>FREE</span></div>
            {codFee > 0 && <div className="line"><span>COD charge</span><span>{fmt(codFee)}</span></div>}
            {prepaidDiscount > 0 && <div className="line" style={{color:'var(--green-700)',fontWeight:600}}><span>Prepaid Discount (5%)</span><span>-{fmt(prepaidDiscount)}</span></div>}<div className="line total"><span>Total Order Value</span><span>{fmt(total)}</span></div>
            {pay === 'cod' && (
              <>
                <div className="line" style={{color:'var(--green-700)',fontWeight:600}}>
                  <span>Prepayment (Pay Now)</span>
                  <span>-{fmt(partialPrepay)}</span>
                </div>
                <div className="line total" style={{borderTop:'1px dashed var(--ink-200)',paddingTop:8,marginTop:4}}>
                  <span>Balance on Delivery</span>
                  <span>{fmt(codBalance)}</span>
                </div>
              </>
            )}
            <div style={{marginTop:14,padding:14,background:'var(--cream-100)',borderRadius:10,fontSize:13,color:'var(--ink-700)'}}>
              <strong style={{display:'block',marginBottom:4}}><Icon name="truck" size={14}/> Estimated delivery</strong>
              4–7 business days · Free shipping pan-India
            </div>
          </aside>
        </div>
      </div>
    </section>
  );
};

const ConfirmationPage = ({ order, goto }) => (
  <section className="section">
    <div className="container" style={{maxWidth:620}}>
      <div className="text-center">
        <div style={{width:80,height:80,borderRadius:'50%',background:'var(--green-50)',color:'var(--green-800)',display:'grid',placeItems:'center',margin:'0 auto 18px',border:'2px solid var(--green-700)'}}>
          <Icon name="check" size={40}/>
        </div>
        <span className="eyebrow">Order confirmed · #SJ{Math.floor(Math.random()*9000)+1000}</span>
        <h1 className="h-display" style={{fontSize:'clamp(34px,5vw,46px)',marginTop:10}}>Dhanyavaad! 🙏</h1>
        <p style={{color:'var(--ink-700)',fontSize:17,maxWidth:480,margin:'10px auto 0'}}>
          Your order has been sent to us on WhatsApp. We'll confirm shortly and ship within 24 hours.{order && order.orderId ? <><br/><strong>Order #{order.orderId}</strong></> : null}
        </p>
      </div>

      <div className="checkout-section" style={{marginTop:32}}>
        <h3>What happens next</h3>
        <div style={{display:'grid',gap:14}}>
          {[
            {t:'Order received', s:'Just now', done:true},
            {t:'Packed in Indore', s:'Within 24 hours', done:false},
            {t:'Out for delivery', s:'4–7 business days', done:false},
            {t:'Enjoy with parathas 🫓', s:'You earned it', done:false},
          ].map((s,i)=>(
            <div key={i} style={{display:'flex',gap:12,alignItems:'flex-start'}}>
              <div style={{width:24,height:24,borderRadius:'50%',background:s.done?'var(--green-700)':'var(--cream-200)',color:s.done?'var(--cream-50)':'var(--ink-500)',display:'grid',placeItems:'center',flexShrink:0,marginTop:2}}>
                {s.done ? <Icon name="check" size={14}/> : <span style={{fontSize:12,fontWeight:600}}>{i+1}</span>}
              </div>
              <div>
                <div style={{fontWeight:600}}>{s.t}</div>
                <div style={{fontSize:13,color:'var(--ink-500)'}}>{s.s}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div style={{display:'flex',gap:12,marginTop:24,justifyContent:'center',flexWrap:'wrap'}}>
        <a className="btn btn-primary" href={`https://wa.me/${window.SJ_DATA.brand.whatsapp}`} target="_blank"><Icon name="whatsapp" size={18}/> Message on WhatsApp</a>
        <button className="btn btn-ghost" onClick={()=>goto('home')}>Back to home</button>
      </div>
    </div>
  </section>
);

Object.assign(window, { CartDrawer, CheckoutPage, ConfirmationPage });
