// Primus IQ — Auth: Login + Onboarding (v1)
// Self-contained: no dependency on other components. All styling via CSS tokens.

// ── TAXONOMY ──────────────────────────────────────────────────────────────────
const TAXONOMY = {
  designations: [
    { value: "analyst", label: "Analyst" },
    { value: "consultant", label: "Consultant" },
    { value: "sr. consultant", label: "Sr. Consultant" },
    { value: "software engineer", label: "Software Engineer" },
    { value: "manager", label: "Manager" },
    { value: "avp", label: "AVP" },
    { value: "senior software engineer", label: "Senior Software Engineer" },
    { value: "vp", label: "VP" },
    { value: "ed", label: "ED" },
    { value: "md/ceo", label: "MD/CEO" },
    { value: "system manager", label: "System Manager" },
    { value: "sr. system manager", label: "Sr. System Manager" },
  ],
  domains: ["Strategy", "Public Policy", "IT/Digital", "Finance", "Operations", "ESG"],
  skills: [
    "Financial Modeling", "Market Research", "Stakeholder Engagement", "Policy Analysis",
    "Data Analytics", "Project Management", "Business Development", "Process Optimization",
  ],
  tools: ["PowerPoint", "Excel", "Power BI", "Tableau", "Python", "SQL", "QGIS"],
  methodologies: [
    "Theory of Change", "Value Chain Analysis", "Porter's Five Forces", "Lean", "Agile",
  ],
  industries: [
    "Industrial Development", "Smart Cities", "Rural Growth", "Digital Government",
    "Climate & Energy", "Health Systems", "Financial Inclusion",
  ],
  regions: [
    "Pan-India", "North India", "South India", "East India", "West India",
    "APAC", "MENA", "Africa", "Europe",
  ],
  languages: ["English", "Hindi", "Tamil", "Telugu", "Marathi", "Bengali", "Gujarati"],
  practices: [
    "Public Policy Realization", "Sector Potential Realization", "Impact Realization",
    "Economic Potential Realization", "Data & Digital Strategy", "Transaction Realization",
  ],
};
window.TAXONOMY = TAXONOMY;

// ── LoginVideo ────────────────────────────────────────────────────────────────
const LoginVideo = () => (
  <>
    <video
      autoPlay loop muted playsInline
      style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }}
      src="assets/primus_iq_login.mp4"
    />
    {/* Maroon tint so white text at the bottom stays readable */}
    <div style={{
      position: "absolute", inset: 0,
      background: "linear-gradient(160deg, rgba(80,16,16,0.45) 0%, rgba(60,10,10,0.72) 100%)",
    }} />
  </>
);

