/* Finance Family — Lead capture & booking flow.
   Flow:  pick service → qualifying questions (per service) → contact + consent
          → availability picker (real Outlook slots via Graph) → confirmation.
   The tile click already tells us the loan purpose, so we never re-ask it —
   we only ask what decides WHICH broker pool, then resolve a single pool and
   show that broker's availability.  See Website_Lead_Flow_Design_Brief.md. */
(function () {
  const DAYNAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

  /* Universal credit-history layer (sub-flag). Adverse credit is the single
     biggest constraint on which lender will say yes, so a "Yes / not sure"
     answer overrides the niche routing and sends the lead to the credit-repair
     pool on the property tiles (see resolvePool). Asked on every tile; on
     asset/business/SMSF it's captured as a flag for the specialist. */
  const CREDIT_Q = {
    key: "credit",
    q: "Any bad credit or late repayments we should know about?",
    opts: ["No, all good", "Yes, or not sure"],
    note: { "Yes, or not sure": "No judgement — we work with lenders who specialise in exactly this. We'll pair you with a broker who knows how to sort it." },
  };

  /* ---- Qualifying questions per service (single-tap only, no free text) ---- */
  const QUESTIONS = {
    buying: [
      { key: "firstHome", q: "Is this your first home?", opts: ["Yes", "No"] },
      { key: "income", q: "How's your income structured?", opts: ["Employee (PAYG)", "Self-employed"] },
      { key: "build", q: "Buying established, or building new?", opts: ["Buying established", "Building new"] },
      CREDIT_Q,
    ],
    refinance: [
      { key: "income", q: "How's your income structured?", opts: ["Employee (PAYG)", "Self-employed"] },
      { key: "debt", q: "Also consolidating debt or accessing equity?", opts: ["Yes", "No"] },
      CREDIT_Q,
    ],
    investment: [
      { key: "firstInvestment", q: "Is this your first investment property?", opts: ["Yes", "No"] },
      { key: "income", q: "How's your income structured?", opts: ["Employee (PAYG)", "Self-employed"] },
      CREDIT_Q,
    ],
    construction: [
      { key: "income", q: "How's your income structured?", opts: ["Employee (PAYG)", "Self-employed"] },
      { key: "buildType", q: "What kind of build?", opts: ["House & land", "Knockdown-rebuild", "Custom build"], optional: true },
      CREDIT_Q,
    ],
    asset: [
      { key: "use", q: "What's it for?", opts: ["Personal", "Business"] },
      CREDIT_Q,
    ],
    business: [
      { key: "purpose", q: "What's the funding for?", opts: ["Cashflow", "Expansion", "Commercial property"] },
      CREDIT_Q,
    ],
    smsf: [
      { key: "smsfSetup", q: "Do you already have an SMSF set up?", opts: ["Yes", "Not yet"], note: { "Not yet": "No problem — note that setting up the SMSF is a prerequisite, and your specialist will walk you through it." } },
      { key: "income", q: "How's your income structured?", opts: ["Employee (PAYG)", "Self-employed"] },
      CREDIT_Q,
    ],
  };

  /* ---- Broker pools — round-robin order = priority order ---- */
  const POOLS = {
    // Buying — first home, PAYG
    POOL_FHB:              { label: "First-home-buyer specialist",       brokers: ["niki","samantha","patricia","mary-ann","sam"] },
    // Buying/refinance/investment — self-employed (all SE routes collapse here)
    POOL_SELF_EMPLOYED:    { label: "Self-employed lending specialist",   brokers: ["steven","niki","tony","samantha"] },
    // Buying — next home, PAYG | Refinancing — PAYG (all residential)
    POOL_RESIDENTIAL:      { label: "Residential lending specialist",     brokers: ["niki","samantha","patricia","mary-ann","sam","tony","steven"] },
    // Refinancing — debt consolidation
    POOL_DEBT_CONSOLIDATION:{ label: "Debt-consolidation specialist",     brokers: ["sam","steven","samantha","niki","tony"] },
    // Adverse credit — any residential tile
    POOL_ADVERSE_CREDIT:   { label: "Credit-repair lending specialist",   brokers: ["sam","steven","samantha","niki","tony"] },
    // Investment — first investment, PAYG (same pool as FHB PAYG)
    POOL_FIRST_INVESTOR:   { label: "First-time-investor specialist",     brokers: ["niki","samantha","patricia","mary-ann","sam"] },
    // Investment — returning investor, PAYG
    POOL_INVESTMENT:       { label: "Investment lending specialist",      brokers: ["niki","samantha","patricia","mary-ann","sam"] },
    // Construction — PAYG
    POOL_CONSTRUCTION:     { label: "Construction finance specialist",    brokers: ["mary-ann","niki","samantha","patricia"] },
    // Construction — self-employed
    POOL_CONSTRUCTION_SE:  { label: "Construction finance specialist",    brokers: ["steven","niki","tony","samantha"] },
    // Car & asset finance
    POOL_ASSET_FINANCE:    { label: "Asset finance specialist",           brokers: ["tony"] },
    // Business loans
    POOL_BUSINESS:         { label: "Business lending specialist",        brokers: ["steven","tony","niki"] },
    // SMSF — PAYG
    POOL_SMSF:             { label: "SMSF lending specialist",            brokers: ["niki","samantha"] },
    // SMSF — self-employed
    POOL_SMSF_SE:          { label: "SMSF lending specialist",            brokers: ["steven","tony"] },
  };

  // Open decision (configurable): does self-employed complexity win over the
  // FHB / investor niches?  Flip to false to let those pools handle their own.
  const SELF_EMPLOYED_PRECEDENCE = true;
  const isSelfEmployed = (a) => (a.income || "").indexOf("Self") === 0;
  const hasAdverseCredit = (a) => (a.credit || "").indexOf("Yes") === 0;

  function resolvePool(purpose, a) {
    // Overlap rule: "Buying a home" + "Building new" re-routes to construction.
    if (purpose === "buying" && a.build === "Building new") purpose = "construction";
    // Adverse credit wins precedence on the residential/property tiles — it's the
    // biggest lender constraint there, so it overrides the FHB / self-employed /
    // investor niches and goes to credit-repair. On asset/business/SMSF it stays
    // with the domain specialist and rides along as a captured sub-flag instead.
    const RESIDENTIAL = ["buying", "refinance", "investment", "construction"];
    if (hasAdverseCredit(a) && RESIDENTIAL.indexOf(purpose) !== -1) return "POOL_ADVERSE_CREDIT";
    const se = isSelfEmployed(a);
    switch (purpose) {
      case "buying":
        if (a.firstHome === "Yes") return se && SELF_EMPLOYED_PRECEDENCE ? "POOL_SELF_EMPLOYED" : "POOL_FHB";
        return se && SELF_EMPLOYED_PRECEDENCE ? "POOL_SELF_EMPLOYED" : "POOL_RESIDENTIAL";
      case "refinance":
        if (a.debt === "Yes") return "POOL_DEBT_CONSOLIDATION";
        return se ? "POOL_SELF_EMPLOYED" : "POOL_RESIDENTIAL";
      case "investment":
        if (se && SELF_EMPLOYED_PRECEDENCE) return "POOL_SELF_EMPLOYED";
        return a.firstInvestment === "Yes" ? "POOL_FIRST_INVESTOR" : "POOL_INVESTMENT";
      case "construction": return se ? "POOL_CONSTRUCTION_SE" : "POOL_CONSTRUCTION";
      case "asset": return "POOL_ASSET_FINANCE";
      case "business": return "POOL_BUSINESS";
      case "smsf": return se ? "POOL_SMSF_SE" : "POOL_SMSF";
      default: return "POOL_RESIDENTIAL";
    }
  }

  // Stand-in broker for the mockup. Live: backend round-robins the resolved
  // pool (membership read from the Notion directory) and reads real Outlook
  // free/busy via Microsoft Graph getSchedule.
  function brokerForPool(pool) {
    const i = Object.keys(POOLS).indexOf(pool);
    return window.FF_BROKERS[(i + 1) % window.FF_BROKERS.length];
  }

  function buildAvailability() {
    const pool = ["9:00 AM", "9:30 AM", "10:30 AM", "11:30 AM", "1:00 PM", "2:00 PM", "3:00 PM", "4:30 PM"];
    const out = []; const d = new Date(); d.setHours(0, 0, 0, 0);
    while (out.length < 6) {
      d.setDate(d.getDate() + 1);
      const wd = d.getDay(); if (wd === 0 || wd === 6) continue;
      const start = (out.length * 3) % pool.length;
      const slots = [];
      for (let i = 0; i < 4; i++) slots.push(pool[(start + i) % pool.length]);
      const uniq = [...new Set(slots)].sort((a, b) => pool.indexOf(a) - pool.indexOf(b));
      out.push({ date: new Date(d), slots: uniq });
    }
    return out;
  }

  function Book() {
    const { Button, Input, Checkbox, Card, Badge } = window.FinanceFamilyDesignSystem_66efc3;
    const Icon = window.Icon;

    const initialPurpose = React.useMemo(() => {
      const p = new URLSearchParams(window.location.search).get("purpose");
      return QUESTIONS[p] ? p : null;
    }, []);

    const [purpose, setPurpose] = React.useState(initialPurpose);
    const [stage, setStage] = React.useState(initialPurpose ? "qualify" : "pick");
    const [answers, setAnswers] = React.useState({});
    const [info, setInfo] = React.useState({ name: "", email: "", phone: "" });
    const [consent, setConsent] = React.useState(false);
    const [touched, setTouched] = React.useState({});
    const [slot, setSlot] = React.useState(null); // { dayIdx, time }
    const avail = React.useMemo(buildAvailability, []);

    const service = window.FF_SERVICES.find((s) => s.id === purpose);
    const qs = purpose ? QUESTIONS[purpose] : [];
    const setAnswer = (k, v) => setAnswers((s) => ({ ...s, [k]: v }));
    const set = (k, v) => setInfo((s) => ({ ...s, [k]: v }));
    const touch = (k) => setTouched((s) => ({ ...s, [k]: true }));

    // progressive reveal: show question i once all prior REQUIRED ones answered
    const visibleCount = (() => {
      let n = 1;
      for (let i = 0; i < qs.length - 1; i++) {
        if (qs[i].optional || answers[qs[i].key]) n = i + 2; else break;
      }
      return Math.min(n, qs.length);
    })();
    const qualifyDone = qs.every((q) => q.optional || answers[q.key]);

    const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(info.email);
    const phoneOk = info.phone.replace(/\D/g, "").length >= 10;
    const nameOk = info.name.trim().length > 1;
    const contactDone = nameOk && emailOk && phoneOk && consent;

    const pool = React.useMemo(() => (purpose ? resolvePool(purpose, answers) : null), [purpose, answers, stage]);
    const broker = React.useMemo(() => (pool ? brokerForPool(pool) : null), [pool]);
    const poolLabel = pool ? POOLS[pool] : "";

    const fmtDay = (d) => `${DAYNAMES[d.getDay()]} ${d.getDate()} ${MONTHS[d.getMonth()]}`;
    const STEPS = ["A few quick questions", "Your details", "Pick a time"];
    const stepNum = { qualify: 1, contact: 2, time: 3 }[stage] || 0;

    function pickService(id) { setPurpose(id); setAnswers({}); setSlot(null); setStage("qualify"); }
    function goConfirm() {
      /* BACKEND HANDOFF: POST /api/leads → resolve pool from Notion directory,
         round-robin a broker, create the Microsoft Graph calendar event on their
         Outlook + invite the visitor, with answers in the event body. */
      setStage("done");
    }

    /* ---------- small presentational helpers ---------- */
    const SegGroup = ({ q }) => (
      <div style={{ marginBottom: 22 }}>
        <div style={{ fontFamily: "var(--font-body)", fontSize: 15, fontWeight: 600, color: "var(--text-strong)", marginBottom: 10 }}>
          {q.q}{q.optional && <span style={{ color: "var(--text-faint)", fontWeight: 500 }}> · optional</span>}
        </div>
        <div className="row wrap" style={{ gap: 10 }}>
          {q.opts.map((o) => {
            const on = answers[q.key] === o;
            return (
              <button key={o} onClick={() => setAnswer(q.key, o)} style={{
                cursor: "pointer", padding: "11px 18px", borderRadius: "var(--radius-pill)",
                border: `1.5px solid ${on ? "var(--brand-primary)" : "var(--border-subtle)"}`,
                background: on ? "var(--blue-10)" : "#fff", color: on ? "var(--blue-deep)" : "var(--text-body)",
                fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 14.5, transition: "all var(--dur) var(--ease-out)",
              }}>{o}</button>
            );
          })}
        </div>
        {q.note && answers[q.key] && q.note[answers[q.key]] && (
          <p style={{ margin: "10px 2px 0", fontFamily: "var(--font-body)", fontSize: 13.5, color: "var(--text-muted)", maxWidth: 460 }}>{q.note[answers[q.key]]}</p>
        )}
      </div>
    );

    const MatchBanner = () => (
      <div className="row" style={{ gap: 14, padding: "14px 16px", borderRadius: "var(--radius-lg)", background: "var(--blue-10)", border: "1.5px solid var(--blue-20)", marginBottom: 22 }}>
        <window.PhotoAvatar name={broker.name} src={broker.photo} tone={broker.tone} size={46} />
        <div style={{ flex: 1 }}>
          <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
            <span style={{ fontFamily: "var(--font-display)", fontSize: 16, color: "var(--text-strong)" }}>Matched with {broker.name}</span>
            <Badge color="blue" size="sm">{poolLabel}</Badge>
          </div>
          <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "var(--text-muted)", marginTop: 2 }}>Times below are this broker's real, open Outlook slots.</div>
        </div>
      </div>
    );

    return (
      <React.Fragment>
        <window.SiteHeader page="book" />
        <main>
          <section style={{ background: "linear-gradient(180deg,var(--grey-40),#fff)" }}>
            <div className="container" style={{ paddingTop: "clamp(44px,4vw,68px)", paddingBottom: 30, textAlign: "center" }}>
              <window.Eyebrow>Talk to a specialist</window.Eyebrow>
              <h1 className="ff-display" style={{ fontSize: "clamp(2rem,1.5rem+2.6vw,3rem)", lineHeight: 1.12, margin: "16px auto 14px", maxWidth: 720 }}>
                {stage === "pick" ? "What can we help you with?" : service ? service.t.replace(/s$/, "") + " — let's match you" : "Let's match you with the right broker"}
              </h1>
              <p className="ff-lead muted" style={{ maxWidth: 540, margin: "0 auto" }}>
                {stage === "pick"
                  ? "Pick what you're financing. A few quick taps and we'll match you with the specialist who's done it a hundred times."
                  : "A couple of quick questions so the right specialist — not just any broker — picks up your enquiry. Takes under a minute."}
              </p>
            </div>
          </section>

          <section className="section" style={{ paddingTop: 0 }}>
            <div className="container" style={{ maxWidth: stage === "pick" ? 1080 : 760 }}>

              {/* step indicator */}
              {stepNum > 0 && (
                <div style={{ display: "flex", gap: 10, marginBottom: 26 }}>
                  {STEPS.map((s, i) => {
                    const n = i + 1, on = n === stepNum, done = n < stepNum;
                    return (
                      <div key={s} style={{ flex: 1, display: "flex", flexDirection: "column", gap: 8 }}>
                        <div style={{ height: 6, borderRadius: 999, background: done || on ? "var(--brand-primary)" : "var(--grey-60)" }} />
                        <span style={{ fontFamily: "var(--font-body)", fontSize: 12.5, fontWeight: on ? 700 : 500, color: on ? "var(--text-strong)" : "var(--text-muted)" }}>{n}. {s}</span>
                      </div>
                    );
                  })}
                </div>
              )}

              {/* ---------- STAGE: pick service ---------- */}
              {stage === "pick" && (
                <div className="grid grid-3">
                  {window.FF_SERVICES.map((s) => (
                    <Card key={s.id} interactive padding="lg" as="button" onClick={() => pickService(s.id)}
                      style={{ height: "100%", display: "flex", flexDirection: "column", textAlign: "left", cursor: "pointer", border: "1.5px solid var(--border-subtle)", background: "#fff" }}>
                      <div className="row" style={{ justifyContent: "space-between", marginBottom: 16 }}>
                        <span style={{ width: 52, height: 52, borderRadius: "var(--radius-md)", background: "var(--blue-10)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                          <Icon name={s.ic} size={25} color="var(--brand-primary)" />
                        </span>
                        {s.tag && <Badge color="mint">{s.tag}</Badge>}
                      </div>
                      <h3 className="ff-h4" style={{ marginBottom: 6 }}>{s.t}</h3>
                      <p className="ff-body" style={{ fontSize: 14, color: "var(--text-muted)", flex: 1, marginBottom: 14 }}>{s.d}</p>
                      <span className="link-arrow">Start <Icon name="arrowRight" size={16} color="var(--brand-primary)" /></span>
                    </Card>
                  ))}
                </div>
              )}

              {/* ---------- STAGE: qualify ---------- */}
              {stage === "qualify" && service && (
                <Card padding="lg">
                  <div className="row" style={{ gap: 12, marginBottom: 20 }}>
                    <span style={{ width: 44, height: 44, borderRadius: "var(--radius-md)", background: "var(--blue-10)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
                      <Icon name={service.ic} size={22} color="var(--brand-primary)" />
                    </span>
                    <div>
                      <div style={{ fontFamily: "var(--font-display)", fontSize: 17, color: "var(--text-strong)" }}>{service.t}</div>
                      <button onClick={() => setStage("pick")} style={{ border: "none", background: "none", padding: 0, cursor: "pointer", fontFamily: "var(--font-body)", fontSize: 13, color: "var(--brand-primary)", fontWeight: 600 }}>Change</button>
                    </div>
                  </div>
                  {qs.slice(0, visibleCount).map((q) => <SegGroup key={q.key} q={q} />)}
                  <div className="row gap-sm" style={{ marginTop: 8 }}>
                    <Button variant="outline" onClick={() => setStage("pick")}>Back</Button>
                    <Button block disabled={!qualifyDone} onClick={() => setStage("contact")} iconRight={<Icon name="arrowRight" size={18} />}>Continue</Button>
                  </div>
                </Card>
              )}

              {/* ---------- STAGE: contact + consent ---------- */}
              {stage === "contact" && (
                <Card padding="lg">
                  <h2 className="ff-h3" style={{ marginBottom: 6 }}>Where can we reach you?</h2>
                  <p className="ff-body muted" style={{ marginBottom: 20, fontSize: 14.5 }}>Just the basics to book you in — your specialist captures everything else on the call.</p>
                  <div className="stack" style={{ gap: 16 }}>
                    <Input label="Full name" placeholder="Jordan Smith" value={info.name} onChange={(e) => set("name", e.target.value)} />
                    <div className="calc-row2">
                      <Input label="Mobile" type="tel" iconLeft={<Icon name="phone" size={18} />} placeholder="0400 000 000" value={info.phone} onChange={(e) => set("phone", e.target.value)} onBlur={() => touch("phone")} error={touched.phone && !phoneOk ? "Enter a valid mobile number" : undefined} />
                      <Input label="Email" type="email" iconLeft={<Icon name="mail" size={18} />} placeholder="you@email.com.au" value={info.email} onChange={(e) => set("email", e.target.value)} onBlur={() => touch("email")} error={touched.email && !emailOk ? "Enter a valid email" : undefined} />
                    </div>
                    <div style={{ padding: "4px 2px" }}>
                      <Checkbox checked={consent} onChange={(e) => setConsent(e.target.checked)}
                        label={<span style={{ fontSize: 13.5, color: "var(--text-muted)", lineHeight: 1.5 }}>I agree to be contacted about my enquiry and to The Finance Family collecting my details per its Privacy Policy. <span style={{ color: "var(--text-faint)" }}>[CONSENT_COPY — final wording pending compliance sign-off]</span></span>} />
                    </div>
                  </div>
                  <div className="row gap-sm" style={{ marginTop: 24 }}>
                    <Button variant="outline" onClick={() => setStage("qualify")}>Back</Button>
                    <Button block disabled={!contactDone} onClick={() => setStage("time")} iconRight={<Icon name="arrowRight" size={18} />}>See available times</Button>
                  </div>
                </Card>
              )}

              {/* ---------- STAGE: availability picker ---------- */}
              {stage === "time" && broker && (
                <Card padding="lg">
                  <MatchBanner />
                  <h2 className="ff-h4" style={{ marginBottom: 4 }}>Pick a time that suits</h2>
                  <p className="ff-body muted" style={{ marginBottom: 18, fontSize: 14 }}>A relaxed 20-minute chat — phone, video or in person at Berwick.</p>
                  <div className="stack" style={{ gap: 20 }}>
                    {avail.map((d, di) => (
                      <div key={di}>
                        <div style={{ fontFamily: "var(--font-body)", fontSize: 13, fontWeight: 700, color: "var(--text-strong)", marginBottom: 9 }}>{fmtDay(d.date)}</div>
                        <div className="book-times">
                          {d.slots.map((t) => {
                            const on = slot && slot.dayIdx === di && slot.time === t;
                            return (
                              <button key={t} onClick={() => setSlot({ dayIdx: di, time: t })} style={{ cursor: "pointer", padding: "11px 8px", borderRadius: "var(--radius-pill)", border: `1.5px solid ${on ? "var(--brand-primary)" : "var(--border-subtle)"}`, background: on ? "var(--blue-10)" : "#fff", color: on ? "var(--blue-deep)" : "var(--text-body)", fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 14, transition: "all var(--dur) var(--ease-out)" }}>{t}</button>
                            );
                          })}
                        </div>
                      </div>
                    ))}
                  </div>
                  <div className="row gap-sm" style={{ marginTop: 26 }}>
                    <Button variant="outline" onClick={() => setStage("contact")}>Back</Button>
                    <Button block disabled={!slot} onClick={goConfirm} iconRight={<Icon name="checkCircle" size={18} />}>Confirm booking</Button>
                  </div>
                  <button onClick={() => setStage("fallback")} style={{ display: "block", margin: "16px auto 0", border: "none", background: "none", cursor: "pointer", fontFamily: "var(--font-body)", fontSize: 13.5, color: "var(--brand-primary)", fontWeight: 600 }}>None of these work? Have us call you instead →</button>
                </Card>
              )}

              {/* ---------- STAGE: confirmation ---------- */}
              {stage === "done" && (
                <Card padding="lg">
                  <div style={{ textAlign: "center", padding: "8px 0 4px" }}>
                    <span style={{ width: 78, height: 78, borderRadius: "50%", background: "var(--mint-10)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 18 }}>
                      <Icon name="checkCircle" size={40} color="var(--mint-shade)" />
                    </span>
                    <h2 className="ff-h2" style={{ marginBottom: 10 }}>You're booked in 🎉</h2>
                    <p className="ff-lead muted" style={{ maxWidth: 480, margin: "0 auto 24px" }}>
                      A calendar invite is on its way to {info.email || "your inbox"}. {broker ? broker.name.split(" ")[0] : "Your specialist"} will call you then with your answers already in hand.
                    </p>
                  </div>
                  <div style={{ maxWidth: 460, margin: "0 auto", textAlign: "left", border: "1.5px solid var(--border-subtle)", borderRadius: "var(--radius-lg)", padding: 22, background: "var(--surface-subtle)" }}>
                    {[["users", broker ? `${broker.name} · ${poolLabel}` : poolLabel], ["clock", slot ? `${fmtDay(avail[slot.dayIdx].date)} · ${slot.time}` : ""], ["fileText", service ? service.t : ""]].map(([ic, v]) => v && (
                      <div key={ic} className="row" style={{ gap: 12, padding: "7px 0" }}>
                        <Icon name={ic} size={18} color="var(--brand-primary)" />
                        <span style={{ fontFamily: "var(--font-body)", fontSize: 15, color: "var(--text-strong)" }}>{v}</span>
                      </div>
                    ))}
                    {qs.filter((q) => answers[q.key]).length > 0 && (
                      <div style={{ marginTop: 6, paddingTop: 12, borderTop: "1.5px dashed var(--border-subtle)", display: "flex", flexWrap: "wrap", gap: 8 }}>
                        {qs.filter((q) => answers[q.key]).map((q) => (
                          <span key={q.key} style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: "var(--text-muted)", background: "#fff", border: "1.5px solid var(--border-subtle)", borderRadius: "var(--radius-pill)", padding: "4px 11px" }}>{answers[q.key]}</span>
                        ))}
                      </div>
                    )}
                  </div>
                  <div className="center" style={{ marginTop: 26 }}>
                    <a href="/" style={{ textDecoration: "none" }}><Button variant="outline">Back to home</Button></a>
                  </div>
                </Card>
              )}

              {/* ---------- STAGE: fallback (no slot taken / none suitable) ---------- */}
              {stage === "fallback" && (
                <Card padding="lg">
                  <div style={{ textAlign: "center", padding: "8px 0 4px" }}>
                    <span style={{ width: 78, height: 78, borderRadius: "50%", background: "var(--blue-10)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 18 }}>
                      <Icon name="phone" size={36} color="var(--brand-primary)" />
                    </span>
                    <h2 className="ff-h2" style={{ marginBottom: 10 }}>We'll call you to book</h2>
                    <p className="ff-lead muted" style={{ maxWidth: 480, margin: "0 auto 24px" }}>
                      Got it — we have your details and a {poolLabel.toLowerCase()} will be in touch on {info.phone || "your mobile"} to lock in a time that actually works for you.
                    </p>
                  </div>
                  <div className="row gap-sm center" style={{ justifyContent: "center" }}>
                    <Button variant="outline" onClick={() => setStage("time")}>See times again</Button>
                    <a href="/" style={{ textDecoration: "none" }}><Button>Back to home</Button></a>
                  </div>
                </Card>
              )}

            </div>
          </section>
        </main>
        <window.SiteFooter />
      </React.Fragment>
    );
  }
  window.Book = Book;
})();
