/* ============================================================
   YAYTUNES APPAREL — 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>
                  <p style={{ color: "var(--ink-soft)" }}>No orders yet.</p>
                </div>
              }
              {tab === "addresses" &&
              <div>
                  <h2 className="serif acct-h">Addresses</h2>
                  <div className="acct-addr-grid">
                    <div className="acct-addr"><strong>Home · {(window.BRAND?.hqCity) || "Abuja"}</strong><p style={{ whiteSpace: "pre-line", color: "var(--ink-soft)", marginTop: 8 }}>{(window.BRAND?.addresses.hq.line) || "Abuja, Nigeria"}</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 ratio="tall" />
        <div className="auth-media-cap"><Logo size={30} /><p className="serif" style={{ fontSize: 28, marginTop: 16, color: "#f6f1e7" }}>RTW Ankara wears.</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) || "Yaytunes Apparel")}</h1>
          <p style={{ color: "var(--ink-soft)", marginBottom: 26 }}>{mode === "login" ? "Sign in to track your orders." : "Create an account for faster checkout and order history."}</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>
          <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 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>);

}

/* ---------------- BOOK A CALL (calendar + time) ---------------- */
const BC_TIMES = ["09:30", "11:00", "12:30", "14:00", "15:30", "17:00"];

function buildCallSlots() {
  const today = new Date();
  const days = [];
  for (let i = 1; i <= 14; i++) {
    const d = new Date(today);
    d.setDate(today.getDate() + i);
    if (d.getDay() === 0) continue; /* closed Sundays */
    const times = BC_TIMES.filter((_, ti) => (i * 7 + ti * 3) % 5 !== 0);
    days.push({ date: d, times });
  }
  return days;
}