// ── Login ─────────────────────────────────────────────────────────────────────
const Login = ({ onLogin }) => {
  const [email, setEmail] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [step, setStep] = React.useState(0); // 0=email, 1=password
  const [err, setErr] = React.useState({});
  const [loading, setLoading] = React.useState(false);

  const isSso = email.toLowerCase().endsWith("@primuspartners.in");

  const onNext = (e) => {
    e && e.preventDefault();
    if (!email.match(/.+@.+\..+/)) { setErr({ email: "Enter a valid work email." }); return; }
    setErr({});
    if (isSso) { setLoading(true); window.location.href = `/auth/sso/login?email=${encodeURIComponent(email)}`; }
    else setStep(1);
  };

  const onManualLogin = async (e) => {
    e.preventDefault();
    if (pw.length < 6) { setErr({ pw: "Password must be at least 6 characters." }); return; }
    setLoading(true);
    try {
      const data = await PrimusAPI.login(email, pw);
      onLogin(data);
    } catch (ex) {
      setErr({ pw: ex.message || "Invalid credentials." });
    } finally { setLoading(false); }
  };

  const inputStyle = (hasErr) => ({
    width: "100%", height: 44, padding: "0 14px",
    border: `1px solid ${hasErr ? "var(--maroon)" : "var(--line-2)"}`,
    borderRadius: "var(--r-md)", fontSize: 14, fontFamily: "inherit",
    background: "var(--bg-card)", color: "var(--ink)", boxSizing: "border-box",
    outline: "none", transition: "border-color 0.15s",
  });

  return (
    <div className="login-container">
      {/* Left brand panel */}
      <div className="login-left-panel">
        <LoginVideo />
        <div style={{ position: "relative", zIndex: 1 }}>
          <div style={{
            color: "rgba(255,255,255,0.5)", fontSize: 10, fontWeight: 700,
            letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 12,
          }}>Primus Partners</div>
          <h1 className="t-display" style={{ color: "white", margin: "0 0 16px" }}>Primus IQ</h1>
          <p className="t-body-sm" style={{ color: "rgba(255,255,255,0.65)", lineHeight: 1.6, maxWidth: 320, margin: 0 }}>
            Every deck, dataset and decision — woven into one firm-wide intelligence layer.
          </p>
        </div>
      </div>

      {/* Right form panel */}
      <div className="login-right-panel">
        <div style={{ width: "100%", maxWidth: 380 }}>
          <div className="t-eyebrow" style={{ marginBottom: 24 }}>Sign in to Primus IQ</div>
          <h2 className="t-h1" style={{ margin: "0 0 8px" }}>{step === 0 ? "Welcome back." : "Enter password."}</h2>
          <p className="t-body-sm" style={{ color: "var(--mute)", marginBottom: 32, margin: "0 0 32px" }}>
            {step === 0 ? "Sign in with your Primus work email." : "Enter your credentials to continue."}
          </p>

          <form onSubmit={step === 0 ? onNext : onManualLogin} style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            {step === 0 ? (
              <div>
                <label style={{ display: "block", fontSize: 12, fontWeight: 600, marginBottom: 6, color: "var(--ink-2)" }}>
                  Work email
                </label>
                <input
                  type="email" value={email}
                  onChange={e => { setEmail(e.target.value); setErr({}); }}
                  placeholder="name@primuspartners.in" autoFocus
                  style={inputStyle(!!err.email)}
                />
                {err.email && <p style={{ color: "var(--maroon)", fontSize: 12, margin: "4px 0 0" }}>{err.email}</p>}
              </div>
            ) : (
              <>
                <div style={{
                  display: "flex", alignItems: "center", gap: 8,
                  padding: "8px 12px", background: "var(--bg-soft)",
                  borderRadius: "var(--r-sm)", fontSize: 13, color: "var(--ink-2)",
                }}>
                  <span style={{ flex: 1 }}>{email}</span>
                  <button
                    type="button" onClick={() => setStep(0)}
                    style={{ border: "none", background: "none", color: "var(--maroon)", fontSize: 12, cursor: "pointer", fontWeight: 600 }}
                  >Edit</button>
                </div>
                <div>
                  <label style={{ display: "block", fontSize: 12, fontWeight: 600, marginBottom: 6, color: "var(--ink-2)" }}>Password</label>
                  <input
                    type="password" value={pw}
                    onChange={e => { setPw(e.target.value); setErr({}); }} autoFocus
                    style={inputStyle(!!err.pw)}
                  />
                  {err.pw && <p style={{ color: "var(--maroon)", fontSize: 12, margin: "4px 0 0" }}>{err.pw}</p>}
                </div>
              </>
            )}

            <button type="submit" className="btn-primary" style={{ width: "100%", justifyContent: "center" }} disabled={loading}>
              {loading ? "Connecting…" : (isSso && step === 0) ? "Continue with Microsoft SSO" : step === 0 ? "Continue" : "Sign in"}
            </button>
          </form>

          <div style={{
            marginTop: 24, padding: "12px 14px", background: "var(--bg-soft)",
            borderRadius: "var(--r-sm)", fontSize: 12, color: "var(--mute)",
            display: "flex", gap: 8, alignItems: "flex-start",
          }}>
            <span>🔐</span>
            <span>
              <strong style={{ color: "var(--ink-2)" }}>Secure by default</strong>
              {" "}· Microsoft Entra ID enforced · @primuspartners.in SSO required
            </span>
          </div>
          <p style={{ marginTop: 16, fontSize: 12, color: "var(--mute)", textAlign: "center" }}>
            Trouble signing in?{" "}
            <a href="mailto:it@primuspartners.in" style={{ color: "var(--maroon)" }}>Contact IT</a>
          </p>
        </div>
      </div>
    </div>
  );
};

