/* global React, useRoute, useToast, Placeholder, I, SERVICES */
const { useState, useEffect, useMemo } = React;

/* ─────────────────────────────────────────────────────────────────
   Booking flow.
   Two visual variants, switchable via Tweaks:
     - 'stepped'    : classic 5-step sidebar wizard (default)
     - 'editorial'  : long-scroll, magazine-style single page
   ───────────────────────────────────────────────────────────────── */

function buildMonth(year, month) {
  const first = new Date(year, month, 1);
  const dim = new Date(year, month + 1, 0).getDate();
  const startDow = first.getDay();
  const cells = [];
  for (let i = 0; i < startDow; i++) cells.push(null);
  for (let d = 1; d <= dim; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);
  return cells;
}

const TIMES = ["09:00", "10:30", "12:00", "14:00", "15:30", "17:00"];

function StepDots({ idx, count }) {
  return (
    <div style={{ display: "flex", gap: 6 }}>
      {Array.from({ length: count }, (_, i) => (
        <span key={i} style={{
          width: i === idx ? 24 : 6, height: 6, borderRadius: 3,
          background: i <= idx ? "var(--gold)" : "var(--border-2)",
          transition: "all 280ms ease",
        }} />
      ))}
    </div>
  );
}

/* ─── Step components (shared by both variants) ─────────────────── */

