/* ============================================================
   PRUDENTIAL ATELIER — Bespoke Services
   Pages: PackagesPage · CustomOrderPage · BookingPage
   Shared: BookingWidget · IntakeForm
   ============================================================ */

/* ── Package data ─────────────────────────────────────────── */
const BS_PACKAGES = [
  {
    id: "bridal-couture",
    name: "Bridal Couture",
    tag: "Most Loved",
    from: 2500000,
    weeks: "6–10 weeks",
    img: "EDITORIAL · BRIDAL",
    intro: "For the bride who deserves a gown as extraordinary as her love story.",
    deliverables: [
      "Full bespoke bridal gown",
      "Headpiece & gele consultation",
      "3 private fittings",
      "Accessories styling session",
      "Dedicated atelier stylist",
      "Luxury garment preservation bag",
    ],
  },
  {
    id: "traditional-heritage",
    name: "Traditional Heritage",
    tag: "Heritage",
    from: 1800000,
    weeks: "4–6 weeks",
    img: "COLLECTION · FESTIVE",
    intro: "Richly crafted traditional wear rooted in Nigerian heritage and handwork.",
    deliverables: [
      "Full traditional outfit (Aso-Oke / Adire)",
      "Gele tying session",
      "Hand-beaded accessories",
      "2 private fittings",
      "Cultural styling consultation",
    ],
  },
  {
    id: "owambe-statement",
    name: "Owambe Statement",
    tag: "Celebration",
    from: 1200000,
    weeks: "3–4 weeks",
    img: "OWAMBE · SHOP",
    intro: "Walk into the party and own the dancefloor completely.",
    deliverables: [
      "Statement Owambe gown",
      "Head-tie & gele styling",
      "2 private fittings",
      "Celebration accessories",
    ],
  },
  {
    id: "couples",
    name: "Couple's Package",
    tag: "His & Hers",
    from: 3500000,
    weeks: "6–8 weeks",
    img: "EDITORIAL · LAGOS NIGHTS",
    intro: "Coordinated looks for two people who want to arrive and be remembered together.",
    deliverables: [
      "Coordinated his & hers outfits",
      "4 joint private fittings",
      "Couples styling consultation",
      "Coordinated accessories",
      "Dedicated stylist for both",
    ],
  },
  {
    id: "event-editorial",
    name: "Event & Editorial",
    tag: "Statement Piece",
    from: 800000,
    weeks: "2–3 weeks",
    img: "LOOK 02 · GOWN",
    intro: "One unforgettable piece for the moment that demands attention.",
    deliverables: [
      "One bespoke statement piece",
      "1 private fitting",
      "Express turnaround available",
      "Styling consultation",
    ],
  },
];

const BS_PROJECT_TYPES = [
  "Bridal / Wedding", "Traditional Ceremony", "Owambe / Celebration",
  "Corporate Event", "Birthday / Milestone", "Editorial / Photoshoot", "Other",
];

/* ── Dual-currency helpers (this page always shows ₦ + $) ──── */
function dualPrice(ngn) {
  return RB.format(ngn, "NGN") + "  ·  " + RB.format(ngn, "USD");
}
function DualPrice({ ngn, className = "", style }) {
  return (
    <span className={className} style={style}>
      {RB.format(ngn, "NGN")}
      <span style={{ color: "var(--ink-faint)", marginLeft: 8, fontSize: "0.9em" }}>{RB.format(ngn, "USD")}</span>
    </span>
  );
}
const BS_BUDGETS = [
  { label: "Prefer not to say", value: "" },
  { label: "Under " + dualPrice(500000), value: "under-500k" },
  { label: dualPrice(500000) + " – " + dualPrice(1000000), value: "500k-1m" },
  { label: dualPrice(1000000) + " – " + dualPrice(2000000), value: "1m-2m" },
  { label: dualPrice(2000000) + " – " + dualPrice(5000000), value: "2m-5m" },
  { label: dualPrice(5000000) + "+", value: "5m-plus" },
];

