/* global React */
// Onboarding — the primary CTA. Multi-step, validated, persisted, animated.
// Two flows after "About you": crew (yacht profile → AI experience + systems
// to integrate) and shore (organization profile → fluency + product interest,
// with an extra Custom development step when that product is picked).
const { Icon, Eyebrow, Btn } = window;

// Role options for Shore Professionals — mirrors yachting-visibility/shared/schema.ts
// SEGMENTS (the segments Visibility prompts the models with; news.jsx uses the same
// list for its signup). The trailing "Other" reveals a free-text field.
const ROLE_SEGMENTS = [
  "Broker (Sales & Purchase)", "Charter Company", "Shipyard (New Build)", "Shipyard (Refit & Repair)",
  "Boatyard / Service Center", "Marina / Port", "Yacht Agent", "Provisioning & Supplies",
  "Chandlery / Marine Supplies", "Insurance Broker", "Surveyor", "Naval Architect / Designer",
  "Design & Engineering", "Interior Designer / Furnishings", "Crew Agency", "Management Company",
  "Brand / Equipment Manufacturer", "Electronics / Navigation Specialist", "Paint / Coating / Refinishing",
  "Rigging / Sail Maker", "Engineering / Mechanical", "PR / Marketing Agency", "Classification Society",
  "Clusters, Forums & Associations", "Transport / Logistics", "Legal / Flag State", "Finance / Leasing",
  "Fuel / Bunkering", "IT / Communications", "Security Services", "Medical / Health Services",
  "Tender / Watersports", "Yacht Club", "Yacht/Boat Shows", "Other",
];
// Role options for Yacht Crew (same roles as the news signup).
const CREW_ROLES = ["Captain", "Officer / Deck", "Engineer / ETO", "Chief Stew / Interior", "Chef / Galley", "Purser / Admin", "Other"];
// LOA brackets and crew complement for the crew flow.
const YACHT_SIZES = ["<20m", "20-30m", "30-40m", "40-50m", "50-60m", "60-70m", "70-80m", "80-90m", "90-100m", "100m+"];
const CREW_COUNT = ["1–3", "4–6", "7–12", "13–25", "26–50", "50+"];
// Organization profile for the shore flow.
const ORG_SIZES = ["Just me", "2–10", "11–50", "51–200", "200+"];
const OFFICES = ["1", "2–3", "4–10", "10+"];
// Slider levels — personal fluency with AI (asked in both flows).
const AI_LEVELS = [
  ["Basic", "I use ChatGPT for everyday questions."],
  ["Advanced", "ChatGPT connected to my documents, email and files."],
  ["Expert", "Some coding experience — Claude Code and other AI coding tools."],
  ["Power user", "I develop AI tools and technologies myself."],
];
// Slider levels — how far AI has spread through the organization (shore only).
const ORG_LEVELS = [
  ["None", "No formal use of AI yet."],
  ["Ad hoc", "The team uses AI individually, in an uncoordinated way."],
  ["Deployed", "Basic AI systems deployed for the group."],
  ["Enterprise", "Enterprise-level AI deployed across the organization."],
];
// Suite products a shore business can flag as what drew them in. Picking
// Custom Development unlocks one extra step about their systems estate.
const CUSTOM_DEV = "Custom Development";
const PRODUCT_INTEREST = [
  ["Eye", "Yachting Visibility", "How AI models perceive your brand and business"],
  ["ShieldAlert", "Yachting Privacy", "What AI knows about a yacht and its related parties"],
  ["Bot", "Yachting AI Agents", "Dedicated agents on your processes and systems"],
  ["Wrench", CUSTOM_DEV, "Bespoke AI built around your operation"],
];
// Custom development intake — the systems estate, one maturity pick per area.
const KEY_SYSTEMS = [
  ["sysCrm", "CRM", "Clients, charters and the sales pipeline"],
  ["sysErp", "ERP / Finance", "Invoices, purchasing, accounting"],
  ["sysOps", "Operations", "Maintenance, compliance, crew and logistics"],
];
const SYSTEM_MATURITY = ["None — spreadsheets & files", "Generic tool", "Dedicated system"];
const KEY = "ym_onboarding_v2";

