// AirStep — Buy block, Cart drawer, Checkout, Confirmation

const SIZES = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
const OOS = []; // all sizes in stock

const formatZAR = (n) =>
  "R" + n.toLocaleString("en-ZA", { maximumFractionDigits: 0 });

// ============================================================
// BUY BLOCK (in-page)
// ============================================================
const BuyBlock = ({ onAddToCart }) => {
  const [size, setSize] = React.useState(8);
  const [qty, setQty] = React.useState(1);
  const [view, setView] = React.useState("hero"); // hero | top | insole | box

  return (
    <section id="buy" style={{background: "var(--paper)"}}>
      <div className="container">
        <div className="section-head">
          <span className="eyebrow">Order yours</span>
          <h2 style={{marginTop:16}}>One pair. Years of protection.</h2>
        </div>

        <div className="buy-block">
          <div>
            <div className="buy-gallery">
              <div className="badge">In Stock</div>
              <div className="photo">
                <ShoePhoto variant={view}/>
              </div>
            </div>
            <div className="buy-thumbs">
              <button className={view==="hero"?"active":""} onClick={()=>setView("hero")} aria-label="Profile view">
                <img src="assets/product-hero-navy.png" alt=""/>
              </button>
              <button className={view==="pair"?"active":""} onClick={()=>setView("pair")} aria-label="Pair view">
                <img src="assets/product-pair-hero.png" alt=""/>
              </button>
              <button className={view==="top"?"active":""} onClick={()=>setView("top")} aria-label="Top-down view">
                <img src="assets/product-top.png" alt=""/>
              </button>
              <button className={view==="insole"?"active":""} onClick={()=>setView("insole")} aria-label="Insole view">
                <img src="assets/product-insole.jpg" alt=""/>
              </button>
              <button className={view==="outsole"?"active":""} onClick={()=>setView("outsole")} aria-label="Outsole view">
                <img src="assets/product-outsole.jpg" alt=""/>
              </button>
              <button className={view==="box"?"active":""} onClick={()=>setView("box")} aria-label="Packaging view">
                <img src="assets/product-box.png" alt=""/>
              </button>
            </div>
          </div>

          <div className="buy-info">
            <span className="eyebrow">Airstep · Class A Medical Device</span>
            <h2>Airstep Therapeutic Trainer</h2>
            <div className="star-row">
              <span style={{color:"var(--sky)", fontWeight:600, fontSize:12, letterSpacing:"0.06em"}}>NAPPI-CODED</span>
              <span style={{color:"var(--ink-mute)"}}>·</span>
              <span>PMB listed</span>
              <span style={{color:"var(--ink-mute)"}}>·</span>
              <span>Telmo-endorsed</span>
            </div>
            <div className="price-row">
              <div className="price">R3,200</div>
            </div>
            <p className="buy-meta">
              Genuine ISO-certified cow leather. FreeStride™ anatomical last. Triple-layer
              removable insole. Up to 4E width. UK sizes 2–13. Unisex.
            </p>

            <div className="option-group">
              <div className="opt-head">
                <span className="opt-label">Colour</span>
                <span className="opt-value">Midnight Navy</span>
              </div>
              <div className="color-row">
                <button className="swatch active" aria-label="Midnight Navy">
                  <span className="inner" style={{background: "#1f3a5c"}}/>
                </button>
                <div style={{display:"flex", flexDirection:"column", gap:2, color:"var(--ink-mute)", fontSize:13}}>
                  <span style={{color:"var(--navy)", fontWeight:600}}>Currently available in Navy</span>
                  <span>Additional colourways arriving Q2 2027</span>
                </div>
              </div>
            </div>

            <div className="option-group">
              <div className="opt-head">
                <span className="opt-label">Size (UK / SA)</span>
                <a href="#" onClick={e=>e.preventDefault()} className="opt-value" style={{textDecoration:"underline"}}>Sizing guide</a>
              </div>
              <div className="size-grid">
                {SIZES.map(s => (
                  <button
                    key={s}
                    className={`size-btn ${size===s?"active":""}`}
                    onClick={()=>setSize(s)}
                    disabled={OOS.includes(s)}>
                    {s}
                  </button>
                ))}
              </div>
            </div>

            <div className="qty-row">
              <div className="qty-stepper">
                <button onClick={()=>setQty(Math.max(1, qty-1))} aria-label="Decrease">−</button>
                <span className="val">{qty}</span>
                <button onClick={()=>setQty(Math.min(9, qty+1))} aria-label="Increase">+</button>
              </div>
              <button className="btn btn-cta btn-block" style={{flex:1}}
                onClick={()=>onAddToCart({size, qty})}>
                Add to Cart · {formatZAR(3200 * qty)}
              </button>
            </div>

            <div className="buy-promise">
              <div className="item">
                <Icon.shield size={18}/>
                <div><strong>Class A device</strong>NAPPI-coded · PMB listed</div>
              </div>
              <div className="item">
                <Icon.truck size={18}/>
                <div><strong>Nationwide delivery</strong>Across South Africa</div>
              </div>
              <div className="item">
                <Icon.refresh size={18}/>
                <div><strong>Exchange or replace</strong>Size or fit issues</div>
              </div>
              <div className="item">
                <Icon.heart size={18}/>
                <div><strong>Made in SA</strong>Class A Medical Device</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

// ============================================================
// CART DRAWER
// ============================================================
const CartDrawer = ({ open, onClose, cart, removeItem, onCheckout }) => {
  const subtotal = cart.reduce((s, i) => s + 3200 * i.qty, 0);
  const shipFree = true;
  const shipping = 0;
  const total = subtotal + shipping;

  return (
    <>
      <div className={`scrim ${open?"show":""}`} onClick={onClose}/>
      <aside className={`drawer ${open?"show":""}`} aria-hidden={!open}>
        <div className="drawer-head">
          <h3>Your Cart ({cart.length})</h3>
          <button className="drawer-close" onClick={onClose} aria-label="Close cart">
            <Icon.x/>
          </button>
        </div>
        <div className="drawer-body">
          {cart.length === 0 && (
            <div className="cart-empty">
              <Icon.bag size={48}/>
              <p>Your cart is empty.</p>
            </div>
          )}
          {cart.map((line, i) => {
            return (
              <div className="cart-line" key={i}>
                <div className="thumb"><img src="assets/product-clean.png" alt=""/></div>
                <div className="info">
                  <h4>Airstep Therapeutic Trainer</h4>
                  <div className="sub">Midnight Navy · Size UK {line.size}</div>
                  <div className="sub" style={{marginTop:6}}>Qty {line.qty}</div>
                </div>
                <div className="actions">
                  <div className="price">{formatZAR(3200 * line.qty)}</div>
                  <button className="remove" onClick={()=>removeItem(i)}>Remove</button>
                </div>
              </div>
            );
          })}
        </div>
        {cart.length > 0 && (
          <div className="drawer-foot">
            <div className="cart-totals">
              <div className="row"><span>Subtotal</span><span>{formatZAR(subtotal)}</span></div>
              <div className="row total"><span>Total</span><span>{formatZAR(total)}</span></div>
            </div>
            <button className="btn btn-cta btn-block" onClick={onCheckout}>
              Secure Checkout <Icon.arrow size={16}/>
            </button>
            <div style={{display:"flex", alignItems:"center", justifyContent:"center", gap:8, marginTop:12, fontSize:12, color:"var(--ink-mute)"}}>
              <Icon.lock size={12}/> Secured with 256-bit SSL encryption
            </div>
          </div>
        )}
      </aside>
    </>
  );
};

// ============================================================
// CHECKOUT DRAWER — Contact -> Shipping -> Stitch redirect
// ============================================================
const CheckoutDrawer = ({ open, onClose, cart }) => {
  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({ email:"", phone:"", first:"", last:"", address1:"", address2:"", city:"", province:"Gauteng", postal:"" });
  const [errs, setErrs] = React.useState({});
  const [processing, setProcessing] = React.useState(false);
  const [payError, setPayError] = React.useState(null);

  React.useEffect(() => {
    if (!open) setTimeout(() => { setStep(1); setErrs({}); setProcessing(false); setPayError(null); }, 400);
  }, [open]);

  const setField = (k, v) => setForm(f => ({...f, [k]: v}));

  const validate = () => {
    const e = {};
    if (step === 1) {
      if (!/^\S+@\S+\.\S+$/.test(form.email)) e.email = "Enter a valid email";
      if (form.phone.replace(/\D/g,"").length < 9) e.phone = "Enter a valid phone";
    }
    if (step === 2) {
      ["first","last","address1","city","postal"].forEach(k => { if (!form[k].trim()) e[k] = "Required"; });
      if (form.postal && !/^\d{4}$/.test(form.postal)) e.postal = "4-digit code";
    }
    setErrs(e);
    return Object.keys(e).length === 0;
  };

  const next = () => { if (validate()) setStep(s => s + 1); };
  const back = () => setStep(s => Math.max(1, s - 1));
  const subtotal = cart.reduce((s, i) => s + 3200 * i.qty, 0);

  const handlePay = () => {
    setProcessing(true);
    setPayError(null);
    fetch("/api/checkout", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        amount: subtotal,
        customer: { email: form.email, first: form.first, last: form.last, phone: form.phone },
        shipping: { street1: form.address1, street2: form.address2, city: form.city, province: form.province, postal: form.postal },
        items: cart.map(i => ({ name: "Airstep Therapeutic Trainer", qty: i.qty, price: 3200, size: i.size })),
      }),
    })
    .then(r => r.json())
    .then(data => {
      if (!data.url) throw new Error(data.error || "No payment URL returned");
      window.location.href = data.url;
    })
    .catch(err => {
      setPayError(err.message || "Something went wrong. Please try again.");
      setProcessing(false);
    });
  };

  return (
    <>
      <div className={`scrim ${open?"show":""}`} onClick={onClose}/>
      <aside className={`drawer wide ${open?"show":""}`} aria-hidden={!open}>
        <div className="drawer-head">
          <h3>Secure Checkout</h3>
          <button className="drawer-close" onClick={onClose} aria-label="Close"><Icon.x/></button>
        </div>
        <div className="checkout-step-bar">
          {["Contact","Shipping","Payment"].map((s, i) => {
            const n = i + 1; const cls = step === n ? "active" : step > n ? "done" : "";
            return <div key={s} className={`step ${cls}`}><span className="num">{step > n ? "\u2713" : n}</span>{s}</div>;
          })}
        </div>
        <div className="drawer-body">
          {step === 1 && (<>
            <div className="section-label">Your details</div>
            <p style={{color:"var(--ink-soft)",fontSize:14,marginTop:-4,marginBottom:16}}>We'll send your order confirmation &amp; NAPPI invoice here.</p>
            <div className="form-grid">
              <div className={`field ${errs.email?"invalid":""}`}>
                <label>Email</label>
                <input type="email" placeholder="you@example.co.za" value={form.email} onChange={e=>setField("email",e.target.value)}/>
                {errs.email && <span className="err">{errs.email}</span>}
              </div>
              <div className={`field ${errs.phone?"invalid":""}`}>
                <label>Phone</label>
                <input type="tel" placeholder="082 123 4567" value={form.phone} onChange={e=>setField("phone",e.target.value)}/>
                {errs.phone && <span className="err">{errs.phone}</span>}
              </div>
            </div>
          </>)}
          {step === 2 && (<>
            <div className="section-label">Shipping address</div>
            <div className="form-grid two">
              <div className={`field ${errs.first?"invalid":""}`}><label>First name</label><input value={form.first} onChange={e=>setField("first",e.target.value)}/>{errs.first && <span className="err">{errs.first}</span>}</div>
              <div className={`field ${errs.last?"invalid":""}`}><label>Last name</label><input value={form.last} onChange={e=>setField("last",e.target.value)}/>{errs.last && <span className="err">{errs.last}</span>}</div>
            </div>
            <div className="form-grid" style={{marginTop:12}}>
              <div className={`field ${errs.address1?"invalid":""}`}><label>Address line 1</label><input value={form.address1} placeholder="Street and number" onChange={e=>setField("address1",e.target.value)}/>{errs.address1 && <span className="err">{errs.address1}</span>}</div>
              <div className="field"><label>Apartment / suite (optional)</label><input value={form.address2} onChange={e=>setField("address2",e.target.value)}/></div>
            </div>
            <div className="form-grid two" style={{marginTop:12}}>
              <div className={`field ${errs.city?"invalid":""}`}><label>City</label><input value={form.city} onChange={e=>setField("city",e.target.value)}/>{errs.city && <span className="err">{errs.city}</span>}</div>
              <div className="field"><label>Province</label><select value={form.province} onChange={e=>setField("province",e.target.value)}>{["Eastern Cape","Free State","Gauteng","KwaZulu-Natal","Limpopo","Mpumalanga","Northern Cape","North West","Western Cape"].map(p=><option key={p}>{p}</option>)}</select></div>
            </div>
            <div className="form-grid" style={{marginTop:12}}>
              <div className={`field ${errs.postal?"invalid":""}`} style={{maxWidth:180}}><label>Postal code</label><input value={form.postal} placeholder="0001" inputMode="numeric" onChange={e=>setField("postal",e.target.value.replace(/\D/g,"").slice(0,4))}/>{errs.postal && <span className="err">{errs.postal}</span>}</div>
            </div>
            <div style={{marginTop:24,padding:16,background:"var(--paper-2)",borderRadius:10,display:"flex",gap:10,fontSize:13,color:"var(--ink-soft)"}}>
              <Icon.truck size={18}/><div>Orders ship within 1 working day \u00b7 2\u20134 working days delivery via Aramex / The Courier Guy</div>
            </div>
          </>)}
          {step === 3 && (<>
            <div className="section-label">Order summary</div>
            <div className="summary-card" style={{marginBottom:20}}>
              <div className="cart-totals">
                {cart.map((l,i)=>(<div className="row" key={i}><span>Airstep Trainer \u00b7 UK {l.size} \u00d7 {l.qty}</span><span>{formatZAR(3200*l.qty)}</span></div>))}
                <div className="row"><span>Shipping</span><span>Free</span></div>
                <div className="row total"><span>Total</span><span>{formatZAR(subtotal)}</span></div>
              </div>
            </div>
            <div className="summary-card">
              <div style={{fontSize:13,color:"var(--ink-soft)",lineHeight:1.6}}>
                <div><strong>Email:</strong> {form.email}</div>
                <div><strong>Phone:</strong> {form.phone}</div>
                <div style={{marginTop:8}}><strong>Ship to:</strong> {form.first} {form.last}, {form.address1}{form.address2?", "+form.address2:""}, {form.city}, {form.province} {form.postal}</div>
              </div>
            </div>
            <div style={{marginTop:20,padding:14,background:"#f0f7ff",borderRadius:10,display:"flex",gap:10,fontSize:13,color:"#1a4a7a",alignItems:"flex-start"}}>
              <Icon.lock size={16}/><div>You'll be redirected to <strong>Stitch</strong> to complete payment securely via Instant EFT or card. Your bank details are never shared with us.</div>
            </div>
            {payError && <div style={{marginTop:16,padding:12,background:"#fff0f0",borderRadius:8,fontSize:13,color:"#c0392b"}}>{payError}</div>}
          </>)}
        </div>
        <div className="drawer-foot" style={{display:"flex",gap:10}}>
          {step > 1 && <button className="btn btn-secondary" onClick={back} disabled={processing}>Back</button>}
          {step < 3 && <button className="btn btn-cta" style={{flex:1}} onClick={next}>Continue <Icon.arrow size={16}/></button>}
          {step === 3 && (
            <button className="btn btn-cta" style={{flex:1}} onClick={handlePay} disabled={processing}>
              {processing ? <><span>Redirecting to Stitch</span><span className="dotdot">\u2026</span></> : <>Pay {formatZAR(subtotal)} via Stitch <Icon.lock size={14}/></>}
            </button>
          )}
        </div>
      </aside>
    </>
  );
};