/* ── The bespoke process ──────────────────────────────────── */
const BS_PROCESS = [
  { n: "01", t: "Enquire", s: "Tell us about your occasion, vision and timeline through the form below — no call required to get started." },
  { n: "02", t: "Consult", s: "A complimentary session with your atelier stylist, in person in Ikoyi or virtually — to refine fabric, silhouette and detail." },
  { n: "03", t: "Quote & Deposit", s: "You'll receive a personalised quote within 24 hours. Work begins once your deposit is confirmed." },
  { n: "04", t: "Fittings", s: "Private fittings at the atelier (or by measurement guide for international clients) as your piece takes shape." },
  { n: "05", t: "Delivery", s: "Final pressing, packaging and delivery to your door — in Lagos or worldwide." },
];

/* ── Booking slot generation ───────────────────────────────── */
function genDays() {
  const days = []; const today = new Date();
  for (let d = 1; d <= 18 && days.length < 10; d++) {
    const dt = new Date(today); dt.setDate(today.getDate() + d);
    if (dt.getDay() === 0) continue; // skip Sunday
    days.push({
      label: dt.toLocaleDateString("en-GB", { weekday: "short", day: "numeric", month: "short" }),
      raw: dt.toISOString().slice(0, 10),
    });
  }
  return days;
}
const BS_TIMES = [
  { band: "Morning",   slots: ["10:00 AM", "11:00 AM"] },
  { band: "Afternoon", slots: ["2:00 PM", "3:00 PM", "4:00 PM"] },
  { band: "Evening",   slots: ["6:00 PM", "7:00 PM"] },
];
const BS_FORMATS = ["In-person · Ikoyi, Lagos", "Virtual · Video Call", "Phone Call"];

/* ════════════════════════════════════════════════════════════
   BOOKING WIDGET — shared scheduling component
   ════════════════════════════════════════════════════════════ */