// ── Onboarding helpers ─────────────────────────────────────────────────────────

const InputField = ({ label, hint, error, required, children }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
    <label style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-2)", display: "flex", gap: 4, alignItems: "center" }}>
      {label}
      {required && <span style={{ color: "var(--maroon)" }}>*</span>}
      {hint && <span style={{ fontWeight: 400, color: "var(--mute)", fontSize: 11 }}>· {hint}</span>}
    </label>
    {children}
    {error && <p style={{ fontSize: 12, color: "var(--maroon)", margin: 0 }}>{error}</p>}
  </div>
);

const textInputStyle = (hasErr) => ({
  width: "100%", height: 40, padding: "0 12px",
  border: `1px solid ${hasErr ? "var(--maroon)" : "var(--line-2)"}`,
  borderRadius: "var(--r-md)", fontSize: 14, fontFamily: "inherit",
  background: "var(--bg-card)", color: "var(--ink)", boxSizing: "border-box",
  outline: "none", transition: "border-color 0.15s",
});

const TextInput = ({ error, ...props }) => (
  <input style={textInputStyle(!!error)} {...props} />
);

const SelectInput = ({ value, onChange, options, placeholder, error, disabled }) => (
  <select
    value={value} onChange={e => onChange(e.target.value)}
    disabled={disabled}
    style={{
      ...textInputStyle(!!error),
      cursor: disabled ? "not-allowed" : "pointer",
      opacity: disabled ? 0.6 : 1,
    }}
  >
    {placeholder && <option value="">{placeholder}</option>}
    {options.map(opt => (
      typeof opt === "string"
        ? <option key={opt} value={opt}>{opt}</option>
        : <option key={opt.value} value={opt.value}>{opt.label}</option>
    ))}
  </select>
);

const MultiChipInput = ({ values, onChange, options, allowCustom }) => {
  const [inputVal, setInputVal] = React.useState("");

  const add = (v) => {
    const trimmed = v.trim();
    if (trimmed && !values.includes(trimmed)) onChange([...values, trimmed]);
    setInputVal("");
  };

  const remove = (v) => onChange(values.filter(x => x !== v));

  const onKeyDown = (e) => {
    if (e.key === "Enter") { e.preventDefault(); if (inputVal.trim()) add(inputVal); }
    if (e.key === "Backspace" && !inputVal && values.length > 0) remove(values[values.length - 1]);
  };

  const filteredOptions = options
    ? options.filter(o => !values.includes(o) && (inputVal === "" || o.toLowerCase().includes(inputVal.toLowerCase())))
    : [];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <div style={{
        display: "flex", flexWrap: "wrap", gap: 6, padding: "6px 10px",
        border: "1px solid var(--line-2)", borderRadius: "var(--r-md)",
        background: "var(--bg-card)", minHeight: 40, alignItems: "center",
      }}>
        {values.map(v => (
          <span key={v} style={{
            display: "inline-flex", alignItems: "center", gap: 4,
            padding: "2px 8px 2px 10px", background: "var(--maroon-06)",
            color: "var(--maroon)", borderRadius: 999, fontSize: 12, fontWeight: 500,
          }}>
            {v}
            <button
              type="button" onClick={() => remove(v)}
              style={{ border: "none", background: "none", cursor: "pointer", color: "var(--maroon)", padding: 0, fontSize: 14, lineHeight: 1, display: "flex", alignItems: "center" }}
            >×</button>
          </span>
        ))}
        <input
          value={inputVal} onChange={e => setInputVal(e.target.value)} onKeyDown={onKeyDown}
          placeholder={values.length === 0 ? "Type and press Enter…" : ""}
          style={{ border: "none", outline: "none", fontSize: 13, fontFamily: "inherit", background: "transparent", flex: 1, minWidth: 80, color: "var(--ink)" }}
        />
      </div>
      {filteredOptions.length > 0 && inputVal && (
        <div style={{
          background: "var(--bg-card)", border: "1px solid var(--line-2)",
          borderRadius: "var(--r-md)", boxShadow: "var(--shadow-sm)",
          maxHeight: 160, overflowY: "auto", padding: "4px 0",
        }}>
          {filteredOptions.slice(0, 8).map(opt => (
            <div
              key={opt} onClick={() => add(opt)}
              style={{ padding: "8px 12px", fontSize: 13, cursor: "pointer", color: "var(--ink)" }}
              onMouseEnter={e => e.currentTarget.style.background = "var(--bg-soft)"}
              onMouseLeave={e => e.currentTarget.style.background = "transparent"}
            >{opt}</div>
          ))}
        </div>
      )}
    </div>
  );
};

