// PassMark onboarding — Student flow step definitions
// Each step: { key, eyebrow, title, subtitle, panel, skip?, validate?, render }
// render(ctx) where ctx = { data, update, errors }

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

function StudentPersonal({ data, update, errors }) {
  return (
    <div className="pm-form-grid two">
      <Field label="First name" value={data.firstName || ""} autoFocus
        onChange={(v) => update({ firstName: v })} placeholder="John" error={errors.firstName} />
      <Field label="Last name" value={data.lastName || ""}
        onChange={(v) => update({ lastName: v })} placeholder="Adeyemi" error={errors.lastName} />
      <Field label="Email address" value={data.email || ""} type="email" wide
        onChange={(v) => update({ email: v })} placeholder="you@email.com" error={errors.email} />
      <Field label="Phone number" value={data.phone || ""} type="tel"
        onChange={(v) => update({ phone: v })} placeholder="0801 234 5678" error={errors.phone} />
      <Field label="Password" value={data.password || ""} type="password"
        onChange={(v) => update({ password: v })} placeholder="Min. 8 characters"
        error={errors.password} hint="At least 8 characters" />
      <Field label="Confirm password" value={data.confirm || ""} type="password"
        onChange={(v) => update({ confirm: v })} placeholder="Re-enter password" error={errors.confirm} />
    </div>
  );
}

function StudentDemographics({ data, update, errors }) {
  const isOther = data.state === "Other";
  return (
    <div className="pm-form-grid two">
      <Select label="Year of birth" value={data.yob} options={YEARS_OF_BIRTH} searchable
        onChange={(v) => update({ yob: v })} placeholder="Select year" error={errors.yob} />
      <Select label="Gender" value={data.gender} options={GENDERS} optional
        onChange={(v) => update({ gender: v })} placeholder="Select" />
      <Select label="State of residence" value={data.state} options={NIGERIAN_STATES} searchable
        onChange={(v) => update({ state: v, country: v === "Other" ? data.country : "" })}
        placeholder="Select state" error={errors.state} />
      {isOther && (
        <Select label="Country of residence" value={data.country} options={COUNTRIES} searchable
          onChange={(v) => update({ country: v })} placeholder="Select country" error={errors.country} />
      )}
    </div>
  );
}

function StudentEducation({ data, update }) {
  return (
    <div className="pm-choice-grid two">
      {EDUCATION_LEVELS.map((e) => (
        <ChoiceCard key={e.id} selected={data.education === e.id} title={e.label} desc={e.desc}
          onClick={() => update({ education: e.id })} />
      ))}
    </div>
  );
}

function StudentFeature({ data, update }) {
  const icons = { cbt: "target", learn: "spark", both: "book" };
  return (
    <div className="pm-choice-grid three">
      {FEATURES.map((f) => (
        <ChoiceCard key={f.id} selected={data.feature === f.id} icon={icons[f.id]}
          tag={f.tag} accent={f.id === "both"} title={f.name} desc={f.desc} points={f.points}
          onClick={() => update({ feature: f.id })} />
      ))}
    </div>
  );
}

function StudentInterests({ data, update }) {
  const picked = data.exams || [];
  const toggle = (id) => {
    update({ exams: picked.includes(id) ? picked.filter((x) => x !== id) : [...picked, id] });
  };
  return (
    <div className="pm-choice-grid two">
      {EXAMS.map((e) => (
        <ChoiceCard key={e.id} selected={picked.includes(e.id)} title={e.name} desc={e.desc}
          onClick={() => toggle(e.id)} />
      ))}
    </div>
  );
}

function ReviewRow({ label, value }) {
  return (
    <div className="pm-review-row">
      <span className="pm-review-label">{label}</span>
      <span className="pm-review-value">{value || "—"}</span>
    </div>
  );
}

