// Inline brand marks — Lucide dropped github/linkedin from its CDN.
function BrandSvg({ kind, size = 16, color = "currentColor" }) {
  const paths = {
    github: "M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.1.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.87-1.54-3.87-1.54-.52-1.32-1.27-1.67-1.27-1.67-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.75 2.69 1.25 3.34.96.1-.74.4-1.25.72-1.54-2.55-.29-5.24-1.28-5.24-5.69 0-1.26.45-2.29 1.18-3.1-.12-.29-.51-1.46.11-3.05 0 0 .97-.31 3.18 1.18a11.05 11.05 0 0 1 5.79 0c2.21-1.49 3.18-1.18 3.18-1.18.62 1.59.23 2.76.11 3.05.74.81 1.18 1.84 1.18 3.1 0 4.42-2.69 5.39-5.26 5.68.41.36.78 1.07.78 2.16 0 1.56-.01 2.81-.01 3.19 0 .31.21.67.8.55C20.21 21.39 23.5 17.08 23.5 12 23.5 5.65 18.35.5 12 .5Z",
    linkedin: "M20.45 20.45h-3.55v-5.57c0-1.33-.02-3.04-1.85-3.04-1.85 0-2.13 1.45-2.13 2.94v5.67H9.36V9h3.41v1.56h.05c.48-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.46v6.28ZM5.34 7.43a2.06 2.06 0 1 1 0-4.12 2.06 2.06 0 0 1 0 4.12ZM7.12 20.45H3.56V9h3.56v11.45ZM22.22 0H1.77C.79 0 0 .77 0 1.72v20.56C0 23.23.79 24 1.77 24h20.45C23.21 24 24 23.227 24 22.28V1.72C24 .77 23.21 0 22.22 0Z",
  };
  if (!paths[kind]) return null;
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={color} aria-hidden="true" style={{ flexShrink: 0 }}>
      <path d={paths[kind]} />
    </svg>
  );
}
window.BrandSvg = BrandSvg;

const LEVEL_OPTIONS = [
  { value: "intern",  label: "Intern",         sub: "Summer or co-op position" },
  { value: "junior",  label: "Junior / Entry",  sub: "0 – 2 years of experience" },
  { value: "mid",     label: "Mid-level",       sub: "2 – 5 years of experience" },
  { value: "senior",  label: "Senior",          sub: "5+ years, owns projects end-to-end" },
];

const ROLE_CHIPS = [
  "Software Engineer", "Frontend Engineer", "Backend Engineer",
  "Full Stack Engineer", "ML Engineer", "Data Scientist",
  "DevOps Engineer", "Product Manager", "Data Engineer",
  "Mobile Engineer", "SWE Intern", "PM Intern",
];

const GOAL_CHIPS = [
  { label: "Land a new job",               icon: "briefcase"   },
  { label: "Prep for an upcoming interview", icon: "calendar"   },
  { label: "Practice & improve",            icon: "trending-up" },
  { label: "Switch careers",               icon: "refresh-cw"  },
];

function useMobile(bp = 768) {
  const [m, setM] = React.useState(() => window.innerWidth < bp);
  React.useEffect(() => {
    const fn = () => setM(window.innerWidth < bp);
    window.addEventListener("resize", fn, { passive: true });
    return () => window.removeEventListener("resize", fn);
  }, [bp]);
  return m;
}

