/* global React, Reveal, MagneticButton, Footer, Store, useStore, formatPrice */
const { useState: useState_c, useEffect: useEffect_c, useMemo: useMemo_c } = React;

/* =================================================
   CART PAGE — full editorial layout
================================================= */
function CartPage({ onNavigate }) {
  const cart = useStore((s) => s.cart);
  const subtotal = cart.reduce((n, l) => n + l.price * l.qty, 0);
  const tax = Math.round(subtotal * 0.0725);
  const total = subtotal + tax;

  return (
    <main className="cart-page" data-screen-label="Cart">
      <div className="page-head">
        <div>
          <Reveal><div className="t-eyebrow" style={{ color: "var(--accent)" }}>— Step 01 · The order</div></Reveal>
          <Reveal delay={120}>
            <h1 className="t-h1" style={{ marginTop: 20 }}>
              Your <span style={{ fontStyle: "italic" }}>atelier</span> order.
            </h1>
          </Reveal>
        </div>
        <Reveal delay={240}>
          <p className="dek">
            Every Delina Living piece is designed in Los Angeles and made to order at our Vietnam atelier. You won't be charged until your piece enters the workshop. Expect a frame photograph in your inbox the day it's joined.
          </p>
        </Reveal>
      </div>

      {cart.length === 0 ? (
        <section style={{ padding: "100px var(--pad-x) 160px", textAlign: "center" }}>
          <h2 className="t-h2" style={{ fontStyle: "italic", maxWidth: "20ch", margin: "0 auto" }}>
            Empty, for now.
          </h2>
          <p className="t-body t-body-lg" style={{ maxWidth: "44ch", margin: "24px auto 32px", color: "var(--ink-soft)" }}>
            The catalog is short — fifty-nine pieces, ten Signature, none in stock. Browse the seating, or read up on how we work.
          </p>
          <div style={{ display: "inline-flex", gap: 12 }}>
            <MagneticButton className="btn btn--solid" data-cursor="View" onClick={() => onNavigate("plp")}>
              <span>The catalog</span><span className="arrow">→</span>
            </MagneticButton>
            <MagneticButton className="btn btn--ghost" data-cursor="Read" onClick={() => onNavigate("atelier")}>
              <span>How we work</span>
            </MagneticButton>
          </div>
        </section>
      ) : (
        <div className="cart-page-grid">
          <div className="cart-page-main">
            <div style={{ paddingTop: 48, borderBottom: "1px solid var(--line-strong)", paddingBottom: 16, display: "flex", justifyContent: "space-between" }}>
              <div className="t-eyebrow" style={{ color: "var(--ink-mute)" }}>Pieces — {cart.length}</div>
              <button className="t-mono" data-cursor="Clear" onClick={() => Store.clearCart()} style={{ color: "var(--ink-mute)" }}>Clear order</button>
            </div>
            {cart.map((l, i) => (
              <div className="cart-line" key={i}>
                <div className="thumb" style={{ backgroundImage: `url(${l.img})` }}></div>
                <div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                    <div>
                      <div className="name">{l.name}</div>
                      <div className="sub">{l.sub}</div>
                    </div>
                    <div className="price" style={{ fontFamily: '"GT Sectra","Instrument Serif",serif', fontSize: 24, fontStyle: "italic" }}>{formatPrice(l.price * l.qty)}</div>
                  </div>
                  <div className="variant">
                    <span className="dot" style={{ background: l.upholsteryColor || "#A8997E" }}></span>
                    <span>Upholstery — {l.upholstery || "Bone Linen"}</span>
                    <span style={{ marginLeft: 16 }}>Legs — {l.leg || "White Oak"}</span>
                  </div>
                  <div className="price-row" style={{ marginTop: 20 }}>
                    <div className="qty">
                      <button data-cursor="-" onClick={() => Store.updateQty(i, l.qty - 1)}>−</button>
                      <span className="val">{l.qty}</span>
                      <button data-cursor="+" onClick={() => Store.updateQty(i, l.qty + 1)}>+</button>
                    </div>
                    <div style={{ display: "flex", gap: 24, alignItems: "center" }}>
                      <span className="t-mono" style={{ color: "var(--ink-mute)" }}>Made-to-order · 8 wk</span>
                      <button className="remove" data-cursor="Remove" onClick={() => Store.removeFromCart(i)}>Remove</button>
                    </div>
                  </div>
                </div>
              </div>
            ))}

            <div style={{ marginTop: 64, paddingTop: 32, borderTop: "1px solid var(--line)", display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 32 }}>
              {[
                { l: "Delivery", v: "White-glove, included. We schedule with you week eight." },
                { l: "Warranty", v: "Fifty-year frame. Five-year upholstery. Both transferable." },
                { l: "Returns", v: "Made-to-order is final. Swap upholstery within ten days of delivery." },
              ].map((b, i) => (
                <div key={i}>
                  <div className="t-eyebrow" style={{ color: "var(--accent)" }}>— {b.l}</div>
                  <p className="t-body" style={{ marginTop: 10, maxWidth: "28ch" }}>{b.v}</p>
                </div>
              ))}
            </div>
          </div>

          <aside className="cart-page-side">
            <div className="t-eyebrow" style={{ color: "var(--ink-mute)" }}>— Summary</div>
            <h3 className="t-h3" style={{ margin: "16px 0 32px", fontStyle: "italic" }}>What you'll pay.</h3>
            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <div className="summary-row"><span className="l">Subtotal</span><span>{formatPrice(subtotal)}</span></div>
              <div className="summary-row"><span className="l">White-glove delivery</span><span>Included</span></div>
              <div className="summary-row"><span className="l">Tax (est.)</span><span>{formatPrice(tax)}</span></div>
              <div className="summary-row total"><span>Total</span><span className="v">{formatPrice(total)}</span></div>
            </div>
            <MagneticButton className="btn btn--solid" data-cursor="Checkout" onClick={() => onNavigate("checkout")}
                            style={{ width: "100%", justifyContent: "center", marginTop: 24 }}>
              <span>Continue to checkout</span><span className="arrow">→</span>
            </MagneticButton>
            <p className="t-small" style={{ textAlign: "center", marginTop: 12 }}>
              No charge today. We confirm pricing and start production in 24 hours.
            </p>

            <div style={{ marginTop: 40, paddingTop: 24, borderTop: "1px solid var(--line)" }}>
              <div className="t-eyebrow" style={{ color: "var(--ink-mute)" }}>— Have a question?</div>
              <p className="t-body" style={{ marginTop: 8 }}>
                A real person will reply within a day. <a onClick={() => onNavigate("contact")} href="#" data-cursor="Write" style={{ borderBottom: "1px solid currentColor" }}>Write us</a> or call <span className="t-mono">+1 (949) 358-8040</span>.
              </p>
            </div>
          </aside>
        </div>
      )}

      <Footer onNavigate={onNavigate} />
    </main>
  );
}

