/* ============================================================
   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 your next favorite piece.</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>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 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 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">#PA-{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="form-grid" style={{ marginTop: 20 }}>
                    <div className="field span2"><label>Account Name</label><input className="input" value="Prudential Atelier Ltd" readOnly /></div>
                    <div className="field span2"><label>Bank</label><input className="input" value="First Bank of Nigeria" readOnly /></div>
                    <div className="field"><label>USD Account Number</label><input className="input" value="3012345678" readOnly /></div>
                    <div className="field"><label>Routing / SWIFT</label><input className="input" value="FBNINGLA" readOnly /></div>
                    <p className="pay-note" style={{ gridColumn: "1/-1", marginTop: 4 }}>Wire transfers in USD only. Your order ships once payment clears — typically 1–2 business days.</p>
                  </div>
                )}
                <label className="pay-check"><input type="checkbox" defaultChecked /> <span>Email me about new drops &amp; private fittings</span></label>
                <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 · LAGOS WORKSHOP" 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">Born in Lagos.</h1>
        </div>
      </section>
      <section className="section-pad">
        <div className="wrap about-intro">
          <Reveal><p className="serif about-lede">Prudential Atelier began with a simple belief: that heritage and modernity belong in the same wardrobe.</p></Reveal>
          <Reveal delay={1}><p style={{ color: "var(--ink-soft)", fontSize: 16, lineHeight: 1.8 }}>Founded in 2019, we set out to dress a new generation of Africans at home and in the diaspora — people who move between cultures and want clothing that holds both. We work with weaving cooperatives in Oyo State and master tailors in Aba to craft pieces that feel rooted and contemporary at once.</p></Reveal>
        </div>
      </section>
      <section className="section-pad">
        <div className="wrap-wide values-grid">
          {[
            ["leaf", "Made responsibly", "Hand-woven Aso-Oke from weaving cooperatives, traceable wools and silks, and zero-waste cutting where we can."],
            ["scissors", "Crafted by hand", "Every signature piece passes through the hands of a master tailor — from first cut to final press."],
            ["globe", "Worn worldwide", "From an owambe in Lagos to a wedding across the country, our pieces travel as far as the stories behind 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 clothes to be worn once. We make heirlooms — pieces your children will find and want to wear.”</blockquote></Reveal>
          <Reveal delay={1}><div className="testi-author" style={{ marginTop: 24 }}>Adé Williams <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">
        <h1 className="serif page-h">Customer care</h1>
        <p className="shop-sub" style={{ maxWidth: "52ch" }}>Our concierge is here in Lagos. We typically reply within a few hours, Monday to Saturday.</p>
        <div className="contact-grid">
          <div className="contact-info">
            {[
              ["mail", "Enquiries", "Use the form", "Send us a message — we reply within a few hours"],
              ["pin", "Lagos atelier", "14 Raymond Njoku St, Ikoyi", "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 });
