// 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 | insole

  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="Studio view">
                <img src="assets/product-clean.png" alt=""/>
              </button>
              <button className={view==="insole"?"active":""} onClick={()=>setView("insole")} aria-label="Insole view">
                <img src="assets/product-insole.jpg" 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>Free shipping</strong>Anywhere in 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">
                <span>Shipping</span>
                <span className={shipFree?"ship-free":""}>
                  {shipFree ? "FREE" : formatZAR(shipping)}
                </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 (full multi-step)
// ============================================================
const fmtCard = (v) => v.replace(/\D/g,"").slice(0,16).replace(/(.{4})/g,"$1 ").trim();
const fmtExp = (v) => {
  const d = v.replace(/\D/g,"").slice(0,4);
  return d.length<=2 ? d : `${d.slice(0,2)}/${d.slice(2)}`;
};

const CheckoutDrawer = ({ open, onClose, cart, onSuccess }) => {
  const [step, setStep] = React.useState(1); // 1=contact 2=shipping 3=payment
  const [form, setForm] = React.useState({
    email: "", phone: "",
    first: "", last: "", address1: "", address2: "", city: "", province: "Gauteng", postal: "",
    cardName: "", cardNum: "", exp: "", cvc: "",
  });
  const [errs, setErrs] = React.useState({});
  const [processing, setProcessing] = React.useState(false);
  // Peach Payments: filled when /api/checkout responds. { mode, checkoutId, scriptUrl }
  const [peach, setPeach] = React.useState(null);
  const peachMountRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) {
      // reset after closing animation
      setTimeout(() => {
        setStep(1); setErrs({}); setProcessing(false);
        setPeach(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";
    }
    if (step === 3) {
      if (!form.cardName.trim()) e.cardName = "Required";
      if (form.cardNum.replace(/\s/g,"").length < 13) e.cardNum = "Invalid card number";
      if (!/^\d{2}\/\d{2}$/.test(form.exp)) e.exp = "MM/YY";
      if (!/^\d{3,4}$/.test(form.cvc)) e.cvc = "3–4 digits";
    }
    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 submit = () => {
    if (!validate()) return;
    setProcessing(true);
    setTimeout(() => {
      const orderId = "AIR-" + Math.floor(100000 + Math.random()*900000);
      onSuccess({ orderId, email: form.email, total: totals.total, items: cart });
    }, 1400);
  };

  const subtotal = cart.reduce((s, i) => s + 3200 * i.qty, 0);
  const shipFree = true;
  const shipping = 0;
  const totals = { subtotal, shipping, total: subtotal + shipping };

  // ---- Peach Payments: create checkout session when entering step 3 ----
  React.useEffect(() => {
    if (!open || step !== 3 || peach) return;
    let cancelled = false;
    (async () => {
      try {
        const resp = await fetch("/api/checkout", {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({
            amount: totals.total,
            customer: { email: form.email, first: form.first, last: form.last, phone: form.phone },
            billing: {
              street1: form.address1, street2: form.address2,
              city: form.city, state: form.province, postcode: form.postal,
            },
            items: cart.map(i => ({ name: "Airstep Therapeutic Trainer", qty: i.qty, price: 3200 })),
          }),
        });
        if (!resp.ok) throw new Error("checkout endpoint not available");
        const data = await resp.json();
        if (!cancelled) setPeach(data);
      } catch {
        // No backend (static demo) → fall back to the existing mock card form
        if (!cancelled) setPeach({ mode: "demo", checkoutId: "LOCAL_DEMO" });
      }
    })();
    return () => { cancelled = true; };
  }, [open, step, peach]);

  // ---- Mount Peach Copy-and-Pay widget when real scriptUrl arrives ----
  React.useEffect(() => {
    if (!peach || !peach.scriptUrl || peach.mode === "demo") return;
    if (document.querySelector(`script[data-peach="${peach.checkoutId}"]`)) return;
    const s = document.createElement("script");
    s.src = peach.scriptUrl;
    s.async = true;
    s.dataset.peach = peach.checkoutId;
    document.body.appendChild(s);
  }, [peach]);

  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 ? "✓" : 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 · 2–4 working days delivery via Aramex / The Courier Guy</div>
              </div>
            </>
          )}

          {step === 3 && !peach && (
            <div style={{padding: "40px 0", textAlign: "center", color: "var(--ink-soft)"}}>
              <div style={{fontSize: 14}}>Preparing secure payment…</div>
            </div>
          )}

          {step === 3 && peach && peach.mode !== "demo" && (
            <>
              <div className="section-label">Payment details</div>
              <div className="card-pay-icons">
                <span className="chip">VISA</span>
                <span className="chip">MASTERCARD</span>
                <span className="chip">AMEX</span>
                <span style={{marginLeft:"auto", display:"flex", alignItems:"center", gap:6}}>
                  <Icon.lock size={12}/> Peach Payments · 3DS Secure
                </span>
              </div>
              {/* Peach Copy-and-Pay widget mounts here */}
              <form
                ref={peachMountRef}
                action={`/api/payment-result?id=${peach.checkoutId}`}
                className="paymentWidgets"
                data-brands="VISA MASTER AMEX"
                style={{minHeight: 280}}
              />
              <div className="secured-row" style={{marginTop: 16}}>
                <Icon.lock size={14}/>
                {peach.mode === "test"
                  ? "TEST mode — use card 4200 0000 0000 0000, any future expiry, CVV 123."
                  : "256-bit SSL · 3DS Secure · processed by Peach Payments."}
              </div>
            </>
          )}

          {step === 3 && peach && peach.mode === "demo" && (
            <>
              <div className="section-label">Payment details</div>
              <div className="card-pay-icons">
                <span className="chip">VISA</span>
                <span className="chip">MASTERCARD</span>
                <span className="chip">AMEX</span>
                <span style={{marginLeft:"auto", display:"flex", alignItems:"center", gap:6}}>
                  <Icon.lock size={12}/> Demo mode
                </span>
              </div>
              <div className="form-grid">
                <div className={`field ${errs.cardName?"invalid":""}`}>
                  <label>Name on card</label>
                  <input value={form.cardName} onChange={e=>setField("cardName", e.target.value)}/>
                  {errs.cardName && <span className="err">{errs.cardName}</span>}
                </div>
                <div className={`field ${errs.cardNum?"invalid":""}`}>
                  <label>Card number</label>
                  <input value={form.cardNum}
                    placeholder="0000 0000 0000 0000"
                    inputMode="numeric"
                    onChange={e=>setField("cardNum", fmtCard(e.target.value))}/>
                  {errs.cardNum && <span className="err">{errs.cardNum}</span>}
                </div>
                <div className="card-input-row">
                  <div className={`field ${errs.exp?"invalid":""}`}>
                    <label>Expiry</label>
                    <input value={form.exp} placeholder="MM/YY" inputMode="numeric"
                      onChange={e=>setField("exp", fmtExp(e.target.value))}/>
                    {errs.exp && <span className="err">{errs.exp}</span>}
                  </div>
                  <div className={`field ${errs.cvc?"invalid":""}`}>
                    <label>CVC</label>
                    <input value={form.cvc} placeholder="123" inputMode="numeric" maxLength={4}
                      onChange={e=>setField("cvc", e.target.value.replace(/\D/g,"").slice(0,4))}/>
                    {errs.cvc && <span className="err">{errs.cvc}</span>}
                  </div>
                </div>
              </div>

              <div className="summary-card" style={{marginTop:24}}>
                <h4>Order summary</h4>
                <div className="cart-totals" style={{marginBottom:0}}>
                  <div className="row"><span>Subtotal ({cart.reduce((s,i)=>s+i.qty,0)} item{cart.reduce((s,i)=>s+i.qty,0)!==1?"s":""})</span><span>{formatZAR(totals.subtotal)}</span></div>
                  <div className="row">
                    <span>Shipping</span>
                    <span className={shipFree?"ship-free":""}>{shipFree?"FREE":formatZAR(totals.shipping)}</span>
                  </div>
                  <div className="row total"><span>Total</span><span>{formatZAR(totals.total)}</span></div>
                </div>
                <div className="secured-row">
                  <Icon.lock size={14}/>
                  Your payment is secured with 256-bit SSL encryption. We never store your card details.
                </div>
              </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 && (!peach || peach.mode === "demo") && (
            <button className="btn btn-cta" style={{flex:1}} onClick={submit} disabled={processing || !peach}>
              {processing ? (
                <>Processing<span className="dotdot">…</span></>
              ) : (
                <>Pay {formatZAR(totals.total)} <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
});