function OnboardingStepper({ onDone, darkMode = false }) {
  const [step, setStep] = React.useState(0);
  const isMobile = useMobile(768);
  const [data, setData] = React.useState({
    goal: "", role: "", level: "", company: "", jobDescription: "",
  });
  const total = 5;

  const finish = (d) => onDone(d || data);
  const next = () => step < total - 1 ? setStep(step + 1) : finish();
  const back = () => step > 0 && setStep(step - 1);
  const skipAll = () => finish();
  // For the company step: just advance without saving a company
  const skipCompany = () => { setData({ ...data, company: "" }); setStep(step + 1); };
  // For the job-description step (last step): finish without a JD
  const skipJob = () => finish({ ...data, jobDescription: "" });

  const bgArt = "radial-gradient(ellipse 70% 55% at 30% -5%, rgba(31,122,79,.08) 0%, transparent 60%), #F4F1EA";

  const isCompanyStep = step === 3;
  const isJobStep = step === 4;

  return (
    <div data-screen-label={`Onboarding · Step ${step + 1}`} style={{ minHeight: "100vh", background: bgArt, display: "flex", flexDirection: "column" }}>
      <header style={{
        borderBottom: "1px solid rgba(20,20,15,.08)",
        background: "rgba(244,241,234,.9)",
        backdropFilter: "blur(20px) saturate(160%)",
        padding: isMobile ? "12px 16px" : "14px 32px", display: "flex", alignItems: "center", gap: 10,
      }}>
        <img src="../../assets/logo.svg" width="22" height="22" alt="" />
        <span style={{ font: "600 15px var(--font-sans)", letterSpacing: "-0.025em" }}>greenroom</span>
        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 16 }}>
          <button onClick={skipAll} style={{
            background: "none", border: "none", cursor: "pointer",
            font: "500 14px var(--font-sans)", color: "var(--fg-3)",
            padding: "4px 8px", borderRadius: 6, transition: "color 120ms",
          }}
            onMouseEnter={e => e.currentTarget.style.color = "var(--fg-1)"}
            onMouseLeave={e => e.currentTarget.style.color = "var(--fg-3)"}
          >Skip setup →</button>
          <div style={{ font: "var(--text-body-sm)", color: "var(--fg-3)" }}>Step {step + 1} of {total}</div>
        </div>
      </header>
      <div style={{ height: 3, background: "var(--gr-stone-100)" }}>
        <div style={{ height: "100%", background: "var(--gr-green-500)", width: `${((step + 1) / total) * 100}%`, transition: "width 280ms var(--ease-out)" }} />
      </div>

      <main style={{ flex: 1, display: "flex", justifyContent: "center", padding: isMobile ? "32px 20px" : "64px 32px" }}>
        <div style={{ width: "100%", maxWidth: 520 }}>
          {step === 0 && <GoalStep         value={data.goal}           onChange={g => setData({ ...data, goal: g })} />}
          {step === 1 && <RoleStep         value={data.role}           onChange={r => setData({ ...data, role: r })} />}
          {step === 2 && <LevelStep        value={data.level}          onChange={l => setData({ ...data, level: l })} />}
          {step === 3 && <CompanyStep      value={data.company}        onChange={c => setData({ ...data, company: c })} />}
          {step === 4 && <JobDescriptionStep value={data.jobDescription} onChange={v => setData({ ...data, jobDescription: v })} isMobile={isMobile} />}

          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: isMobile ? 24 : 36 }}>
            <Button variant="ghost" onClick={back} disabled={step === 0}>Back</Button>
            <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
              {isCompanyStep && (
                <button onClick={skipCompany} style={{
                  background: "none", border: "1px solid var(--border-1)", borderRadius: 8,
                  padding: "8px 18px", cursor: "pointer",
                  font: "500 14px var(--font-sans)", color: "var(--fg-3)",
                  transition: "border-color 120ms, color 120ms",
                }}
                  onMouseEnter={e => { e.currentTarget.style.color = "var(--fg-1)"; e.currentTarget.style.borderColor = "var(--border-2)"; }}
                  onMouseLeave={e => { e.currentTarget.style.color = "var(--fg-3)"; e.currentTarget.style.borderColor = "var(--border-1)"; }}
                >No company, skip →</button>
              )}
              {isJobStep && (
                <button onClick={skipJob} style={{
                  background: "none", border: "1px solid var(--border-1)", borderRadius: 8,
                  padding: "8px 18px", cursor: "pointer",
                  font: "500 14px var(--font-sans)", color: "var(--fg-3)",
                  transition: "border-color 120ms, color 120ms",
                }}
                  onMouseEnter={e => { e.currentTarget.style.color = "var(--fg-1)"; e.currentTarget.style.borderColor = "var(--border-2)"; }}
                  onMouseLeave={e => { e.currentTarget.style.color = "var(--fg-3)"; e.currentTarget.style.borderColor = "var(--border-1)"; }}
                >Skip →</button>
              )}
              <Button variant="primary" onClick={next} trailingIcon={<span style={{ fontFamily: "var(--font-mono)" }}>→</span>}>
                {step === total - 1 ? "Finish" : "Continue"}
              </Button>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}