/* =================================================
   CHECKOUT — 4 step flow
================================================= */
const STEPS = ["Contact", "Shipping", "Payment", "Review"];

function CheckoutPage({ onNavigate }) {
  const cart = useStore((s) => s.cart);
  const user = useStore((s) => s.user);
  const [step, setStep] = useState_c(0);
  const [form, setForm] = useState_c({
    email: user?.email || "",
    firstName: "", lastName: "",
    address1: "", address2: "", city: "", state: "", zip: "",
    phone: "",
    delivery: "white-glove",
    cardName: "", cardNumber: "", exp: "", cvc: "",
    billingSame: true,
    notes: "",
  });

  const subtotal = cart.reduce((n, l) => n + l.price * l.qty, 0);
  const tax = Math.round(subtotal * 0.0725);
  const total = subtotal + tax;

  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  /* Empty cart guard — show a friendly nudge */
  if (cart.length === 0) {
    return (
      <main className="checkout">
        <div style={{ padding: "160px var(--pad-x)", textAlign: "center" }}>
          <h1 className="t-h1" style={{ fontStyle: "italic", maxWidth: "20ch", margin: "0 auto" }}>
            Nothing to check out, yet.
          </h1>
          <p className="t-body t-body-lg" style={{ maxWidth: "44ch", margin: "24px auto 40px", color: "var(--ink-soft)" }}>
            Add a piece from the catalog and we'll meet you back here.
          </p>
          <MagneticButton className="btn btn--solid" data-cursor="View" onClick={() => onNavigate("plp")}>
            <span>The catalog</span><span className="arrow">→</span>
          </MagneticButton>
        </div>
        <Footer onNavigate={onNavigate} />
      </main>
    );
  }

  const submitOrder = () => {
    const orderNum = "HLD-" + String(Math.floor(100000 + Math.random() * 900000));
    /* Save order, clear cart, navigate */
    window.__lastOrder = { num: orderNum, cart: [...cart], total, shipping: { ...form } };
    Store.clearCart();
    if (form.email) Store.signIn({ email: form.email, name: form.firstName + " " + form.lastName });
    onNavigate("order");
  };

  return (
    <main className="checkout" data-screen-label={`Checkout ${step + 1}`}>
      <div className="checkout-grid">
        <div className="checkout-main">
          <div className="stepper">
            {STEPS.map((s, i) => (
              <div key={s} className={`step ${i === step ? "is-on" : ""} ${i < step ? "is-done" : ""}`}>
                <span className="n">{i < step ? "✓" : String(i + 1).padStart(2, "0")}</span>
                <span>{s}</span>
              </div>
            ))}
          </div>

          {step === 0 && (
            <section>
              <Reveal><h2 className="t-h2" style={{ marginBottom: 12 }}><span style={{ fontStyle: "italic" }}>Hello.</span> Who shall we write to?</h2></Reveal>
              <Reveal delay={120}><p className="t-body" style={{ maxWidth: "44ch", marginBottom: 32 }}>You'll get a weekly photograph from the workshop, then white-glove delivery confirmation. No marketing.</p></Reveal>
              <div className="field"><label>Email</label><input type="email" placeholder="you@somewhere.com" value={form.email} onChange={set("email")} data-cursor="Type" /></div>
              <div className="field-row" style={{ marginTop: 12 }}>
                <div className="field"><label>First name</label><input type="text" value={form.firstName} onChange={set("firstName")} data-cursor="Type" /></div>
                <div className="field"><label>Last name</label><input type="text" value={form.lastName} onChange={set("lastName")} data-cursor="Type" /></div>
              </div>
              <div className="field"><label>Phone (for delivery scheduling)</label><input type="tel" placeholder="+1 (___) ___-____" value={form.phone} onChange={set("phone")} data-cursor="Type" /></div>

              <div style={{ marginTop: 32, display: "flex", justifyContent: "space-between" }}>
                <button className="t-mono" data-cursor="Back" onClick={() => onNavigate("cart")} style={{ color: "var(--ink-mute)" }}>← Back to cart</button>
                <MagneticButton className="btn btn--solid" data-cursor="Next" onClick={() => setStep(1)} disabled={!form.email}>
                  <span>Continue to shipping</span><span className="arrow">→</span>
                </MagneticButton>
              </div>
            </section>
          )}

          {step === 1 && (
            <section>
              <Reveal><h2 className="t-h2" style={{ marginBottom: 12 }}>Where shall we <span style={{ fontStyle: "italic" }}>deliver?</span></h2></Reveal>
              <Reveal delay={120}><p className="t-body" style={{ maxWidth: "44ch", marginBottom: 32 }}>White-glove delivery is included on every piece. We schedule a two-hour window the week of arrival.</p></Reveal>

              <div className="field"><label>Address line 1</label><input type="text" placeholder="125 Pine Street" value={form.address1} onChange={set("address1")} data-cursor="Type" /></div>
              <div className="field"><label>Address line 2 (apt, floor)</label><input type="text" placeholder="Apt 4B (optional)" value={form.address2} onChange={set("address2")} data-cursor="Type" /></div>
              <div className="field-row-3">
                <div className="field"><label>City</label><input type="text" value={form.city} onChange={set("city")} data-cursor="Type" /></div>
                <div className="field"><label>State</label><input type="text" value={form.state} onChange={set("state")} data-cursor="Type" /></div>
                <div className="field"><label>ZIP</label><input type="text" value={form.zip} onChange={set("zip")} data-cursor="Type" /></div>
              </div>
              <div className="field"><label>Delivery notes (gate codes, stairs, narrow doorways)</label><textarea rows={3} value={form.notes} onChange={set("notes")} data-cursor="Type" /></div>

              <div style={{ marginTop: 24 }}>
                <div className="t-eyebrow" style={{ color: "var(--ink-mute)" }}>— Delivery</div>
                <div className="radio-card-list">
                  {[
                    { v: "white-glove", l: "White-glove delivery", s: "Two-person team places the piece in your room. Removes packaging. No charge.", r: "Included" },
                    { v: "curbside", l: "Curbside drop", s: "Crated freight to your driveway. Available outside the continental US.", r: "−$200" },
                  ].map((o) => (
                    <button key={o.v} className={`radio-card ${form.delivery === o.v ? "is-on" : ""}`} onClick={() => setForm({ ...form, delivery: o.v })} data-cursor="Select">
                      <div><div className="l">{o.l}</div><div className="s">{o.s}</div></div>
                      <div className="r">{o.r}</div>
                    </button>
                  ))}
                </div>
              </div>

              <div style={{ marginTop: 32, display: "flex", justifyContent: "space-between" }}>
                <button className="t-mono" data-cursor="Back" onClick={() => setStep(0)} style={{ color: "var(--ink-mute)" }}>← Contact</button>
                <MagneticButton className="btn btn--solid" data-cursor="Next" onClick={() => setStep(2)}>
                  <span>Continue to payment</span><span className="arrow">→</span>
                </MagneticButton>
              </div>
            </section>
          )}

          {step === 2 && (
            <section>
              <Reveal><h2 className="t-h2" style={{ marginBottom: 12 }}><span style={{ fontStyle: "italic" }}>Payment.</span></h2></Reveal>
              <Reveal delay={120}><p className="t-body" style={{ maxWidth: "44ch", marginBottom: 32 }}>We don't charge today. Your card is authorized; the actual charge runs the day your frame is joined — about ten days from now.</p></Reveal>

              <div className="field"><label>Cardholder name</label><input type="text" placeholder="Astrid Vance" value={form.cardName} onChange={set("cardName")} data-cursor="Type" /></div>
              <div className="field"><label>Card number</label><input type="text" placeholder="•••• •••• •••• 4242" value={form.cardNumber} onChange={set("cardNumber")} data-cursor="Type" /></div>
              <div className="field-row">
                <div className="field"><label>Expiry</label><input type="text" placeholder="MM / YY" value={form.exp} onChange={set("exp")} data-cursor="Type" /></div>
                <div className="field"><label>CVC</label><input type="text" placeholder="•••" value={form.cvc} onChange={set("cvc")} data-cursor="Type" /></div>
              </div>

              <div style={{ marginTop: 24, display: "flex", gap: 12, alignItems: "center" }}>
                <input type="checkbox" id="bs" checked={form.billingSame} onChange={(e) => setForm({ ...form, billingSame: e.target.checked })} style={{ accentColor: "var(--accent)" }} />
                <label htmlFor="bs" className="t-mono">Billing address same as shipping</label>
              </div>

              <div style={{ marginTop: 32, display: "flex", justifyContent: "space-between" }}>
                <button className="t-mono" data-cursor="Back" onClick={() => setStep(1)} style={{ color: "var(--ink-mute)" }}>← Shipping</button>
                <MagneticButton className="btn btn--solid" data-cursor="Next" onClick={() => setStep(3)}>
                  <span>Review order</span><span className="arrow">→</span>
                </MagneticButton>
              </div>
            </section>
          )}

          {step === 3 && (
            <section>
              <Reveal><h2 className="t-h2" style={{ marginBottom: 12 }}>Review and <span style={{ fontStyle: "italic" }}>place order.</span></h2></Reveal>
              <Reveal delay={120}><p className="t-body" style={{ maxWidth: "44ch", marginBottom: 32 }}>Everything looks correct? Once you confirm we'll begin cutting wood this week.</p></Reveal>

              <ReviewSection title="Contact" onEdit={() => setStep(0)}>
                <div>{form.firstName} {form.lastName}</div>
                <div className="t-mono" style={{ color: "var(--ink-mute)" }}>{form.email}</div>
                <div className="t-mono" style={{ color: "var(--ink-mute)" }}>{form.phone}</div>
              </ReviewSection>

              <ReviewSection title="Shipping" onEdit={() => setStep(1)}>
                <div>{form.address1}{form.address2 ? ", " + form.address2 : ""}</div>
                <div>{form.city}, {form.state} {form.zip}</div>
                <div className="t-mono" style={{ color: "var(--ink-mute)", marginTop: 6 }}>
                  {form.delivery === "white-glove" ? "White-glove · included" : "Curbside drop · -$200"}
                </div>
              </ReviewSection>

              <ReviewSection title="Payment" onEdit={() => setStep(2)}>
                <div>{form.cardName || "—"}</div>
                <div className="t-mono" style={{ color: "var(--ink-mute)" }}>
                  Card ending {(form.cardNumber || "").replace(/\s/g, "").slice(-4) || "••••"} · {form.exp || "—"}
                </div>
              </ReviewSection>

              <div style={{ marginTop: 32, display: "flex", justifyContent: "space-between" }}>
                <button className="t-mono" data-cursor="Back" onClick={() => setStep(2)} style={{ color: "var(--ink-mute)" }}>← Payment</button>
                <MagneticButton className="btn btn--accent" data-cursor="Place" onClick={submitOrder}>
                  <span>Place order — {formatPrice(total)}</span><span className="arrow">→</span>
                </MagneticButton>
              </div>
            </section>
          )}
        </div>

        <aside className="checkout-side">
          <div className="t-eyebrow" style={{ color: "var(--ink-mute)" }}>— Your order</div>
          <h3 className="t-h3" style={{ margin: "12px 0 32px", fontStyle: "italic" }}>{cart.length} piece{cart.length === 1 ? "" : "s"}.</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 16, marginBottom: 32 }}>
            {cart.map((l, i) => (
              <div key={i} style={{ display: "grid", gridTemplateColumns: "64px 1fr auto", gap: 16, alignItems: "center" }}>
                <div style={{ aspectRatio: "4/5", backgroundImage: `url(${l.img})`, backgroundSize: "cover", backgroundPosition: "center", backgroundColor: "var(--bone-deep)" }}></div>
                <div>
                  <div style={{ fontFamily: '"GT Sectra","Instrument Serif",serif', fontSize: 17 }}>{l.name} <span className="t-mono" style={{ color: "var(--ink-mute)", marginLeft: 6 }}>× {l.qty}</span></div>
                  <div className="t-mono" style={{ color: "var(--ink-mute)", fontSize: 10 }}>{l.upholstery} · {l.leg}</div>
                </div>
                <div className="t-mono" style={{ fontSize: 13 }}>{formatPrice(l.price * l.qty)}</div>
              </div>
            ))}
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 12, paddingTop: 24, borderTop: "1px solid var(--line)" }}>
            <div className="summary-row"><span className="l">Subtotal</span><span>{formatPrice(subtotal)}</span></div>
            <div className="summary-row"><span className="l">Delivery</span><span>Included</span></div>
            <div className="summary-row"><span className="l">Tax (est.)</span><span>{formatPrice(tax)}</span></div>
            <div className="summary-row total"><span>Total</span><span className="v">{formatPrice(total)}</span></div>
          </div>
          <p className="t-small" style={{ marginTop: 16, textAlign: "left", color: "var(--ink-mute)" }}>
            Card authorized today. Charged the day your frame is joined (≈ day 10).
          </p>
        </aside>
      </div>
    </main>
  );
}