function field(label, req, missing) {
  return <label style={{ display: "block", fontFamily: "var(--font-ui)", fontSize: 13, fontWeight: 500,
    color: "var(--ink-2)", marginBottom: 8 }}>{label}{req && <span style={{ color: missing ? "var(--bad)" : "var(--cyan)" }}> *</span>}</label>;
}
const inputStyle = (err) => ({ width: "100%", fontFamily: "var(--font-ui)", fontSize: 14.5, color: "var(--ink)",
  padding: "13px 15px", borderRadius: 11, border: `1px solid ${err ? "var(--bad)" : "var(--hairline-2)"}`,
  background: "var(--panel)", outline: "none", transition: "border-color .2s" });

function Chip({ active, onClick, children, style = {} }) {
  return (
    <button type="button" onClick={onClick} style={{ all: "unset", cursor: "pointer", fontFamily: "var(--font-ui)",
      fontSize: 13.5, fontWeight: 500, padding: "10px 16px", borderRadius: 11, transition: "all .2s",
      color: active ? "var(--cyan-ink)" : "var(--ink-2)", background: active ? "var(--cyan)" : "var(--wa-03)",
      border: `1px solid ${active ? "var(--cyan)" : "var(--hairline-2)"}`, ...style }}>{children}</button>
  );
}

function Select({ value, onChange, placeholder, options, err }) {
  return (
    <select value={value || ""} onChange={(e) => onChange(e.target.value)}
      style={{ ...inputStyle(err), appearance: "none", WebkitAppearance: "none", cursor: "pointer",
        color: value ? "var(--ink)" : "var(--ink-4)",
        backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%2394C1DA' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><polyline points='6 9 12 15 18 9'/></svg>\")",
        backgroundRepeat: "no-repeat", backgroundPosition: "right 14px center", paddingRight: 40 }}>
      <option value="" disabled style={{ background: "#0d1626", color: "#8A97A6" }}>{placeholder}</option>
      {options.map((o) => <option key={o} value={o} style={{ background: "#0d1626", color: "#fff" }}>{o}</option>)}
    </select>
  );
}