// ── Onboarding step components ─────────────────────────────────────────────────

const BasicStep = ({ form, set, errors }) => {
  const handleFileChange = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const isValid = file.type === "application/pdf" || file.name.endsWith(".docx") || file.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    if (!isValid) { alert("Please upload a PDF or DOCX file."); return; }
    if (file.size > 10 * 1024 * 1024) { alert("File must be under 10 MB."); return; }
    set("resumeFile", file);
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div className="pi-grid-2">
        <InputField label="Primus email" hint="Read-only">
          <TextInput value={form.email} readOnly style={{ ...textInputStyle(false), opacity: 0.65, cursor: "not-allowed" }} />
        </InputField>
        <InputField label="Full name" required error={errors.fullName}>
          <TextInput value={form.fullName} onChange={e => set("fullName", e.target.value)} placeholder="As on records" error={errors.fullName} />
        </InputField>
      </div>
      <div className="pi-grid-2">
        <InputField label="Employee code" required error={errors.empCode}>
          <TextInput value={form.empCode} onChange={e => set("empCode", e.target.value.toUpperCase())} placeholder="e.g. PP-04129" error={errors.empCode} />
        </InputField>
        <InputField label="Designation" hint="Synced from Microsoft Graph">
          <TextInput value={form.designation || "—"} readOnly style={{ ...textInputStyle(false), opacity: 0.65, cursor: "not-allowed" }} />
        </InputField>
      </div>
      <div className="pi-grid-2">
        <InputField label="Years of experience" required error={errors.yoe}>
          <TextInput type="number" min="0" max="50" value={form.yoe} onChange={e => set("yoe", e.target.value)} placeholder="0" error={errors.yoe} />
        </InputField>
        <InputField label="Resume" hint="PDF or DOCX · max 10 MB">
          <div style={{
            height: 40, padding: "0 12px", border: "1px solid var(--line-2)",
            borderRadius: "var(--r-md)", display: "flex", alignItems: "center", gap: 8,
            background: "var(--bg-card)", cursor: "pointer", fontSize: 13, color: "var(--ink-2)",
            position: "relative", overflow: "hidden",
          }}>
            <input
              type="file" accept=".pdf,.docx"
              onChange={handleFileChange}
              style={{ position: "absolute", inset: 0, opacity: 0, cursor: "pointer", width: "100%", height: "100%" }}
            />
            <span style={{ fontSize: 14 }}>📎</span>
            <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: form.resumeFile ? "var(--ink)" : "var(--mute-2)" }}>
              {form.resumeFile ? form.resumeFile.name : "Choose file…"}
            </span>
          </div>
        </InputField>
      </div>
    </div>
  );
};