function BookingWidget({ modes }) {
  const slots = useRef(buildCallSlots()).current;
  const [mode, setMode] = useState(modes[0]);
  const [dayIdx, setDayIdx] = useState(0);
  const [time, setTime] = useState(null);
  const [booked, setBooked] = useState(null);

  const day = slots[dayIdx];
  const fmtShort = (d) => d.toLocaleDateString("en-GB", { weekday: "short", day: "numeric", month: "short" });

  if (booked) {
    return (
      <div className="bw-held">
        <div className="bw-held-badge"><Icon name="check" size={20} /></div>
        <div>
          <strong className="bw-held-title">Call booked</strong>
          <p className="bw-held-meta">
            {booked.mode} · {booked.date.toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long" })} at {booked.time}
          </p>
          <p className="bw-held-note">We’ll send a confirmation and a reminder the day before.</p>
          <button type="button" className="bw-release" onClick={() => { setBooked(null); setTime(null); }}>Choose a different time</button>
        </div>
      </div>
    );
  }

  return (
    <div className="bw">
      <span className="bw-slabel">How should we talk?</span>
      <div className="bw-modes">
        {modes.map((m) => (
          <button key={m} type="button" className={"chip" + (mode === m ? " active" : "")} onClick={() => setMode(m)}>{m}</button>
        ))}
      </div>

      <span className="bw-slabel">Pick a date</span>
      <div className="bw-days">
        {slots.map((s, i) => (
          <button key={i} type="button"
            className={"bw-day" + (dayIdx === i ? " active" : "") + (s.times.length === 0 ? " full" : "")}
            disabled={s.times.length === 0}
            onClick={() => { setDayIdx(i); setTime(null); }}>
            <span className="bw-day-dow">{s.date.toLocaleDateString("en-GB", { weekday: "short" })}</span>
            <span className="bw-day-num">{s.date.getDate()}</span>
            <span className="bw-day-mon">{s.date.toLocaleDateString("en-GB", { month: "short" })}</span>
          </button>
        ))}
      </div>

      <span className="bw-slabel">Pick a time (WAT)</span>
      <div className="bw-times">
        {day.times.length === 0 ?
          <p className="bw-none">No slots remaining — try another day.</p> :
          BC_TIMES.map((tm) => {
            const open = day.times.includes(tm);
            return (
              <button key={tm} type="button" disabled={!open}
                className={"bw-time" + (time === tm ? " active" : "") + (!open ? " taken" : "")}
                onClick={() => setTime(tm)}>{tm}{!open && <em>booked</em>}</button>
            );
          })
        }
      </div>

      <button type="button" className="bw-confirm" disabled={!time}
        onClick={() => setBooked({ mode, date: day.date, time })}>
        {time ? "Book " + fmtShort(day.date) + " · " + time : "Select a time"}
      </button>
      <p className="bw-note">Free 20-minute call. Closed Sundays.</p>
    </div>
  );
}

function BookACallSection() {
  const city = (window.BRAND?.addresses.hq.label) || "Abuja";
  return (
    <section className="section-pad bookcall-sec">
      <div className="wrap-wide bookcall-grid">
        <div>
          <Eyebrow line>Book a call</Eyebrow>
          <h2 className="serif" style={{ fontSize: "clamp(30px,3.6vw,46px)", fontWeight: 500, marginTop: 22, lineHeight: 1.06 }}>
            Rather talk it through first?
          </h2>
          <p style={{ color: "var(--ink-soft)", marginTop: 22, maxWidth: "42ch" }}>
            Pick a date and time that suits you and we’ll call to talk through prints, cuts,
            measurements and timing before you commit to anything.
          </p>
          <ul className="bookcall-why">
            {[
              "20 minutes, free, no obligation",
              "Bring photos or a print you’ve seen — we’ll tell you what’s possible",
              "We’ll confirm pricing and turnaround on the call",
              "Video, phone, or in person at the " + city + " studio",
            ].map((x) => (
              <li key={x}><Icon name="check" size={16} /><span>{x}</span></li>
            ))}
          </ul>
        </div>
        <BookingWidget modes={["Video call", "Phone call", city + " studio"]} />
      </div>
    </section>
  );
}

/* ---------------- CUSTOM ORDER / BESPOKE ---------------- */
function BespokePage({ onNav }) {
  const [sent, setSent] = useState(false);
  const [type, setType] = useState("Gown");
  const [mode, setMode] = useState("Virtual");
  const city = (window.BRAND?.addresses.hq.label) || "Abuja";
  const studio = city + " studio";
  return (
    <div className="fade-page">
      <section className="bespoke-hero">
        <Ph label="GOWNS · ANKARA" ratio="cinema" className="about-hero-bg" />
        <div className="about-hero-ov" />
        <div className="wrap about-hero-content">
          <Eyebrow style={{ color: "var(--accent-bright)" }}>Custom Orders</Eyebrow>
          <h1 className="serif about-hero-h">Made to your measure.</h1>
          <p className="lede on-img" style={{ maxWidth: "46ch", marginTop: 16 }}>
            Love a Yaytunes piece but want it in your own measurements, or in a print you’ve picked yourself?
            Commission a custom Ankara make — virtually, or with us at the {studio}.
          </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 a consultation", "Pick a date and whether you’d like to meet us at the " + studio + " or talk it through virtually."],
              ["02", "Choose print & cut", "Pick your Ankara print and the silhouette — gown, two-piece, kimono or trousers."],
              ["03", "Measurements & fitting", "We take your measurements and fit the piece to you before it’s finished."],
              ["04", "Delivered to you", "Same-day delivery within " + city + ", 3–5 days interstate across Nigeria."],
            ].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" }}>Consultation requested</h3>
                <p style={{ color: "var(--ink-soft)" }}>Thank you. We’ll confirm your {mode.toLowerCase()} consultation for a custom {type.toLowerCase()} within 24 hours.</p>
                <div style={{ marginTop: 20 }}><Btn onClick={() => onNav("home", {})}>Back to home</Btn></div>
              </div> :

            <form onSubmit={(e) => { e.preventDefault(); setSent(true); }}>
                <h2 className="serif" style={{ fontSize: 30, marginBottom: 6 }}>Request a consultation</h2>
                <p style={{ color: "var(--ink-soft)", marginBottom: 22, fontSize: 14 }}>Free &amp; no obligation.</p>
                <label className="bk-label">What would you like made?</label>
                <div className="bk-pills">{["Gown", "Two-Piece Set", "Kimono", "Pants", "Other"].map((x) =>
                  <button type="button" key={x} className={"chip" + (type === x ? " active" : "")} onClick={() => setType(x)}>{x}</button>)}</div>
                <label className="bk-label">Consultation type</label>
                <div className="bk-pills">{["Virtual", studio].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>Phone</label><input className="input" type="tel" placeholder="080…" /></div>
                  <div className="field"><label>Preferred 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 guest, birthday, work — and any print you have in mind…"></textarea></div>
                </div>
                <div style={{ marginTop: 18 }}><Btn block arrow={false} type="submit">Request consultation</Btn></div>
              </form>
            }
          </div>
        </div>
      </section>
      <BookACallSection />
    </div>);

}

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