function StepService({ value, onChange }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      {Object.values(SERVICES).map((s, i) => {
        const selected = value === s.key;
        return (
          <button key={s.key} onClick={() => onChange(s.key)}
            style={{
              position: "relative",
              textAlign: "left",
              padding: "22px 28px 22px 22px",
              background: selected ? "linear-gradient(180deg, rgba(255,204,83,0.06), rgba(255,204,83,0.01))" : "#0a0a0a",
              border: `1px solid ${selected ? "var(--gold)" : "var(--border)"}`,
              borderRadius: 12,
              color: "inherit",
              cursor: "pointer",
              display: "grid",
              gridTemplateColumns: "160px 1fr auto",
              gap: 28,
              alignItems: "center",
              transition: "all 200ms",
            }}>
            {(() => {
              const ms = window.MEDIA?.home?.services?.[s.key];
              return (
                <Placeholder
                  label={s.name.toLowerCase()}
                  variant={i === 0 ? "warm" : i === 1 ? "deep" : "cool"}
                  src={ms?.kind === "image" ? ms.file : undefined}
                  video={ms?.kind === "video" ? ms.file : undefined}
                  poster={ms?.kind === "video" ? ms.poster : undefined}
                  focal={ms?.focal}
                  style={{ aspectRatio: "4/3", margin: 0 }} />
              );
            })()}
            <div style={{ minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                <span className="mono" style={{ fontSize: 10, letterSpacing: "0.18em", color: "var(--text-3)", textTransform: "uppercase" }}>No. 0{i + 1} / 03</span>
                <I name={s.icon} size={16} stroke={selected ? "var(--gold)" : "var(--text-2)"} />
              </div>
              <h3 className="serif" style={{ fontSize: 26, margin: "0 0 6px", letterSpacing: "-0.005em", lineHeight: 1.05 }}>{s.name}</h3>
              <p className="serif" style={{ color: "var(--text-1)", fontSize: 15, margin: "0 0 8px", fontStyle: "italic", lineHeight: 1.35 }}>{s.tagline}</p>
              <p style={{ color: "var(--text-2)", fontSize: 12.5, margin: 0, lineHeight: 1.55 }}>{s.tiers.length} engagements · starts at {s.tiers[0].priceBand.replace("from ", "")}</p>
            </div>
            <div style={{ width: 26, height: 26, borderRadius: "50%", background: selected ? "var(--gold)" : "transparent", border: `1px solid ${selected ? "var(--gold)" : "var(--border)"}`, display: "flex", alignItems: "center", justifyContent: "center" }}>
              {selected && <I name="check" size={13} stroke="#181004" />}
            </div>
          </button>
        );
      })}
    </div>
  );
}

function StepTier({ service, value, onChange }) {
  if (!service) return null;
  return (
    <div style={{ display: "grid", gap: 12 }}>
      {service.tiers.map((t, i) => (
        <button key={t.key} onClick={() => onChange(t.key)}
          style={{
            display: "grid",
            gridTemplateColumns: "auto 1fr auto auto",
            gap: 24, alignItems: "center",
            textAlign: "left",
            padding: "24px 28px",
            background: value === t.key ? "linear-gradient(180deg, rgba(255,204,83,0.08), transparent)" : "transparent",
            border: `1px solid ${value === t.key ? "var(--gold)" : "var(--border)"}`,
            borderRadius: 12,
            color: "inherit",
            cursor: "pointer",
          }}>
          <span className="num" style={{ fontSize: 12 }}>{String(i + 1).padStart(2, "0")}</span>
          <div>
            <h4 className="serif" style={{ fontSize: 22, margin: "0 0 4px" }}>{t.name}</h4>
            <p style={{ color: "var(--text-2)", fontSize: 13, margin: 0 }}>{t.duration} · {t.deliver}</p>
            <div style={{ display: "flex", gap: 6, marginTop: 10, flexWrap: "wrap" }}>
              {t.highlights.map((h) => <span key={h} className="chip" style={{ height: 22, padding: "0 8px", fontSize: 9.5 }}>{h}</span>)}
            </div>
          </div>
          <span className="serif" style={{ fontSize: 22, color: "var(--gold)" }}>{t.priceBand}</span>
          <I name={value === t.key ? "check" : "arrow"} size={16} stroke={value === t.key ? "var(--gold)" : "var(--text-3)"} />
        </button>
      ))}
    </div>
  );
}

function StepSchedule({ date, time, onDate, onTime }) {
  const today = new Date();
  const [{ year, month }, setMonth] = useState({ year: today.getFullYear(), month: today.getMonth() + 1 });
  const cells = useMemo(() => buildMonth(year, month), [year, month]);
  const monthName = new Date(year, month, 1).toLocaleDateString("en-US", { month: "long", year: "numeric" });
  const isPast = (d) => new Date(year, month, d) < new Date(today.getFullYear(), today.getMonth(), today.getDate());
  // mark some days as available, pseudo random but stable
  const seed = year * 100 + month;
  const isAvailable = (d) => ((d * 7 + seed) % 4 !== 0) && !isPast(d);

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 36 }}>
      <div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
          <button className="icon-btn" onClick={() => setMonth(m => m.month === 0 ? { year: m.year - 1, month: 11 } : { ...m, month: m.month - 1 })} aria-label="Prev month">
            <I name="arrowL" size={16} />
          </button>
          <span className="serif" style={{ fontSize: 22 }}>{monthName}</span>
          <button className="icon-btn" onClick={() => setMonth(m => m.month === 11 ? { year: m.year + 1, month: 0 } : { ...m, month: m.month + 1 })} aria-label="Next month">
            <I name="arrow" size={16} />
          </button>
        </div>
        <div className="cal" style={{ marginBottom: 8 }}>
          {["S","M","T","W","T","F","S"].map((d, i) => <div key={i} className="mono" style={{ textAlign: "center", color: "var(--text-3)", fontSize: 10, letterSpacing: "0.12em", padding: "6px 0" }}>{d}</div>)}
        </div>
        <div className="cal">
          {cells.map((d, i) => {
            if (!d) return <div key={i} />;
            const sel = date && date.year === year && date.month === month && date.day === d;
            const avail = isAvailable(d);
            return (
              <button key={i} className="cal-cell"
                onClick={() => avail && onDate({ year, month, day: d })}
                disabled={!avail}
                data-state={sel ? "selected" : avail ? "available" : ""}
                style={{ position: "relative" }}>
                {d}
              </button>
            );
          })}
        </div>
      </div>
      <div>
        <div className="label">Available times</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          {TIMES.map((t) => (
            <button key={t}
              onClick={() => onTime(t)}
              className="chip"
              data-active={time === t}
              style={{ height: 44, justifyContent: "center" }}>
              <I name="clock" size={12} /> {t}
            </button>
          ))}
        </div>
        <div style={{ marginTop: 22, padding: 16, border: "1px solid var(--border)", borderRadius: 8, background: "#0d0d0d" }}>
          <div className="mono" style={{ fontSize: 10, letterSpacing: "0.12em", color: "var(--text-3)", textTransform: "uppercase", marginBottom: 8 }}>Studio hours</div>
          <p style={{ fontSize: 13, color: "var(--text-1)", margin: 0, lineHeight: 1.6 }}>
            Mon–Fri · 09:00–19:00 · Sat by appointment.<br/>
            All times Eastern · we travel for the right brief.
          </p>
        </div>
      </div>
    </div>
  );
}

