// Atlas · Onboarding — shown once after first Google sign-in
const { useState: useOBState } = React;

const STEPS = [
  { id: "profile", label: "Your profile" },
  { id: "role",    label: "Your role" },
];

const USE_CASES = [
  "Technology Landscape",
  "Market Intelligence",
  "Corporate R&D",
  "Biotech / Pharma",
  "Investment Due Diligence",
  "Academic / University Research",
  "Other",
];

const COMPANY_SIZES = ["1–10", "11–50", "51–200", "201–1,000", "1,000+"];

function Onboarding({ user, onComplete }) {
  const [step, setStep] = useOBState(0);
  const [saving, setSaving] = useOBState(false);

  const [form, setForm] = useOBState({
    name: user?.name || "",
    title: "",
    company: "",
    department: "",
    companySize: "",
    useCase: "",
  });

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

  const canNext = () => {
    if (step === 0) return form.name.trim().length > 1;
    if (step === 1) return form.title.trim().length > 0 && form.company.trim().length > 0;
    return true;
  };

  const handleFinish = async () => {
    setSaving(true);
    try {
      await fetch("/api/profile", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...form, onboardingDone: true }),
      });
      
      // Track completion safely
      try {
        if (window.posthog && typeof posthog.capture === 'function') {
          posthog.capture('onboarding_complete', { ...form });
          if (posthog.people && typeof posthog.people.set === 'function') {
            posthog.people.set({ ...form, onboardingDone: true });
          }
        }
      } catch (err) {
        console.warn("PostHog capture failed:", err);
      }

      onComplete({ ...user, name: form.name, profile: { ...form, onboardingDone: true } });
    } catch (e) {
      alert("Could not save profile: " + e.message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="onboard-wrap">
      <div className="onboard-card">
        {/* Logo */}
        <div className="onboard-logo">
          <span style={{ fontFamily: "var(--serif)", fontSize: 20, fontWeight: 600, letterSpacing: "-0.02em", color: "var(--ink)" }}>Atlas</span>
        </div>

        {/* Progress dots */}
        <div className="onboard-progress">
          {STEPS.map((s, i) => (
            <div key={s.id} className={`onboard-progress-dot ${i <= step ? "done" : ""}`} />
          ))}
        </div>

        {/* Step label */}
        <div className="onboard-step-label">Step {step + 1} of {STEPS.length} · {STEPS[step].label}</div>

        {/* ── Step 0: Name ── */}
        {step === 0 && (
          <>
            <h1 className="onboard-title">Welcome to Atlas.</h1>
            <p className="onboard-sub">Let's get your account set up. We'll start with the basics.</p>

            <div className="onboard-field">
              <label>Full name</label>
              <input value={form.name} onChange={(e) => set("name", e.target.value)} placeholder="Your full name" autoFocus />
            </div>
          </>
        )}

        {/* ── Step 1: Role ── */}
        {step === 1 && (
          <>
            <h1 className="onboard-title">Tell us about your work.</h1>
            <p className="onboard-sub">This helps Atlas tailor reports to the right depth and audience.</p>

            <div className="onboard-row">
              <div className="onboard-field">
                <label>Job title</label>
                <input value={form.title} onChange={(e) => set("title", e.target.value)} placeholder="e.g. VP of R&D" autoFocus />
              </div>
              <div className="onboard-field">
                <label>Company / organisation</label>
                <input value={form.company} onChange={(e) => set("company", e.target.value)} placeholder="e.g. Acme Bio" />
              </div>
            </div>

            <div className="onboard-row">
              <div className="onboard-field">
                <label>Department <span style={{ color: "var(--ink-4)", fontWeight: 400 }}>(optional)</span></label>
                <input value={form.department} onChange={(e) => set("department", e.target.value)} placeholder="e.g. Business Development" />
              </div>
              <div className="onboard-field">
                <label>Company size</label>
                <select value={form.companySize} onChange={(e) => set("companySize", e.target.value)}>
                  <option value="">Select…</option>
                  {COMPANY_SIZES.map((s) => <option key={s} value={s}>{s} employees</option>)}
                </select>
              </div>
            </div>

            <div className="onboard-field">
              <label>Primary use case</label>
              <select value={form.useCase} onChange={(e) => set("useCase", e.target.value)}>
                <option value="">Select…</option>
                {USE_CASES.map((u) => <option key={u} value={u}>{u}</option>)}
              </select>
            </div>
          </>
        )}


        {/* Nav buttons */}
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 32 }}>
          <button
            className="btn ghost"
            onClick={() => step > 0 ? setStep(step - 1) : null}
            style={{ visibility: step > 0 ? "visible" : "hidden" }}
          >Back</button>

          {step < STEPS.length - 1 ? (
            <button className="btn primary lg" disabled={!canNext()} onClick={() => setStep(step + 1)}>
              Continue <Icon name="arrowRight" size={14} />
            </button>
          ) : (
            <button className="btn primary lg" disabled={saving} onClick={handleFinish}>
              {saving ? "Saving…" : "Get started"} {!saving && <Icon name="arrowRight" size={14} />}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

window.Onboarding = Onboarding;
