// pages-checkout.jsx — CartDrawer, CheckoutPage, OrderConfirmPage — wired to real API + Razorpay
const { useState: useStateC, useEffect: useEffectC } = React;

// ─── CART DRAWER ─────────────────────────────────────────────────────────────
function CartDrawer({ open, onClose, cart, updateQty, removeItem, goto }) {
  const subtotal = cart.reduce((s, i) => s + i.price * i.qty, 0);
  if (!open) return null;
  return (
    <div style={{ position:'fixed', inset:0, zIndex:200 }}>
      <div onClick={onClose} style={{ position:'absolute', inset:0, background:'rgba(0,0,0,.45)' }}/>
      <div style={{ position:'absolute', right:0, top:0, bottom:0, width:'min(420px,100%)', background:'var(--ff-bg)', borderLeft:'var(--ff-border)', display:'flex', flexDirection:'column', animation:'ffSlideIn .22s' }}>
        <div style={{ padding:'20px 24px', borderBottom:'var(--ff-border)', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
          <h2 className="ff-display" style={{ fontSize:24 }}>Your bag ({cart.length})</h2>
          <button onClick={onClose}><Icon.Close/></button>
        </div>
        {cart.length === 0 ? (
          <div style={{ flex:1, display:'grid', placeItems:'center', textAlign:'center', padding:40 }}>
            <div>
              <div style={{ fontSize:48 }}>🛍️</div>
              <h3 className="ff-display" style={{ fontSize:24, marginTop:10 }}>Empty bag</h3>
              <p style={{ color:'var(--ff-muted)', marginTop:6 }}>Go find something fussy.</p>
              <button className="ff-btn ff-btn--primary" style={{ marginTop:16 }} onClick={()=>{ onClose(); goto({page:'shop'}); }}>Shop now</button>
            </div>
          </div>
        ) : (
          <>
            <div style={{ flex:1, overflowY:'auto', padding:24, display:'grid', gap:16 }}>
              {cart.map(item => (
                <div key={item.product_id} style={{ display:'flex', gap:14, alignItems:'center' }}>
                  <div style={{ width:72, height:72, borderRadius:10, flexShrink:0, overflow:'hidden', border:'var(--ff-border)', background:item.swatch||'#FFC7A8' }}>
                    {item.image
                      ? <img src={item.image} alt={item.name} style={{ width:'100%', height:'100%', objectFit:'cover' }} onError={e=>e.target.style.display='none'}/>
                      : <ProductArt product={{ id:item.product_id, name:item.name, cat:'home', swatch:item.swatch||'#FFC7A8' }} ratio="1/1" size="sm"/>
                    }
                  </div>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontWeight:700, fontSize:15, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{item.name}</div>
                    <div style={{ fontSize:13, color:'var(--ff-muted)', marginTop:2 }}>{fmtINR(item.price)}</div>
                    <div style={{ display:'flex', alignItems:'center', gap:8, marginTop:8 }}>
                      <button onClick={()=>updateQty(item.product_id, item.qty-1)} style={{ width:28, height:28, borderRadius:6, border:'var(--ff-border)', fontWeight:700, display:'grid', placeItems:'center' }}>−</button>
                      <span style={{ fontWeight:700, minWidth:20, textAlign:'center' }}>{item.qty}</span>
                      <button onClick={()=>updateQty(item.product_id, item.qty+1)} style={{ width:28, height:28, borderRadius:6, border:'var(--ff-border)', fontWeight:700, display:'grid', placeItems:'center' }}>+</button>
                      <button onClick={()=>removeItem(item.product_id)} style={{ marginLeft:'auto', fontSize:12, color:'var(--ff-muted)' }}>Remove</button>
                    </div>
                  </div>
                  <div style={{ fontWeight:700, fontSize:15 }}>{fmtINR(item.price*item.qty)}</div>
                </div>
              ))}
            </div>
            <div style={{ padding:24, borderTop:'var(--ff-border)' }}>
              <div style={{ display:'flex', justifyContent:'space-between', fontWeight:700, fontSize:18, marginBottom:16 }}>
                <span>Subtotal</span><span>{fmtINR(subtotal)}</span>
              </div>
              <button className="ff-btn ff-btn--primary ff-btn--block" onClick={()=>{ onClose(); goto({page:'checkout'}); }}>
                Checkout · {fmtINR(subtotal)} <Icon.Arrow/>
              </button>
              <button className="ff-btn ff-btn--block" style={{ marginTop:8 }} onClick={onClose}>Continue shopping</button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}


// ─── India States + Major Cities ─────────────────────────────────────────────



// ─── PincodeInput — auto-fills city + state, fully controlled ───────────────────
function PincodeInput({ value, onChange }) {
  const [loading, setLoading] = useStateC(false);
  const [msg,     setMsg]     = useStateC('');
  const prevPin = React.useRef('');

  // Lookup whenever value reaches 6 digits AND is different from last lookup
  useEffectC(() => {
    if (value && value.length === 6 && value !== prevPin.current) {
      prevPin.current = value;
      setLoading(true); setMsg('');
      fetch('https://api.postalpincode.in/pincode/' + value)
        .then(r => r.json())
        .then(data => {
          const post = data?.[0];
          if (post?.Status === 'Success' && post?.PostOffice?.length) {
            const po    = post.PostOffice[0];
            const city  = po.Block && po.Block !== 'NA' ? po.Block : po.District;
            const state = po.State;
            onChange(value, city, state);
            setMsg('✓ ' + po.District + ', ' + state);
          } else {
            setMsg('Pincode not found — fill city/state manually');
          }
        })
        .catch(() => setMsg(''))
        .finally(() => setLoading(false));
    }
    if (!value || value.length < 6) { setMsg(''); prevPin.current = ''; }
  }, [value]);

  return (
    <div>
      <div style={{ position:'relative' }}>
        <input className="ff-input" value={value} maxLength={6} placeholder="Enter 6-digit pincode"
          onChange={e => {
            const pin = e.target.value.replace(/\D/g,'').slice(0,6);
            onChange(pin, null, null);  // null = don't clear city/state
            setMsg('');
          }}
          style={{ paddingRight: loading ? 40 : undefined }}
        />
        {loading && <div style={{ position:'absolute', right:14, top:'50%', transform:'translateY(-50%)', fontSize:14 }}>⏳</div>}
      </div>
      {msg && <div style={{ fontSize:12, marginTop:4, fontWeight:500, color: msg.startsWith('✓') ? 'var(--ff-teal)' : 'var(--ff-accent)' }}>{msg}</div>}
    </div>
  );
}

// ─── CitySelect — searchable city dropdown ───────────────────────────────────
function CitySelect({ state, value, onChange }) {
  const [query,    setQuery]    = useStateC('');
  const [showList, setShowList] = useStateC(false);
  const [other,    setOther]    = useStateC(false);

  const allCities = (window.INDIA_CITIES && state) ? (window.INDIA_CITIES[state] || []) : [];
  const filtered  = query.trim()
    ? allCities.filter(c => c.toLowerCase().includes(query.toLowerCase()))
    : allCities;

  // When state changes, reset
  useEffectC(() => { setQuery(''); setOther(false); }, [state]);

  // If currently entered value matches a city, show it
  const displayValue = value && value !== '__other__' ? value : (other ? query : '');

  if (!state) return (
    <input className="ff-input" placeholder="Select state first" disabled style={{ opacity:.5 }}/>
  );

  return (
    <div style={{ position:'relative' }}>
      <input
        className="ff-input"
        value={showList ? query : displayValue}
        onChange={e => { setQuery(e.target.value); onChange(e.target.value); setShowList(true); setOther(true); }}
        onFocus={() => { setShowList(true); setQuery(''); }}
        onBlur={() => setTimeout(() => setShowList(false), 180)}
        placeholder={`Search ${allCities.length} cities in ${state}…`}
      />
      {showList && filtered.length > 0 && (
        <div style={{
          position:'absolute', top:'100%', left:0, right:0, zIndex:100,
          background:'#fff', border:'1.5px solid var(--ff-line)',
          borderRadius:'0 0 10px 10px', maxHeight:200, overflowY:'auto',
          boxShadow:'0 8px 24px rgba(0,0,0,.10)',
        }}>
          {filtered.slice(0, 40).map(city => (
            <div key={city} onMouseDown={() => { onChange(city); setQuery(city); setShowList(false); setOther(false); }}
              style={{ padding:'9px 14px', fontSize:14, cursor:'pointer', borderBottom:'1px solid var(--ff-line)',
                background: value===city ? 'var(--ff-lime)' : 'transparent',
              }}
              onMouseOver={e=>e.currentTarget.style.background='var(--ff-bg-2)'}
              onMouseOut={e=>e.currentTarget.style.background=value===city?'var(--ff-lime)':'transparent'}>
              {city}
            </div>
          ))}
          {filtered.length === 0 && (
            <div style={{ padding:'9px 14px', fontSize:13, color:'var(--ff-muted)' }}>
              No match — your city will be saved as typed
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ─── CHECKOUT PAGE ────────────────────────────────────────────────────────────
function CheckoutPage({ cart, user, goto, placeOrder, setToast }) {
  useEffectA(() => { if (window.FF_TRACK) window.FF_TRACK('checkout_start'); }, []);
  const [settings, setSettings] = useStateA({ free_shipping_min:999, shipping_fee:49, cod_available:true, cod_fee:49 });
  useEffectA(() => {
    if (typeof FF_API === 'undefined') return;
    FF_API.content?.settings().then(s=>{ if(s?.free_shipping_min) setSettings(s); });
  }, []);
  const [step,        setStep]       = useStateC(1);
  const [addresses,   setAddresses]  = useStateC([]);
  const [selectedAddr,setSelectedAddr]=useStateC(null);
  const [newAddr,     setNewAddr]    = useStateC({ name:'', phone:'', line1:'', line2:'', city:'', state:'', pincode:'' });
  const [showNewAddr, setShowNewAddr]= useStateC(false);
  const [promo,       setPromo]      = useStateC('');
  const [promoData,   setPromoData]  = useStateC(null);
  const [promoErr,    setPromoErr]   = useStateC('');
  const [processing,  setProcessing] = useStateC(false);
  const [payMethod,   setPayMethod]  = useStateC('razorpay'); // razorpay | cod

  const subtotal = cart.reduce((s, i) => s + i.price * i.qty, 0);
  const discount = promoData?.discount || 0;
  const shipping  = subtotal >= settings.free_shipping_min ? 0 : settings.shipping_fee;
  const total     = subtotal - discount + shipping;

  // Load saved addresses for logged-in users
  useEffectC(() => {
    if (user) {
      FF_API.orders.getAddresses().then(a => {
        setAddresses(a);
        const def = a.find(x => x.is_default == 1) || a[0];
        if (def) setSelectedAddr(def.id);
      });
    }
  }, [user]);

  // Pre-fill new address from user profile
  useEffectC(() => {
    if (user) setNewAddr(a => ({ ...a, name: user.name || '', phone: user.phone || '' }));
  }, [user]);

  if (!cart.length) return (
    <main style={{ maxWidth:600, margin:'60px auto', padding:24, textAlign:'center' }}>
      <h1 className="ff-display" style={{ fontSize:36 }}>Your bag is empty</h1>
      <button className="ff-btn ff-btn--primary" style={{ marginTop:16 }} onClick={()=>goto({page:'shop'})}>Go shopping</button>
    </main>
  );

  const applyPromo = async () => {
    setPromoErr('');
    const { ok, data } = await FF_API.cart.applyPromo(promo, subtotal);
    if (ok) { setPromoData(data); setToast('Promo applied! ✦'); }
    else    { setPromoErr(data.error || 'Invalid code'); setPromoData(null); }
  };

  const saveAddressAndProceed = async () => {
    // Entering new address — either showNewAddr is true OR user has no saved addresses
    const enteringNew = showNewAddr || addresses.length === 0;

    if (enteringNew) {
      // Validate required fields
      const required = ['name','phone','line1','city','state','pincode'];
      for (const f of required) {
        if (!newAddr[f]?.trim()) { setToast(`Please fill in ${f}`); return; }
      }
      if (!/^\d{6}$/.test(newAddr.pincode)) { setToast('Pincode must be 6 digits'); return; }

      const { ok, data } = await FF_API.orders.addAddress({ ...newAddr, isDefault: addresses.length === 0 });
      if (!ok) { setToast(data.error || 'Address save failed'); return; }
      setAddresses(a => [...a, data]);
      setSelectedAddr(data.id);
      setShowNewAddr(false);
    } else {
      // Using saved address
      if (!selectedAddr) { setToast('Please select an address'); return; }
    }
    setStep(2);
  };

  const handleCOD = async () => {
    if (!user) { goto({ page:'home', openLogin:true }); return; }
    const addrId = selectedAddr;
    if (!addrId) { setToast('Please select an address'); return; }
    setProcessing(true);
    try {
      const items = cart.map(i => ({ productId: i.product_id, qty: i.qty }));
      console.log('[COD] items:', items, 'addrId:', addrId);
      const { ok, data } = await FF_API.orders.createCOD(items, addrId, promoData?.code || null);
      console.log('[COD] response ok:', ok, 'data:', data);
      if (!ok) {
        const errMsg = data?.error || JSON.stringify(data) || 'COD order failed';
        setToast(errMsg);
        setProcessing(false);
        return;
      }
      if (!data?.orderId) {
        setToast('Order placed but no ID returned. Check phpMyAdmin orders table.');
        setProcessing(false);
        return;
      }
      placeOrder(data.orderId);  // clear cart
      location.href = FF_URLS.order(data.orderId);  // redirect to order page
    } catch (err) {
      console.error('[COD] exception:', err);
      setToast('Order failed: ' + err.message);
      setProcessing(false);
    }
  };

  const handlePayment = async () => {
    if (payMethod === 'cod') { handleCOD(); return; }
    if (!user) { goto({ page:'home', openLogin:true }); return; }
    const addrId = selectedAddr;
    if (!addrId) { setToast('Please select an address'); return; }

    setProcessing(true);
    try {
      // Step 1: create Razorpay order on our server
      const items = cart.map(i => ({ productId: i.product_id, qty: i.qty }));
      const { ok, data } = await FF_API.orders.createPayment(items, addrId, promoData?.code || null);
      if (!ok) { setToast(data.error || 'Payment init failed'); setProcessing(false); return; }

      // Step 2: open real Razorpay checkout
      const rzpOptions = {
        key:         data.keyId,
        amount:      data.amount,
        currency:    'INR',
        order_id:    data.razorpayOrderId,
        name:        'Fussy Finds',
        description: 'Order payment',
        prefill:     data.prefill,
        theme:       { color: '#E4439C' },
        handler: async (response) => {
          // Don't setProcessing here — show a redirect message instead
          setToast('✓ Payment successful! Taking you to your order…');
          try {
            const { ok: cOk, data: cData } = await FF_API.orders.confirm({
              razorpayOrderId:   response.razorpay_order_id,
              razorpayPaymentId: response.razorpay_payment_id,
              razorpaySignature: response.razorpay_signature,
            }, data.orderSummary);

            if (cOk) {
              placeOrder(cData.orderId);
              location.href = FF_URLS.order(cData.orderId);
            } else {
              setToast('Payment received but confirmation failed. Your payment ID: ' + response.razorpay_payment_id + ' — contact support.');
              setProcessing(false);
            }
          } catch(e) {
            setToast('Confirmation error. Your payment ID: ' + response.razorpay_payment_id);
            setProcessing(false);
          }
        },
        modal: { ondismiss: () => { setProcessing(false); setToast('Payment cancelled — your cart is safe.'); } },
      };

      // Load Razorpay SDK if not loaded
      if (!window.Razorpay) {
        await new Promise((res, rej) => {
          const s = document.createElement('script');
          s.src = 'https://checkout.razorpay.com/v1/checkout.js';
          s.onload = res; s.onerror = rej;
          document.head.appendChild(s);
        });
      }
      const rzp = new window.Razorpay(rzpOptions);
      rzp.open();
      // Reset button after modal opens so it doesn't stay stuck
      setTimeout(() => setProcessing(false), 1500);

    } catch (err) {
      console.error(err);
      setToast('Payment error. Please try again.');
      setProcessing(false);
    }
  };

  const currentAddr = addresses.find(a => a.id === selectedAddr);

  return (
    <main style={{ maxWidth:1100, margin:'0 auto', padding:'32px 24px 80px' }}>
      <h1 className="ff-display" style={{ fontSize:48, marginBottom:8 }}>Checkout</h1>

      {/* Steps indicator */}
      <div style={{ display:'flex', gap:8, marginBottom:32, alignItems:'center' }}>
        {['Delivery','Payment','Confirm'].map((s,i)=>(
          <React.Fragment key={i}>
            <div style={{ display:'flex', alignItems:'center', gap:6 }}>
              <div style={{ width:24, height:24, borderRadius:999, background: step>i ? 'var(--ff-accent)' : step===i+1 ? 'var(--ff-ink)' : 'var(--ff-bg-2)', color:'#fff', display:'grid', placeItems:'center', fontSize:12, fontWeight:700 }}>{step>i ? '✓' : i+1}</div>
              <span style={{ fontSize:13, fontWeight:step===i+1?700:400, color:step===i+1?'var(--ff-ink)':'var(--ff-muted)' }}>{s}</span>
            </div>
            {i<2 && <div style={{ flex:1, height:2, background: step>i+1 ? 'var(--ff-accent)' : 'var(--ff-bg-2)', maxWidth:40 }}/>}
          </React.Fragment>
        ))}
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'1fr 360px', gap:32 }} className="ff-checkout-grid">
        <div>
          {/* STEP 1: Address */}
          {step === 1 && (
            <div className="ff-card" style={{ padding:24 }}>
              <h2 className="ff-display" style={{ fontSize:24, marginBottom:16 }}>Delivery address</h2>

              {!user && (
                <div style={{ padding:14, background:'var(--ff-lime)', border:'var(--ff-border)', borderRadius:10, marginBottom:16, fontSize:14 }}>
                  <b>Log in</b> to save addresses and track orders. <a onClick={()=>goto({page:'home', openLogin:true})} style={{ textDecoration:'underline', cursor:'pointer', fontWeight:700 }}>Log in →</a>
                </div>
              )}

              {/* Saved addresses */}
              {addresses.length > 0 && !showNewAddr && (
                <div style={{ display:'grid', gap:10, marginBottom:16 }}>
                  {addresses.map(a => (
                    <label key={a.id} style={{ display:'flex', gap:12, padding:14, border:`2px solid ${selectedAddr===a.id ? 'var(--ff-accent)' : 'rgba(0,0,0,.12)'}`, borderRadius:10, cursor:'pointer', background: selectedAddr===a.id ? 'rgba(228,67,156,.04)' : '#fff' }}>
                      <input type="radio" name="addr" checked={selectedAddr===a.id} onChange={()=>setSelectedAddr(a.id)} style={{ marginTop:2 }}/>
                      <div>
                        <div style={{ fontWeight:700 }}>{a.name} <span style={{ fontWeight:400, color:'var(--ff-muted)' }}>· {a.phone}</span></div>
                        <div style={{ fontSize:13, color:'var(--ff-ink-2)', marginTop:2 }}>{a.line1}{a.line2 ? ', '+a.line2 : ''}, {a.city}, {a.state} — {a.pincode}</div>
                        <div style={{ fontSize:11, color:'var(--ff-muted)', marginTop:2 }}>{a.label}</div>
                      </div>
                    </label>
                  ))}
                  <button className="ff-btn" onClick={()=>setShowNewAddr(true)}>+ Add new address</button>
                </div>
              )}

              {/* New address form */}
              {(showNewAddr || addresses.length === 0) && (
                <div style={{ display:'grid', gap:10, marginBottom:16 }}>
                  <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
                    <div><label className="ff-label">Full name</label><input className="ff-input" value={newAddr.name} onChange={e=>setNewAddr(a=>({...a,name:e.target.value}))} placeholder="Priya Sharma"/></div>
                    <div><label className="ff-label">Phone</label><input className="ff-input" value={newAddr.phone} onChange={e=>setNewAddr(a=>({...a,phone:e.target.value}))} placeholder="9876543210"/></div>
                  </div>
                  <div><label className="ff-label">Address line 1</label><input className="ff-input" value={newAddr.line1} onChange={e=>setNewAddr(a=>({...a,line1:e.target.value}))} placeholder="Flat, building, street"/></div>
                  <div><label className="ff-label">Address line 2 (optional)</label><input className="ff-input" value={newAddr.line2} onChange={e=>setNewAddr(a=>({...a,line2:e.target.value}))} placeholder="Area, landmark"/></div>
                  <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
                    <div>
                      <label className="ff-label">State</label>
                      <select className="ff-input" value={newAddr.state}
                        onChange={e => setNewAddr(a=>({...a, state:e.target.value, city:'', pincode:''}))}>
                        <option value="">Select state / UT</option>
                        {(window.INDIA_STATES||[]).map(s=><option key={s} value={s}>{s}</option>)}
                      </select>
                    </div>
                    <div>
                      <label className="ff-label">City</label>
                      <CitySelect
                        state={newAddr.state}
                        value={newAddr.city}
                        onChange={(city) => {
                          // Use functional update to get fresh state
                          setNewAddr(a => {
                            const updated = {...a, city};
                            // Reverse pincode lookup with current state
                            if (city && a.state) {
                              fetch('https://api.postalpincode.in/postoffice/' + encodeURIComponent(city))
                                .then(r => r.json())
                                .then(data => {
                                  const offices = data?.[0]?.PostOffice || [];
                                  const match = offices.find(o => o.State === a.state) || offices[0];
                                  if (match?.Pincode) setNewAddr(prev => ({...prev, city, pincode: match.Pincode}));
                                }).catch(()=>{});
                            }
                            return updated;
                          });
                        }}
                      />
                    </div>
                  </div>
                  <div>
                    <label className="ff-label">Pincode</label>
                    <PincodeInput
                      value={newAddr.pincode}
                      onChange={(pin, autoCity, autoState) => setNewAddr(a => ({
                        ...a,
                        pincode: pin,
                        // null means "don't change", '' means "clear", string means "set"
                        ...(autoCity  !== null ? { city: autoCity||a.city }   : {}),
                        ...(autoState !== null ? { state: autoState||a.state } : {}),
                      }))}
                    />
                  </div>
                  {showNewAddr && <button className="ff-btn" onClick={()=>setShowNewAddr(false)}>Cancel</button>}
                </div>
              )}

              <button className="ff-btn ff-btn--primary" style={{ width:'100%' }} onClick={saveAddressAndProceed}>
                Continue to payment <Icon.Arrow/>
              </button>
            </div>
          )}

          {/* STEP 2: Payment */}
          {step === 2 && (
            <div>
              {currentAddr && (
                <div className="ff-card" style={{ padding:18, marginBottom:16, display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                  <div>
                    <div style={{ fontSize:12, color:'var(--ff-muted)', textTransform:'uppercase', letterSpacing:'.08em' }}>Delivering to</div>
                    <div style={{ fontWeight:700, marginTop:2 }}>{currentAddr.name} · {currentAddr.line1}, {currentAddr.city}</div>
                  </div>
                  <button className="ff-btn ff-btn--sm" onClick={()=>setStep(1)}>Change</button>
                </div>
              )}

              <div className="ff-card" style={{ padding:24 }}>
                <h2 className="ff-display" style={{ fontSize:24, marginBottom:16 }}>Payment method</h2>

                {/* Method selector */}
                <div style={{ display:'grid', gap:10, marginBottom:20 }}>

                  {/* Razorpay option */}
                  <label onClick={()=>setPayMethod('razorpay')} style={{
                    display:'flex', gap:14, padding:16, borderRadius:12, cursor:'pointer',
                    border: payMethod==='razorpay' ? '2.5px solid var(--ff-accent)' : '2px solid rgba(0,0,0,.12)',
                    background: payMethod==='razorpay' ? 'rgba(228,67,156,.04)' : '#fff',
                    alignItems:'center',
                  }}>
                    <div style={{
                      width:18, height:18, borderRadius:999, flexShrink:0, marginTop:1,
                      border: payMethod==='razorpay' ? '5px solid var(--ff-accent)' : '2px solid rgba(0,0,0,.25)',
                      background: '#fff',
                    }}/>
                    <div style={{ flex:1 }}>
                      <div style={{ fontWeight:700, fontSize:14 }}>UPI / Cards / Netbanking</div>
                      <div style={{ fontSize:12, color:'var(--ff-muted)', marginTop:2 }}>GPay · PhonePe · Paytm · Visa · Mastercard · RuPay</div>
                    </div>
                    <div style={{ fontSize:11, fontWeight:700, color:'var(--ff-accent)', background:'rgba(228,67,156,.1)', padding:'3px 8px', borderRadius:6 }}>Razorpay</div>
                  </label>

                  {/* COD option */}
                  {settings.cod_available ? (
                  <label onClick={()=>setPayMethod('cod')} style={{
                    display:'flex', gap:14, padding:16, borderRadius:12, cursor:'pointer',
                    border: payMethod==='cod' ? 'var(--ff-border)' : '2px solid rgba(0,0,0,.12)',
                    background: payMethod==='cod' ? 'var(--ff-lime)' : '#fff',
                    alignItems:'center',
                  }}>
                    <div style={{
                      width:18, height:18, borderRadius:999, flexShrink:0, marginTop:1,
                      border: payMethod==='cod' ? '5px solid var(--ff-ink)' : '2px solid rgba(0,0,0,.25)',
                      background: '#fff',
                    }}/>
                    <div style={{ flex:1 }}>
                      <div style={{ fontWeight:700, fontSize:14 }}>Cash on Delivery</div>
                      <div style={{ fontSize:12, color:'var(--ff-muted)', marginTop:2 }}>
                        Pay cash at delivery · +{fmtINR(settings.cod_fee)} COD handling fee
                      </div>
                    </div>
                    <div style={{ fontSize:11, fontWeight:700, color:'var(--ff-ink)', background:'rgba(0,0,0,.08)', padding:'3px 8px', borderRadius:6 }}>COD</div>
                  </label>
                  ) : (
                  <div style={{ padding:16, borderRadius:12, border:'2px solid rgba(0,0,0,.08)', background:'var(--ff-bg-2)', opacity:.6 }}>
                    <div style={{ fontWeight:700, fontSize:14, color:'var(--ff-muted)' }}>Cash on Delivery</div>
                    <div style={{ fontSize:12, color:'var(--ff-muted)', marginTop:2 }}>Not available at this time</div>
                  </div>
                  )}
                </div>

                {payMethod === 'razorpay' && (
                  <div style={{ fontSize:12, color:'var(--ff-muted)', display:'flex', alignItems:'center', gap:6, marginBottom:16 }}>
                    <Icon.Check/> Secured by Razorpay · 256-bit SSL encrypted
                  </div>
                )}
                {payMethod === 'cod' && (
                  <div style={{ fontSize:12, color:'var(--ff-ink-2)', padding:'10px 14px', background:'rgba(0,0,0,.04)', borderRadius:8, marginBottom:16 }}>
                    {fmtINR(total + settings.cod_fee)} will be collected at delivery (includes {fmtINR(settings.cod_fee)} COD fee). No advance payment needed.
                  </div>
                )}

                <button
                  className="ff-btn ff-btn--primary ff-btn--block"
                  onClick={handlePayment}
                  disabled={processing}
                  style={{ fontSize:16 }}
                >
                  {processing
                    ? (payMethod==='cod' ? 'Placing order…' : 'Opening payment…')
                    : payMethod==='cod'
                      ? `Place COD order · ${fmtINR(total)}`
                      : `Pay ${fmtINR(total)} securely`
                  }
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Order summary sidebar */}
        <div>
          <div className="ff-card" style={{ padding:20 }}>
            <h3 className="ff-display" style={{ fontSize:20, marginBottom:14 }}>Order summary</h3>
            <div style={{ display:'grid', gap:12, marginBottom:16 }}>
              {cart.map(i => (
                <div key={i.product_id} style={{ display:'flex', gap:10, alignItems:'center' }}>
                  <div style={{ width:52, height:52, borderRadius:8, overflow:'hidden', border:'var(--ff-border)', flexShrink:0, background:i.swatch||'#FFC7A8' }}>
                    {i.image ? (
                      <img src={i.image} alt={i.name} style={{ width:'100%', height:'100%', objectFit:'cover' }}
                        onError={e=>e.target.style.display='none'}/>
                    ) : (
                      <ProductArt product={{ id:i.product_id, name:i.name, cat:'home', swatch:i.swatch||'#FFC7A8' }} ratio="1/1" size="sm"/>
                    )}
                  </div>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:13, fontWeight:600 }}>{i.name}</div>
                    <div style={{ fontSize:12, color:'var(--ff-muted)' }}>Qty: {i.qty}</div>
                  </div>
                  <span style={{ fontSize:13, fontWeight:700 }}>{fmtINR(i.price*i.qty)}</span>
                </div>
              ))}
            </div>

            {/* Promo code */}
            <div style={{ borderTop:'var(--ff-border)', paddingTop:14, marginBottom:14 }}>
              <div style={{ display:'flex', gap:8 }}>
                <input className="ff-input" placeholder="Promo code" value={promo} onChange={e=>setPromo(e.target.value.toUpperCase())} style={{ flex:1 }}/>
                <button className="ff-btn" onClick={applyPromo}>Apply</button>
              </div>
              {promoErr  && <div style={{ fontSize:12, color:'var(--ff-accent)', marginTop:6 }}>{promoErr}</div>}
              {promoData && <div style={{ fontSize:12, color:'var(--ff-teal)', marginTop:6 }}>✓ {promoData.code} — saving {fmtINR(discount)}</div>}
            </div>

            <div style={{ borderTop:'var(--ff-border)', paddingTop:14, display:'grid', gap:8 }}>
              <div style={{ display:'flex', justifyContent:'space-between', fontSize:14 }}><span>Subtotal</span><span>{fmtINR(subtotal)}</span></div>
              {discount > 0 && <div style={{ display:'flex', justifyContent:'space-between', fontSize:14, color:'var(--ff-teal)' }}><span>Discount</span><span>−{fmtINR(discount)}</span></div>}
              <div style={{ display:'flex', justifyContent:'space-between', fontSize:14 }}><span>Shipping</span><span>{shipping === 0 ? <span style={{ color:'var(--ff-teal)' }}>Free</span> : fmtINR(shipping)}</span></div>
              <div style={{ display:'flex', justifyContent:'space-between', fontWeight:700, fontSize:18, paddingTop:8, borderTop:'var(--ff-border)' }}><span>Total</span><span>{fmtINR(total)}</span></div>
            </div>
          </div>
        </div>
      </div>
    </main>
  );
}

// ─── ORDER CONFIRMATION PAGE ──────────────────────────────────────────────────
function OrderConfirmPage({ orderId, goto }) {
  const [order, setOrder] = useStateC(null);

  useEffectC(() => {
    if (!orderId) return;
    FF_API.orders.get(orderId)
      .then(setOrder)
      .catch(console.error);
  }, [orderId]);

  return (
    <main style={{ maxWidth:640, margin:'60px auto', padding:'24px 24px 80px', textAlign:'center' }}>
      <div style={{ fontSize:64 }}>✦</div>
      <h1 className="ff-display" style={{ fontSize:48, marginTop:12 }}>Order placed!</h1>
      <p style={{ fontSize:16, marginTop:8, color:'var(--ff-ink-2)' }}>
        Your order <b>#{orderId}</b> is confirmed. We'll ship it in 48 hours.
      </p>

      {order && (
        <div className="ff-card" style={{ padding:24, marginTop:28, textAlign:'left' }}>
          <h3 className="ff-display" style={{ fontSize:20, marginBottom:14 }}>Tracking</h3>
          <div style={{ display:'grid', gap:10 }}>
            {(order.tracking || []).map((t, i) => (
              <div key={i} style={{ display:'flex', gap:12, alignItems:'center' }}>
                <div style={{ width:20, height:20, borderRadius:999, background: t.done==1 ? 'var(--ff-accent)' : 'var(--ff-bg-2)', border:'var(--ff-border)', display:'grid', placeItems:'center', flexShrink:0 }}>
                  {t.done==1 && <span style={{ fontSize:10, color:'#fff' }}>✓</span>}
                </div>
                <div>
                  <div style={{ fontWeight: t.done==1 ? 700 : 400, fontSize:14 }}>{t.label}</div>
                  {t.event_date && t.event_date !== '—' && <div style={{ fontSize:12, color:'var(--ff-muted)' }}>{t.event_date}</div>}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      <div style={{ display:'flex', gap:12, marginTop:24, justifyContent:'center', flexWrap:'wrap' }}>
        <button className="ff-btn ff-btn--primary" onClick={()=>goto({page:'account', tab:'orders'})}>View my orders</button>
        <button className="ff-btn" onClick={()=>goto({page:'shop'})}>Keep shopping</button>
      </div>
    </main>
  );
}

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