function GoalStep({ value, onChange }) {
  React.useEffect(() => { window.lucide?.createIcons(); }, [value]);
  return (
    <div>
      <StepHeading
        eyebrow="Step 1 · Your goal"
        title="What are you here for?"
        subtitle="This helps Ari understand what you're working toward so every session is focused on what matters."
      />
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {GOAL_CHIPS.map(({ label, icon }) => {
          const selected = value === label;
          return (
            <button key={label} onClick={() => onChange(label)} style={{
              display: "flex", alignItems: "center", gap: 14,
              padding: "14px 18px", borderRadius: 12, cursor: "pointer", textAlign: "left",
              border: `1.5px solid ${selected ? "var(--gr-green-500)" : "var(--border-1)"}`,
              background: selected ? "var(--bg-brand-soft)" : "var(--bg-surface)",
              transition: "all 150ms",
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: 8, flexShrink: 0,
                display: "flex", alignItems: "center", justifyContent: "center",
                background: selected ? "var(--gr-green-100)" : "var(--bg-subtle)",
              }}>
                <i data-lucide={icon} style={{ width: 16, height: 16, color: selected ? "var(--gr-green-600)" : "var(--fg-3)" }}></i>
              </div>
              <span style={{ font: "500 15px var(--font-sans)", color: selected ? "var(--gr-green-700)" : "var(--fg-1)" }}>{label}</span>
              {selected && <i data-lucide="check-circle-2" style={{ width: 16, height: 16, color: "var(--gr-green-500)", marginLeft: "auto" }}></i>}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function StepHeading({ eyebrow, title, subtitle }) {
  return (
    <div style={{ marginBottom: 28 }}>
      <Eyebrow color="var(--gr-green-600)">{eyebrow}</Eyebrow>
      <h1 style={{ font: "400 32px/1.15 var(--font-display)", letterSpacing: "-0.02em", margin: "10px 0 8px" }}>{title}</h1>
      <p style={{ font: "var(--text-body-lg)", color: "var(--fg-2)", margin: 0 }}>{subtitle}</p>
    </div>
  );
}

function LevelStep({ value, onChange }) {
  return (
    <div>
      <StepHeading
        eyebrow="Step 3 · Seniority"
        title="What level are you interviewing for?"
        subtitle="Ari adjusts question depth, expected knowledge, and follow-up intensity to match the seniority bar."
      />
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {LEVEL_OPTIONS.map(({ value: v, label, sub }) => {
          const selected = value === v;
          return (
            <button key={v} onClick={() => onChange(v)} style={{
              display: "flex", alignItems: "center", gap: 14,
              padding: "16px 18px", borderRadius: 12, cursor: "pointer", textAlign: "left",
              border: `1.5px solid ${selected ? "var(--gr-green-500)" : "var(--border-1)"}`,
              background: selected ? "var(--bg-brand-soft)" : "var(--bg-surface)",
              transition: "all 150ms", width: "100%",
            }}>
              <div style={{ flex: 1 }}>
                <div style={{ font: "400 17px/1.2 var(--font-display)", letterSpacing: "-0.01em", color: selected ? "var(--gr-green-700)" : "var(--fg-1)", marginBottom: 3 }}>{label}</div>
                <div style={{ font: "13px var(--font-sans)", color: "var(--fg-3)" }}>{sub}</div>
              </div>
              {selected && <i data-lucide="check-circle-2" style={{ width: 18, height: 18, color: "var(--gr-green-500)", flexShrink: 0 }}></i>}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function RoleStep({ value, onChange }) {
  const [focused, setFocused] = React.useState(false);
  return (
    <div>
      <StepHeading
        eyebrow="Step 2 · Role"
        title="What role are you interviewing for?"
        subtitle="Type your target job title — Ari will calibrate difficulty, topics, and questions to match."
      />
      <input
        autoFocus
        value={value}
        onChange={e => onChange(e.target.value)}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        placeholder="e.g. Software Engineer, ML Engineer, Data Scientist…"
        style={{
          width: "100%", height: 52, padding: "0 16px", boxSizing: "border-box",
          border: `1.5px solid ${focused ? "var(--border-focus)" : "var(--border-1)"}`,
          borderRadius: 10, outline: "none",
          font: "500 16px var(--font-sans)", color: "var(--fg-1)",
          background: "var(--bg-surface)",
          boxShadow: focused ? "var(--ring-focus)" : "none",
          transition: "border-color 150ms, box-shadow 150ms",
        }}
      />
      <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 16 }}>
        {ROLE_CHIPS.map(r => (
          <button key={r} onClick={() => onChange(r)} style={{
            padding: "6px 14px", borderRadius: 999, cursor: "pointer",
            font: "500 13px var(--font-sans)",
            border: `1px solid ${value === r ? "var(--gr-green-500)" : "var(--border-1)"}`,
            background: value === r ? "var(--bg-brand-soft)" : "var(--bg-surface)",
            color: value === r ? "var(--gr-green-700)" : "var(--fg-2)",
            transition: "all 120ms",
          }}>{r}</button>
        ))}
      </div>
    </div>
  );
}

function CompanyStep({ value, onChange }) {
  return (
    <div>
      <StepHeading eyebrow="Step 4 · Company" title="Any company in mind?" subtitle="Optional — we'll tailor system-design topics and question style to their interview format." />
      <TextField label="Target company" placeholder="e.g. Google, Stripe, Figma" value={value} onChange={e => onChange(e.target.value)} helper="Skip if you're casting a wider net." />
    </div>
  );
}

function JobDescriptionStep({ value, onChange, isMobile = false }) {
  const wordCount = value.trim().split(/\s+/).filter(Boolean).length;
  return (
    <div>
      <StepHeading
        eyebrow="Step 5 · Job description"
        title="Paste the job description"
        subtitle="Ari reads the required skills and responsibilities to ask questions that match exactly what this role needs."
      />
      <textarea
        value={value}
        onChange={e => onChange(e.target.value)}
        placeholder={"Paste the full JD from the company's careers page.\n\nExample:\n'We're looking for a Software Engineer with 2+ years of experience in React, Node.js, and PostgreSQL. You'll be designing APIs, owning features end-to-end…'"}
        rows={isMobile ? 5 : 10}
        autoFocus
        style={{
          width: "100%", padding: "14px 16px", boxSizing: "border-box",
          border: "1.5px solid var(--border-1)", borderRadius: 10,
          font: "14px/1.7 var(--font-sans)", color: "var(--fg-1)",
          outline: "none", resize: "none", background: "var(--bg-surface)",
          transition: "border-color 150ms, box-shadow 150ms",
        }}
        onFocus={e => { e.target.style.borderColor = "var(--border-focus)"; e.target.style.boxShadow = "var(--ring-focus)"; }}
        onBlur={e =>  { e.target.style.borderColor = "var(--border-1)";    e.target.style.boxShadow = "none"; }}
      />
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 10 }}>
        {wordCount > 30 ? (
          <div style={{ display: "flex", alignItems: "center", gap: 6, font: "13px var(--font-sans)", color: "var(--gr-green-600)" }}>
            <Icon name="check-circle-2" size={14} color="var(--gr-green-500)" />
            {wordCount} words — Ari will use this to personalise your questions
          </div>
        ) : (
          <div style={{ font: "13px var(--font-sans)", color: "var(--fg-4)" }}>
            {wordCount > 0 ? `${wordCount} words — paste more for better personalisation` : "Optional — skip if you don't have the JD yet"}
          </div>
        )}
      </div>

      {/* Connect accounts teaser */}
      <div style={{ marginTop: isMobile ? 16 : 28, padding: isMobile ? "12px 14px" : "16px 18px", borderRadius: 12, border: "1px solid var(--border-1)", background: "var(--bg-subtle)" }}>
        <div style={{ font: "600 13px var(--font-sans)", color: "var(--fg-1)", marginBottom: 10 }}>Connect your profiles after setup</div>
        <div style={{ display: "flex", gap: 10 }}>
          <a href="https://api.usegreenroom.app/auth/github" style={{
            flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 7,
            height: 36, borderRadius: 8, textDecoration: "none",
            background: "#24292e", color: "#fff", font: "500 13px var(--font-sans)",
            transition: "opacity 150ms",
          }}
            onMouseEnter={e => e.currentTarget.style.opacity = "0.85"}
            onMouseLeave={e => e.currentTarget.style.opacity = "1"}
          >
            <BrandSvg kind="github" size={14} color="#fff" /> GitHub
          </a>
          <a href="https://api.usegreenroom.app/auth/linkedin" style={{
            flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 7,
            height: 36, borderRadius: 8, textDecoration: "none",
            background: "#0077b5", color: "#fff", font: "500 13px var(--font-sans)",
            transition: "opacity 150ms",
          }}
            onMouseEnter={e => e.currentTarget.style.opacity = "0.85"}
            onMouseLeave={e => e.currentTarget.style.opacity = "1"}
          >
            <BrandSvg kind="linkedin" size={14} color="#fff" /> LinkedIn
          </a>
        </div>
        <div style={{ font: "12px var(--font-sans)", color: "var(--fg-4)", marginTop: 8 }}>
          You can also connect these anytime from Settings.
        </div>
      </div>
    </div>
  );
}

window.OnboardingStepper = OnboardingStepper;