const ExpertiseStep = ({ form, set, errors }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
    <div className="pi-grid-2">
      <InputField label="Primary domain" required error={errors.primary}>
        <SelectInput
          value={form.primary} onChange={v => set("primary", v)}
          options={TAXONOMY.domains} placeholder="Select domain…" error={errors.primary}
        />
      </InputField>
      <InputField label="Secondary domain" hint="Optional">
        <SelectInput
          value={form.secondary} onChange={v => set("secondary", v)}
          options={TAXONOMY.domains.filter(d => d !== form.primary)} placeholder="Optional…"
        />
      </InputField>
    </div>
    <InputField label="Skills" required hint="Type and press Enter to add" error={errors.skills}>
      <MultiChipInput values={form.skills} onChange={v => set("skills", v)} options={TAXONOMY.skills} allowCustom />
    </InputField>
    <InputField label="Tools / Tech" hint="Optional">
      <MultiChipInput values={form.tools} onChange={v => set("tools", v)} options={TAXONOMY.tools} allowCustom />
    </InputField>
    <InputField label="Methodologies" hint="Optional">
      <MultiChipInput values={form.methodologies} onChange={v => set("methodologies", v)} options={TAXONOMY.methodologies} />
    </InputField>
  </div>
);

const IndustryStep = ({ form, set, errors }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
    <InputField label="Industries" required hint="Sectors you have delivered work in" error={errors.industries}>
      <MultiChipInput values={form.industries} onChange={v => set("industries", v)} options={TAXONOMY.industries} />
    </InputField>
    <InputField label="Regions" hint="Optional">
      <MultiChipInput values={form.regions} onChange={v => set("regions", v)} options={TAXONOMY.regions} />
    </InputField>
    <InputField label="Languages" hint="Spoken · for stakeholder fit">
      <MultiChipInput values={form.languages} onChange={v => set("languages", v)} options={TAXONOMY.languages} allowCustom />
    </InputField>
  </div>
);

