/* ============================================================
   AUSTICH — Cart, Checkout, About, Contact
   ============================================================ */

/* ---------------- CART PAGE ---------------- */
function CartPage({ onNav }) {
  const { cart, updateQty, removeFromCart, cartTotal } = useContext(RBCtx);
  if (cart.length === 0) {
    return (
      <div className="fade-page page-shell center" style={{ minHeight: "60vh", display: "grid", placeItems: "center" }}>
        <div>
          <Icon name="cart" size={46} stroke={1} style={{ color: "var(--ink-faint)" }} />
          <h1 className="serif" style={{ fontSize: 44, margin: "18px 0 10px" }}>Your bag is empty</h1>
          <p style={{ color: "var(--ink-soft)", marginBottom: 26 }}>Let's find something for you.</p>
          <Btn onClick={() => onNav("shop", {})}>Start shopping</Btn>
        </div>
      </div>
    );
  }
  return (
    <div className="fade-page page-shell">
      <div className="wrap-wide">
        <h1 className="serif page-h">Your Bag</h1>
        <div className="cart-grid">
          <div className="cart-items">
            {cart.map((it) => (
              <div className="cart-row" key={it.key}>
                <button className="cart-row-media zoomable" onClick={() => onNav("product", { id: it.id })}><Ph label={it.label} ratio="portrait" /></button>
                <div className="cart-row-body">
                  <div className="spread" style={{ alignItems: "flex-start" }}>
                    <div>
                      <button className="serif cart-row-name" onClick={() => onNav("product", { id: it.id })}>{it.name}</button>
                      <div className="mono cart-row-meta">{it.size} · {it.color}</div>
                    </div>
                    <Price ngn={it.price * it.qty} style={{ fontFamily: "var(--font-display)", fontSize: 22 }} />
                  </div>
                  <div className="spread" style={{ marginTop: 18 }}>
                    <div className="qty">
                      <button onClick={() => updateQty(it.key, -1)}><Icon name="minus" size={14} /></button>
                      <span>{it.qty}</span>
                      <button onClick={() => updateQty(it.key, 1)}><Icon name="plus" size={14} /></button>
                    </div>
                    <button className="cart-remove" onClick={() => removeFromCart(it.key)}>Remove</button>
                  </div>
                </div>
              </div>
            ))}
          </div>
          <OrderSummary onNav={onNav} cta="Checkout" onCta={() => onNav("checkout", {})} />
        </div>
      </div>
    </div>
  );
}

function OrderSummary({ onNav, cta, onCta, ship = 0, showItems }) {
  const { cart, cartTotal } = useContext(RBCtx);
  const [code, setCode] = useState(""); const [applied, setApplied] = useState(false);
  const discount = applied ? Math.round(cartTotal * 0.1) : 0;
  const total = cartTotal - discount + ship;
  return (
    <aside className="summary">
      <h3 className="serif" style={{ fontSize: 24, marginBottom: 18 }}>Order summary</h3>
      {showItems && (
        <div className="summary-items">
          {cart.map((it) => (
            <div className="summary-item" key={it.key}>
              <div className="summary-item-img"><Ph label={it.label} ratio="square" /><span className="summary-qty">{it.qty}</span></div>
              <div style={{ flex: 1 }}><div className="serif" style={{ fontSize: 15, lineHeight: 1.2 }}>{it.name}</div><div className="mono" style={{ fontSize: 10.5, color: "var(--ink-faint)" }}>{it.size} · {it.color}</div></div>
              <Price ngn={it.price * it.qty} style={{ fontSize: 13 }} />
            </div>
          ))}
        </div>
      )}
      <div className="promo">
        <input className="input" placeholder="Promo code" value={code} onChange={(e) => setCode(e.target.value)} />
        <button className="promo-apply" onClick={() => setApplied(code.trim().length > 0)}>Apply</button>
      </div>
      {applied && <div className="promo-ok"><Icon name="check" size={14} /> Code applied — 10% off</div>}
      <div className="summary-lines">
        <div className="sline"><span>Subtotal</span><Price ngn={cartTotal} /></div>
        {discount > 0 && <div className="sline disc"><span>Discount</span><span>– {RB.formatDual(discount)}</span></div>}
        <div className="sline"><span>Shipping</span>{ship === 0 ? <span className="free">Complimentary</span> : <Price ngn={ship} />}</div>
        <div className="sline"><span>Duties &amp; taxes</span><span style={{ color: "var(--ink-faint)" }}>Calculated next</span></div>
      </div>
      <div className="summary-total"><span>Total</span><Price ngn={total} style={{ fontFamily: "var(--font-display)", fontSize: 25 }} /></div>
      {cta && <Btn block onClick={onCta} style={{ marginTop: 18 }}>{cta}</Btn>}
      <div className="summary-assure">
        <span><Icon name="shield" size={15} /> Secure checkout</span>
        <span><Icon name="truck" size={15} /> Worldwide shipping</span>
      </div>
    </aside>
  );
}