function ReviewSection({ title, children, onEdit }) {
  return (
    <div style={{ padding: "24px 0", borderTop: "1px solid var(--line)" }}>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 12 }}>
        <div className="t-eyebrow" style={{ color: "var(--ink-mute)" }}>— {title}</div>
        <button className="t-mono" data-cursor="Edit" onClick={onEdit} style={{ color: "var(--accent)" }}>Edit</button>
      </div>
      <div style={{ fontSize: 16, lineHeight: 1.6 }}>{children}</div>
    </div>
  );
}

/* =================================================
   ORDER CONFIRMATION
================================================= */
function OrderPage({ onNavigate }) {
  const order = window.__lastOrder || { num: "HLD-482012", total: 4820, cart: [] };
  const today = new Date();
  const fmtDate = (offsetDays) => {
    const d = new Date(today); d.setDate(d.getDate() + offsetDays);
    return d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
  };

  return (
    <main data-screen-label="Order Confirmation">
      <section className="order-confirm">
        <Reveal><div className="num">— Order {order.num} · confirmed</div></Reveal>
        <Reveal delay={120}>
          <h1>
            Thank you. The <span style={{ fontStyle: "italic" }}>workshop</span> has your order.
          </h1>
        </Reveal>
        <Reveal delay={240}>
          <p className="t-body t-body-lg" style={{ maxWidth: "52ch", margin: "0 auto", color: "var(--ink-soft)" }}>
            We've sent a confirmation to <span className="t-mono" style={{ color: "var(--ink)" }}>{order.shipping?.email || "you"}</span>. You'll get a weekly photograph from the atelier for the next eight weeks. The first one — a stack of kiln-dried acacia with your name chalked on it — arrives in three days.
          </p>
        </Reveal>

        <Reveal delay={400}>
          <div className="timeline">
            <div className="step is-done">
              <div className="week">Today — {fmtDate(0)}</div>
              <div className="title">Order placed</div>
              <div className="body">Card authorized, not yet charged. Wood selected from the rack.</div>
            </div>
            <div className="step">
              <div className="week">Week 02 — {fmtDate(10)}</div>
              <div className="title">Frame joined</div>
              <div className="body">Mortise-and-tenon, hand-cut, dry-fitted. Card charged today.</div>
            </div>
            <div className="step">
              <div className="week">Week 06 — {fmtDate(42)}</div>
              <div className="title">Upholstery</div>
              <div className="body">Eight-way hand-tied. Down-and-feather. Last sand of the legs.</div>
            </div>
            <div className="step">
              <div className="week">Week 08 — {fmtDate(56)}</div>
              <div className="title">White-glove delivery</div>
              <div className="body">Two-person team places it in your room. Packaging removed.</div>
            </div>
          </div>
        </Reveal>

        <Reveal delay={600}>
          <div style={{ marginTop: 80, display: "flex", gap: 12, justifyContent: "center" }}>
            <MagneticButton className="btn btn--solid" data-cursor="View" onClick={() => onNavigate("account")}>
              <span>Track this order</span><span className="arrow">→</span>
            </MagneticButton>
            <MagneticButton className="btn btn--ghost" data-cursor="View" onClick={() => onNavigate("home")}>
              <span>Back to Delina Living</span>
            </MagneticButton>
          </div>
        </Reveal>
      </section>

      <section className="section section--bone-warm">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 80, alignItems: "center" }}>
          <Reveal variant="img"><div style={{ aspectRatio: "5/4", backgroundImage: "url(assets/detail-tenon.jpg)", backgroundSize: "cover", backgroundPosition: "center" }}></div></Reveal>
          <div>
            <Reveal><div className="t-eyebrow" style={{ color: "var(--accent)" }}>— A note from Astrid</div></Reveal>
            <Reveal delay={120}><h3 className="t-h2" style={{ marginTop: 16 }}>Thank you for waiting eight weeks.</h3></Reveal>
            <Reveal delay={240}>
              <p className="t-body t-body-lg" style={{ marginTop: 20, maxWidth: "44ch", color: "var(--ink-soft)" }}>
                I know patience is a strange thing to ask in 2026. It's why we do it this way — and why the piece will still be in your room in 2076. If anything looks off when it arrives, write me directly: <span className="t-mono">astrid@delinalv.com</span>
              </p>
            </Reveal>
          </div>
        </div>
      </section>

      <Footer onNavigate={onNavigate} />
    </main>
  );
}

window.CartPage = CartPage;
window.CheckoutPage = CheckoutPage;
window.OrderPage = OrderPage;
