/* ============================================================
   RACK & BOX — Service features built on the shared engine
     · CustomOrderPage  — open-ended intake → draft → invoice
     · PackagesPage     — fixed-price offerings → same intake
     · BookingPage      — standalone Booking Service
     · InvoicePage      — personalised invoice (magic-link style)
   ============================================================ */

/* ───────────────────────────────────────────────────────────
   CUSTOM ORDERS
   ─────────────────────────────────────────────────────────── */
function CustomOrderPage({ onNav, route }) {
  const [draft, setDraft] = useState(null); /* {ref, consult, heldSlot} */

  if (draft) {
    return (
      <div className="fade-page page-shell">
        <div className="wrap co-draft">
          <div className="co-draft-badge"><Icon name="check" size={28} /></div>
          <Eyebrow>Brief received</Eyebrow>
          <h1 className="serif co-draft-h">Your vision is with us.</h1>
          <p className="co-draft-sub">
            Thank you. Our design team is reviewing every detail and will finalise your bespoke pricing.
          </p>

          <div className="co-draft-card">
            <div className="co-draft-row">
              <span>Reference</span><strong className="mono">{draft.ref}</strong>
            </div>
            <div className="co-draft-row">
              <span>Status</span><strong className="co-pill">Draft · pricing in progress</strong>
            </div>
            <div className="co-draft-row">
              <span>{draft.consult ? "Consultation" : "Review"}</span>
              <strong>
                {draft.consult && draft.heldSlot
                  ? `${draft.heldSlot.mode} · ${draft.heldSlot.date.toLocaleDateString("en-GB", { day: "numeric", month: "short" })} at ${draft.heldSlot.time}`
                  : "Within 48 hours"}
              </strong>
            </div>
          </div>

          {draft.hasVideo && (
            <div className="co-proc">
              <span className="co-proc-ic">🎬</span>
              <div>
                <strong>Your video is processing…</strong>
                <div className="co-proc-bar"><span></span></div>
              </div>
            </div>
          )}

          <div className="co-steps-mini">
            {[["Brief submitted", "done"], ["Design review & pricing", "active"], ["Personalised invoice sent", "todo"], ["Production begins", "todo"]].map(([t, s], i) => (
              <div className={"co-stepm co-" + s} key={t}>
                <span className="co-stepm-dot">{s === "done" && <Icon name="check" size={11} />}</span>
                <span className="co-stepm-t">{t}</span>
              </div>
            ))}
          </div>

          <div className="co-draft-actions">
            <Btn variant="ghost" arrow={false} onClick={() => setDraft(null)}>Edit brief</Btn>
            <Btn arrow={false} onClick={() => onNav("invoice", { ref: draft.ref })}>Preview your invoice</Btn>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="fade-page">
      <section className="bespoke-hero">
        <Ph label="ATELIER · WINNS COUTURE STUDIO" ratio="cinema" className="about-hero-bg" />
        <div className="about-hero-ov" />
        <div className="wrap about-hero-content">
          <Eyebrow style={{ color: "#e9c97a" }}>Custom Orders</Eyebrow>
          <h1 className="serif about-hero-h">Commission anything.</h1>
          <p className="lede on-img" style={{ maxWidth: "46ch", marginTop: 16 }}>
            Open-ended, made entirely to you. Share your vision in as much detail as you like — we price it
            individually and send a personalised invoice once it's perfect.
          </p>
        </div>
      </section>

      <section className="section-pad">
        <div className="wrap-wide co-grid">
          <aside className="co-aside">
            <Eyebrow line>How it works</Eyebrow>
            {[
              ["01", "Submit your brief", "Text, links, images, video and voice notes — whatever captures it best."],
              ["02", "Optional consultation", "Book a call with your designer, synced to the studio calendar."],
              ["03", "We price it for you", "Bespoke work starts unpriced. We cost it precisely and send an invoice link."],
              ["04", "Approve & pay", "Pay your deposit from the personalised invoice. Production begins."],
            ].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 className="co-aside-note">
              <Icon name="shield" size={18} />
              <p>Price starts unknown by design — you only ever pay for exactly what you commission.</p>
            </div>
          </aside>

          <div className="co-form">
            <IntakeEngine context="a Custom Commission" submitLabel="Submit brief"
              onSubmit={(payload) => { window.scrollTo({ top: 0 }); setDraft(payload); }} />
          </div>
        </div>
      </section>
    </div>
  );
}

/* ───────────────────────────────────────────────────────────
   PACKAGES
   ─────────────────────────────────────────────────────────── */
const RB_PACKAGES = [
  {
    id: "bridal", name: "Bridal Couture Package", base: 1450000, label: "BRIDAL · WHITE WEDDING", featured: true,
    blurb: "A full bridal wardrobe, hand-built from first sketch to final fitting.",
    deliverables: ["Up to 3 bespoke looks", "Hand-beadwork & lace detailing", "Unlimited fittings", "On-day gele stylist", "Asoebi coordination (6 guests)", "Dedicated design manager"],
    lead: "12–16 weeks",
  },
  {
    id: "reception", name: "The Reception Look", base: 680000, label: "RECEPTION · SECOND LOOK",
    blurb: "The show-stopping second look for your reception and after-party.",
    deliverables: ["1 bespoke reception gown", "Beadwork or feather detailing", "3 fittings included", "Accessory styling", "Garment travel bag"],
    lead: "8–10 weeks",
  },
  {
    id: "owambe", name: "Owambe Ready", base: 380000, label: "ASOEBI · OWAMBE",
    blurb: "Show-stopping asoebi, turned around for the next big celebration.",
    deliverables: ["1 bespoke occasion look", "Fabric sourcing & sampling", "2 fittings included", "Priority 3-week production", "Doorstep delivery"],
    lead: "3–4 weeks",
  },
];

function PackagesPage({ onNav }) {
  const [active, setActive] = useState(null); /* package id being intaken */
  const [draft, setDraft] = useState(null);
  const pkg = RB_PACKAGES.find((p) => p.id === active);

  if (draft) {
    return (
      <div className="fade-page page-shell">
        <div className="wrap co-draft">
          <div className="co-draft-badge"><Icon name="check" size={28} /></div>
          <Eyebrow>{draft.pkgName} · reserved</Eyebrow>
          <h1 className="serif co-draft-h">You're booked in.</h1>
          <p className="co-draft-sub">Your package is reserved with its fixed base price. We'll confirm the finer details from your brief.</p>
          <div className="co-draft-card">
            <div className="co-draft-row"><span>Reference</span><strong className="mono">{draft.ref}</strong></div>
            <div className="co-draft-row"><span>Package</span><strong>{draft.pkgName}</strong></div>
            <div className="co-draft-row"><span>Base price</span><strong>{fmtNGN(draft.base)}</strong></div>
            <div className="co-draft-row"><span>Status</span><strong className="co-pill">Confirmed · invoice ready</strong></div>
          </div>
          <div className="co-draft-actions">
            <Btn variant="ghost" arrow={false} onClick={() => { setDraft(null); setActive(null); }}>Back to packages</Btn>
            <Btn arrow={false} onClick={() => onNav("invoice", { ref: draft.ref, pkg: draft.pkgId })}>Go to invoice</Btn>
          </div>
        </div>
      </div>
    );
  }

  if (pkg) {
    return (
      <div className="fade-page page-shell">
        <div className="wrap-wide">
          <div className="crumb"><button onClick={() => setActive(null)}>Packages</button> / <span>{pkg.name}</span></div>
          <div className="pkg-intake-grid">
            <aside className="pkg-intake-summary">
              <div className="pkg-mini-media"><Ph label={pkg.label} ratio="portrait" /></div>
              <h2 className="serif pkg-mini-name">{pkg.name}</h2>
              <div className="pkg-mini-price">{fmtNGN(pkg.base)} <span>base</span></div>
              <ul className="pkg-mini-list">
                {pkg.deliverables.map((d) => <li key={d}><Icon name="check" size={14} /> <span>{d}</span></li>)}
              </ul>
              <div className="pkg-mini-lead"><Icon name="truck" size={16} /> Lead time {pkg.lead}</div>
            </aside>
            <div className="co-form">
              <IntakeEngine context={pkg.name} submitLabel={`Reserve — ${fmtNGN(pkg.base)} base`}
                onSubmit={(payload) => { window.scrollTo({ top: 0 }); setDraft({ ...payload, pkgName: pkg.name, pkgId: pkg.id, base: pkg.base }); }} />
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="fade-page">
      <section className="bespoke-hero">
        <Ph label="COLLECTION · BRIDAL" ratio="cinema" className="about-hero-bg" />
        <div className="about-hero-ov" />
        <div className="wrap about-hero-content">
          <Eyebrow style={{ color: "#e9c97a" }}>Packages</Eyebrow>
          <h1 className="serif about-hero-h">Couture, simplified.</h1>
          <p className="lede on-img" style={{ maxWidth: "46ch", marginTop: 16 }}>
            Fixed-price service packages with everything defined upfront — built on the same couture intake,
            so every piece is still made to you.
          </p>
        </div>
      </section>

      <section className="section-pad">
        <div className="wrap-wide">
          <div className="pkg-grid">
            {RB_PACKAGES.map((p, i) => (
              <Reveal key={p.id} delay={i % 3 + 1}>
                <div className={"pkg-card" + (p.featured ? " featured" : "")}>
                  {p.featured && <span className="pkg-badge">Most booked</span>}
                  <div className="pkg-media"><Ph label={p.label} ratio="wide" /></div>
                  <div className="pkg-body">
                    <h3 className="serif pkg-name">{p.name}</h3>
                    <p className="pkg-blurb">{p.blurb}</p>
                    <div className="pkg-price">{fmtNGN(p.base)} <span>base price</span></div>
                    <ul className="pkg-list">
                      {p.deliverables.map((d) => <li key={d}><Icon name="check" size={14} /> <span>{d}</span></li>)}
                    </ul>
                    <div className="pkg-lead mono">Lead time · {p.lead}</div>
                    <Btn block arrow={false} variant={p.featured ? undefined : "ghost"} onClick={() => { window.scrollTo({ top: 0 }); setActive(p.id); }}>
                      Start this package
                    </Btn>
                  </div>
                </div>
              </Reveal>
            ))}
          </div>
          <div className="pkg-custom-band">
            <div>
              <h3 className="serif">Need something entirely your own?</h3>
              <p>Custom Orders are open-ended — no fixed price, no template. Just your vision.</p>
            </div>
            <Btn arrow={false} onClick={() => onNav("custom", {})}>Start a custom order</Btn>
          </div>
        </div>
      </section>
    </div>
  );
}

/* ───────────────────────────────────────────────────────────
   BOOKING SERVICE  (standalone)
   ─────────────────────────────────────────────────────────── */
function BookingPage({ onNav }) {
  const [held, setHeld] = useState(null);
  return (
    <div className="fade-page">
      <section className="bespoke-hero">
        <Ph label="ATELIER · THE FITTING ROOM" ratio="cinema" className="about-hero-bg" />
        <div className="about-hero-ov" />
        <div className="wrap about-hero-content">
          <Eyebrow style={{ color: "#e9c97a" }}>Booking</Eyebrow>
          <h1 className="serif about-hero-h">Reserve your fitting.</h1>
          <p className="lede on-img" style={{ maxWidth: "46ch", marginTop: 16 }}>
            Live availability across our Port Harcourt studio, Lagos suite and virtual studio — slots held
            instantly, synced to your designer's calendar.
          </p>
        </div>
      </section>

      <section className="section-pad">
        <div className="wrap-wide booking-grid">
          <div className="booking-main">
            <Eyebrow line>Choose a time</Eyebrow>
            <BookingWidget onHeld={setHeld} />
          </div>
          <aside className="booking-aside">
            <div className="booking-info">
              <Icon name="globe" size={20} />
              <div><strong>Three ways to meet</strong><p>Virtual from anywhere, or in person at our Port Harcourt studio and Lagos suite.</p></div>
            </div>
            <div className="booking-info">
              <Icon name="ruler" size={20} />
              <div><strong>What to expect</strong><p>Measurements, fabric selection and design direction — about 45 minutes.</p></div>
            </div>
            <div className="booking-info">
              <Icon name="swap" size={20} />
              <div><strong>Flexible</strong><p>Reschedule any time up to 24 hours before. Your hold is free.</p></div>
            </div>
            {held && (
              <Btn block arrow={false} onClick={() => onNav("custom", {})} style={{ marginTop: 8 }}>
                Add your brief →
              </Btn>
            )}
          </aside>
        </div>
      </section>
    </div>
  );
}

/* ───────────────────────────────────────────────────────────
   PERSONALISED INVOICE  (magic-link style)
   ─────────────────────────────────────────────────────────── */
function InvoicePage({ onNav, route }) {
  const ref = (route && route.params && route.params.ref) || genRef();
  const pkgId = route && route.params && route.params.pkg;
  const pkg = pkgId && RB_PACKAGES.find((p) => p.id === pkgId);

  const lines = pkg
    ? [[pkg.name + " — base", pkg.base], ["Bespoke fittings (3)", 0], ["Premium beadwork upgrade", 120000]]
    : [["Bespoke bridal gown", 950000], ["Cathedral veil & styling", 65000], ["Asoebi coordination (6)", 210000], ["Crystal & coral beadwork", 80000]];
  const subtotal = lines.reduce((s, [, v]) => s + v, 0);
  const vat = Math.round(subtotal * 0.075);
  const total = subtotal + vat;
  const deposit = Math.round(total / 2);

  const [secs, setSecs] = useState(47 * 3600 + 59 * 60);
  useEffect(() => { const t = setInterval(() => setSecs((s) => (s > 0 ? s - 1 : 0)), 1000); return () => clearInterval(t); }, []);
  const h = Math.floor(secs / 3600), m = Math.floor((secs % 3600) / 60);

  return (
    <div className="fade-page page-shell">
      <div className="wrap-wide">
        <div className="crumb"><button onClick={() => onNav("home", {})}>Home</button> / <span>Invoice {ref}</span></div>
        <div className="inv-grid">
          <div>
            <Eyebrow>Personalised invoice</Eyebrow>
            <h1 className="serif page-h">Your proposal.</h1>
            <p className="inv-meta">Reference <strong className="mono">{ref}</strong> · Prepared exclusively for you</p>

            <div className="inv-client">
              <div><span>Client</span><strong>Adaeze Okafor</strong></div>
              <div><span>Occasion</span><strong>White Wedding · Port Harcourt</strong></div>
              <div><span>Lead time</span><strong>{pkg ? pkg.lead : "12–16 weeks"}</strong></div>
            </div>

            <div className="inv-deliv-h">Deliverables</div>
            <div className="inv-lines">
              {lines.map(([name, val]) => (
                <div className="inv-line" key={name}>
                  <span className="inv-line-c"><Icon name="check" size={14} /></span>
                  <span className="inv-line-n">{name}</span>
                  <span className="inv-line-v">{val === 0 ? "Included" : fmtNGN(val)}</span>
                </div>
              ))}
            </div>
            <div className="inv-notes">
              <strong>Studio notes</strong>
              Fabric samples ship before production. A second fitting is scheduled at the 6-week mark.
            </div>
          </div>

          <aside className="inv-side">
            <div className="inv-card">
              <div className="inv-card-h">Payment summary</div>
              <div className="inv-card-b">
                <div className="inv-srow"><span>Subtotal</span><span>{fmtNGN(subtotal)}</span></div>
                <div className="inv-srow"><span>VAT (7.5%)</span><span>{fmtNGN(vat)}</span></div>
                <div className="inv-div"></div>
                <div className="inv-srow inv-total"><span>Total</span><span className="serif">{fmtNGN(total)}</span></div>
                <div className="inv-srow inv-dep"><span>50% deposit today</span><span>{fmtNGN(deposit)}</span></div>
              </div>
              <div className="inv-card-f">
                <button className="inv-pay" onClick={() => onNav("checkout", {})}>
                  <Icon name="shield" size={15} /> Pay deposit — {fmtNGN(deposit)}
                </button>
                <p className="inv-secure">Secured by Paystack · SSL encrypted</p>
              </div>
              <div className="inv-expiry">Invoice expires in <span>{h}:{String(m).padStart(2, "0")}</span></div>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CustomOrderPage, PackagesPage, BookingPage, InvoicePage, RB_PACKAGES });