function BookingWidget({ onConfirm, onSkip }) {
  const days    = useMemo(() => genDays(), []);
  const [day,   setDay]    = useState(null);
  const [time,  setTime]   = useState(null);
  const [fmt,   setFmt]    = useState(BS_FORMATS[0]);

  /* Scatter some unavailable slots realistically */
  const unavail = useMemo(() => {
    const u = new Set();
    days.forEach((d, i) => {
      if ([1, 3, 5, 7].includes(i))
        BS_TIMES[0].slots.forEach((t) => u.add(d.raw + "_" + t));
      if ([2, 6, 8].includes(i))
        BS_TIMES[1].slots.slice(0, 1).forEach((t) => u.add(d.raw + "_" + t));
    });
    return u;
  }, [days]);

  return (
    <div className="bk-widget">
      <div className="bk-label mono">Select a date</div>
      <div className="bk-days">
        {days.map((d) => (
          <button key={d.raw}
            className={"bk-day" + (day === d.raw ? " active" : "")}
            onClick={() => { setDay(d.raw); setTime(null); }}>
            {d.label}
          </button>
        ))}
      </div>

      {day && (<>
        <div className="bk-label mono" style={{ marginTop: 22 }}>Select a time</div>
        {BS_TIMES.map((tb) => (
          <div key={tb.band} className="bk-time-band">
            <span className="bk-band-label">{tb.band}</span>
            <div className="bk-times">
              {tb.slots.map((t) => {
                const taken = unavail.has(day + "_" + t);
                return (
                  <button key={t} disabled={taken}
                    className={"bk-time" + (time === t ? " active" : "") + (taken ? " taken" : "")}
                    onClick={() => setTime(t)}>
                    {taken ? "Taken" : t}
                  </button>
                );
              })}
            </div>
          </div>
        ))}
      </>)}

      {time && (<>
        <div className="bk-label mono" style={{ marginTop: 22 }}>Consultation format</div>
        <div className="bk-formats">
          {BS_FORMATS.map((f) => (
            <button key={f} className={"bk-fmt" + (fmt === f ? " active" : "")}
              onClick={() => setFmt(f)}>{f}</button>
          ))}
        </div>
      </>)}

      <div className="bk-actions">
        {onSkip && <button className="bk-skip" onClick={onSkip}>Skip — I'll book later</button>}
        <Btn disabled={!day || !time}
          onClick={() => day && time && onConfirm({ day: days.find((d) => d.raw === day)?.label, time, format: fmt })}>
          Confirm Consultation
        </Btn>
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   CATALOGUE INSPIRATION PICKER — modal for the intake form
   ════════════════════════════════════════════════════════════ */
const INSPIRATION_MAX = 3;

function CataloguePickerModal({ selected, onToggle, onClose }) {
  const products = (window.RB && window.RB.PRODUCTS) || [];
  const imgs = window.RB_IMGS || {};
  const isSelected = (id) => selected.some((s) => s.id === id);
  const atMax = selected.length >= INSPIRATION_MAX;
  return (
    <div className="cat-picker-overlay" onClick={onClose}>
      <div className="cat-picker" onClick={(e) => e.stopPropagation()}>
        <div className="cat-picker-head">
          <div>
            <h3 className="serif cat-picker-title">Add from catalogue</h3>
            <p className="cat-picker-sub">Select pieces from our collection as inspiration for your bespoke order.</p>
            <span className="cat-picker-cap">{atMax ? `Max 3 selected (${selected.length}/3)` : `Up to 3 (${selected.length}/3)`}</span>
          </div>
          <button className="cat-picker-close" onClick={onClose} aria-label="Close">
            <Icon name="x" size={18} />
          </button>
        </div>
        <div className="cat-picker-grid">
          {products.map((p) => {
            const active = isSelected(p.id);
            const disabled = !active && atMax;
            return (
              <button key={p.id} className={"cat-pick-card" + (active ? " active" : "") + (disabled ? " disabled" : "")}
                onClick={() => { if (!disabled) onToggle(p); }} disabled={disabled}>
                <div className="cat-pick-img">
                  <img src={imgs[p.label] || ""} alt={p.name} />
                  {active && <span className="cat-pick-check"><Icon name="check" size={13} /></span>}
                </div>
                <span className="cat-pick-name">{p.name}</span>
              </button>
            );
          })}
        </div>
        <div className="cat-picker-foot">
          <Btn onClick={onClose}>Done{selected.length ? ` — ${selected.length} selected` : ""}</Btn>
        </div>
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   INTAKE FORM — multi-step engine (Custom Orders + Packages)
   ════════════════════════════════════════════════════════════ */
function IntakeForm({ config = {}, onNav }) {
  const steps = 6;
  const [step, setStep]   = useState(1);
  const [data, setData]   = useState({
    projectType: config.packageName || "",
    vision: "", links: "", files: [],
    inspirationProducts: [],
    weeks: "", budget: "", booking: null,
    name: "", email: "", phone: "", city: "",
  });
  const [done, setDone] = useState(false);
  const [catalogueOpen, setCatalogueOpen] = useState(false);
  const set = (k, v) => setData((p) => ({ ...p, [k]: v }));
  const next = () => setStep((s) => Math.min(s + 1, steps));
  const back = () => setStep((s) => Math.max(s - 1, 1));
  const toggleInspiration = (p) => {
    setData((prev) => {
      const exists = prev.inspirationProducts.some((s) => s.id === p.id);
      if (!exists && prev.inspirationProducts.length >= INSPIRATION_MAX) return prev;
      return {
        ...prev,
        inspirationProducts: exists
          ? prev.inspirationProducts.filter((s) => s.id !== p.id)
          : [...prev.inspirationProducts, { id: p.id, name: p.name, label: p.label }],
      };
    });
  };
  const removeInspiration = (id) =>
    setData((prev) => ({ ...prev, inspirationProducts: prev.inspirationProducts.filter((s) => s.id !== id) }));
  const submitEnquiry = () => {
    const payload = {
      ...data,
      inspirationProductNames: data.inspirationProducts.map((p) => p.name),
    };
    // eslint-disable-next-line no-console
    console.log("Bespoke enquiry submitted:", payload);
    setDone(true);
  };

  if (done) return (
    <div className="intake-confirm center">
      <div className="confirm-badge">
        <Icon name="check" size={32} />
      </div>
      <h2 className="serif" style={{ fontSize: "clamp(32px,5vw,54px)", margin: "26px 0 14px" }}>
        We'll be in touch.
      </h2>
      <p style={{ color: "var(--ink-soft)", maxWidth: "44ch", margin: "0 auto 28px", lineHeight: 1.7 }}>
        Your request has been received. Our atelier team will review your vision and respond within 24 hours with a personalised quote.
      </p>
      {data.booking && (
        <div className="intake-bk-confirm">
          <Icon name="check" size={15} />
          Consultation confirmed: <strong>{data.booking.day} at {data.booking.time}</strong> &middot; {data.booking.format}
        </div>
      )}
      <div className="intake-done-cta">
        <Btn onClick={() => onNav("home", {})}>Back to Home</Btn>
        <Btn variant="ghost" onClick={() => onNav("shop", {})}>Browse Collections</Btn>
      </div>
    </div>
  );

  const progress = ((step - 1) / (steps - 1)) * 100;

  return (
    <div className="intake-wrap">
      {/* Progress bar */}
      <div className="intake-bar-track"><div className="intake-bar-fill" style={{ width: progress + "%" }} /></div>
      <div className="intake-step-label mono">Step {step} of {steps}</div>

      {/* ── Step 1: Project type ── */}
      {step === 1 && (
        <div className="intake-step">
          <h2 className="serif intake-h">What are you creating?</h2>
          <p className="intake-sub">Select what you're creating — this helps us match you with the right atelier specialist.</p>
          <div className="proj-grid">
            {BS_PROJECT_TYPES.map((o) => (
              <button key={o} className={"proj-card" + (data.projectType === o ? " active" : "")}
                onClick={() => set("projectType", o)}>{o}</button>
            ))}
          </div>
          <div className="intake-nav">
            <span />
            <Btn disabled={!data.projectType} onClick={next}>Continue</Btn>
          </div>
        </div>
      )}

      {/* ── Step 2: Vision ── */}
      {step === 2 && (
        <div className="intake-step">
          <h2 className="serif intake-h">Describe your vision.</h2>
          <p className="intake-sub">Share fabric preferences, silhouette, colours, feeling — as much as you'd like.</p>
          <div className="field">
            <label>Your vision</label>
            <textarea className="input" rows="6"
              placeholder="I'm imagining a floor-length gown with hand-beaded details…"
              value={data.vision} onChange={(e) => set("vision", e.target.value)} />
          </div>
          <div className="field" style={{ marginTop: 16 }}>
            <label>Inspiration links <span className="field-opt">(optional)</span></label>
            <input className="input" placeholder="Pinterest boards, Instagram posts, websites…"
              value={data.links} onChange={(e) => set("links", e.target.value)} />
          </div>
          <div className="field" style={{ marginTop: 16 }}>
            <label>Inspiration <span className="field-opt">(optional)</span></label>
            <div className="cat-add-row">
              <button type="button" className="cat-add-btn" onClick={() => setCatalogueOpen(true)}>
                <Icon name="plus" size={15} />
                Add from catalogue
              </button>
              <span className="cat-add-hint">
                {data.inspirationProducts.length >= INSPIRATION_MAX
                  ? `Max 3 selected (${data.inspirationProducts.length}/3)`
                  : "Up to 3"}
              </span>
            </div>
            {data.inspirationProducts.length > 0 && (
              <div className="insp-chips">
                {data.inspirationProducts.map((p) => (
                  <span key={p.id} className="insp-chip">
                    <img src={(window.RB_IMGS || {})[p.label] || ""} alt="" />
                    <span className="insp-chip-name">{p.name}</span>
                    <button type="button" className="insp-chip-x" onClick={() => removeInspiration(p.id)} aria-label={"Remove " + p.name}>
                      <Icon name="x" size={11} />
                    </button>
                  </span>
                ))}
              </div>
            )}
          </div>
          <div className="intake-nav">
            <button className="intake-back" onClick={back}>← Back</button>
            <Btn disabled={!data.vision.trim()} onClick={next}>Continue</Btn>
          </div>
        </div>
      )}

      {/* ── Step 3: Media upload ── */}
      {step === 3 && (
        <div className="intake-step">
          <h2 className="serif intake-h">Share your inspiration.</h2>
          <p className="intake-sub">Upload reference images, mood boards, voice notes or video — up to 8 files.</p>
          <label className="upload-zone">
            <input type="file" multiple accept="image/*,video/*,audio/*" style={{ display: "none" }}
              onChange={(e) => set("files", [...data.files, ...Array.from(e.target.files)].slice(0, 8))} />
            <Icon name="plus" size={30} style={{ color: "var(--accent)" }} />
            <span className="upload-cta">Tap to upload</span>
            <span className="upload-hint">JPEG · PNG · MP4 · MOV · M4A — up to 50 MB each</span>
          </label>
          {data.files.length > 0 && (
            <div className="upload-list">
              {data.files.map((f, i) => (
                <div key={i} className="upload-item">
                  <Icon name="check" size={14} />
                  <span>{f.name.length > 30 ? f.name.slice(0, 28) + "…" : f.name}</span>
                  <button className="upload-rm" onClick={() => set("files", data.files.filter((_, j) => j !== i))}>×</button>
                </div>
              ))}
            </div>
          )}
          <div className="intake-nav">
            <button className="intake-back" onClick={back}>← Back</button>
            <Btn onClick={next}>Continue</Btn>
          </div>
        </div>
      )}

      {/* ── Step 4: Timeline & budget ── */}
      {step === 4 && (
        <div className="intake-step">
          <h2 className="serif intake-h">Timeline & budget.</h2>
          <p className="intake-sub">Helps us prioritise your order and suggest the most suitable options.</p>
          <div className="form-grid">
            <div className="field">
              <label>When do you need it?</label>
              <select className="input" value={data.weeks} onChange={(e) => set("weeks", e.target.value)}>
                <option value="">Select a timeframe</option>
                <option>Within 2 weeks (express)</option>
                <option>2–4 weeks</option>
                <option>4–6 weeks</option>
                <option>6–10 weeks</option>
                <option>10+ weeks (no rush)</option>
              </select>
            </div>
            <div className="field">
              <label>Budget range <span className="field-opt">(optional)</span></label>
              <select className="input" value={data.budget} onChange={(e) => set("budget", e.target.value)}>
                {BS_BUDGETS.map((b) => (
                  <option key={b.value} value={b.value}>{b.label}</option>
                ))}
              </select>
            </div>
          </div>
          <div className="intake-nav">
            <button className="intake-back" onClick={back}>← Back</button>
            <Btn disabled={!data.weeks} onClick={next}>Continue</Btn>
          </div>
        </div>
      )}

      {/* ── Step 5: Book a consultation ── */}
      {step === 5 && (
        <div className="intake-step">
          <h2 className="serif intake-h">Book a consultation.</h2>
          <p className="intake-sub">Complimentary. Our team will review your intake before the call.</p>
          <BookingWidget
            onConfirm={(bk) => { set("booking", bk); next(); }}
            onSkip={next}
          />
          <div className="intake-nav" style={{ marginTop: 0 }}>
            <button className="intake-back" onClick={back}>← Back</button>
            <span />
          </div>
        </div>
      )}

      {/* ── Step 6: Contact details ── */}
      {step === 6 && (
        <div className="intake-step">
          <h2 className="serif intake-h">Almost there.</h2>
          <p className="intake-sub">We'll use these details to send your personalised quote.</p>
          <div className="form-grid">
            <div className="field"><label>Full name</label>
              <input className="input" required placeholder="Your name"
                value={data.name} onChange={(e) => set("name", e.target.value)} /></div>
            <div className="field"><label>Email address</label>
              <input className="input" type="email" required placeholder="you@email.com"
                value={data.email} onChange={(e) => set("email", e.target.value)} /></div>
            <div className="field"><label>Phone number</label>
              <input className="input" placeholder="+234 …"
                value={data.phone} onChange={(e) => set("phone", e.target.value)} /></div>
            <div className="field"><label>City / Country</label>
              <input className="input" placeholder="Lagos, Nigeria"
                value={data.city} onChange={(e) => set("city", e.target.value)} /></div>
          </div>
          <div className="intake-nav">
            <button className="intake-back" onClick={back}>← Back</button>
            <Btn disabled={!data.name || !data.email} onClick={submitEnquiry}>
              Submit Request
            </Btn>
          </div>
        </div>
      )}

      {catalogueOpen && (
        <CataloguePickerModal
          selected={data.inspirationProducts}
          onToggle={toggleInspiration}
          onClose={() => setCatalogueOpen(false)}
        />
      )}
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   PACKAGES PAGE
   ════════════════════════════════════════════════════════════ */
function PackagesPage({ onNav }) {
  const imgs = window.RB_IMGS || {};
  return (
    <div className="fade-page">

      {/* Hero */}
      <div className="bs-hero wrap-wide">
        <div className="bs-hero-text">
          <Eyebrow line>The Bespoke Experience</Eyebrow>
          <h1 className="display bs-hero-h">Every piece, a promise.</h1>
          <p className="lede bs-hero-sub">
            Choose a package built around your moment — or start with a custom order and let us guide you from the very first stitch.
          </p>
          <div className="bs-hero-cta">
            <Btn onClick={() => onNav("custom-order", {})}>Start a Custom Order</Btn>
            <Btn variant="ghost" onClick={() => onNav("booking", {})}>Book a Consultation</Btn>
          </div>
        </div>
        <div className="bs-hero-media">
          <Ph label="EDITORIAL · BRIDAL" ratio="portrait" />
        </div>
      </div>

      {/* Three-feature row */}
      <div className="bs-features wrap">
        {[
          ["24h", "Quote turnaround", "We respond to every enquiry within 24 hours with a detailed proposal."],
          ["100%", "Bespoke", "Every piece is built from scratch — no off-the-rack adjustments."],
          ["Worldwide", "Delivery", "Seamless delivery from our Ikoyi atelier to your door, anywhere in the world."],
        ].map(([n, t, s]) => (
          <div key={t} className="bs-feat">
            <strong className="serif bs-feat-n">{n}</strong>
            <span className="bs-feat-t">{t}</span>
            <p className="bs-feat-s">{s}</p>
          </div>
        ))}
      </div>

      {/* The bespoke process */}
      <div className="section-pad wrap-wide bs-process-sec">
        <div className="center" style={{ marginBottom: 54 }}>
          <Eyebrow line>How It Works</Eyebrow>
          <h2 className="serif" style={{ fontSize: "clamp(36px,5vw,64px)", margin: "16px 0 0" }}>
            From vision to garment.
          </h2>
        </div>
        <div className="bs-process-grid">
          {BS_PROCESS.map((p) => (
            <div key={p.n} className="bs-process-step">
              <span className="mono bs-process-n">{p.n}</span>
              <h3 className="serif bs-process-t">{p.t}</h3>
              <p className="bs-process-s">{p.s}</p>
            </div>
          ))}
        </div>
      </div>

      {/* Packages grid */}
      <div className="section-pad wrap-wide">
        <div className="center" style={{ marginBottom: 54 }}>
          <Eyebrow line>Our Packages</Eyebrow>
          <h2 className="serif" style={{ fontSize: "clamp(36px,5vw,64px)", margin: "16px 0 0" }}>
            Crafted for your moment.
          </h2>
        </div>

        <div className="pkg-grid">
          {BS_PACKAGES.map((pkg) => (
            <div key={pkg.id} className="pkg-card">
              <div className="pkg-img zoomable">
                <img src={imgs[pkg.img] || ""} alt={pkg.name} />
                <span className="pkg-tag mono">{pkg.tag}</span>
              </div>
              <div className="pkg-body">
                <div className="pkg-top">
                  <h3 className="serif pkg-name">{pkg.name}</h3>
                  <div className="pkg-price">From <DualPrice ngn={pkg.from} /></div>
                </div>
                <p className="pkg-intro">{pkg.intro}</p>
                <ul className="pkg-list">
                  {pkg.deliverables.map((d) => (
                    <li key={d}><Icon name="check" size={13} />{d}</li>
                  ))}
                </ul>
                <div className="pkg-meta mono">{pkg.weeks}</div>
                <Btn block onClick={() => onNav("custom-order", { packageId: pkg.id, packageName: pkg.name })}>
                  Begin This Package
                </Btn>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Custom order CTA band */}
      <div className="bs-custom-band">
        <div className="wrap center">
          <Eyebrow line>Something Else in Mind?</Eyebrow>
          <h2 className="serif" style={{ fontSize: "clamp(32px,5vw,58px)", margin: "16px 0 18px" }}>
            Start a custom order — no brief too bold.
          </h2>
          <p style={{ color: "var(--ink-soft)", maxWidth: "48ch", margin: "0 auto 32px" }}>
            Submit your vision, inspiration and timeline. We'll come back to you with a personalised quote within 24 hours.
          </p>
          <Btn onClick={() => onNav("custom-order", {})}>Begin Your Custom Order</Btn>
        </div>
      </div>

    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   CUSTOM ORDER PAGE
   ════════════════════════════════════════════════════════════ */
function CustomOrderPage({ route, onNav }) {
  const cfg = route?.params || {};
  return (
    <div className="fade-page page-shell">
      <div className="wrap" style={{ maxWidth: 760 }}>
        {cfg.packageName && (
          <div className="co-pkg-label">
            <Icon name="check" size={14} />
            <span className="mono">Package selected: <strong>{cfg.packageName}</strong></span>
          </div>
        )}
        <IntakeForm config={cfg} onNav={onNav} />
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   BOOKING PAGE — standalone scheduling
   ════════════════════════════════════════════════════════════ */
function BookingPage({ onNav }) {
  const [confirmed, setConfirmed] = useState(false);
  const [bk, setBk] = useState(null);
  return (
    <div className="fade-page page-shell">
      <div className="wrap" style={{ maxWidth: 680 }}>
        {confirmed ? (
          <div className="intake-confirm center">
            <div className="confirm-badge"><Icon name="check" size={32} /></div>
            <h2 className="serif" style={{ fontSize: "clamp(30px,5vw,52px)", margin: "24px 0 14px" }}>
              Consultation confirmed.
            </h2>
            <p style={{ color: "var(--ink-soft)", maxWidth: "40ch", margin: "0 auto 20px" }}>
              You're booked. Our stylist will be in touch ahead of your session with preparation notes.
            </p>
            <div className="intake-bk-confirm">
              <Icon name="check" size={15} />
              {bk?.day} at {bk?.time} &middot; {bk?.format}
            </div>
            <div className="intake-done-cta">
              <Btn onClick={() => onNav("home", {})}>Back to Home</Btn>
            </div>
          </div>
        ) : (
          <>
            <Eyebrow line>The Atelier</Eyebrow>
            <h1 className="serif page-h">Book a Consultation</h1>
            <p className="shop-sub" style={{ maxWidth: "50ch", marginBottom: 36 }}>
              All consultations are complimentary. Choose a slot that works for you — in person at our Ikoyi atelier, or virtually from anywhere in the world.
            </p>
            <BookingWidget
              onConfirm={(b) => { setBk(b); setConfirmed(true); }}
            />
          </>
        )}
      </div>
    </div>
  );
}

/* ── Export all to global scope ──────────────────────────── */
Object.assign(window, { PackagesPage, CustomOrderPage, BookingPage, BookingWidget });