// Slider-style level picker — stops on a track, tap one to select. The
// selected level's description renders underneath so labels stay short.
function LevelPicker({ value, onChange, levels, err }) {
  const idx = levels.findIndex((l) => l[0] === value);
  const n = levels.length;
  const side = 100 / (2 * n);          // inset so the track spans dot centers
  const span = 100 - 100 / n;
  return (
    <div>
      <div style={{ position: "relative", paddingTop: 6 }}>
        <div style={{ position: "absolute", top: 13, left: `${side}%`, width: `${span}%`, height: 2, borderRadius: 2, background: "var(--wa-05)" }} />
        {idx > 0 && <div style={{ position: "absolute", top: 13, left: `${side}%`, width: `${(span * idx) / (n - 1)}%`, height: 2, borderRadius: 2,
          background: "linear-gradient(90deg, var(--cyan-deep), var(--cyan))", transition: "width .3s var(--ease)" }} />}
        <div style={{ position: "relative", display: "flex" }}>
          {levels.map(([label], i) => {
            const on = idx >= 0 && i <= idx; const active = i === idx;
            return (
              <button key={label} type="button" onClick={() => onChange(label)}
                style={{ all: "unset", cursor: "pointer", flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
                <span style={{ width: 15, height: 15, borderRadius: 999, boxSizing: "border-box", transition: "all .2s",
                  background: on ? "var(--cyan)" : "var(--panel)",
                  border: `2px solid ${on ? "var(--cyan)" : err ? "var(--bad)" : "var(--hairline-2)"}`,
                  boxShadow: active ? "0 0 0 4px rgba(80,134,182,.22)" : "none" }} />
                <span style={{ fontFamily: "var(--font-ui)", fontSize: 11.5, textAlign: "center", lineHeight: 1.3, padding: "0 2px",
                  fontWeight: active ? 600 : 400, color: active ? "var(--cyan-2)" : "var(--ink-3)" }}>{label}</span>
              </button>
            );
          })}
        </div>
      </div>
      <div style={{ marginTop: 7, minHeight: 18, fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 12.5,
        color: idx >= 0 ? "var(--ink-2)" : err ? "var(--bad)" : "var(--ink-4)" }}>
        {idx >= 0 ? levels[idx][1] : "Tap the level that fits best."}
      </div>
    </div>
  );
}

// The submitted answers as ordered [label, value] rows. ONE source for all
// three places they surface: the Review step, the emailed receipt (whose BCC to
// the team is how a new request is noticed) and the CRM lead's note — so what
// the visitor confirms is exactly what lands in the inbox and the CRM.
function submissionRows(d, crew, wantsCustom) {
  const roleDisplay = d.role === "Other" ? (d.roleOther ? `Other — ${d.roleOther}` : "Other") : d.role;
  return [
    ["Contact", `${d.name} · ${d.company}`], ["Email", d.email], ["LinkedIn", d.linkedin || "—"],
    ["Role", crew ? `Yacht crew · ${roleDisplay}` : roleDisplay],
    crew
      ? ["Yacht", `${d.yachtSize} LOA · ${d.crewCount} crew`]
      : ["Organization", `${d.orgSize} people · ${d.offices} ${d.offices === "1" ? "office" : "offices"}${d.mainOffice ? ` · ${d.mainOffice}` : ""}`],
    ["AI experience", d.aiExperience || "—"],
    !crew && ["Organization AI", d.orgFluency || "—"],
    !crew && ["Drawn to", (d.products || []).join(", ") || "—"],
    crew && ["Integrate", d.systemsNote || "—"],
    wantsCustom && ["Key systems", KEY_SYSTEMS.map(([k, t]) => `${t}: ${d[k] || "—"}`).join(" · ")],
    wantsCustom && ["Build", d.customNote || "—"],
    !crew && ["Notes", d.note || "—"],
  ].filter(Boolean);
}

function Onboarding({ go, mode = "onboarding" }) {
  const isSales = mode === "contact-sales";
  const [step, setStep] = React.useState(0);
  const [done, setDone] = React.useState(false);
  const [touched, setTouched] = React.useState(false);
  const [d, setD] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem(KEY)) || {}; } catch (e) { return {}; }
  });
  const set = (k, v) => setD((s) => ({ ...s, [k]: v }));
  const toggle = (k, v) => setD((s) => { const a = s[k] || []; return { ...s, [k]: a.includes(v) ? a.filter((x) => x !== v) : [...a, v] }; });
  React.useEffect(() => { try { localStorage.setItem(KEY, JSON.stringify(d)); } catch (e) {} }, [d]);

  // The page that sent the visitor here (stashed by go() at CTA click) — e.g.
  // "product:simulation" from its Request-access CTA. Persisted into the draft
  // so the flag survives reloads and rides the submission.
  React.useEffect(() => {
    try {
      const f = sessionStorage.getItem("ym_onboarding_from");
      if (f) setD((s) => (s.source === f ? s : { ...s, source: f }));
    } catch (e) {}
  }, []);

  const crew = d.audience === "crew";
  const shore = d.audience === "shore";
  const wantsCustom = shore && (d.products || []).includes(CUSTOM_DEV);
  // Steps flex per audience; picking Custom Development inserts its own step.
  const steps = crew
    ? ["About you", "Your yacht", "Where AI fits", "Review"]
    : shore
      ? ["About you", "Your organization", "Where AI fits", ...(wantsCustom ? ["Custom development"] : []), "Review"]
      : ["About you", "Your operation", "Where AI fits", "Review"];
  const stepName = steps[step];
  const last = step === steps.length - 1;

  const emailOk = /.+@.+\..+/.test(d.email || "");
  const validNow = (() => {
    switch (stepName) {
      case "About you": return !!(d.audience && d.name && d.company && emailOk && d.role);
      case "Your yacht": return !!(d.yachtSize && d.crewCount);
      case "Your organization": return !!(d.orgSize && d.offices);
      case "Where AI fits": return crew ? !!d.aiExperience : !!(d.aiExperience && d.orgFluency && (d.products || []).length);
      case "Custom development": return KEY_SYSTEMS.every(([k]) => d[k]);
      default: return true;
    }
  })();
  const next = () => { if (!validNow) { setTouched(true); return; } setTouched(false); setStep((s) => Math.min(s + 1, steps.length - 1)); window.scrollTo(0, 0); };
  const back = () => { setTouched(false); setStep((s) => Math.max(s - 1, 0)); };

  if (done) return <Success email={d.email} go={go} reset={() => { localStorage.removeItem(KEY); }} isSales={isSales} />;

  return (
    <div style={{ minHeight: "100vh", paddingTop: 69, display: "flex", flexDirection: "column", alignItems: "center" }}>
      <div style={{ width: "100%", maxWidth: 680, padding: "48px 32px 80px" }}>
        <button onClick={() => go("home")} style={{ all: "unset", cursor: "pointer", display: "inline-flex", alignItems: "center",
          gap: 7, fontFamily: "var(--font-ui)", fontSize: 13, color: "var(--ink-3)", marginBottom: 28 }}>
          <Icon name="ArrowLeft" size={15} /> Back to site
        </button>

        {/* progress */}
        <div style={{ marginBottom: 8, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <Eyebrow>{isSales ? "Contact sales" : "Onboarding"}</Eyebrow>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--ink-3)" }}>Step {step + 1} of {steps.length} · {stepName}</span>
        </div>
        <div style={{ height: 4, borderRadius: 4, background: "var(--wa-05)", overflow: "hidden", marginBottom: 36 }}>
          <div style={{ height: "100%", width: `${((step + 1) / steps.length) * 100}%`, borderRadius: 4,
            background: "linear-gradient(90deg, var(--cyan-deep), var(--cyan))", transition: "width .5s var(--ease)" }} />
        </div>

        <div key={step} className="ymstep">
          {/* CTA-origin flag — which page (and purpose) brought the visitor here */}
          {(() => {
            const from = d.source || "";
            const p = from.indexOf("product:") === 0 ? (window.PRODUCTS || {})[from.slice(8)] : null;
            const label = p ? `${(p.cta && p.cta.label) || "Onboarding"} · ${p.name}` : from === "onboard" ? "For your yacht" : null;
            if (!label) return null;
            return (
              <div style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "6px 12px", borderRadius: 999, marginBottom: 14,
                background: "rgba(80,134,182,.08)", border: "1px solid rgba(80,134,182,.28)" }}>
                <Icon name={p ? p.icon : "Anchor"} size={13} color="var(--cyan-2)" />
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 600, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--cyan-2)" }}>{label}</span>
              </div>
            );
          })()}
          <h1 style={{ fontFamily: "var(--font-head)", fontWeight: 700, fontSize: 30, color: "var(--ink)", margin: "0 0 28px" }}>{stepName}</h1>

          {stepName === "About you" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
              {/* Conditional form: crew vs shore drives the role options here and the
                  whole flow after this step. */}
              <div>{field("I am…", true)}
                <div style={{ display: "flex", gap: 10 }}>
                  {[["crew", "Anchor", "Yacht Crew"], ["shore", "Building2", "Shore Professional"]].map(([k, ic, l]) => {
                    const active = d.audience === k;
                    return (
                      <button key={k} type="button" onClick={() => setD((s) => ({ ...s, audience: k, role: undefined, roleOther: undefined }))}
                        style={{ all: "unset", cursor: "pointer", flex: 1, boxSizing: "border-box", padding: "13px 14px", borderRadius: 11, textAlign: "center",
                          border: `1px solid ${active ? "rgba(80,134,182,.5)" : touched && !d.audience ? "var(--bad)" : "var(--hairline-2)"}`,
                          background: active ? "rgba(80,134,182,.1)" : "var(--wa-02)", transition: "background .2s, border-color .2s" }}>
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 8, fontFamily: "var(--font-ui)", fontSize: 14,
                          fontWeight: active ? 600 : 400, color: active ? "var(--cyan-2)" : "var(--ink-2)" }}>
                          <Icon name={ic} size={16} color={active ? "var(--cyan-2)" : "var(--ink-3)"} />{l}
                        </span>
                      </button>
                    );
                  })}
                </div>
              </div>
              <div className="responsive-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                <div>{field("Your name", true)}<input value={d.name || ""} onChange={(e) => set("name", e.target.value)} placeholder="Your name" style={inputStyle(touched && !d.name)} /></div>
                <div>{field("Company / Yacht", true)}<input value={d.company || ""} onChange={(e) => set("company", e.target.value)} placeholder="Company or yacht name" style={inputStyle(touched && !d.company)} /></div>
              </div>
              <div>{field("Email", true)}<input type="email" value={d.email || ""} onChange={(e) => set("email", e.target.value)} placeholder="you@email.com" style={inputStyle(touched && !emailOk)} />
                {touched && !emailOk && <span style={{ fontFamily: "var(--font-ui)", fontSize: 12, color: "var(--bad)", marginTop: 6, display: "block" }}>Enter a valid email — we sign in with a magic link.</span>}</div>
              <div>{field("LinkedIn (optional)")}<input type="url" value={d.linkedin || ""} onChange={(e) => set("linkedin", e.target.value)} placeholder="linkedin.com/in/you" style={inputStyle(false)} /></div>
              {d.audience && (
                <div className="ymfade">{field(crew ? "Role onboard" : "Your role", true)}
                  <Select value={d.role} onChange={(v) => set("role", v)} err={touched && !d.role}
                    placeholder={crew ? "Select your role…" : "Select your segment…"}
                    options={crew ? CREW_ROLES : ROLE_SEGMENTS} />
                  {d.role === "Other" && (
                    <input className="ymfade" value={d.roleOther || ""} onChange={(e) => set("roleOther", e.target.value)}
                      placeholder={crew ? "Tell us your role onboard" : "Tell us what you do"} style={{ ...inputStyle(false), marginTop: 10 }} />
                  )}
                </div>
              )}
            </div>
          )}

          {stepName === "Your yacht" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
              <div className="responsive-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                <div>{field("Yacht size (LOA)", true)}
                  <Select value={d.yachtSize} onChange={(v) => set("yachtSize", v)} err={touched && !d.yachtSize}
                    placeholder="Select length overall…" options={YACHT_SIZES} /></div>
                <div>{field("Crew on board", true)}
                  <Select value={d.crewCount} onChange={(v) => set("crewCount", v)} err={touched && !d.crewCount}
                    placeholder="Select crew count…" options={CREW_COUNT} /></div>
              </div>
            </div>
          )}

          {stepName === "Your organization" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
              <div className="responsive-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                <div>{field("People in your organization", true)}
                  <Select value={d.orgSize} onChange={(v) => set("orgSize", v)} err={touched && !d.orgSize}
                    placeholder="Select team size…" options={ORG_SIZES} /></div>
                <div>{field("Offices / locations", true)}
                  <Select value={d.offices} onChange={(v) => set("offices", v)} err={touched && !d.offices}
                    placeholder="Select office count…" options={OFFICES} /></div>
              </div>
              <div>{field("Main office location (optional)")}
                <input value={d.mainOffice || ""} onChange={(e) => set("mainOffice", e.target.value)}
                  placeholder="Palma, Monaco, Fort Lauderdale…" style={inputStyle(false)} /></div>
            </div>
          )}

          {stepName === "Where AI fits" && crew && (
            <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
              <div>{field("My experience with AI", true, touched && !d.aiExperience)}
                <LevelPicker value={d.aiExperience} onChange={(v) => set("aiExperience", v)} levels={AI_LEVELS} err={touched && !d.aiExperience} /></div>
              <div>{field("Systems on board you'd like integrated (optional)")}
                <textarea value={d.systemsNote || ""} onChange={(e) => set("systemsNote", e.target.value)} rows={4}
                  placeholder="List the systems you currently use on board and would like integrated — maintenance software, inventory, monitoring, spreadsheets…"
                  style={{ ...inputStyle(false), resize: "vertical", lineHeight: 1.5 }} /></div>
            </div>
          )}

          {stepName === "Where AI fits" && !crew && (
            <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
              <div>{field("Your experience with AI", true, touched && !d.aiExperience)}
                <LevelPicker value={d.aiExperience} onChange={(v) => set("aiExperience", v)} levels={AI_LEVELS} err={touched && !d.aiExperience} /></div>
              <div>{field("AI in your organization", true, touched && !d.orgFluency)}
                <LevelPicker value={d.orgFluency} onChange={(v) => set("orgFluency", v)} levels={ORG_LEVELS} err={touched && !d.orgFluency} /></div>
              <div>{field("What drew your attention? Pick any.", true, touched && !(d.products || []).length)}
                <div className="responsive-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                  {PRODUCT_INTEREST.map(([ic, t, s]) => {
                    const on = (d.products || []).includes(t);
                    return (
                      <button key={t} type="button" onClick={() => toggle("products", t)} style={{ all: "unset", cursor: "pointer", padding: "16px 16px",
                        borderRadius: 14, transition: "all .2s", background: on ? "rgba(80,134,182,.08)" : "var(--wa-02)",
                        border: `1px solid ${on ? "rgba(80,134,182,.4)" : "var(--hairline-2)"}` }}>
                        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
                          <span style={{ width: 36, height: 36, borderRadius: 10, display: "flex", alignItems: "center", justifyContent: "center",
                            background: on ? "var(--cyan)" : "var(--wa-04)", color: on ? "var(--cyan-ink)" : "var(--cyan-2)" }}><Icon name={ic} size={17} /></span>
                          {on && <Icon name="Check" size={16} color="var(--cyan)" />}
                        </div>
                        <div style={{ fontFamily: "var(--font-ui)", fontSize: 14.5, fontWeight: 600, color: "var(--ink)" }}>{t}</div>
                        <div style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 12.5, color: "var(--ink-3)", marginTop: 3 }}>{s}</div>
                      </button>
                    );
                  })}
                </div>
                {wantsCustom && <div className="ymfade" style={{ marginTop: 10, fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 12.5, color: "var(--ink-3)" }}>
                  Custom Development adds one short step about the systems you run today.</div>}
              </div>
              <div>{field("Anything else? (optional)")}
                <textarea value={d.note || ""} onChange={(e) => set("note", e.target.value)} rows={3} placeholder="A line about your operation or what prompted this…"
                  style={{ ...inputStyle(false), resize: "vertical", lineHeight: 1.5 }} /></div>
            </div>
          )}

          {stepName === "Custom development" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
              <p style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 15, color: "var(--ink-3)", margin: 0, lineHeight: 1.6 }}>
                Custom builds start from the systems you already run. Tell us what's in place today.
              </p>
              {KEY_SYSTEMS.map(([k, t, s]) => (
                <div key={k}>
                  <div style={{ marginBottom: 8 }}>
                    <span style={{ fontFamily: "var(--font-ui)", fontSize: 13, fontWeight: 500, color: "var(--ink-2)" }}>{t}
                      <span style={{ color: touched && !d[k] ? "var(--bad)" : "var(--cyan)" }}> *</span></span>
                    <span style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 12, color: "var(--ink-4)", marginLeft: 8 }}>{s}</span>
                  </div>
                  <div style={{ display: "flex", gap: 9, flexWrap: "wrap" }}>
                    {SYSTEM_MATURITY.map((m) => <Chip key={m} active={d[k] === m} onClick={() => set(k, m)}>{m}</Chip>)}
                  </div>
                </div>
              ))}
              <div>{field("What would you like to build? (optional)")}
                <textarea value={d.customNote || ""} onChange={(e) => set("customNote", e.target.value)} rows={3}
                  placeholder="The workflow, department or problem you'd want a custom build to take on…"
                  style={{ ...inputStyle(false), resize: "vertical", lineHeight: 1.5 }} /></div>
            </div>
          )}

          {stepName === "Review" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <p style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 15, color: "var(--ink-3)", margin: "0 0 6px", lineHeight: 1.6 }}>
                {isSales
                  ? "Here's what we'll bring to your sales call. We'll send a secure magic link to confirm and follow up to schedule a time."
                  : "Here's what we'll bring to our first conversation. We'll send a secure magic link to confirm."}
              </p>
              {submissionRows(d, crew, wantsCustom).map(([k, v]) => (
                <div key={k} style={{ display: "flex", gap: 16, padding: "13px 16px", borderRadius: 12, background: "var(--surface)", border: "1px solid var(--hairline)" }}>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--ink-4)", width: 90, flexShrink: 0, paddingTop: 2 }}>{k}</span>
                  <span style={{ fontFamily: "var(--font-ui)", fontSize: 14, color: "var(--ink)", lineHeight: 1.5 }}>{v}</span>
                </div>
              ))}
            </div>
          )}
        </div>

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 36 }}>
          {step > 0 ? <Btn variant="ghost" onClick={back} icon="ArrowLeft">Back</Btn> : <span />}
          {!last
            ? <Btn onClick={next} iconRight="ArrowRight" style={!validNow ? { opacity: 0.5 } : {}}>Continue</Btn>
            : <Btn onClick={() => {
                // Deliver the lead to the suite's public lead-intake (the AI News
                // API service) — it stores it, mirrors it into the Main CRM and
                // emails the person a receipt. Fire-and-forget: the thank-you
                // screen must show even if the network call fails. Flow-specific
                // fields are gated on audience so a switched draft can't leak
                // stale answers from the other flow.
                try {
                  // Exactly the rows the visitor just confirmed, plus the CTA
                  // origin — internal context the Review step has no reason to
                  // show, but which tells the team where the request came from.
                  // String-coerce every value: the intake validates these as
                  // [string, string] pairs, and one stray undefined would fail
                  // the whole body — losing the lead over a display row.
                  const rows = [
                    ...submissionRows(d, crew, wantsCustom),
                    ...(d.source ? [["Came from", d.source]] : []),
                  ].map(([k, v]) => [String(k), String(v ?? "—")]);
                  const summary = rows.map(([k, v]) => `${k}: ${v}`).join(" · ");
                  fetch("https://news.yachtingstack.ai/api/leads/onboarding", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ email: (d.email || "").trim().toLowerCase(), name: d.name, company: d.company,
                      role: d.role, audience: d.audience, sales: !!isSales, details: rows, summary: summary.slice(0, 2000) }),
                  }).catch(() => {});
                } catch (e) { /* never block the thank-you screen */ }
                setDone(true);
              }} iconRight="Check">{isSales ? "Submit & schedule a call" : "Submit & book a conversation"}</Btn>}
        </div>
      </div>
    </div>
  );
}

