/* ============================================================
   ZURIEL AFRIQUE — Cart, Checkout, About, Contact
   ============================================================ */

/* ---------------- CART PAGE ---------------- */
function CartPage({ onNav }) {
  const { cart, updateQty, removeFromCart, cartTotal, currency } = 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 to love.</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, currency } = 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="" 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.format(discount, currency)}</span></div>}
        <div className="sline"><span>Delivery</span>{ship === 0 ? <span className="free">Complimentary</span> : <Price ngn={ship} />}</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} /> Nationwide delivery</span>
      </div>
    </aside>
  );
}

/* ---------------- CHECKOUT ---------------- */
function CheckoutPage({ onNav }) {
  const { cart, cartTotal, clearCart, currency } = useContext(RBCtx);
  const [step, setStep] = useState(1);
  const [shipIdx, setShipIdx] = useState(0);
  const [pay, setPay] = useState("paystack");
  const [orderRef] = useState(() => RB.genOrderRef());
  const [form, setForm] = useState({ email: "", firstName: "", lastName: "", address: "", city: "", phone: "", postal: "" });
  const [errors, setErrors] = useState({});
  const setField = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const validateStep1 = () => {
    const e = {};
    if (!form.email.trim()) e.email = "Email is required.";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = "Enter a valid email address.";
    if (!form.firstName.trim()) e.firstName = "First name is required.";
    if (!form.lastName.trim()) e.lastName = "Last name is required.";
    if (!form.address.trim()) e.address = "Address is required.";
    if (!form.city.trim()) e.city = "City is required.";
    if (!form.phone.trim()) e.phone = "Phone number is required.";
    if (!form.postal.trim()) e.postal = "Postal code is required.";
    setErrors(e);
    return Object.keys(e).length === 0;
  };
  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. Order <strong className="mono">#{orderRef}</strong> is being prepared for delivery.</p>
          <p style={{ color: "var(--ink-soft)", marginBottom: 14 }}>Estimated delivery to {ship.region}: <strong>{ship.time}</strong></p>
          <button type="button" className="wire-modal-btn" style={{ marginBottom: 30 }} onClick={() => onNav("track", { ref: orderRef, region: ship.region, time: ship.time })}>Track your order →</button>
          <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" + (errors.email ? " err" : "")}>
                    <label>Email address</label>
                    <input className="input" type="email" placeholder="you@email.com" value={form.email} onChange={setField("email")} />
                    {errors.email && <span className="field-err">{errors.email}</span>}
                  </div>
                  <div className={"field" + (errors.firstName ? " err" : "")}>
                    <label>First name</label>
                    <input className="input" placeholder="First name" value={form.firstName} onChange={setField("firstName")} />
                    {errors.firstName && <span className="field-err">{errors.firstName}</span>}
                  </div>
                  <div className={"field" + (errors.lastName ? " err" : "")}>
                    <label>Last name</label>
                    <input className="input" placeholder="Last name" value={form.lastName} onChange={setField("lastName")} />
                    {errors.lastName && <span className="field-err">{errors.lastName}</span>}
                  </div>
                  <div className={"field span2" + (errors.address ? " err" : "")}>
                    <label>Address</label>
                    <input className="input" placeholder="Street address" value={form.address} onChange={setField("address")} />
                    {errors.address && <span className="field-err">{errors.address}</span>}
                  </div>
                  <div className={"field" + (errors.city ? " err" : "")}>
                    <label>City</label>
                    <input className="input" placeholder="City" value={form.city} onChange={setField("city")} />
                    {errors.city && <span className="field-err">{errors.city}</span>}
                  </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>Canada</option></select>
                  </div>
                  <div className={"field" + (errors.phone ? " err" : "")}>
                    <label>Phone</label>
                    <input className="input" placeholder="+234 …" value={form.phone} onChange={setField("phone")} />
                    {errors.phone && <span className="field-err">{errors.phone}</span>}
                  </div>
                  <div className={"field" + (errors.postal ? " err" : "")}>
                    <label>Postal code</label>
                    <input className="input" placeholder="Postcode" value={form.postal} onChange={setField("postal")} />
                    {errors.postal && <span className="field-err">{errors.postal}</span>}
                  </div>
                </div>
                <div className="checkout-nav">
                  <button className="back-link" onClick={() => onNav("cart", {})}>← Return to bag</button>
                  <Btn arrow={false} onClick={() => { if (validateStep1()) setStep(2); }}>Continue to shipping</Btn>
                </div>
              </div>
            )}
            {step === 2 && (
              <div className="fade-page">
                <h2 className="serif checkout-h">Delivery 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.format(t.price, currency)}</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="pay-methods">
                  {[["paystack", "Paystack"], ["flutterwave", "Flutterwave"], ["stripe", "Card (Stripe)"]].map(([k, l]) => (
                    <button key={k} className={"pay-tab" + (pay === k ? " on" : "")} onClick={() => setPay(k)}>{l}</button>
                  ))}
                </div>
                {pay === "paystack" && <p className="pay-note">You'll be securely redirected to Paystack to complete payment in {(window.BRAND?.currency.base) || "NGN"}.</p>}
                {pay === "flutterwave" && <p className="pay-note">You'll be securely redirected to Flutterwave to complete payment in {(window.BRAND?.currency.base) || "NGN"}.</p>}
                {pay === "stripe" && <p className="pay-note">You'll be securely redirected to Stripe to complete payment in {(window.BRAND?.currency.altCode) || "USD"}.</p>}
                <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)}>← Delivery</button>
                  <Btn arrow={false} onClick={() => setStep(4)}>Pay <Price ngn={cartTotal + ship.price} /></Btn>
                </div>
              </div>
            )}
          </div>
          <OrderSummary onNav={onNav} ship={step >= 2 ? ship.price : 0} showItems />
        </div>
      </div>
    </div>
  );
}

