/* ============================================================
   KAY FASHION — Service features built on the shared engine
     · CustomOrderPage  — open-ended intake → draft → invoice
     · 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 atelier 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>
            {draft.inspiration && draft.inspiration.length > 0 && (
              <div className="co-draft-row">
                <span>Inspiration</span><strong>{draft.inspiration.join(", ")}</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"], ["Atelier 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 · WORKSHOP" 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">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 stylist, synced to the atelier 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>
  );
}

/* ───────────────────────────────────────────────────────────
   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: "var(--accent-bright)" }}>Booking</Eyebrow>
          <h1 className="serif about-hero-h">Reserve your appointment.</h1>
          <p className="lede on-img" style={{ maxWidth: "46ch", marginTop: 16 }}>
            Kay Fashion is appointment-only. Live availability across our Abuja atelier and virtual studio —
            slots held instantly, synced to your tailor'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>Two ways to meet</strong><p>Virtual from anywhere, or in person at our Abuja atelier.</p></div>
            </div>
            <div className="booking-info">
              <Icon name="ruler" size={20} />
              <div><strong>What to expect</strong><p>Measurements, fabric selection and embroidery 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 lines = [["Gold-embroidered bespoke agbada", 520000], ["Fittings (3)", 0], ["Premium gold-thread upgrade", 120000]];
  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>Occasion</span><strong>Traditional Wedding</strong></div>
              <div><span>Lead time</span><strong>8–10 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>Atelier 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, BookingPage, InvoicePage });