function Success({ email, go, reset, isSales }) {
  React.useEffect(() => { reset && reset(); }, []);
  return (
    <div style={{ minHeight: "100vh", paddingTop: 69, display: "flex", alignItems: "center", justifyContent: "center", textAlign: "center", position: "relative", overflow: "hidden" }}>
      {/* Same backdrop as the home page's "AI Agents, deployed on board" section */}
      <img loading="lazy" decoding="async" src="/assets/images/passarelle-boarding.webp" alt=""
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", objectPosition: "center", opacity: 0.06 }} />
      <div style={{ position: "absolute", inset: 0,
        background: "linear-gradient(90deg, var(--bg) 0%, rgba(11,17,30,.94) 16%, rgba(11,17,30,.82) 30%, rgba(11,17,30,.62) 44%, rgba(11,17,30,.42) 58%, rgba(11,17,30,.24) 72%, rgba(11,17,30,.1) 86%, transparent 100%)" }} />
      <div className="ymstep" style={{ position: "relative", maxWidth: 460, padding: 32 }}>
        <div style={{ width: 72, height: 72, margin: "0 auto 24px", borderRadius: 20, background: "rgba(52,211,153,.12)",
          border: "1px solid rgba(52,211,153,.3)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--good)" }}>
          <Icon name="Check" size={34} /></div>
        <h1 style={{ fontFamily: "var(--font-head)", fontWeight: 700, fontSize: 32, color: "var(--ink)", margin: "0 0 12px" }}>
          {isSales ? "Let's get a call on the calendar." : "You're aboard."}
        </h1>
        <p style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 16, lineHeight: 1.7, color: "var(--ink-3)", margin: "0 0 28px" }}>
          {isSales
            ? <>We've got your details. A secure sign-in link is on its way to{" "}
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 14, color: "var(--cyan-2)" }}>{email || "your inbox"}</span> — pick a time below and our team will confirm the call.</>
            : <>We've got your details. A secure sign-in link is on its way to{" "}
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 14, color: "var(--cyan-2)" }}>{email || "your inbox"}</span> — we'll be in touch soon.</>}
        </p>
        <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
          {isSales && <Btn href="mailto:sales@yachtingstack.ai?subject=Schedule%20a%20call" iconRight="Calendar">Schedule a call</Btn>}
          <Btn onClick={() => go("home")} variant={isSales ? "ghost" : "primary"} iconRight="ArrowRight">Back to home</Btn>
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { Onboarding });