const ReviewStep = ({ form }) => {
  const designationLabel = TAXONOMY.designations.find(d => d.value === form.designation)?.label || form.designation || "—";
  const Row = ({ k, v }) => {
    let display;
    if (Array.isArray(v)) {
      display = v.length > 0
        ? v.map(x => (
          <span key={x} style={{
            display: "inline-flex", alignItems: "center", padding: "2px 8px",
            background: "var(--bg-soft)", borderRadius: 999, fontSize: 12,
            border: "1px solid var(--line)", marginRight: 4, marginBottom: 2,
          }}>{x}</span>
        ))
        : <span style={{ color: "var(--mute)" }}>—</span>;
    } else {
      display = v || <span style={{ color: "var(--mute)" }}>—</span>;
    }
    return (
      <div style={{ display: "flex", gap: 16, padding: "10px 0", borderBottom: "1px solid var(--line)" }}>
        <div style={{ width: 160, flexShrink: 0, fontSize: 12, fontWeight: 600, color: "var(--mute)", paddingTop: 2 }}>{k}</div>
        <div style={{ flex: 1, fontSize: 13, color: "var(--ink)", display: "flex", flexWrap: "wrap", alignItems: "flex-start" }}>{display}</div>
      </div>
    );
  };
  return (
    <div style={{ background: "var(--bg-card)", borderRadius: "var(--r-lg)", border: "1px solid var(--line)", padding: "20px 24px" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
        <h3 className="t-h2" style={{ margin: 0 }}>Review your Consultant DNA</h3>
        <span style={{
          padding: "3px 10px", borderRadius: "var(--r-sm)",
          background: "var(--maroon-06)", color: "var(--maroon)",
          fontSize: 12, fontWeight: 600,
        }}>{designationLabel}</span>
      </div>
      <Row k="Email" v={form.email} />
      <Row k="Full name" v={form.fullName} />
      <Row k="Employee code" v={form.empCode} />
      <Row k="Designation" v={designationLabel} />
      <Row k="Experience" v={form.yoe ? `${form.yoe} years` : null} />
      <Row k="Resume" v={form.resumeFile ? form.resumeFile.name : "Not uploaded"} />
      <Row k="Primary domain" v={form.primary} />
      <Row k="Secondary domain" v={form.secondary} />
      <Row k="Skills" v={form.skills} />
      <Row k="Tools / Tech" v={form.tools} />
      <Row k="Methodologies" v={form.methodologies} />
      <Row k="Industries" v={form.industries} />
      <Row k="Regions" v={form.regions} />
      <Row k="Languages" v={form.languages} />
    </div>
  );
};

// ── Onboarding ─────────────────────────────────────────────────────────────────
const ONBOARDING_STEPS = ["Basic", "Expertise", "Industry", "Review"];

const Onboarding = ({ user, onComplete }) => {
  const [step, setStep] = React.useState(0);
  const [form, setForm] = React.useState({
    email: user?.primus_email || user?.email || "",
    fullName: user?.full_name || "",
    empCode: user?.emp_code || "",
    designation: user?.designation || "",
    yoe: String(user?.yoe ?? ""),
    resumeFile: null,
    primary: user?.primary_domain || "",
    secondary: user?.secondary_domain || "",
    skills: user?.skills || [],
    tools: user?.tools || [],
    methodologies: user?.methodologies || [],
    industries: user?.industries || [],
    regions: user?.regions || [],
    languages: user?.languages || [],
  });
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const validateStep = () => {
    const e = {};
    if (step === 0) {
      if (!form.fullName.trim()) e.fullName = "Full name is required.";
      if (!form.empCode.trim()) e.empCode = "Employee code is required.";
      if (form.yoe === "" || isNaN(+form.yoe) || +form.yoe < 0) e.yoe = "Enter a number ≥ 0.";
    } else if (step === 1) {
      if (!form.primary) e.primary = "Pick a primary domain.";
      if (form.skills.length === 0) e.skills = "Add at least one skill.";
    } else if (step === 2) {
      if (form.industries.length === 0) e.industries = "Select at least one industry.";
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const next = async () => {
    if (!validateStep()) return;
    setLoading(true);
    try {
      if (step === 0) {
        await PrimusAPI.profileStep1({ full_name: form.fullName, emp_code: form.empCode, yoe: parseInt(form.yoe, 10), designation: form.designation || undefined });
        if (form.resumeFile) {
          try { await PrimusAPI.uploadResume(form.resumeFile); } catch (ex) { console.warn("Resume upload failed:", ex); }
        }
      } else if (step === 1) {
        await PrimusAPI.profileStep2({ primary_domain: form.primary, secondary_domain: form.secondary || "", skills: form.skills, tools: form.tools, methodologies: form.methodologies });
      } else if (step === 2) {
        await PrimusAPI.profileStep3({ industries: form.industries, regions: form.regions, languages: form.languages });
      }
      setStep(s => s + 1);
    } catch (ex) { setErrors({ api: ex.message }); }
    finally { setLoading(false); }
  };

  const handleSubmit = async () => {
    setLoading(true);
    try { await PrimusAPI.profileFinalize(); onComplete(); }
    catch (ex) { setErrors({ api: ex.message }); }
    finally { setLoading(false); }
  };

  const stepTitles = ["Identity", "Expertise", "Background", "Review"];
  const stepDescs = [
    "Your basic profile information.",
    "Your domain expertise and skills.",
    "Industries and regions you've worked in.",
    "Review your profile before submitting.",
  ];

  return (
    <div className="onboarding-container">
      {/* Left aside */}
      <div className="onboarding-left-panel">
        <div className="t-eyebrow">Primus IQ</div>
        <h1 className="t-h1" style={{ margin: 0 }}>
          Build your<br />
          <em style={{ fontFamily: "Fraunces, Georgia, serif", fontStyle: "italic", color: "var(--maroon)" }}>Consultant DNA.</em>
        </h1>
        <p className="t-body-sm" style={{ color: "var(--mute)", lineHeight: 1.7, margin: 0 }}>
          A few minutes to map your expertise — so the firm's intelligence layer can route work to you and surface your past contributions.
        </p>
        <div style={{ display: "flex", flexDirection: "column", gap: 16, marginTop: 8 }}>
          {["Capture once. Used everywhere.", "Edit any time from your profile.", "Your data. Restricted views by role."].map((t, i) => (
            <div key={i} style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
              <span style={{
                width: 20, height: 20, borderRadius: "50%",
                background: "var(--maroon-soft)", color: "var(--maroon)",
                fontSize: 10, fontWeight: 700, display: "grid", placeItems: "center", flexShrink: 0,
              }}>{i + 1}</span>
              <span className="t-body-sm" style={{ color: "var(--ink-2)" }}>{t}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Right form */}
      <div className="onboarding-right-panel">
        <div style={{ maxWidth: 560 }}>
          {/* Step indicator */}
          <div style={{ display: "flex", alignItems: "center", gap: 0, marginBottom: 32 }}>
            {ONBOARDING_STEPS.map((s, i) => (
              <React.Fragment key={s}>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                  <div style={{
                    width: 28, height: 28, borderRadius: "50%", display: "grid", placeItems: "center",
                    fontSize: 12, fontWeight: 700,
                    background: i <= step ? "var(--maroon)" : "var(--line)",
                    color: i <= step ? "white" : "var(--mute)",
                  }}>
                    {i < step ? "✓" : i + 1}
                  </div>
                  <span style={{
                    fontSize: 10, fontWeight: i === step ? 700 : 400,
                    color: i === step ? "var(--maroon)" : "var(--mute)", whiteSpace: "nowrap",
                  }}>{s}</span>
                </div>
                {i < ONBOARDING_STEPS.length - 1 && (
                  <div style={{
                    flex: 1, height: 2,
                    background: i < step ? "var(--maroon)" : "var(--line)",
                    margin: "0 4px", marginBottom: 18,
                  }} />
                )}
              </React.Fragment>
            ))}
          </div>

          <h2 className="t-h2" style={{ margin: "0 0 6px" }}>{stepTitles[step]}</h2>
          <p className="t-body-sm" style={{ color: "var(--mute)", marginBottom: 24 }}>{stepDescs[step]}</p>

          {errors.api && (
            <div style={{
              padding: "10px 14px", background: "#fef2f2", color: "#dc2626",
              borderRadius: "var(--r-sm)", fontSize: 13, marginBottom: 16,
            }}>{errors.api}</div>
          )}

          {step === 0 && <BasicStep form={form} set={set} errors={errors} />}
          {step === 1 && <ExpertiseStep form={form} set={set} errors={errors} />}
          {step === 2 && <IndustryStep form={form} set={set} errors={errors} />}
          {step === 3 && <ReviewStep form={form} />}

          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 32, paddingTop: 20, borderTop: "1px solid var(--line)" }}>
            <button
              className="btn-ghost"
              onClick={() => setStep(s => Math.max(s - 1, 0))}
              disabled={step === 0 || loading}
              style={{ visibility: step === 0 ? "hidden" : "visible" }}
            >&larr; Back</button>
            <div style={{ display: "flex", gap: 8 }}>
              {step < ONBOARDING_STEPS.length - 1 ? (
                <button className="btn-primary" onClick={next} disabled={loading}>
                  {loading ? "Saving…" : "Continue →"}
                </button>
              ) : (
                <button className="btn-primary" onClick={handleSubmit} disabled={loading}>
                  {loading ? "Submitting…" : "Submit profile ✓"}
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ── Expose on window ────────────────────────────────────────────────────────────
Object.assign(window, { Login, Onboarding });