function StepBrief({ value, onChange }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>
      <div className="field-row" style={{ gridColumn: "1 / -1" }}>
        <label className="label">Project name (working title)</label>
        <input className="input" value={value.title} onChange={(e) => onChange({ ...value, title: e.target.value })} placeholder="A working title is fine" />
      </div>
      <div className="field-row">
        <label className="label">Budget range</label>
        <select className="input" value={value.budget} onChange={(e) => onChange({ ...value, budget: e.target.value })}>
          <option>Under $10k</option>
          <option>$10k – $25k</option>
          <option>$25k – $75k</option>
          <option>$75k – $200k</option>
          <option>$200k+</option>
          <option>Open / on retainer</option>
        </select>
      </div>
      <div className="field-row">
        <label className="label">Timeline</label>
        <select className="input" value={value.timeline} onChange={(e) => onChange({ ...value, timeline: e.target.value })}>
          <option>Within 4 weeks</option>
          <option>1–2 months</option>
          <option>2–4 months</option>
          <option>This year, no rush</option>
        </select>
      </div>
      <div className="field-row" style={{ gridColumn: "1 / -1" }}>
        <label className="label">Tell us about the project</label>
        <textarea className="ta" rows={6}
          value={value.brief}
          onChange={(e) => onChange({ ...value, brief: e.target.value })}
          placeholder="The brief, the audience, the rooms it'll live in. References welcome, links, files, half-formed thoughts." />
      </div>
      <div className="field-row" style={{ gridColumn: "1 / -1" }}>
        <label className="label">Reference reel (optional)</label>
        <div style={{ display: "flex", gap: 10, alignItems: "center", padding: 18, border: "1px dashed var(--border-2)", borderRadius: 8, background: "#0a0a0a" }}>
          <I name="film" size={18} stroke="var(--text-2)" />
          <span style={{ color: "var(--text-2)", fontSize: 13.5 }}>Drop a Vimeo / Frame.io link, or upload up to 5 files</span>
          <button className="btn btn-ghost btn-sm" style={{ marginLeft: "auto" }}>Browse…</button>
        </div>
      </div>
    </div>
  );
}

function StepContact({ value, onChange }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
      <div className="field-row"><label className="label">First name</label><input className="input" value={value.first} onChange={(e) => onChange({ ...value, first: e.target.value })} /></div>
      <div className="field-row"><label className="label">Last name</label><input className="input" value={value.last} onChange={(e) => onChange({ ...value, last: e.target.value })} /></div>
      <div className="field-row" style={{ gridColumn: "1 / -1" }}><label className="label">Company / studio</label><input className="input" value={value.company} onChange={(e) => onChange({ ...value, company: e.target.value })} /></div>
      <div className="field-row"><label className="label">Email</label><input className="input" type="email" value={value.email} onChange={(e) => onChange({ ...value, email: e.target.value })} /></div>
      <div className="field-row"><label className="label">Phone</label><input className="input" value={value.phone} onChange={(e) => onChange({ ...value, phone: e.target.value })} /></div>
      <div className="field-row" style={{ gridColumn: "1 / -1" }}>
        <label className="label">How did you hear of us?</label>
        <select className="input" value={value.source} onChange={(e) => onChange({ ...value, source: e.target.value })}>
          <option>A friend or colleague</option>
          <option>Press / a publication</option>
          <option>Instagram / Vimeo</option>
          <option>The journal</option>
          <option>Other</option>
        </select>
      </div>
    </div>
  );
}

