/* ============================================================
   NELSON — Account, 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="acct-head">
            <div><Eyebrow>Welcome back</Eyebrow><h1 className="serif page-h" style={{ margin: "8px 0 0" }}>Welcome, friend</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"], ["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>
                  {[["NL-48201", "Delivered", "Classic Leather Oxford", "89,000", "FORMAL · OXFORD"], ["NL-47330", "In transit", "Chelsea Boot", "95,000", "BOOTS · CHELSEA"]].map(([id, st, items, amt, lbl]) =>
                <div className="acct-order" key={id}>
                      <div className="acct-order-media"><Ph label={lbl} 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 === "addresses" &&
              <div>
                  <h2 className="serif acct-h">Addresses</h2>
                  <div className="acct-addr-grid">
                    <div className="acct-addr"><strong>Home</strong><p style={{ whiteSpace: "pre-line", color: "var(--ink-soft)", marginTop: 8 }}>Add your delivery address at checkout.</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" placeholder="First name" /></div>
                    <div className="field"><label>Last name</label><input className="input" placeholder="Last name" /></div>
                    <div className="field span2"><label>Email</label><input className="input" placeholder="you@email.com" /></div>
                    <div className="field span2"><label>Phone</label><input className="input" placeholder="+234 …" /></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="SIGNATURE · PROFILE" ratio="tall" />
        <div className="auth-media-cap"><Logo size={30} /><p className="serif" style={{ fontSize: 28, marginTop: 16, color: "#f6f1e7" }}>Shoes for the modern man.</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) || "Nelson")}</h1>
          <p style={{ color: "var(--ink-soft)", marginBottom: 26 }}>{mode === "login" ? "Sign in to track your orders." : "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>);

}

/* ---------------- 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">
        <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 shoe to save it here.</p>
            <Btn onClick={() => onNav("shop", {})}>Browse all shoes</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>);

}

/* ---------------- BESPOKE ORDER ---------------- */
function BespokePage({ onNav }) {
  const [sent, setSent] = useState(false);
  const [ref] = useState(() => ((window.BRAND?.orderPrefix) || "NL") + "-BSP-" + Math.floor(1000 + Math.random() * 9000));
  const [form, setForm] = useState({ style: "Oxford", leather: "Crocodile-embossed", size: "43", customLast: false, notes: "", name: "", contact: "", signature: "" });
  const up = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const goSheet = () => { const el = document.getElementById("bsp-sheet"); if (el) window.scrollTo({ top: el.offsetTop - 70, behavior: "smooth" }); };
  const [callOpen, setCallOpen] = useState(false);
  const SILS = {
    "Oxford":       "M5 26c0 2.5 2.5 4 6 4h42c4 0 8-1.5 8-4 0-4-9-5.5-15-7l-11-9c-3-2.5-9-2.5-12 0l-4 4c-3 2-11 3-13 6-1 1.6-1 4-1 6z M27 14l7 6 M31 11.5l7 6",
    "Derby":        "M5 26c0 2.5 2.5 4 6 4h42c4 0 8-1.5 8-4 0-4-9-5.5-15-7l-11-9c-3-2.5-9-2.5-12 0l-4 4c-3 2-11 3-13 6-1 1.6-1 4-1 6z M24 16l10-4 M25 20l11-4",
    "Loafer":       "M5 26c0 2.5 2.5 4 6 4h42c4 0 8-1.5 8-4 0-4-9-5.5-15-7l-10-8c-3-2.5-10-2.5-13 0l-4 3c-3 2-10 3-12 6-1 1.6-2 4-2 6z M26 15c3-2 8-2 11 0",
    "Monk strap":   "M5 26c0 2.5 2.5 4 6 4h42c4 0 8-1.5 8-4 0-4-9-5.5-15-7l-11-9c-3-2.5-9-2.5-12 0l-4 4c-3 2-11 3-13 6-1 1.6-1 4-1 6z M27 13h9v6h-9z",
    "Chelsea boot": "M5 26c0 2.5 2.5 4 6 4h42c4 0 8-1.5 8-4 0-4-9-5.5-15-7l-9-8V5H17v11c-4 2-9 3-11 6-1 1.6-1 4-1 6z M22 6v9 M32 6v8",
    "Sneaker":      "M5 25c0 1.5 1 2.5 3 2.5h48c3 0 6-1 6-3 0-3.5-8-5-14-6l-11-8c-3-2.5-9-2.5-12 0l-4 3.5c-3 2-10 2.5-12 5-1 1.4-4 3-4 6z M4 30h58 M27 14l6 5 M31 11.5l6 5",
    "Sandal":       "M6 28c0 1.5 1.5 2.5 4 2.5h44c3 0 6-1 6-2.5 0-2-2-3-5-3H11c-3 0-5 1-5 3z M18 25V14l8-6 M26 25V12 M18 18h8 M44 25v-8l6-4",
  };
  const LEATHERS = [
    { name: "Crocodile-embossed", sw: "linear-gradient(135deg, #4a2418 0%, #6e3a1e 45%, #3a1c10 100%)" },
    { name: "Full-grain calf", sw: "linear-gradient(135deg, #1f1712 0%, #362419 100%)" },
    { name: "Suede", sw: "linear-gradient(135deg, #a97f52 0%, #8a6540 100%)" },
    { name: "Patent", sw: "linear-gradient(135deg, #241a14 0%, #57392a 50%, #241a14 100%)" },
    { name: "Two-tone burnished", sw: "linear-gradient(135deg, #7f431d 0%, #2b1a12 100%)" },
    { name: "Maker's choice", sw: "var(--surface-2)" },
  ];
  const SIZES = ["39", "40", "41", "42", "43", "44", "45", "46", "47"];
  return (
    <div className="fade-page">
      {/* ── Concierge opening ── */}
      <section className="bsp-conc">
        <div className="wrap bsp-conc-inner">
          <Reveal><Eyebrow style={{ color: "var(--accent)" }}>Bespoke by Nelson</Eyebrow></Reveal>
          <Reveal delay={1}><h1 className="serif bsp-conc-h">Tell us what you<br />dream of. <em>We'll make it real.</em></h1></Reveal>
          <Reveal delay={2}><p className="lede bsp-conc-sub">One craftsman, one pair, made to your foot. Begin however suits you.</p></Reveal>
          <Reveal delay={3} className="bsp-paths">
            <button className="bsp-path" onClick={() => setCallOpen(true)}>
              <Icon name="phone" size={24} stroke={1.4} />
              <span className="bsp-path-t serif">Book a call</span>
              <span className="bsp-path-s">A short fitting call with the atelier</span>
              <span className="link-arrow">Pick a time</span>
            </button>
            <button className="bsp-path" onClick={goSheet}>
              <Icon name="ruler" size={24} stroke={1.4} />
              <span className="bsp-path-t serif">Fill the order sheet</span>
              <span className="bsp-path-s">Specify your pair in five short entries</span>
              <span className="link-arrow">Open the docket</span>
            </button>
          </Reveal>
          <Reveal delay={4} className="bsp-conc-specs mono">
            <span>4–6 weeks</span><i />
            <span>One of one</span><i />
            <span>From ₦850,000 · 50% deposit</span>
          </Reveal>
        </div>
      </section>
      {/* ── The order sheet ── */}
      <section className="bsp-sheet-sec" id="bsp-sheet">
        <div className="wrap">
          <div className="bsp-sheet">
            <header className="bsp-sheet-head">
              <div>
                <span className="mono bsp-sheet-no">Commission № {ref}</span>
                <h2 className="serif bsp-sheet-h">Bespoke order sheet</h2>
              </div>
              <Logo size={24} />
            </header>
            {sent ? (
              <div className="bsp-received">
                <span className="bsp-stamp mono">Received</span>
                <h3 className="serif" style={{ fontSize: 32, margin: "18px 0 10px" }}>Your commission is with the atelier</h3>
                <p style={{ color: "var(--ink-soft)", maxWidth: "46ch", margin: "0 auto" }}>Keep your reference <strong className="mono">{ref}</strong>. We'll be in touch within 24 hours to arrange your consultation.</p>
                <Btn style={{ marginTop: 26 }} onClick={() => onNav("shop", {})}>Browse ready-to-wear</Btn>
              </div>
            ) : (
              <form className="bsp-sheet-grid" onSubmit={(e) => { e.preventDefault(); setSent(true); const el = document.getElementById("bsp-sheet"); if (el) window.scrollTo({ top: el.offsetTop - 90, behavior: "smooth" }); }}>
                <div className="bsp-sheet-fields">
                  <fieldset className="bsp-fs">
                    <legend className="bsp-fs-l"><span className="serif bsp-rn">I.</span> The style</legend>
                    <div className="bsp-sils">
                      {Object.keys(SILS).map((s) => (
                        <button type="button" key={s} className={"bsp-sil" + (form.style === s ? " on" : "")} onClick={() => set("style", s)}>
                          <svg viewBox="0 0 64 36" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d={SILS[s]} /></svg>
                          <span>{s}</span>
                        </button>
                      ))}
                    </div>
                  </fieldset>
                  <fieldset className="bsp-fs">
                    <legend className="bsp-fs-l"><span className="serif bsp-rn">II.</span> The leather</legend>
                    <div className="bsp-swatches">
                      {LEATHERS.map((l) => (
                        <button type="button" key={l.name} className={"bsp-swatch" + (form.leather === l.name ? " on" : "")} onClick={() => set("leather", l.name)}>
                          <span className="bsp-swatch-chip" style={{ background: l.sw }} />
                          <span className="bsp-swatch-t">{l.name}</span>
                        </button>
                      ))}
                    </div>
                  </fieldset>
                  <fieldset className="bsp-fs">
                    <legend className="bsp-fs-l"><span className="serif bsp-rn">III.</span> Size &amp; fit</legend>
                    <div className="bsp-sizes">
                      {SIZES.map((s) => (
                        <button type="button" key={s} className={"bsp-size" + (!form.customLast && form.size === s ? " on" : "")} onClick={() => { set("size", s); set("customLast", false); }}>{s}</button>
                      ))}
                      <button type="button" className={"bsp-size wide" + (form.customLast ? " on" : "")} onClick={() => set("customLast", !form.customLast)}>Custom last — measure me</button>
                    </div>
                  </fieldset>
                  <fieldset className="bsp-fs">
                    <legend className="bsp-fs-l"><span className="serif bsp-rn">IV.</span> Notes to the maker</legend>
                    <textarea className="bsp-lines" rows="3" placeholder="Colour, occasion, details you love — reference photos welcome during your call." value={form.notes} onChange={up("notes")}></textarea>
                  </fieldset>
                  <fieldset className="bsp-fs">
                    <legend className="bsp-fs-l"><span className="serif bsp-rn">V.</span> Your details</legend>
                    <div className="form-grid">
                      <div className="field"><label>Name</label><input className="input" required placeholder="Your name" value={form.name} onChange={up("name")} /></div>
                      <div className="field"><label>Email</label><input className="input" type="email" required placeholder="you@email.com" value={form.contact} onChange={up("contact")} /></div>
                    </div>
                  </fieldset>
                </div>
                <aside className="bsp-docket">
                  <span className="mono bsp-docket-l">Docket</span>
                  <dl className="bsp-docket-list">
                    <div><dt>Style</dt><dd>{form.style}</dd></div>
                    <div><dt>Leather</dt><dd>{form.leather}</dd></div>
                    <div><dt>Fit</dt><dd>{form.customLast ? "Custom last" : "EU " + form.size}</dd></div>
                    <div><dt>Lead time</dt><dd>4–6 weeks</dd></div>
                    <div><dt>From</dt><dd><Price ngn={850000} /></dd></div>
                    <div><dt>Deposit</dt><dd>50% to confirm</dd></div>
                  </dl>
                  <label className="bsp-sign-l mono" htmlFor="bsp-sign">Sign &amp; send</label>
                  <input id="bsp-sign" className="bsp-sign" required placeholder="Type your name as signature" value={form.signature} onChange={up("signature")} autoComplete="off" />
                  <Btn block arrow={false} type="submit" style={{ marginTop: 18 }}>Send to the atelier</Btn>
                  <p className="bsp-docket-note">No payment now — every detail is confirmed with you first.</p>
                </aside>
              </form>
            )}
          </div>
        </div>
      </section>
      {callOpen && <BookCallModal onClose={() => setCallOpen(false)} />}
    </div>
  );
}