function StudentReview({ data }) {
  const feat = FEATURES.find((f) => f.id === data.feature);
  const edu = EDUCATION_LEVELS.find((e) => e.id === data.education);
  const examNames = (data.exams || []).map((id) => EXAMS.find((e) => e.id === id)?.name).join(", ");
  return (
    <div className="pm-review">
      <div className="pm-review-card">
        <div className="pm-review-head"><Icon name="user" size={16} /> Account</div>
        <ReviewRow label="Name" value={`${data.firstName || ""} ${data.lastName || ""}`.trim()} />
        <ReviewRow label="Email" value={data.email} />
        <ReviewRow label="Phone" value={data.phone} />
      </div>
      <div className="pm-review-card">
        <div className="pm-review-head"><Icon name="target" size={16} /> Profile</div>
        <ReviewRow label="Year of birth" value={data.yob} />
        {data.gender && <ReviewRow label="Gender" value={data.gender} />}
        <ReviewRow label="Location" value={data.state === "Other" ? data.country : data.state} />
        <ReviewRow label="Education" value={edu?.label} />
      </div>
      <div className="pm-review-card span">
        <div className="pm-review-head"><Icon name="spark" size={16} /> Plan</div>
        <ReviewRow label="Selected" value={feat?.name} />
        {(data.feature === "cbt" || data.feature === "both") && (
          <ReviewRow label="Exam focus" value={examNames || "—"} />
        )}
      </div>
    </div>
  );
}

const STUDENT_STEPS = [
  {
    key: "personal", eyebrow: "Step 1", title: "Create your account",
    subtitle: "Your basic details. You can change these later in settings.",
    panel: "Let's get you set up",
    validate: (d) => {
      const e = {};
      if (!d.firstName?.trim()) e.firstName = "Required";
      if (!d.lastName?.trim()) e.lastName = "Required";
      if (!d.email?.trim()) e.email = "Required";
      else if (!EMAIL_RE.test(d.email)) e.email = "Enter a valid email";
      if (!d.phone?.trim()) e.phone = "Required";
      if (!d.password) e.password = "Required";
      else if (d.password.length < 8) e.password = "At least 8 characters";
      if (!d.confirm) e.confirm = "Re-enter your password";
      else if (d.confirm !== d.password) e.confirm = "Passwords don't match";
      return e;
    },
    render: (ctx) => <StudentPersonal {...ctx} />,
  },
  {
    key: "demographics", eyebrow: "Step 2", title: "A bit about you",
    subtitle: "This helps us tailor content and benchmarks to learners like you.",
    panel: "Tell us about yourself",
    validate: (d) => {
      const e = {};
      if (!d.yob) e.yob = "Required";
      if (!d.state) e.state = "Required";
      if (d.state === "Other" && !d.country) e.country = "Select your country";
      return e;
    },
    render: (ctx) => <StudentDemographics {...ctx} />,
  },
  {
    key: "education", eyebrow: "Step 3", title: "Where are you in your studies?",
    subtitle: "The Learning Assistant works for every level — pick what fits you best.",
    panel: "Your learning level",
    validate: (d) => (d.education ? {} : { _: "Select your education level" }),
    render: (ctx) => <StudentEducation {...ctx} />,
  },
  {
    key: "feature", eyebrow: "Step 4", title: "How do you want to use PassMark?",
    subtitle: "Choose a focus now — you can upgrade or switch any time.",
    panel: "Pick your toolkit",
    validate: (d) => (d.feature ? {} : { _: "Choose a plan to continue" }),
    render: (ctx) => <StudentFeature {...ctx} />,
  },
  {
    key: "interests", eyebrow: "Step 5", title: "Which exams are you preparing for?",
    subtitle: "Select all that apply. We'll prioritise these in your practice library.",
    panel: "Choose your exams",
    skip: (d) => d.feature === "learn",
    validate: (d) => ((d.exams || []).length ? {} : { _: "Pick at least one exam" }),
    render: (ctx) => <StudentInterests {...ctx} />,
  },
  {
    key: "review", eyebrow: "Almost done", title: "Review & confirm",
    subtitle: "Check everything looks right, then create your account.",
    panel: "One last look",
    render: (ctx) => <StudentReview {...ctx} />,
  },
];

Object.assign(window, { STUDENT_STEPS });