function Summary({ form }) {
  const s = SERVICES[form.service];
  const tier = s?.tiers.find((t) => t.key === form.tier);
  const dateStr = form.date ? new Date(form.date.year, form.date.month, form.date.day).toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" }) : "—";
  return (
    <div style={{ display: "grid", gap: 18 }}>
      <Placeholder label={s?.name.toLowerCase() || ""} variant="warm" style={{ aspectRatio: "5/3" }} />
      <div style={{ display: "grid", gap: 10 }}>
        {[
          ["Service", s?.name],
          ["Engagement", tier?.name],
          ["Estimate", tier?.priceBand],
          ["First call", `${dateStr}${form.time ? " · " + form.time : ""}`],
          ["Lead", form.contact.first + (form.contact.last ? " " + form.contact.last : "")],
          ["Studio", form.contact.company || "—"],
          ["Brief", form.brief.title || "Untitled brief"],
        ].map(([k, v]) => (
          <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "10px 0", borderBottom: "1px solid var(--border-1)", gap: 24 }}>
            <span className="mono" style={{ fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--text-3)", whiteSpace: "nowrap" }}>{k}</span>
            <span style={{ textAlign: "right", fontSize: 14, color: "var(--text)" }}>{v || "—"}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

const STEPS = [
  { key: "service",  label: "Service",    numeral: "01" },
  { key: "tier",     label: "Engagement", numeral: "02" },
  { key: "schedule", label: "Schedule",   numeral: "03" },
  { key: "brief",    label: "Brief",      numeral: "04" },
  { key: "contact",  label: "Contact",    numeral: "05" },
];

/* ─── Container ─────────────────────────────────────────────────── */
function Booking({ variant = "stepped" }) {
  const { route, goto } = useRoute();
  const toast = useToast();

  const pkg = (window.PACKAGES || []).find((p) => p.id === route.params?.package);
  const initService = pkg?.lane === "designs" ? "photography"
                    : pkg?.lane === "nights"  ? "video"
                    : pkg?.lane === "moments" ? "photography"
                    : (route.params?.service || "photography");

  const [stepIdx, setStepIdx] = useState(0);
  const [done, setDone] = useState(false);
  const [form, setForm] = useState({
    service: initService,
    tier: SERVICES[initService].tiers[0].key,
    package: pkg?.id || null,
    date: null,
    time: null,
    brief: {
      title: pkg ? `${pkg.name}, ${pkg.subtitle}` : "",
      budget: pkg ? pkg.totalLabel : "$25k – $75k",
      timeline: pkg ? pkg.duration : "1–2 months",
      brief: pkg ? `Booking the ${pkg.name} package (${pkg.code}). Deposit $${pkg.deposit}.\n\nContext: ` : "",
    },
    contact: { first: "", last: "", company: "", email: "", phone: "", source: "A friend or colleague" },
  });

  // sync default tier when service changes
  useEffect(() => {
    if (!SERVICES[form.service].tiers.find((t) => t.key === form.tier)) {
      setForm((f) => ({ ...f, tier: SERVICES[f.service].tiers[0].key }));
    }
  }, [form.service]);

  const service = SERVICES[form.service];

  const canNext = (() => {
    const k = STEPS[stepIdx].key;
    if (k === "service") return !!form.service;
    if (k === "tier") return !!form.tier;
    if (k === "schedule") return !!form.date && !!form.time;
    if (k === "brief") return form.brief.brief.trim().length >= 10;
    if (k === "contact") return form.contact.first && form.contact.email.includes("@");
    return true;
  })();

  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);

  async function submit() {
    if (submitting) return;
    setSubmitting(true);
    setSubmitError(null);
    const payload = {
      service: form.service,
      tier: form.tier,
      package: form.package || null,
      date: form.date,
      time: form.time,
      brief: form.brief,
      contact: form.contact,
    };
    try {
      const r = await fetch("/api/booking", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      // If the static-only preview can't reach /api/booking we still let the user
      // see the success view (graceful local-dev fallback).
      const offline = r.status === 404 || r.status === 405;
      if (!r.ok && !offline) {
        const data = await r.json().catch(() => ({}));
        throw new Error(data.error || `request_failed_${r.status}`);
      }
      setDone(true);
      toast(offline ? "Saved locally, endpoint not deployed yet." : "Inquiry sent. We'll write back within 24 hours.");
      window.scrollTo({ top: 0, behavior: "smooth" });
    } catch (err) {
      setSubmitError(err.message || "Could not send right now, try again or email studio@elevenviews.io.");
      toast("Send failed. Try again, or email studio@elevenviews.io.");
    } finally {
      setSubmitting(false);
    }
  }

  /* ── Variant: editorial (long single page) ─────────────────── */
  if (variant === "editorial" && !done) {
    return (
      <main className="fade">
        <section style={{ padding: "80px 0 24px" }}>
          <div className="container" style={{ maxWidth: 920 }}>
            <span className="eyebrow eyebrow-gold">§ Inquire · Editorial form</span>
            <h1 className="serif balance" style={{ fontSize: "clamp(48px, 7vw, 100px)", lineHeight: 0.96, margin: "16px 0 24px" }}>
              <em style={{ fontStyle: "italic", color: "var(--gold-soft)" }}>Tell us</em> about the work.
            </h1>
            <p className="pretty" style={{ color: "var(--text-1)", fontSize: 17, lineHeight: 1.65, maxWidth: 640 }}>
              Five short sections. Skim them, fill what's true, and we'll write back within a day. There's no commitment until both sides agree there should be.
            </p>
            {pkg && (
              <div style={{ marginTop: 28, padding: "18px 22px", border: "1px solid var(--gold)", borderRadius: 10, background: "rgba(255,204,83,0.06)", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 18, flexWrap: "wrap" }}>
                <div>
                  <div className="mono" style={{ fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--gold)", marginBottom: 6 }}>Booking package · {pkg.code}</div>
                  <div className="serif" style={{ fontSize: 22, lineHeight: 1.1 }}>{pkg.name}</div>
                  <div style={{ fontSize: 13, color: "var(--text-2)", marginTop: 4 }}>{pkg.subtitle} · {pkg.totalLabel}</div>
                </div>
                <button className="btn btn-line" onClick={() => location.reload()}>Switch to open brief</button>
              </div>
            )}
          </div>
        </section>

        <div className="container" style={{ maxWidth: 920, paddingBottom: 80 }}>
          {STEPS.map((s, i) => (
            <section key={s.key} style={{ padding: "48px 0", borderTop: "1px solid var(--border-1)" }}>
              <div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: 32, alignItems: "start" }}>
                <div style={{ position: "sticky", top: "calc(var(--hdr) + 24px)" }}>
                  <div className="mono" style={{ fontSize: 36, color: "var(--gold)", lineHeight: 1, fontWeight: 400, letterSpacing: "-0.02em" }}>{s.numeral}</div>
                  <div className="mono" style={{ fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--text-2)", marginTop: 10 }}>{s.label}</div>
                </div>
                <div>
                  {s.key === "service"  && <StepService value={form.service} onChange={(v) => setForm({ ...form, service: v })} />}
                  {s.key === "tier"     && <StepTier service={service} value={form.tier} onChange={(v) => setForm({ ...form, tier: v })} />}
                  {s.key === "schedule" && <StepSchedule date={form.date} time={form.time} onDate={(d) => setForm({ ...form, date: d })} onTime={(t) => setForm({ ...form, time: t })} />}
                  {s.key === "brief"    && <StepBrief value={form.brief} onChange={(v) => setForm({ ...form, brief: v })} />}
                  {s.key === "contact"  && <StepContact value={form.contact} onChange={(v) => setForm({ ...form, contact: v })} />}
                </div>
              </div>
            </section>
          ))}
          <section style={{ padding: "48px 0 0", borderTop: "1px solid var(--border-1)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 18 }}>
              <p className="serif-it" style={{ fontSize: 22, color: "var(--text-1)", margin: 0, maxWidth: 480 }}>
                "Send when ready. We read every inquiry by hand."
              </p>
              <button className="btn btn-gold btn-lg" onClick={submit} disabled={submitting}>
                {submitting ? "Sending…" : "Send inquiry"} <I name="send" size={16} />
              </button>
            </div>
            {submitError && <p style={{ marginTop: 16, fontSize: 13, color: "#ff8a80" }}>{submitError}</p>}
          </section>
        </div>
      </main>
    );
  }

  /* ── Done view ─────────────────────────────────────────────── */
  if (done) {
    const dateStr = form.date ? new Date(form.date.year, form.date.month, form.date.day).toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" }) : "soon";
    return (
      <main className="fade" style={{ minHeight: "calc(100vh - var(--hdr))" }}>
        <section style={{ padding: "100px 0" }}>
          <div className="container" style={{ maxWidth: 720, textAlign: "center" }}>
            <I name="spark" size={32} stroke="var(--gold)" style={{ marginBottom: 24 }} />
            <span className="eyebrow eyebrow-gold">Inquiry · EV-{Math.floor(Math.random() * 9000 + 1000)}</span>
            <h1 className="serif balance" style={{ fontSize: "clamp(40px, 5vw, 68px)", lineHeight: 1.04, margin: "16px 0 24px" }}>
              We've got it. Eleven thanks.
            </h1>
            <p className="pretty" style={{ color: "var(--text-1)", fontSize: 16, lineHeight: 1.7, maxWidth: 540, margin: "0 auto 36px" }}>
              {form.contact.first ? form.contact.first + ", " : ""}we'll write back within a working day with notes on the brief and a 30-minute call invite for {dateStr}{form.time ? " around " + form.time : ""}.
              In the meantime, here's a copy of the inquiry.
            </p>
            <div style={{ maxWidth: 560, margin: "0 auto 48px", textAlign: "left" }}>
              <Summary form={form} />
            </div>
            <div style={{ display: "flex", gap: 10, justifyContent: "center" }}>
              <button className="btn btn-line" onClick={() => { setDone(false); setStepIdx(0); }}>Send another</button>
              <button className="btn btn-ghost" onClick={() => goto("home")}>Back to studio</button>
            </div>
          </div>
        </section>
      </main>
    );
  }

  /* ── Variant: stepped (sidebar wizard, default) ─────────────── */
  return (
    <main className="fade">
      <section style={{ padding: "56px 0 24px", borderBottom: "1px solid var(--border-1)" }}>
        <div className="container">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "end", flexWrap: "wrap", gap: 18 }}>
            <div>
              <span className="eyebrow eyebrow-gold">§ Booking · {pkg ? `Reserving ${pkg.code}` : "Studio inquiry"}</span>
              <h1 className="serif" style={{ fontSize: "clamp(40px, 5.2vw, 68px)", lineHeight: 1, margin: "12px 0 0" }}>
                {pkg ? pkg.name : "A short form, in five parts."}
              </h1>
              {pkg && (
                <p style={{ fontSize: 14, color: "var(--text-2)", margin: "10px 0 0", maxWidth: 540 }}>
                  {pkg.subtitle} · <b style={{ color: "var(--gold)" }}>{pkg.totalLabel}</b>
                </p>
              )}
            </div>
            <StepDots idx={stepIdx} count={STEPS.length} />
          </div>
        </div>
      </section>

      <section style={{ padding: "48px 0 96px" }}>
        <div className="container" style={{ display: "grid", gridTemplateColumns: "260px 1fr 320px", gap: 48 }}>
          {/* Step rail */}
          <aside>
            <div style={{ position: "sticky", top: "calc(var(--hdr) + 32px)" }}>
              <ol style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 6 }}>
                {STEPS.map((s, i) => {
                  const state = i === stepIdx ? "active" : i < stepIdx ? "done" : "";
                  return (
                    <li key={s.key}>
                      <button onClick={() => i <= stepIdx && setStepIdx(i)}
                        style={{
                          width: "100%",
                          display: "flex", alignItems: "center", gap: 14,
                          padding: "14px 14px",
                          background: state === "active" ? "linear-gradient(90deg, rgba(255,204,83,0.08), transparent)" : "transparent",
                          border: 0, borderLeft: `2px solid ${state === "active" ? "var(--gold)" : state === "done" ? "var(--gold-deep)" : "var(--border)"}`,
                          color: state ? "var(--text)" : "var(--text-3)",
                          textAlign: "left",
                          cursor: i <= stepIdx ? "pointer" : "default",
                          fontFamily: "var(--sans)",
                        }}>
                        <span className="mono" style={{ fontSize: 18, color: state === "active" ? "var(--gold)" : state === "done" ? "var(--gold-deep)" : "var(--text-3)", minWidth: 28, fontWeight: 500 }}>
                          {s.numeral}
                        </span>
                        <div>
                          <div className="mono" style={{ fontSize: 9.5, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--text-3)", marginBottom: 2 }}>Step {i + 1}</div>
                          <div style={{ fontSize: 14 }}>{s.label}</div>
                        </div>
                        {state === "done" && <I name="check" size={14} stroke="var(--gold-deep)" style={{ marginLeft: "auto" }} />}
                      </button>
                    </li>
                  );
                })}
              </ol>

              <div style={{ marginTop: 28, padding: 18, border: "1px solid var(--border)", borderRadius: 10, background: "#0c0c0c" }}>
                <div className="mono" style={{ fontSize: 10, letterSpacing: "0.14em", color: "var(--text-3)", textTransform: "uppercase", marginBottom: 8 }}>Need a hand?</div>
                <p style={{ fontSize: 13, color: "var(--text-1)", lineHeight: 1.6, margin: "0 0 12px" }}>Studio managers are on email Mon–Fri.</p>
                <a className="lk" style={{ fontSize: 13 }}>studio@elevenviews.io</a>
              </div>
            </div>
          </aside>

          {/* Step content */}
          <div>
            <div style={{ marginBottom: 32 }}>
              <span className="num">Step {stepIdx + 1} of {STEPS.length}</span>
              <h2 className="serif" style={{ fontSize: "clamp(28px, 3vw, 40px)", lineHeight: 1.05, margin: "8px 0 6px" }}>
                {STEPS[stepIdx].key === "service"  && "What kind of work?"}
                {STEPS[stepIdx].key === "tier"     && "How deep should we go?"}
                {STEPS[stepIdx].key === "schedule" && "When should we start?"}
                {STEPS[stepIdx].key === "brief"    && "Tell us about the brief."}
                {STEPS[stepIdx].key === "contact"  && "And one last thing, you."}
              </h2>
              <p className="pretty" style={{ color: "var(--text-2)", fontSize: 14.5, maxWidth: 600, margin: 0 }}>
                {STEPS[stepIdx].key === "service"  && "Pick the room that fits, you can change your mind on the next call."}
                {STEPS[stepIdx].key === "tier"     && "An estimate, not a quote. We'll firm everything up after a 30-minute conversation."}
                {STEPS[stepIdx].key === "schedule" && "Pick a date and time for the introductory call. Studio hours are New York time."}
                {STEPS[stepIdx].key === "brief"    && "A few sentences is plenty. The form is conversational; we read each one by hand."}
                {STEPS[stepIdx].key === "contact"  && "So we can write back, and so we know who's behind the project."}
              </p>
            </div>

            <div style={{ minHeight: 360 }}>
              {STEPS[stepIdx].key === "service"  && <StepService value={form.service} onChange={(v) => setForm({ ...form, service: v })} />}
              {STEPS[stepIdx].key === "tier"     && <StepTier service={service} value={form.tier} onChange={(v) => setForm({ ...form, tier: v })} />}
              {STEPS[stepIdx].key === "schedule" && <StepSchedule date={form.date} time={form.time} onDate={(d) => setForm({ ...form, date: d })} onTime={(t) => setForm({ ...form, time: t })} />}
              {STEPS[stepIdx].key === "brief"    && <StepBrief value={form.brief} onChange={(v) => setForm({ ...form, brief: v })} />}
              {STEPS[stepIdx].key === "contact"  && <StepContact value={form.contact} onChange={(v) => setForm({ ...form, contact: v })} />}
            </div>

            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 48, paddingTop: 24, borderTop: "1px solid var(--border-1)" }}>
              <button className="btn btn-ghost" onClick={() => setStepIdx(Math.max(0, stepIdx - 1))} disabled={stepIdx === 0} style={{ opacity: stepIdx === 0 ? 0.4 : 1 }}>
                <I name="arrowL" size={14} /> Back
              </button>
              {stepIdx < STEPS.length - 1 ? (
                <button className="btn btn-gold" onClick={() => canNext && setStepIdx(stepIdx + 1)} disabled={!canNext} style={{ opacity: canNext ? 1 : 0.5 }}>
                  Continue <I name="arrow" size={16} />
                </button>
              ) : (
                <button className="btn btn-gold btn-lg" onClick={() => canNext && submit()} disabled={!canNext || submitting} style={{ opacity: (canNext && !submitting) ? 1 : 0.5 }}>
                  {submitting ? "Sending…" : "Send inquiry"} <I name="send" size={16} />
                </button>
              )}
              {submitError && (
                <span style={{ display: "block", flexBasis: "100%", marginTop: 12, fontSize: 12, color: "#ff8a80" }}>{submitError}</span>
              )}
            </div>
          </div>

          {/* Live summary */}
          <aside>
            <div style={{ position: "sticky", top: "calc(var(--hdr) + 32px)", padding: 24, border: "1px solid var(--border)", borderRadius: 12, background: "linear-gradient(180deg, #0e0e0e, #0a0a0a)" }}>
              <span className="eyebrow">Inquiry · Live</span>
              <div style={{ marginTop: 12 }}>
                <Summary form={form} />
              </div>
            </div>
          </aside>
        </div>
      </section>
    </main>
  );
}

window.Booking = Booking;
