/* TTS Marketing — multi-step enrollment with a build-your-plan course picker. */
const { Button, Input, Select, Checkbox, Card, ProgressBar, Tag, Badge } = window.TTSTechnicalTradeSchoolDesignSystem_281306;

// New pricing (per-course, by series). Tunable — mirrors TTS-Pricing-Structure.
// Bootcamps carry an explicit per-course `price` in the catalog data.
function priceFor(code) {
  const c = ((window.TTS_DATA && window.TTS_DATA.courses) || []).find((x) => x.code === code);
  if (c && c.price) return c.price;
  if (/^BAS-1/.test(code)) return 99;
  if (/^BAS-2/.test(code)) return 149;
  if (/^BAS-3/.test(code)) return 199;
  if (/^BAS-4/.test(code)) return 249;
  if (/^BAS-5/.test(code)) return 299;
  return 199; // SPEC / BRD
}
const money = (n) => "$" + n.toLocaleString();

function EnrollPage({ go }) {
  const mobile = useIsMobile();
  const [step, setStep] = React.useState(0);
  const [selected, setSelected] = React.useState([]); // course codes
  const [funding, setFunding] = React.useState("Tuition / payment plan");
  const [firstName, setFirstName] = React.useState("");
  const [lastName, setLastName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [err, setErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);

  const DATA = window.TTS_DATA || { tracks: [], courses: [] };
  const courseByCode = React.useMemo(() => Object.fromEntries(DATA.courses.map((c) => [c.code, c])), [DATA]);
  const total = selected.reduce((s, code) => s + priceFor(code), 0);
  const toggle = (code) => setSelected((cur) => cur.includes(code) ? cur.filter((x) => x !== code) : [...cur, code]);
  const addTrack = (tid) => setSelected((cur) => {
    const codes = DATA.courses.filter((c) => c.track === tid).map((c) => c.code);
    const all = codes.every((c) => cur.includes(c));
    return all ? cur.filter((c) => !codes.includes(c)) : [...new Set([...cur, ...codes])];
  });

  const saveEnrollment = () => {
    try {
      const s = JSON.parse(localStorage.getItem("ttsenroll") || "{}");
      s.list = s.list || [];
      selected.forEach((code) => {
        const c = courseByCode[code] || {};
        if (!s.list.find((e) => e.code === code)) s.list.unshift({ code, title: c.title || code, funding, ts: Date.now() });
      });
      localStorage.setItem("ttsenroll", JSON.stringify(s));
    } catch (e) {}
  };
  const submitEnroll = async () => {
    setErr(""); saveEnrollment();
    if (!window.TTS || !window.TTS.isConfigured) { setStep(3); return; }
    setBusy(true);
    try {
      await window.TTS.auth.signUp({ email, password, fullName: `${firstName} ${lastName}`.trim() });
      setStep(3);
    } catch (e) { setErr(e.message || "Could not create your account."); }
    finally { setBusy(false); }
  };
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });

  const steps = ["Your details", "Build your plan", "Confirm"];
  const pct = ((step + 1) / (steps.length + 1)) * 100;

  const StepHeader = () => (
    <div style={{ marginBottom: 28 }}>
      <a href="#" onClick={(e) => { e.preventDefault(); step === 0 ? go("home") : setStep(step - 1); }}
        style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-secondary)", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 6 }}>
        <Icon name="arrow-left" size={14} /> {step === 0 ? "Back to home" : "Previous step"}
      </a>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginTop: 18, marginBottom: 10 }}>
        <span className="tts-kicker">Step {step + 1} of {steps.length}</span>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-muted)" }}>{steps[step]}</span>
      </div>
      <ProgressBar value={pct} />
    </div>
  );

  const AssessmentCta = () => (
    <a href="../assessment/index.html" style={{ textDecoration: "none", display: "block" }}>
      <div style={{ display: "flex", gap: 12, alignItems: "center", padding: "14px 16px", borderRadius: "var(--radius-md)", background: "var(--color-ember-50, #FCEEE6)", border: "1px solid var(--color-ember-100, #F2B591)" }}>
        <Icon name="compass" size={22} color="var(--color-ember-600, #B23A1E)" />
        <div>
          <div style={{ fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 14.5, color: "var(--text-primary)" }}>Not sure where to start?</div>
          <div style={{ fontFamily: "var(--font-sans)", fontSize: 13.5, color: "var(--text-secondary)" }}>Take the free placement assessment — it tests you out of what you know and builds your plan for you. →</div>
        </div>
      </div>
    </a>
  );

  return (
    <div className="tts-blueprint-light" style={{ minHeight: "calc(100vh - 68px)" }}>
      <div style={{ maxWidth: step === 1 ? 720 : 560, margin: "0 auto", padding: mobile ? "32px 20px 64px" : "56px 20px 80px" }}>
        <Card padding={mobile ? 24 : 36}>
          {step < 3 && <StepHeader />}

          {step === 0 && (
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 28, letterSpacing: "-0.02em", margin: 0 }}>Create your account</h1>
              <AssessmentCta />
              <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr" : "1fr 1fr", gap: 14 }}>
                <Input label="First name" placeholder="Marcus" value={firstName} onChange={(e) => setFirstName(e.target.value)} />
                <Input label="Last name" placeholder="Reed" value={lastName} onChange={(e) => setLastName(e.target.value)} />
              </div>
              <Input label="Email" type="email" placeholder="you@email.com" value={email} onChange={(e) => setEmail(e.target.value)} leftIcon={<Icon name="mail" size={18} />} />
              <Input label="Password" type="password" placeholder="Create a password" value={password} onChange={(e) => setPassword(e.target.value)} leftIcon={<Icon name="lock" size={18} />} />
              <Button variant="primary" size="lg" fullWidth onClick={() => setStep(1)} rightIcon={<Icon name="arrow-right" size={20} />}>Continue</Button>
            </div>
          )}

          {step === 1 && (
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 28, letterSpacing: "-0.02em", margin: 0 }}>Build your plan</h1>
              <AssessmentCta />
              <p style={{ fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-secondary)", margin: 0 }}>Pick the courses you want. Add a whole track, or choose individual courses — your total updates as you go.</p>
              {DATA.tracks.map((t) => {
                const courses = DATA.courses.filter((c) => c.track === t.id);
                const allIn = courses.length > 0 && courses.every((c) => selected.includes(c.code));
                return (
                  <div key={t.id} style={{ border: "1px solid var(--color-line)", borderRadius: "var(--radius-md)", overflow: "hidden" }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10, padding: "12px 14px", background: "var(--color-stone-50)", borderBottom: "1px solid var(--color-line)" }}>
                      <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16 }}>{t.label} <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-muted)", fontWeight: 400 }}>· {courses.length} courses</span></span>
                      <Button variant={allIn ? "secondary" : "ghost"} size="sm" onClick={() => addTrack(t.id)}>{allIn ? "Remove all" : "Add all"}</Button>
                    </div>
                    <div>
                      {courses.map((c) => (
                        <label key={c.code} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10, padding: "10px 14px", borderBottom: "1px solid var(--color-line)", cursor: "pointer" }}>
                          <span style={{ display: "flex", gap: 10, alignItems: "center" }}>
                            <input type="checkbox" checked={selected.includes(c.code)} onChange={() => toggle(c.code)} />
                            <span style={{ fontFamily: "var(--font-sans)", fontSize: 13.5 }}><b>{c.code}</b> — {c.title}</span>
                          </span>
                          <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--text-secondary)" }}>{money(priceFor(c.code))}</span>
                        </label>
                      ))}
                    </div>
                  </div>
                );
              })}
              <div>
                <div style={{ fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600, marginBottom: 10 }}>Funding</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                  <Checkbox label="I'll pay tuition / use a payment plan" checked={funding === "Tuition / payment plan"} onChange={() => setFunding("Tuition / payment plan")} />
                  <Checkbox label="Apply for a need-based scholarship" checked={funding === "Need-based scholarship — applied"} onChange={() => setFunding("Need-based scholarship — applied")} />
                  <Checkbox label="My employer is sponsoring me" checked={funding === "Employer sponsored"} onChange={() => setFunding("Employer sponsored")} />
                </div>
              </div>
              <div style={{ position: "sticky", bottom: 0, background: "#fff", paddingTop: 12, borderTop: "1px solid var(--color-line)", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
                <span style={{ fontFamily: "var(--font-sans)", fontSize: 15 }}>{selected.length} course{selected.length === 1 ? "" : "s"} · <b>{money(total)}</b></span>
                <Button variant="primary" size="lg" disabled={!selected.length} onClick={() => setStep(2)} rightIcon={<Icon name="arrow-right" size={20} />}>Review</Button>
              </div>
            </div>
          )}

          {step === 2 && (
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 28, letterSpacing: "-0.02em", margin: 0 }}>Confirm enrollment</h1>
              <div style={{ border: "1px solid var(--color-line)", borderRadius: "var(--radius-md)", overflow: "hidden" }}>
                {selected.map((code, i) => (
                  <div key={code} style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: "12px 16px", background: i % 2 ? "var(--color-stone-50)" : "#fff", borderBottom: "1px solid var(--color-line)" }}>
                    <span style={{ fontFamily: "var(--font-sans)", fontSize: 14 }}><b>{code}</b> — {(courseByCode[code] || {}).title || code}</span>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 13 }}>{money(priceFor(code))}</span>
                  </div>
                ))}
                <div style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: "14px 16px", background: "var(--color-ink)", color: "#fff" }}>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, textTransform: "uppercase", letterSpacing: "0.08em" }}>Total · {funding}</span>
                  <span style={{ fontFamily: "var(--font-sans)", fontSize: 15, fontWeight: 700 }}>{money(total)}</span>
                </div>
              </div>
              <Checkbox label="I agree to the enrollment terms and code of conduct." defaultChecked />
              {err && <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, color: "var(--color-danger)" }}>{err}</div>}
              <Button variant="primary" size="lg" fullWidth disabled={busy} onClick={submitEnroll}>{busy ? "Creating your account…" : "Confirm & enroll"}</Button>
            </div>
          )}

          {step === 3 && (
            <div style={{ textAlign: "center", padding: "20px 0" }}>
              <div style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--color-success-soft)", display: "inline-flex", alignItems: "center", justifyContent: "center", margin: "0 auto 20px" }}>
                <Icon name="check" size={32} color="var(--color-success)" />
              </div>
              <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 30, letterSpacing: "-0.02em", margin: "0 0 10px" }}>Request received.</h1>
              <p style={{ fontFamily: "var(--font-sans)", fontSize: 16, color: "var(--text-secondary)", margin: "0 auto 28px", maxWidth: 380, lineHeight: 1.6 }}>
                We've created your account and your enrollment request{selected.length ? ` for ${selected.length} course${selected.length === 1 ? "" : "s"}` : ""}. An admin will review and approve it — you'll get access in your portal once approved.
              </p>
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                <Button variant="primary" size="lg" fullWidth onClick={() => { window.location.href = "../portal/index.html"; }}>Go to my portal</Button>
                <Button variant="ghost" fullWidth onClick={() => { setStep(0); go("home"); }}>Back to home</Button>
              </div>
            </div>
          )}
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { EnrollPage });