/* ---------------- ORDER TRACKING ---------------- */
function OrderTrackingPage({ onNav, route }) {
  const p = (route && route.params) || {};
  const ref = p.ref || "";
  const region = p.region || RB.SHIPPING_TIERS[0].region;
  const time = p.time || RB.SHIPPING_TIERS[0].time;
  const steps = [["Order placed", "done"], ["Processing", "active"], ["Dispatched", "todo"], ["Delivered", "todo"]];
  return (
    <div className="fade-page page-shell">
      <div className="wrap confirm" style={{ paddingTop: 90 }}>
        <div className="confirm-badge sm"><Icon name="truck" size={26} /></div>
        <Eyebrow>Order tracking</Eyebrow>
        <h1 className="serif" style={{ fontSize: "clamp(32px,4.4vw,48px)", fontWeight: 500, margin: "12px 0 18px" }}>
          {ref ? <>Order <span className="mono">#{ref}</span></> : "Track your order"}
        </h1>
        <p className="lede" style={{ maxWidth: "48ch", margin: "0 auto 30px" }}>
          Estimated delivery to {region}: <strong>{time}</strong>. Tracking details will appear here once your order ships.
        </p>
        <div className="co-steps-mini" style={{ maxWidth: 420, margin: "0 auto 36px" }}>
          {steps.map(([t, s]) => (
            <div className={"co-stepm co-" + s} key={t}>
              <span className="co-stepm-dot">{s === "done" && <Icon name="check" size={11} />}</span>
              <span className="co-stepm-t">{t}</span>
            </div>
          ))}
        </div>
        <div className="row" style={{ gap: 14, justifyContent: "center" }}>
          <Btn onClick={() => onNav("home", {})}>Back to home</Btn>
          <Btn variant="ghost" arrow={false} onClick={() => onNav("shop", {})}>Continue shopping</Btn>
        </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) || "Made in Nigeria,\nworn everywhere."}</h1>
        </div>
      </section>
      <section className="section-pad">
        <div className="wrap about-intro">
          <Reveal><p className="serif about-lede">{(window.BRAND?.story.lede) || "Zuriel Afrique designs for the woman who wants her clothes to feel considered."}</p></Reveal>
          <Reveal delay={1}><p style={{ color: "var(--ink-soft)", fontSize: 16, lineHeight: 1.8 }}>{(window.BRAND?.story.body) || "Every piece is designed and made in Nigeria."} {(window.BRAND?.story.craftLine) || "From print sourcing to the final seam, each piece is developed and produced locally."}</p></Reveal>
        </div>
      </section>
      <section className="section-pad">
        <div className="wrap-wide values-grid">
          {[
            ["leaf", "Rooted in fabric", "African textiles and prints anchor every piece — the starting point for every silhouette, not an afterthought."],
            ["scissors", "Considered tailoring", "Easy, wearable shapes cut to move — clothing designed to work as hard as the women who wear it."],
            ["globe", "Made in Nigeria", (window.BRAND?.story.valuesLine) || "Designed and produced locally, piece by piece."],
          ].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>
      <CustomBand onNav={onNav} />
    </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">Get in touch</h1>
        <p className="shop-sub" style={{ maxWidth: "52ch" }}>Questions about an order, sizing or anything else — send us a message and we'll get back to you.</p>
        <div className="contact-form-wrap" style={{ maxWidth: 560, margin: "0 auto" }}>
          {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 &amp; fit</option><option>Custom order</option><option>Returns &amp; exchange</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>
  );
}

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