/* ============================================================
   RACK & BOX — Cart, Checkout, About, Contact, Account,
   Lookbook, Bespoke, Collections, Wishlist
   ============================================================ */

/* ---------------- 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 worth the occasion.</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="" 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 moment begins.</h1>
          <p className="lede" style={{ maxWidth: "48ch", margin: "0 auto 10px" }}>We've emailed your receipt and tracking details. Order <strong className="mono">#WC-{Math.floor(Math.random() * 90000 + 10000)}</strong> ships via DHL Express.</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} · DHL Express</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 drops &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>Winns Couture 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">WC-{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 · WINNS COUTURE STUDIO" ratio="cinema" className="about-hero-bg" />
        <div className="about-hero-ov" />
        <div className="wrap about-hero-content">
          <Eyebrow style={{ color: "#e9c97a" }}>Our Story</Eyebrow>
          <h1 className="serif about-hero-h">Couture born<br />in Port Harcourt.</h1>
        </div>
      </section>
      <section className="section-pad">
        <div className="wrap about-intro">
          <Reveal><p className="serif about-lede">Winns Couture began with a simple belief: that every woman deserves to feel unforgettable on the day that matters most.</p></Reveal>
          <Reveal delay={1}><p style={{ color: "var(--ink-soft)", fontSize: 16, lineHeight: 1.8 }}>Founded in Port Harcourt, we set out to dress brides, celebrants and tastemakers across Nigeria and the diaspora — women who want couture that is dramatic, intricate and entirely their own. From hand-beaded bridal gowns to statement asoebi, every piece is designed and crafted by our atelier, then delivered worldwide. Our fashion academy trains the next generation of Nigerian designers to carry that craft forward.</p></Reveal>
        </div>
      </section>
      <section className="section-pad-sm">
        <div className="wrap-wide about-stats">
          {[["PH", "Founded in Port Harcourt"], ["40+", "Countries shipped"], ["500+", "Brides dressed"], ["1", "Fashion academy"]].map(([n, l]) => (
            <Reveal key={l} className="about-stat"><strong className="serif">{n}</strong><span>{l}</span></Reveal>
          ))}
        </div>
      </section>
      <section className="section-pad">
        <div className="wrap-wide values-grid">
          {[
            ["leaf", "Made to measure", "Every couture piece is cut to your exact measurements — your fabric, your palette, your silhouette, nothing off the rack."],
            ["scissors", "Crafted by hand", "From the first sketch to the final bead, each gown passes through the hands of our master couturiers."],
            ["globe", "Worn worldwide", "From owambe in Lagos to weddings in London and Houston, our gowns travel as far as the women who wear them."],
          ].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>
      <section className="about-quote-sec">
        <div className="wrap center">
          <Reveal><blockquote className="serif about-quote">“We don't make dresses to be worn once and forgotten. We make the gown you'll see in every photograph for the rest of your life.”</blockquote></Reveal>
          <Reveal delay={1}><div className="testi-author" style={{ marginTop: 24 }}>Winnie · <span>Founder &amp; Creative Director</span></div></Reveal>
        </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 concierge is here from Nigeria. We typically reply within a few hours, Monday to Saturday. For custom orders, DM @winns_couture.</p>
        <div className="contact-grid">
          <div className="contact-info">
            {[
              ["whatsapp", "WhatsApp concierge", "+234 803 555 0116", "Fastest response, 9am–9pm WAT"],
              ["mail", "Email", "hello@winnscouture.com", "Replies within a few hours"],
              ["ig", "Instagram", "@winns_couture", "DM for bridal consultations"],
              ["pin", "Studio", "Port Harcourt, Nigeria", "By appointment"],
            ].map(([ic, t, v, s]) => (
              <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>
          </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 & fit</option><option>Bespoke commission</option><option>Returns & exchange</option><option>Press & 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 });