function BookCallModal({ onClose }) {
  const [day, setDay] = useState(null);
  const [slot, setSlot] = useState(null);
  const [form, setForm] = useState({ name: "", email: "" });
  const [booked, setBooked] = useState(false);
  const up = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);
  const days = [];
  const d = new Date();
  while (days.length < 6) {
    d.setDate(d.getDate() + 1);
    if (d.getDay() !== 0) days.push(new Date(d));
  }
  const SLOTS = ["10:00", "11:00", "12:00", "14:00", "15:00", "16:00"];
  const fmtD = (x) => x.toLocaleDateString("en-GB", { weekday: "short", day: "numeric", month: "short" });
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-card bsp-call" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">×</button>
        {booked ? (
          <div style={{ textAlign: "center", padding: "18px 0 6px" }}>
            <div className="confirm-badge sm"><Icon name="check" size={26} /></div>
            <h3 className="serif" style={{ fontSize: 28, margin: "14px 0 8px" }}>Call booked</h3>
            <p style={{ color: "var(--ink-soft)", fontSize: 14.5 }}>{fmtD(day)} at {slot} (WAT). A confirmation is on its way to <strong>{form.email}</strong>.</p>
            <Btn style={{ marginTop: 20 }} arrow={false} onClick={onClose}>Done</Btn>
          </div>
        ) : (
          <form onSubmit={(e) => { e.preventDefault(); if (day && slot) setBooked(true); }}>
            <span className="eyebrow">Fitting call</span>
            <h3 className="serif" style={{ fontSize: 30, fontWeight: 500, margin: "10px 0 4px" }}>Book a call</h3>
            <p style={{ color: "var(--ink-soft)", fontSize: 14, marginBottom: 6 }}>15 minutes with the atelier — style, leather and fit.</p>
            <span className="bsp-call-l mono">Day</span>
            <div className="bsp-call-days">
              {days.map((x) => (
                <button type="button" key={x.toISOString()} className={"bsp-size" + (day && day.getTime() === x.getTime() ? " on" : "")} onClick={() => setDay(x)}>{fmtD(x)}</button>
              ))}
            </div>
            <span className="bsp-call-l mono">Time · WAT</span>
            <div className="bsp-call-days">
              {SLOTS.map((s) => (
                <button type="button" key={s} className={"bsp-size" + (slot === s ? " on" : "")} onClick={() => setSlot(s)}>{s}</button>
              ))}
            </div>
            <div className="form-grid" style={{ marginTop: 28 }}>
              <div className="field"><label>Name</label><input className="input" required placeholder="Your name" value={form.name} onChange={up("name")} /></div>
              <div className="field"><label>Email</label><input className="input" type="email" required placeholder="you@email.com" value={form.email} onChange={up("email")} /></div>
            </div>
            <Btn block arrow={false} type="submit" style={{ marginTop: 44, opacity: day && slot ? 1 : 0.5 }} disabled={!day || !slot}>Confirm booking</Btn>
          </form>
        )}
      </div>
    </div>
  );
}

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