/* global React */
// Onboarding — the primary CTA. Multi-step, validated, persisted, animated.
const { Icon, Eyebrow, Btn } = window;

const STEPS = ["About you", "Your operation", "Where AI fits", "Review"];
const ROLES = ["Owner", "Captain", "Management", "Brokerage", "Crew", "Other"];
const SEGMENTS = ["Charter", "Private", "Management", "Brokerage", "Marina / shipyard"];
const FLEET = ["1 vessel", "2–5", "6–15", "16+"];
const SYSTEMS = ["YachtManager", "Sails.crm", "Certispec", "AIS data", "Spreadsheets", "Other"];
const GOALS = [
  ["Eye", "Be seen by AI", "Visibility & Agent-Ready Score"],
  ["ShieldAlert", "Protect privacy", "Exposure scanning & monitoring"],
  ["Bot", "Custom agents", "Agents connected to your data"],
  ["Workflow", "SOPs & simulation", "Generate and test procedures"],
  ["Cpu", "Data & models", "Structured data, tuned models"],
  ["HelpCircle", "Not sure yet", "Help us map where AI fits"],
];
const KEY = "ym_onboarding_v1";

function field(label, req) {
  return <label style={{ display: "block", fontFamily: "var(--font-ui)", fontSize: 13, fontWeight: 500,
    color: "var(--ink-2)", marginBottom: 8 }}>{label}{req && <span style={{ color: "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)" : "rgba(255,255,255,.03)",
      border: `1px solid ${active ? "var(--cyan)" : "var(--hairline-2)"}`, ...style }}>{children}</button>
  );
}

function Onboarding({ go }) {
  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]);

  const emailOk = /.+@.+\..+/.test(d.email || "");
  const valid = [
    !!(d.name && d.company && emailOk && d.role),
    !!(d.segment && d.fleet),
    !!(d.goals && d.goals.length),
    true,
  ];
  const next = () => { if (!valid[step]) { setTouched(true); return; } setTouched(false); setStep((s) => Math.min(s + 1, 3)); 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); }} />;

  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>Onboarding</Eyebrow>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--ink-3)" }}>Step {step + 1} of 4 · {STEPS[step]}</span>
        </div>
        <div style={{ height: 4, borderRadius: 4, background: "rgba(255,255,255,.05)", overflow: "hidden", marginBottom: 36 }}>
          <div style={{ height: "100%", width: `${((step + 1) / 4) * 100}%`, borderRadius: 4,
            background: "linear-gradient(90deg, var(--cyan-deep), var(--cyan))", transition: "width .5s var(--ease)" }} />
        </div>

        <div key={step} className="ymstep">
          <h1 style={{ fontFamily: "var(--font-head)", fontWeight: 700, fontSize: 30, color: "var(--ink)", margin: "0 0 28px" }}>{STEPS[step]}</h1>

          {step === 0 && (
            <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
              <div 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="Alex Marin" style={inputStyle(touched && !d.name)} /></div>
                <div>{field("Company", true)}<input value={d.company || ""} onChange={(e) => set("company", e.target.value)} placeholder="Ibiza Charter Yachts" style={inputStyle(touched && !d.company)} /></div>
              </div>
              <div>{field("Work email", true)}<input type="email" value={d.email || ""} onChange={(e) => set("email", e.target.value)} placeholder="you@company.yachts" 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("Your role", true)}<div style={{ display: "flex", gap: 9, flexWrap: "wrap" }}>{ROLES.map((r) => <Chip key={r} active={d.role === r} onClick={() => set("role", r)}>{r}</Chip>)}</div></div>
            </div>
          )}

          {step === 1 && (
            <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
              <div>{field("What's your segment?", true)}<div style={{ display: "flex", gap: 9, flexWrap: "wrap" }}>{SEGMENTS.map((s) => <Chip key={s} active={d.segment === s} onClick={() => set("segment", s)}>{s}</Chip>)}</div></div>
              <div>{field("Fleet size", true)}<div style={{ display: "flex", gap: 9, flexWrap: "wrap" }}>{FLEET.map((f) => <Chip key={f} active={d.fleet === f} onClick={() => set("fleet", f)}>{f}</Chip>)}</div></div>
              <div>{field("Where do you operate?")}<div style={{ display: "flex", gap: 9, flexWrap: "wrap" }}>
                {["On board", "On shore"].map((x) => <Chip key={x} active={(d.where || []).includes(x)} onClick={() => toggle("where", x)}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}><Icon name={x === "On board" ? "Anchor" : "Building2"} size={14} />{x}</span></Chip>)}</div></div>
              <div>{field("Systems you run (optional)")}<div style={{ display: "flex", gap: 9, flexWrap: "wrap" }}>{SYSTEMS.map((s) => <Chip key={s} active={(d.systems || []).includes(s)} onClick={() => toggle("systems", s)}>{s}</Chip>)}</div></div>
            </div>
          )}

          {step === 2 && (
            <div>
              {field("What are you hoping AI can do? Pick any.", true)}
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                {GOALS.map(([ic, t, s]) => {
                  const on = (d.goals || []).includes(t);
                  return (
                    <button key={t} type="button" onClick={() => toggle("goals", t)} style={{ all: "unset", cursor: "pointer", padding: "16px 16px",
                      borderRadius: 14, transition: "all .2s", background: on ? "rgba(250,204,21,.08)" : "rgba(255,255,255,.02)",
                      border: `1px solid ${on ? "rgba(250,204,21,.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)" : "rgba(255,255,255,.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>
              <div style={{ marginTop: 22 }}>{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>
          )}

          {step === 3 && (
            <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 }}>
                Here's what we'll bring to our first conversation. We'll send a secure magic link to confirm.
              </p>
              {[["Contact", `${d.name} · ${d.company}`], ["Email", d.email], ["Role", d.role],
                ["Operation", `${d.segment} · ${d.fleet}${(d.where || []).length ? " · " + d.where.join(" + ") : ""}`],
                ["Systems", (d.systems || []).join(", ") || "—"], ["Goals", (d.goals || []).join(", ") || "—"]].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 />}
          {step < 3
            ? <Btn onClick={next} iconRight="ArrowRight" style={!valid[step] ? { opacity: 0.5 } : {}}>Continue</Btn>
            : <Btn onClick={() => setDone(true)} iconRight="Check">Submit &amp; book a conversation</Btn>}
        </div>
      </div>
    </div>
  );
}

function Success({ email, go, reset }) {
  React.useEffect(() => { reset && reset(); }, []);
  return (
    <div style={{ minHeight: "100vh", paddingTop: 69, display: "flex", alignItems: "center", justifyContent: "center", textAlign: "center", position: "relative", overflow: "hidden" }}>
      <div style={{ position: "absolute", inset: 0, background: "radial-gradient(ellipse 50% 50% at 50% 40%, rgba(250,204,21,.1), transparent 70%)" }} />
      <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" }}>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" }}>
          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 to map where AI fits.
        </p>
        <div style={{ display: "flex", gap: 12, justifyContent: "center" }}>
          <Btn onClick={() => go("home")} iconRight="ArrowRight">Back to home</Btn>
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { Onboarding });