/* ---------------- CHECKOUT ---------------- */
function CheckoutPage({ onNav }) {
  const { cart, cartTotal, clearCart } = useContext(RBCtx);
  const [step, setStep] = useState(1);
  const [shipIdx, setShipIdx] = useState(0);
  const [payMethod, setPayMethod] = useState("card");
  const ship = RB.SHIPPING_TIERS[shipIdx];
  const steps = ["Information", "Shipping", "Payment"];

  if (cart.length === 0 && step < 4) {
    return (
      <div className="fade-page page-shell center" style={{ minHeight: "50vh", display: "grid", placeItems: "center" }}>
        <div><h1 className="serif" style={{ fontSize: 38, marginBottom: 16 }}>Nothing to check out</h1><Btn onClick={() => onNav("shop", {})}>Browse the collection</Btn></div>
      </div>
    );
  }

  if (step === 4) {
    return (
      <div className="fade-page page-shell">
        <div className="wrap confirm">
          <div className="confirm-badge"><Icon name="check" size={34} /></div>
          <Eyebrow>Order confirmed</Eyebrow>
          <h1 className="serif" style={{ fontSize: "clamp(38px,5vw,64px)", fontWeight: 500, margin: "12px 0 16px" }}>Thank you for your order.</h1>
          <p className="lede" style={{ maxWidth: "48ch", margin: "0 auto 10px" }}>We've emailed your receipt and tracking details. Order <strong className="mono">#{(window.BRAND && window.BRAND.orderPrefix) || "AU"}-{Math.floor(Math.random() * 90000 + 10000)}</strong> is on its way.</p>
          <p style={{ color: "var(--ink-soft)", marginBottom: 32 }}>Estimated delivery to {ship.region}: <strong>{ship.time}</strong></p>
          <div className="row" style={{ gap: 14, justifyContent: "center" }}>
            <Btn onClick={() => { clearCart(); onNav("home", {}); }}>Back to home</Btn>
            <Btn variant="ghost" arrow={false} onClick={() => { clearCart(); onNav("shop", {}); }}>Continue shopping</Btn>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="fade-page page-shell">
      <div className="wrap-wide">
        <div className="checkout-top">
          <Logo size={26} onClick={() => onNav("home", {})} />
          <div className="checkout-steps">
            {steps.map((s, i) => (
              <div key={s} className={"cstep" + (step === i + 1 ? " on" : "") + (step > i + 1 ? " done" : "")}>
                <span className="cstep-n">{step > i + 1 ? <Icon name="check" size={13} /> : i + 1}</span>{s}
              </div>
            ))}
          </div>
          <button className="checkout-secure"><Icon name="shield" size={15} /> Secure</button>
        </div>

        <div className="checkout-grid">
          <div className="checkout-main">
            {step === 1 && (
              <div className="fade-page">
                <h2 className="serif checkout-h">Contact &amp; delivery</h2>
                <div className="form-grid">
                  <div className="field span2"><label>Email address</label><input className="input" type="email" placeholder="you@email.com" /></div>
                  <div className="field"><label>First name</label><input className="input" placeholder="First name" /></div>
                  <div className="field"><label>Last name</label><input className="input" placeholder="Last name" /></div>
                  <div className="field span2"><label>Address</label><input className="input" placeholder="Street address" /></div>
                  <div className="field"><label>City</label><input className="input" placeholder="City" /></div>
                  <div className="field"><label>Country / Region</label>
                    <select className="input"><option>Nigeria</option><option>United Kingdom</option><option>United States</option><option>Ghana</option><option>United Arab Emirates</option><option>Canada</option></select>
                  </div>
                  <div className="field"><label>Phone</label><input className="input" placeholder="+234 …" /></div>
                  <div className="field"><label>Postal code</label><input className="input" placeholder="Postcode" /></div>
                </div>
                <div className="checkout-nav">
                  <button className="back-link" onClick={() => onNav("cart", {})}>← Return to bag</button>
                  <Btn arrow={false} onClick={() => setStep(2)}>Continue to shipping</Btn>
                </div>
              </div>
            )}
            {step === 2 && (
              <div className="fade-page">
                <h2 className="serif checkout-h">Shipping method</h2>
                <div className="ship-options">
                  {RB.SHIPPING_TIERS.map((t, i) => (
                    <button key={t.region} className={"ship-opt" + (shipIdx === i ? " on" : "")} onClick={() => setShipIdx(i)}>
                      <span className="ship-radio" />
                      <div className="ship-opt-body"><strong>{t.region}</strong><span>{t.time}</span></div>
                      <span className="ship-price">{t.price === 0 ? "Free" : RB.formatDual(t.price)}</span>
                    </button>
                  ))}
                </div>
                <div className="checkout-nav">
                  <button className="back-link" onClick={() => setStep(1)}>← Information</button>
                  <Btn arrow={false} onClick={() => setStep(3)}>Continue to payment</Btn>
                </div>
              </div>
            )}
            {step === 3 && (
              <div className="fade-page">
                <h2 className="serif checkout-h">Payment</h2>
                <div className="ship-options">
                  <button className={"ship-opt" + (payMethod === "card" ? " on" : "")} onClick={() => setPayMethod("card")}>
                    <span className="ship-radio" />
                    <div className="ship-opt-body"><strong>Card / bank transfer (NGN)</strong><span>Pay securely via Paystack</span></div>
                  </button>
                  <button className={"ship-opt" + (payMethod === "wire" ? " on" : "")} onClick={() => setPayMethod("wire")}>
                    <span className="ship-radio" />
                    <div className="ship-opt-body"><strong>USD wire transfer</strong><span>For international orders</span></div>
                  </button>
                </div>
                {payMethod === "card" ? (
                  <p className="pay-note">You'll be securely redirected to Paystack to complete payment.</p>
                ) : (
                  <div className="wire-info">
                    <div className="wire-details">
                      <div className="wire-row"><span>Bank</span><strong>{(window.BRAND && window.BRAND.wire && window.BRAND.wire.bank) || "First Bank of Nigeria"}</strong></div>
                      <div className="wire-row"><span>Account name</span><strong>{(window.BRAND && window.BRAND.wire && window.BRAND.wire.accountName) || (window.BRAND && window.BRAND.name) || "Austich"}</strong></div>
                      <div className="wire-row"><span>USD account no.</span><strong>{(window.BRAND && window.BRAND.wire && window.BRAND.wire.accountNo) || "0123456789"}</strong></div>
                      <div className="wire-row"><span>SWIFT / BIC</span><strong>{(window.BRAND && window.BRAND.wire && window.BRAND.wire.swift) || "FBNINGLA"}</strong></div>
                    </div>
                    <div className="wire-note"><strong>Reference your order</strong>Include your order number in the transfer memo, then email proof of payment to confirm your order.</div>
                  </div>
                )}
                <label className="pay-check"><input type="checkbox" defaultChecked /> <span>Email me about new arrivals</span></label>
                <div className="checkout-nav">
                  <button className="back-link" onClick={() => setStep(2)}>← Shipping</button>
                  <Btn arrow={false} onClick={() => setStep(4)}>{payMethod === "card" ? <React.Fragment>Pay <Price ngn={cartTotal + ship.price} /></React.Fragment> : "I've sent the transfer"}</Btn>
                </div>
              </div>
            )}
          </div>
          <OrderSummary onNav={onNav} ship={step >= 2 ? ship.price : 0} showItems />
        </div>
      </div>
    </div>
  );
}

/* ---------------- ABOUT ---------------- */
function AboutPage({ onNav }) {
  return (
    <div className="fade-page">
      <section className="about-hero">
        <Ph label="ABOUT · HERO" ratio="cinema" className="about-hero-bg" />
        <div className="about-hero-ov" />
        <div className="wrap about-hero-content">
          <Eyebrow style={{ color: "var(--accent-bright)" }}>Our Story</Eyebrow>
          <h1 className="serif about-hero-h" style={{ whiteSpace: "pre-line" }}>{(window.BRAND?.story.heroHeading) || "Clothing,\nmade to be worn."}</h1>
        </div>
      </section>
      <section className="section-pad">
        <div className="wrap about-intro">
          <Reveal><p className="serif about-lede">{(window.BRAND?.story.lede) || "Austich makes contemporary clothing for men and women."}</p></Reveal>
          <Reveal delay={1}><p style={{ color: "var(--ink-soft)", fontSize: 16, lineHeight: 1.8 }}>{(window.BRAND?.story.body) || "Every piece is chosen and put together with care, for everyday wear."}</p></Reveal>
        </div>
      </section>
      <section className="section-pad">
        <div className="wrap-wide values-grid">
          {[
            ["truck", "Worldwide shipping", "Tracked delivery across Nigeria and internationally."],
            ["shield", "Secure checkout", "Card payment via Paystack, priced in NGN and USD."],
            ["return", "Easy returns", "Unworn items with tags can be returned within 14 days."],
          ].map(([ic, t, d], i) => (
            <Reveal key={t} delay={i + 1} className="value-card">
              <Icon name={ic} size={26} stroke={1.3} />
              <h3 className="serif" style={{ fontSize: 26, fontWeight: 500, margin: "16px 0 10px" }}>{t}</h3>
              <p style={{ color: "var(--ink-soft)" }}>{d}</p>
            </Reveal>
          ))}
        </div>
      </section>
    </div>
  );
}

/* ---------------- CONTACT ---------------- */
function ContactPage({ onNav }) {
  const [sent, setSent] = useState(false);
  return (
    <div className="fade-page page-shell">
      <div className="wrap-wide">
        <h1 className="serif page-h">Customer care</h1>
        <p className="shop-sub" style={{ maxWidth: "52ch" }}>Send a message below and we'll get back to you.</p>
        <div className="contact-grid" style={{ gridTemplateColumns: "1fr" }}>
          <div className="contact-form-wrap" style={{ maxWidth: 640 }}>
            {sent ? (
              <div className="contact-sent"><div className="confirm-badge sm"><Icon name="check" size={26} /></div><h3 className="serif" style={{ fontSize: 30, margin: "14px 0 8px" }}>Message received</h3><p style={{ color: "var(--ink-soft)" }}>Thank you for reaching out. We'll be in touch shortly.</p></div>
            ) : (
              <form className="contact-form" onSubmit={(e) => { e.preventDefault(); setSent(true); }}>
                <h3 className="serif" style={{ fontSize: 28, marginBottom: 18 }}>Send a message</h3>
                <div className="form-grid">
                  <div className="field"><label>Name</label><input className="input" required placeholder="Your name" /></div>
                  <div className="field"><label>Email</label><input className="input" type="email" required placeholder="you@email.com" /></div>
                  <div className="field span2"><label>Subject</label>
                    <select className="input"><option>Order enquiry</option><option>Sizing & fit</option><option>Returns & exchange</option><option>Other</option></select>
                  </div>
                  <div className="field span2"><label>Message</label><textarea className="input" rows="5" required placeholder="How can we help?"></textarea></div>
                </div>
                <Btn block arrow={false} type="submit" style={{ marginTop: 16 }}>Send message</Btn>
              </form>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CartPage, CheckoutPage, AboutPage, ContactPage, BespokePage, OrderSummary });

/* ---------------- BESPOKE ---------------- */
function BespokePage({ onNav }) {
  const [sent, setSent] = useState(false);
  const [mode, setMode] = useState("form");
  const [slot, setSlot] = useState(null);
  const slots = ["Mon 10:00", "Mon 15:00", "Tue 11:00", "Wed 14:00", "Thu 10:30", "Fri 16:00"];
  const steps = [
    { n: "01", t: "Tell us the occasion", d: "Agbada, kaftan, gown or suit — share the event and your vision." },
    { n: "02", t: "Measurements", d: "Submit your measurements below, or book a fitting in Lagos." },
    { n: "03", t: "Fabric & fit review", d: "We confirm fabric, embellishment and silhouette with you before cutting." },
    { n: "04", t: "Made to order", d: "Your piece is hand-finished and delivered in 3–5 weeks." },
  ];
  return (
    <div className="fade-page page-shell">
      <div className="wrap-wide">
        <h1 className="serif page-h">Bespoke order</h1>
        <p className="shop-sub" style={{ maxWidth: "56ch" }}>Made-to-measure agbada, kaftan and eveningwear, cut for you. Tell us what you need and we'll follow up to confirm fit and fabric.</p>
        <div className="bespoke-book-grid" style={{ marginTop: 40 }}>
          <div className="bespoke-steps-col">
            {steps.map((s) =>
            <div className="bk-step" key={s.n}>
                <span className="mono">{s.n}</span>
                <div><strong>{s.t}</strong><p>{s.d}</p></div>
              </div>)}
          </div>
          <div className="bespoke-form-card">
            {sent ? (
              <div className="contact-sent"><div className="confirm-badge sm"><Icon name="check" size={26} /></div><h3 className="serif" style={{ fontSize: 30, margin: "14px 0 8px" }}>{mode === "call" ? "Call booked" : "Request received"}</h3><p style={{ color: "var(--ink-soft)" }}>{mode === "call" ? `We'll call you ${slot}. Look out for a confirmation message.` : "We'll reach out to confirm details and next steps."}</p></div>
            ) : (
              <React.Fragment>
                <div className="row" style={{ gap: 8, marginBottom: 22 }}>
                  <button type="button" onClick={() => setMode("form")} style={{ flex: 1, padding: "10px 14px", borderRadius: 100, fontSize: 12.5, letterSpacing: "0.06em", textTransform: "uppercase", fontWeight: 600, border: "1px solid var(--line-2)", background: mode === "form" ? "var(--ink)" : "transparent", color: mode === "form" ? "var(--bg)" : "var(--ink-soft)", transition: "all .2s" }}>Submit request</button>
                  <button type="button" onClick={() => setMode("call")} style={{ flex: 1, padding: "10px 14px", borderRadius: 100, fontSize: 12.5, letterSpacing: "0.06em", textTransform: "uppercase", fontWeight: 600, border: "1px solid var(--line-2)", background: mode === "call" ? "var(--ink)" : "transparent", color: mode === "call" ? "var(--bg)" : "var(--ink-soft)", transition: "all .2s" }}>Book a call</button>
                </div>
                {mode === "form" ? (
                <form onSubmit={(e) => { e.preventDefault(); setSent(true); }}>
                <h3 className="serif" style={{ fontSize: 26, marginBottom: 6 }}>Start your order</h3>
                <label className="bk-label">Garment</label>
                <div className="bk-pills">
                  {["Agbada", "Kaftan", "Gown", "Suit", "Other"].map((g) =>
                  <button type="button" key={g} style={{ padding: "8px 16px", borderRadius: 100, border: "1px solid var(--line-2)", fontSize: 13, color: "var(--ink-soft)", background: "transparent" }}>{g}</button>)}
                </div>
                <div className="form-grid" style={{ marginTop: 18 }}>
                  <div className="field"><label>Name</label><input className="input" required placeholder="Your name" /></div>
                  <div className="field"><label>Phone</label><input className="input" required placeholder="080..." /></div>
                  <div className="field span2"><label>Occasion / date needed by</label><input className="input" placeholder="e.g. Wedding, 20 Sept" /></div>
                  <div className="field span2"><label>Details</label><textarea className="input" rows="4" placeholder="Fabric preference, colours, references..."></textarea></div>
                </div>
                <Btn block arrow={false} type="submit" style={{ marginTop: 16 }}>Submit request</Btn>
                </form>
                ) : (
                <form onSubmit={(e) => { e.preventDefault(); if (slot) setSent(true); }}>
                <h3 className="serif" style={{ fontSize: 26, marginBottom: 6 }}>Book a call</h3>
                <p style={{ color: "var(--ink-soft)", fontSize: 14, marginBottom: 16 }}>Pick a time and we'll call to talk through fit, fabric and pricing.</p>
                <div className="form-grid">
                  <div className="field"><label>Name</label><input className="input" required placeholder="Your name" /></div>
                  <div className="field"><label>Phone</label><input className="input" required placeholder="080..." /></div>
                </div>
                <label className="bk-label" style={{ marginTop: 14, display: "block" }}>Choose a time</label>
                <div className="bk-pills">
                  {slots.map((s) =>
                  <button type="button" key={s} onClick={() => setSlot(s)} style={{ padding: "8px 16px", borderRadius: 100, border: "1px solid " + (slot === s ? "var(--accent)" : "var(--line-2)"), fontSize: 13, color: slot === s ? "var(--ink)" : "var(--ink-soft)", background: slot === s ? "var(--surface)" : "transparent" }}>{s}</button>)}
                </div>
                <Btn block arrow={false} type="submit" disabled={!slot} style={{ marginTop: 16 }}>Confirm call</Btn>
                </form>
                )}
              </React.Fragment>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