// ============================================================
// SUCCESS DRAWER
// ============================================================
const SuccessDrawer = ({ open, onClose, order }) => {
  if (!order) return null;
  return (
    <>
      <div className={`scrim ${open?"show":""}`} onClick={onClose}/>
      <aside className={`drawer wide ${open?"show":""}`} aria-hidden={!open}>
        <div className="drawer-head">
          <h3>Order Confirmed</h3>
          <button className="drawer-close" onClick={onClose} aria-label="Close"><Icon.x/></button>
        </div>
        <div className="drawer-body">
          <div className="success">
            <div className="check"><Icon.check size={32}/></div>
            <h3>Thank you for your order.</h3>
            <p>
              A confirmation &amp; NAPPI invoice are on their way to <strong>{order.email}</strong>.
              Your AirSteps will ship within 1 working day.
            </p>
            <div className="order-box">
              <div style={{display:"flex", justifyContent:"space-between", marginBottom:14}}>
                <div>
                  <div style={{fontSize:11, letterSpacing:"0.08em", textTransform:"uppercase", color:"var(--ink-mute)"}}>Order number</div>
                  <div style={{fontFamily:"var(--serif)", fontSize:20, marginTop:4}}>#{order.orderId}</div>
                </div>
                <div style={{textAlign:"right"}}>
                  <div style={{fontSize:11, letterSpacing:"0.08em", textTransform:"uppercase", color:"var(--ink-mute)"}}>Total paid</div>
                  <div style={{fontFamily:"var(--serif)", fontSize:20, marginTop:4}}>{formatZAR(order.total)}</div>
                </div>
              </div>
              {order.items.map((l, i) => {
                return (
                  <div className="cart-line" key={i} style={{borderBottom:"1px solid var(--line-soft)"}}>
                    <div className="thumb"><img src="assets/product-clean.png" alt=""/></div>
                    <div className="info">
                      <h4>Airstep Therapeutic Trainer</h4>
                      <div className="sub">Midnight Navy · Size UK {l.size} · Qty {l.qty}</div>
                    </div>
                    <div className="actions"><div className="price">{formatZAR(3200 * l.qty)}</div></div>
                  </div>
                );
              })}
            </div>
            <p style={{marginTop:24, fontSize:13, color:"var(--ink-mute)"}}>
              Questions about your order? Reply to your confirmation email or contact our care team — we usually reply within 4 hours.
            </p>
          </div>
        </div>
        <div className="drawer-foot">
          <button className="btn btn-cta btn-block" onClick={onClose}>Continue Shopping</button>
        </div>
      </aside>
    </>
  );
};

// Sticky Buy Bar
const StickyBuy = ({ show, onBuy }) => (
  <div className={`sticky-buy ${show?"show":""}`}>
    <div className="meta">
      <div>
        <div className="sb-name">Airstep Therapeutic Trainer</div>
        <div className="sb-price">Class A Medical Device · NAPPI-coded</div>
      </div>
    </div>
    <button className="btn btn-primary" onClick={onBuy}>Shop now</button>
  </div>
);

Object.assign(window, {
  BuyBlock, CartDrawer, CheckoutDrawer, SuccessDrawer, StickyBuy, formatZAR
});
