/* ============================================================
   RACK & BOX — Account, Lookbook, Bespoke, Collections, Wishlist
   ============================================================ */

/* ---------------- ACCOUNT ---------------- */
function AccountPage({ onNav }) {
  const [loggedIn, setLoggedIn] = useState(false);
  const [mode, setMode] = useState("login");
  const [tab, setTab] = useState("orders");

  if (loggedIn) {
    return (
      <div className="fade-page page-shell">
        <div className="wrap-wide">
          <div className="crumb"><button onClick={() => onNav("home", {})}>Home</button> / <span>Account</span></div>
          <div className="acct-head">
            <div><Eyebrow>Welcome back</Eyebrow><h1 className="serif page-h" style={{ margin: "8px 0 0" }}>Adé Williams</h1></div>
            <button className="link-arrow" onClick={() => setLoggedIn(false)}>Sign out</button>
          </div>
          <div className="acct-grid">
            <aside className="acct-nav">
              {[["orders", "Orders"], ["wishlist", "Wishlist"], ["fittings", "Fittings"], ["addresses", "Addresses"], ["details", "Details"]].map(([k, l]) =>
              <button key={k} className={"acct-link" + (tab === k ? " on" : "")} onClick={() => k === "wishlist" ? onNav("wishlist", {}) : setTab(k)}>{l}<Icon name="chevron" size={15} /></button>
              )}
            </aside>
            <div className="acct-body">
              {tab === "orders" &&
              <div>
                  <h2 className="serif acct-h">Your orders</h2>
                  {[["RB-48201", "Delivered", "Adé Royal Agbada + 1", "685,000"], ["RB-47330", "In transit", "London Cashmere Overcoat", "780,000"], ["RB-46115", "Delivered", "Eko Velvet Loafer", "165,000"]].map(([id, st, items, amt]) =>
                <div className="acct-order" key={id}>
                      <div className="acct-order-media"><Ph label="" ratio="square" /></div>
                      <div className="acct-order-body">
                        <div className="spread"><span className="mono">#{id}</span><span className={"order-status " + (st === "Delivered" ? "ok" : "warn")}>{st}</span></div>
                        <div className="serif" style={{ fontSize: 19, margin: "4px 0" }}>{items}</div>
                        <span style={{ color: "var(--ink-soft)", fontSize: 13 }}>₦{amt}</span>
                      </div>
                      <button className="link-arrow" onClick={() => onNav("shop", {})}>Buy again</button>
                    </div>
                )}
                </div>
              }
              {tab === "fittings" &&
              <div>
                  <h2 className="serif acct-h">Your fittings</h2>
                  <div className="acct-fitting">
                    <div><Eyebrow>Upcoming</Eyebrow><h3 className="serif" style={{ fontSize: 24, margin: "6px 0" }}>Virtual fitting — Bespoke Agbada</h3><p style={{ color: "var(--ink-soft)" }}>Saturday 21 June · 14:00 WAT · with stylist Tobi</p></div>
                    <Btn variant="ghost" arrow={false} onClick={() => onNav("bespoke", {})}>Reschedule</Btn>
                  </div>
                  <button className="acct-add" onClick={() => onNav("bespoke", {})}><Icon name="plus" size={18} /> Book a new fitting</button>
                </div>
              }
              {tab === "addresses" &&
              <div>
                  <h2 className="serif acct-h">Addresses</h2>
                  <div className="acct-addr-grid">
                    {[["Home · " + ((window.BRAND?.hqCity) || "Lagos"), (window.BRAND?.addresses.hq.full) || "14 Raymond Njoku St\nIkoyi, Lagos\nNigeria"], [(window.BRAND?.secondCity) || "London", (window.BRAND?.addresses.second.full) || "22 Mount St\nMayfair, London W1\nUnited Kingdom"]].map(([t, a]) =>
                  <div className="acct-addr" key={t}><strong>{t}</strong><p style={{ whiteSpace: "pre-line", color: "var(--ink-soft)", marginTop: 8 }}>{a}</p><button className="opt-link" style={{ marginTop: 12 }}>Edit</button></div>
                  )}
                  </div>
                </div>
              }
              {tab === "details" &&
              <div>
                  <h2 className="serif acct-h">Your details</h2>
                  <div className="form-grid" style={{ maxWidth: 520 }}>
                    <div className="field"><label>First name</label><input className="input" defaultValue="Adé" /></div>
                    <div className="field"><label>Last name</label><input className="input" defaultValue="Williams" /></div>
                    <div className="field span2"><label>Email</label><input className="input" defaultValue="ade@email.com" /></div>
                    <div className="field span2"><label>Phone</label><input className="input" defaultValue="+234 803 555 0116" /></div>
                  </div>
                  <Btn arrow={false} style={{ marginTop: 18 }}>Save changes</Btn>
                </div>
              }
            </div>
          </div>
        </div>
      </div>);

  }

  return (
    <div className="fade-page auth-page">
      <div className="auth-media">
        <Ph label="ATELIER · THE FITTING ROOM" ratio="tall" />
        <div className="auth-media-cap"><Logo size={30} /><p className="serif" style={{ fontSize: 28, marginTop: 16, color: "#f6f1e7" }}>Every stitch tells a story.</p></div>
      </div>
      <div className="auth-form-side">
        <div className="auth-box">
          <div className="auth-tabs">
            <button className={mode === "login" ? "on" : ""} onClick={() => setMode("login")}>Sign in</button>
            <button className={mode === "register" ? "on" : ""} onClick={() => setMode("register")}>Create account</button>
          </div>
          <h1 className="serif" style={{ fontSize: 38, margin: "22px 0 6px" }}>{mode === "login" ? "Welcome back" : "Join " + ((window.BRAND && window.BRAND.name) || "Rack & Box")}</h1>
          <p style={{ color: "var(--ink-soft)", marginBottom: 26 }}>{mode === "login" ? "Sign in to track orders & fittings." : "Create an account for faster checkout, order history and early access."}</p>
          <form onSubmit={(e) => {e.preventDefault();setLoggedIn(true);}} className="stack" style={{ gap: 16 }}>
            {mode === "register" && <div className="field"><label>Full 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"><label>Password</label><input className="input" type="password" required placeholder="••••••••" /></div>
            {mode === "login" && <button type="button" className="opt-link" style={{ alignSelf: "flex-end" }}>Forgot password?</button>}
            <Btn block arrow={false} type="submit">{mode === "login" ? "Sign in" : "Create account"}</Btn>
          </form>
          <div className="auth-or"><span>or</span></div>
          <button className="auth-social"><Icon name="globe" size={17} /> Continue with Google</button>
          <button className="auth-guest" onClick={() => onNav("shop", {})}>Continue as guest →</button>
        </div>
      </div>
    </div>);

}

/* ---------------- LOOKBOOK ---------------- */
function LookbookPage({ onNav }) {
  return (
    <div className="fade-page">
      <section className="lb-page-hero">
        <div className="wrap center">
          <div className="crumb" style={{ justifyContent: "center" }}><button onClick={() => onNav("home", {})}>Home</button> / <span>Lookbook</span></div>
          <Eyebrow style={{ marginTop: 18, display: "inline-block" }}>Bespoke Editorials</Eyebrow>
          <h1 className="serif" style={{ fontSize: "clamp(48px,8vw,118px)", fontWeight: 500, lineHeight: 0.98, margin: "14px 0 14px" }}>The Lookbook</h1>
          <p className="lede" style={{ maxWidth: "46ch", margin: "0 auto" }}>Three stories, one atelier — every look cut to the man who wears it.</p>
        </div>
      </section>
      <section style={{ paddingBottom: 90 }}>
        <div className="wrap-wide lb-stories">
          {RB.LOOKBOOK.map((l, i) =>
          <Reveal key={l.id} className={"lb-story" + (i % 2 ? " rev" : "")}>
              <button className="lb-story-media zoomable" onClick={() => onNav("shop", {})}><Ph label={l.label} ratio={i === 0 ? "wide" : "portrait"} /></button>
              <div className="lb-story-body">
                <span className="mono" style={{ color: "var(--accent)", fontSize: 11, letterSpacing: "0.2em" }}>{l.season}</span>
                <h2 className="serif" style={{ fontSize: "clamp(34px,4.5vw,64px)", fontWeight: 500, margin: "12px 0 14px", lineHeight: 1 }}>{l.title}</h2>
                <p className="lede" style={{ marginBottom: 24 }}>{l.blurb}</p>
                <Btn onClick={() => onNav("shop", {})}>Shop the story</Btn>
              </div>
            </Reveal>
          )}
        </div>
      </section>
      <LookbookTeaser onNav={onNav} />
    </div>);

}

/* ---------------- BESPOKE ---------------- */
/* Looping brand video behind the hero. Poster (brand photo) shows until
   the video decodes; blob-fetch works around the asset server's missing
   Range support (same approach as the collage hero strips). */
function BespokeHeroVideo() {
  const ref = useRef(null);
  const [ready, setReady] = useState(false);
  const poster = (window.RB_IMGS || {})["BESPOKE · MEASURING TAPE & CLOTH"] || "";
  useEffect(() => {
    let cancelled = false, objUrl = null;
    const el = ref.current;
    (async () => {
      try {
        const res = await fetch("uploads/Screen_Recording_20260704_202217_Instagram.webm");
        if (!res.ok) throw new Error("HTTP " + res.status);
        const blob = await res.blob();
        if (cancelled || !el) return;
        objUrl = URL.createObjectURL(blob);
        el.src = objUrl;
        el.load();
        const p = el.play();
        if (p && p.catch) p.catch(() => {});
      } catch (e) {/* poster stays */}
    })();
    return () => { cancelled = true; if (objUrl) URL.revokeObjectURL(objUrl); };
  }, []);
  return (
    <div className="about-hero-bg" aria-hidden="true">
      <img src={poster} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", objectPosition: "center 30%" }} />
      <video ref={ref} autoPlay muted loop playsInline preload="auto"
        onLoadedData={() => setReady(true)} onCanPlay={() => setReady(true)}
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", objectPosition: "center 30%", opacity: ready ? 1 : 0, transition: "opacity .8s ease" }}>
      </video>
    </div>);
}

function BespokePage({ onNav }) {
  const [sent, setSent] = useState(false);
  const [type, setType] = useState("Agbada");
  const [mode, setMode] = useState("Virtual");
  return (
    <div className="fade-page">
      <section className="bespoke-hero">
        <BespokeHeroVideo />
        <div className="about-hero-ov" />
        <div className="wrap about-hero-content">
          <Eyebrow style={{ color: "var(--accent-bright)" }}>The Bespoke Service</Eyebrow>
          <h1 className="serif about-hero-h">Book a fitting.</h1>
          <p className="lede on-img" style={{ maxWidth: "44ch", marginTop: 16 }}>Commission a one-of-one agbada, suit or kaftan, measured to you — in our {(window.BRAND?.addresses.hq.label) || "Lagos atelier"}, our {(window.BRAND?.addresses.second.label) || "London showroom"}, or virtually from anywhere.</p>
        </div>
      </section>
      <section className="section-pad">
        <div className="wrap-wide bespoke-book-grid">
          <div className="bespoke-steps-col">
            <Eyebrow line>How it works</Eyebrow>
            {[["01", "Book your fitting", "Pick a date and whether you'd like to meet in person or virtually."], ["02", "Design together", "Choose your cloth, cut, lining and finishings with your tailor — every detail on the table."], ["03", "Fittings until it's right", "We perfect the cut across up to three fittings — measure twice, cut once."], ["04", "Delivered worldwide", "Your finished piece ships in 3–6 weeks, anywhere in the world."]].map(([n, t, d]) =>
            <div className="bk-step" key={n}><span className="mono">{n}</span><div><strong>{t}</strong><p>{d}</p></div></div>
            )}
          </div>
          <div className="bespoke-form-card">
            {sent ?
            <div className="contact-sent" style={{ padding: "30px 0" }}>
                <div className="confirm-badge sm"><Icon name="check" size={26} /></div>
                <h3 className="serif" style={{ fontSize: 30, margin: "14px 0 8px" }}>Fitting requested</h3>
                <p style={{ color: "var(--ink-soft)" }}>Thank you. The atelier will confirm your {mode.toLowerCase()} {type.toLowerCase()} fitting within 24 hours.</p>
                <Btn style={{ marginTop: 20 }} onClick={() => onNav("home", {})}>Back to home</Btn>
              </div> :

            <form onSubmit={(e) => {e.preventDefault();setSent(true);}}>
                <h2 className="serif" style={{ fontSize: 30, marginBottom: 6 }}>Request a fitting</h2>
                <p style={{ color: "var(--ink-soft)", marginBottom: 22, fontSize: 14 }}>Complimentary &amp; no obligation.</p>
                <label className="bk-label">What are you commissioning?</label>
                <div className="bk-pills">{["Agbada", "Suit", "Kaftan", "Senator", "Other"].map((t) => <button type="button" key={t} className={"chip" + (type === t ? " active" : "")} onClick={() => setType(t)}>{t}</button>)}</div>
                <label className="bk-label">Fitting type</label>
                <div className="bk-pills">{["Virtual", (window.BRAND?.addresses.hq.label) || "Lagos atelier", (window.BRAND?.addresses.second.label) || "London showroom"].map((m) => <button type="button" key={m} className={"chip" + (mode === m ? " active" : "")} onClick={() => setMode(m)}>{m}</button>)}</div>
                <div className="form-grid" style={{ marginTop: 6 }}>
                  <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"><label>Preferred date</label><input className="input" type="date" /></div>
                  <div className="field"><label>Occasion date</label><input className="input" type="date" /></div>
                  <div className="field span2"><label>Tell us about the occasion</label><textarea className="input" rows="3" placeholder="Wedding, owambe, corporate…"></textarea></div>
                </div>
                <Btn block arrow={false} type="submit" style={{ marginTop: 18 }}>Request fitting</Btn>
              </form>
            }
          </div>
        </div>
      </section>
    </div>);

}

/* ---------------- COLLECTIONS ---------------- */
function CollectionsPage({ onNav }) {
  const map = { wedding: "Wedding", festive: "Festive", corporate: "Corporate", casual: "Casual Luxury" };
  return (
    <div className="fade-page page-shell">
      <div className="wrap-wide">
        <div className="crumb"><button onClick={() => onNav("home", {})}>Home</button> / <span>Collections</span></div>
        <h1 className="serif page-h">Collections</h1>
        <p className="shop-sub" style={{ maxWidth: "50ch" }}>Curated edits from the Oyecouture atelier — from the aisle to the boardroom to the owambe dancefloor.</p>
        <div className="collections-grid">
          {RB.COLLECTIONS.map((c, i) =>
          <Reveal key={c.id} delay={i % 2 + 1} className="coll-card zoomable">
              <button className="coll-card-btn" onClick={() => onNav("shop", { occasion: map[c.id] })}>
                <Ph label={c.label} ratio="wide" />
                <div className="coll-ov" />
                <div className="coll-cap">
                  <span className="mono">{c.tag} · {c.count} pieces</span>
                  <span className="serif coll-title">{c.title}</span>
                  <span className="coll-blurb">{c.blurb}</span>
                  <span className="link-arrow on-img">Shop the edit</span>
                </div>
              </button>
            </Reveal>
          )}
        </div>
      </div>
    </div>);

}

/* ---------------- WISHLIST ---------------- */
function WishlistPage({ onNav }) {
  const { wishlist, addToCart, toggleWish } = useContext(RBCtx);
  const items = RB.PRODUCTS.filter((p) => wishlist.includes(p.id));
  return (
    <div className="fade-page page-shell">
      <div className="wrap-wide">
        <div className="crumb"><button onClick={() => onNav("home", {})}>Home</button> / <span>Wishlist</span></div>
        <h1 className="serif page-h">Your wishlist</h1>
        {items.length === 0 ?
        <div className="center" style={{ padding: "60px 0" }}>
            <Icon name="heart" size={42} stroke={1} style={{ color: "var(--ink-faint)" }} />
            <p className="serif" style={{ fontSize: 28, margin: "16px 0 10px" }}>No saved pieces yet</p>
            <p style={{ color: "var(--ink-soft)", marginBottom: 24 }}>Tap the heart on any piece to save it here.</p>
            <Btn onClick={() => onNav("shop", {})}>Browse the collection</Btn>
          </div> :

        <div className="product-grid" style={{ marginTop: 30 }}>
            {items.map((p, i) =>
          <Reveal key={p.id} delay={i % 4 + 1}>
                <ProductCard p={p} onNav={onNav} onAdd={addToCart} wished={true} onWish={toggleWish} />
              </Reveal>
          )}
          </div>
        }
      </div>
    </div>);

}

Object.assign(window, { AccountPage, LookbookPage, BespokePage, CollectionsPage, WishlistPage });