/* ============================================================
   EMAGINE BY BUKOLA — 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 you'll love.</p>
          <Btn onClick={() => onNav("shop", {})}>Start shopping</Btn>
        </div>
      </div>
    );
  }
  return (
    <div className="fade-page page-shell">
      <div className="wrap-wide">
        <div className="crumb"><button onClick={() => onNav("home", {})}>Home</button> / <span>Bag</span></div>
        <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={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.format(discount, currency)}</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, currency } = useContext(RBCtx);
  const [step, setStep] = useState(1);
  const [shipIdx, setShipIdx] = useState(0);
  const [pay, setPay] = useState("paystack");
  const [wireModal, setWireModal] = useState(false);
  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. Your Emagine story continues.</h1>
          <p className="lede" style={{ maxWidth: "48ch", margin: "0 auto 10px" }}>We've emailed your receipt and tracking details. Order <strong className="mono">#EB-{Math.floor(Math.random() * 90000 + 10000)}</strong> ships via tracked courier.</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 States</option><option>United Kingdom</option><option>Canada</option><option>Ghana</option><option>United Arab Emirates</option><option>Other</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} · Tracked courier</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"], ["wire", "Dollar Wire Transfer"]].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 {currency}.</p>}
                {pay === "wire" && (
                  <div className="wire-info">
                    <p className="pay-note">USD wire transfer — details are below and will also be emailed to you.</p>
                    <button type="button" className="wire-modal-btn" onClick={() => setWireModal(true)}>View full account details →</button>
                  </div>
                )}
                <label className="pay-check"><input type="checkbox" defaultChecked /> <span>Email me about new collections &amp; private fittings</span></label>
                {wireModal && (
                  <div className="modal-overlay" onClick={() => setWireModal(false)}>
                    <div className="modal-card" onClick={(e) => e.stopPropagation()}>
                      <button className="modal-close" onClick={() => setWireModal(false)}>×</button>
                      <h3 className="serif modal-h">Wire transfer details</h3>
                      <div className="wire-details">
                        <div className="wire-row"><span>Account holder</span><strong>Emagine by Bukola Limited</strong></div>
                        <div className="wire-row"><span>Bank</span><strong>Standard Chartered Bank</strong></div>
                        <div className="wire-row"><span>Swift code</span><strong className="mono">SCBLNGLA</strong></div>
                        <div className="wire-row"><span>Account number</span><strong className="mono">0123456789</strong></div>
                        <div className="wire-row"><span>Sort code</span><strong className="mono">05-20-36</strong></div>
                        <div className="wire-row"><span>Currency</span><strong>USD</strong></div>
                        <div className="wire-row"><span>Amount</span><strong className="serif">{fmtNGN(cartTotal + ship.price)}</strong></div>
                        <div className="wire-row"><span>Reference</span><strong className="mono">EB-{Math.random().toString(36).slice(2,8).toUpperCase()}</strong></div>
                        <div className="wire-note">
                          <strong>Important:</strong> Include the reference number in your payment memo so we can match your transfer to your order. Once funds clear (typically 3–5 business days), we'll confirm and begin production.
                        </div>
                      </div>
                      <button className="modal-btn" onClick={() => setWireModal(false)}>Close</button>
                    </div>
                  </div>
                )}
                <div className="checkout-nav">
                  <button className="back-link" onClick={() => setStep(2)}>← Shipping</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>
  );
}

/* ---------------- ABOUT ---------------- */
function AboutPage({ onNav }) {
  return (
    <div className="fade-page">
      <section className="about-hero">
        <Ph label="ATELIER · THE FOUNDER'S STUDIO" ratio="cinema" className="about-hero-bg" />
        <div className="about-hero-ov" />
        <div className="wrap about-hero-content">
          <Eyebrow style={{ color: "#e9c97a" }}>The Emagine Atelier</Eyebrow>
          <h1 className="serif about-hero-h">Quiet luxury,<br />made by hand.</h1>
        </div>
      </section>

      <section className="section-pad">
        <div className="wrap about-intro">
          <Reveal><p className="serif about-lede">Emagine by Bukola is a Nigerian luxury womenswear atelier — hand-beaded couture with fluid lines and quiet-luxury detailing.</p></Reveal>
          <Reveal delay={1}><p style={{ color: "var(--ink-soft)", fontSize: 16, lineHeight: 1.8 }}>Founded by Creative Director Bukola Owolabi, the Emagine Atelier works from Lagos, Nigeria — every gown begins on a sketch table and ends in thousands of hand-placed beads. Nothing is rushed, and nothing is mass-produced.</p></Reveal>
          <Reveal delay={2}><p style={{ color: "var(--ink-soft)", fontSize: 16, lineHeight: 1.8 }}>We build four collections at the atelier — Red Carpet, Prom, Bridal (our bridal line, @ebbridals) and fully bespoke Custom commissions. Every piece is made in Nigeria and shipped worldwide, with dedicated service to the US, UK and Canada.</p></Reveal>
        </div>
      </section>

      <section className="section-pad-sm">
        <div className="wrap-wide about-stats">
          {[["Hand-Beaded", "Every gown finished entirely by hand"], ["Made in Nigeria", "Designed and produced at our Lagos atelier"], ["Worldwide", "Shipped to the US, UK, Canada & beyond"], ["Bespoke", "Custom commissions — no fixed price list"]].map(([n, l]) => (
            <Reveal key={l} className="about-stat"><strong className="serif" style={{ fontSize: "clamp(24px,2.6vw,34px)" }}>{n}</strong><span>{l}</span></Reveal>
          ))}
        </div>
      </section>

      <section className="section-pad">
        <div className="wrap-wide values-grid">
          {[
            ["scissors", "Hand-beaded, always", "Every bead is placed by hand at our Lagos atelier — hours upon hours across a single gown, never mass-produced."],
            ["heart", "Fluid lines, quiet luxury", "Sculpted silhouettes and quiet-luxury detailing define the Emagine look — bold on the red carpet, tender on a wedding day."],
            ["globe", "Worn worldwide", "From Lagos red carpets to weddings and premieres across the US, UK and Canada — made in Nigeria, worn everywhere."],
          ].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>

      {/* Press credit */}
      <section className="section-pad-sm press-band">
        <div className="wrap-wide press-grid">
          <Reveal className="press-media zoomable"><Ph label="PRESS · AMVCA 2026" ratio="wide" /></Reveal>
          <div className="press-body">
            <Reveal><Eyebrow line>As Seen</Eyebrow></Reveal>
            <Reveal delay={1}><h2 className="serif press-h">Dressed for the AMVCA red carpet.</h2></Reveal>
            <Reveal delay={2}>
              <p className="lede" style={{ marginBottom: 22 }}>
                At the AMVCA 2026 in Lagos, Emagine by Bukola dressed Nomzamo Mbatha in a hand-beaded, sculptural
                gown built entirely at our atelier — a piece made for one of the biggest stages in African entertainment.
              </p>
            </Reveal>
            <Reveal delay={3}><button className="link-arrow" onClick={() => onNav("shop", { cat: "Red Carpet" })}>Shop Red Carpet</button></Reveal>
          </div>
        </div>
      </section>

      {/* Real brides */}
      <section className="section-pad-sm">
        <div className="wrap-wide">
          <Reveal className="section-head" style={{ marginBottom: 40 }}>
            <h2 className="serif">Real brides, real moments</h2>
          </Reveal>
          <div className="moments-grid">
            {RB.REAL_MOMENTS.map((m, i) => (
              <Reveal key={m.label} delay={(i % 4) + 1} className="moment-card zoomable">
                <Ph label={m.label} ratio="portrait" />
                <span className="moment-cap">{m.caption}</span>
              </Reveal>
            ))}
          </div>
        </div>
      </section>

      <BespokeBand onNav={onNav} />
    </div>
  );
}

/* ---------------- CONTACT ---------------- */
function ContactPage({ onNav }) {
  const [sent, setSent] = useState(false);
  return (
    <div className="fade-page page-shell">
      <div className="wrap-wide">
        <div className="crumb"><button onClick={() => onNav("home", {})}>Home</button> / <span>Contact</span></div>
        <h1 className="serif page-h">Customer care</h1>
        <p className="shop-sub" style={{ maxWidth: "52ch" }}>Our team is here from Lagos. We typically reply within a few hours, Monday to Saturday, 9am–9pm WAT.</p>
        <div className="contact-grid">
          <div className="contact-info">
            {[
              ["mail", "Email", "info.emaginebybukola@gmail.com", "Replies within a few hours"],
              ["pin", "Lagos atelier", "Lagos, Nigeria", "By appointment — request a consultation"],
              ["ig", "Instagram", "@emaginebybukola", "Follow the atelier", "https://www.instagram.com/emaginebybukola"],
            ].map(([ic, t, v, s, href]) => (
              href ? (
                <a key={t} className="contact-card" href={href} target="_blank" rel="noopener noreferrer">
                  <span className="contact-ic"><Icon name={ic} size={20} /></span>
                  <div><span className="contact-t">{t}</span><strong>{v}</strong><span className="contact-s">{s}</span></div>
                </a>
              ) : (
                <div key={t} className="contact-card">
                  <span className="contact-ic"><Icon name={ic} size={20} /></span>
                  <div><span className="contact-t">{t}</span><strong>{v}</strong><span className="contact-s">{s}</span></div>
                </div>
              )
            ))}
            <div className="contact-hours">
              <span className="footer-h" style={{ color: "var(--accent)" }}>Opening hours</span>
              <div className="hours-row"><span>Mon – Fri</span><span>9:00 – 19:00 WAT</span></div>
              <div className="hours-row"><span>Saturday</span><span>10:00 – 17:00 WAT</span></div>
              <div className="hours-row"><span>Sunday</span><span>Closed</span></div>
            </div>
            <button className="acct-add" style={{ marginTop: 4 }} onClick={() => onNav("custom", {})}>
              <Icon name="scissors" size={16} /> Enquiring about custom or bridal? Request a consultation →
            </button>
          </div>
          <div className="contact-form-wrap">
            {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>Bespoke commission</option><option>Returns &amp; exchange</option><option>Press &amp; partnerships</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, OrderSummary });
