// Auth flow — Login, Signup, OTP, Onboarding, Forgot password
// All wrapped in a split-panel AuthShell. Forms are visual only — submit just calls go().

const AuthShell = ({ tagline, children, accent = "var(--coral)" }) => (
  <div className="codeland" style={{
    minHeight: "100vh", display: "grid", gridTemplateColumns: "1.05fr 1fr",
    background: "var(--paper)",
  }}>
    {/* Left brand panel */}
    <div style={{
      background: accent, color: "white", padding: "56px 48px",
      display: "flex", flexDirection: "column", justifyContent: "space-between",
      position: "relative", overflow: "hidden", borderRight: "var(--border)",
    }}>
      {/* Decorative shapes */}
      <div style={{
        position: "absolute", top: -60, right: -60,
        width: 220, height: 220, borderRadius: "50%",
        background: "var(--gold)", border: "var(--border)", opacity: 0.85,
      }}/>
      <div style={{
        position: "absolute", bottom: -40, left: -40,
        width: 160, height: 160, borderRadius: "50%",
        background: "var(--moss)", border: "var(--border)", opacity: 0.75,
      }}/>
      <div style={{
        position: "absolute", top: "40%", left: "55%",
        width: 60, height: 60, borderRadius: "50%",
        background: "var(--sky)", border: "var(--border)",
      }}/>

      <a href="https://epiqminds.com" style={{
        position: "relative", textDecoration: "none", color: "white",
        fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 24,
        letterSpacing: "-0.03em", zIndex: 2,
      }}>
        EpiqMinds
      </a>

      <div style={{ position: "relative", zIndex: 2 }}>
        <Mascot size={120} variant="default"/>
        <h2 className="display" style={{
          fontSize: 44, lineHeight: 1, margin: "24px 0 12px",
          letterSpacing: "-0.03em", maxWidth: 420,
        }}>
          {tagline || "Let's get coding."}
        </h2>
        <p style={{ fontSize: 15, opacity: 0.92, maxWidth: 380, lineHeight: 1.5, margin: 0 }}>
          Join 1,200+ kids who've turned coding into their favorite afternoon.
        </p>
      </div>

      <div style={{ position: "relative", zIndex: 2, fontSize: 12, opacity: 0.85 }}>
        © 2026 EpiqMinds · made for kids who'd rather be playing
      </div>
    </div>

    {/* Right form panel */}
    <div style={{
      padding: "56px 48px", display: "flex", flexDirection: "column",
      justifyContent: "center", overflowY: "auto",
    }}>
      <div style={{ maxWidth: 420, width: "100%", margin: "0 auto" }}>
        {children}
      </div>
    </div>
  </div>
);

// Form primitives
const Field = ({ label, ...props }) => (
  <div style={{ marginBottom: 14 }}>
    <label style={{
      display: "block", fontSize: 11, fontWeight: 700,
      color: "var(--ink-soft)", fontFamily: "var(--font-mono)",
      textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 6,
    }}>{label}</label>
    <input {...props} style={{
      width: "100%", padding: "13px 18px",
      border: "var(--border)", borderRadius: "var(--r-pill)",
      background: "var(--paper-card)", fontSize: 15, fontFamily: "var(--font-ui)",
      outline: "none", color: "var(--ink)",
      ...(props.style || {}),
    }}/>
  </div>
);

const RoleCard = ({ icon, name, desc, selected, onClick, color }) => (
  <button onClick={onClick} style={{
    background: selected ? color : "var(--paper-card)",
    color: selected ? "white" : "var(--ink)",
    border: "var(--border)", borderRadius: "var(--r-lg)",
    padding: 18, textAlign: "left", cursor: "pointer",
    boxShadow: selected ? "var(--sh-3)" : "var(--sh-1)",
    transition: "all 100ms",
    display: "flex", flexDirection: "column", gap: 6,
  }}>
    <div style={{
      width: 36, height: 36, borderRadius: 10,
      background: selected ? "rgba(255,255,255,0.25)" : color, color: "white",
      border: "1.5px solid var(--rule-bold)",
      display: "grid", placeItems: "center", marginBottom: 4,
    }}>{icon}</div>
    <div style={{ fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 700 }}>{name}</div>
    <div style={{ fontSize: 12, opacity: selected ? 0.9 : 0.65 }}>{desc}</div>
  </button>
);

// LOGIN
const LoginScreen = ({ go, setSession }) => {
  const [email, setEmail]       = React.useState("");
  const [password, setPassword] = React.useState("");
  const [error, setError]       = React.useState("");
  const [loading, setLoading]   = React.useState(false);

  const submit = async (e) => {
    e?.preventDefault?.();
    setError("");
    setLoading(true);
    try {
      // Auth is cookie-based now — no token is stored in JS.
      const user = await authApi.login(email, password);
      setSession({ authed: true, ...user });
      const dest = { student: "/app/student", parent: "/app/parent", teacher: "/app/teacher", admin: "/app/admin", superadmin: "/app/admin", content_manager: "/app/content" };
      go(dest[user.role] || "/app/admin");
    } catch (err) {
      setError(err.message || "Could not reach server. Try again.");
      setLoading(false);
    }
  };

  return (
    <AuthShell tagline="Welcome back.">
      <h1 className="display" style={{ fontSize: 36, margin: "6px 0 24px", letterSpacing: "-0.03em" }}>Sign in</h1>

      <form onSubmit={submit}>
        <div style={{ marginBottom: 16 }}>
          <div className="mono" style={{ fontSize: 11, fontWeight: 700, marginBottom: 6, letterSpacing: ".06em" }}>EMAIL</div>
          <input type="email" value={email} onChange={e => setEmail(e.target.value)} required
            placeholder="you@epiqminds.com" autoComplete="email"
            style={{ width: "100%", padding: "12px 14px", borderRadius: 12, border: "var(--border-thin)",
              background: "var(--paper-card)", fontSize: 15, fontFamily: "var(--font-ui)", boxSizing: "border-box" }}/>
        </div>
        <div style={{ marginBottom: 8 }}>
          <div className="mono" style={{ fontSize: 11, fontWeight: 700, marginBottom: 6, letterSpacing: ".06em" }}>PASSWORD</div>
          <input type="password" value={password} onChange={e => setPassword(e.target.value)} required
            placeholder="Your password" autoComplete="current-password"
            style={{ width: "100%", padding: "12px 14px", borderRadius: 12, border: "var(--border-thin)",
              background: "var(--paper-card)", fontSize: 15, fontFamily: "var(--font-ui)", boxSizing: "border-box" }}/>
        </div>

        <div style={{ display: "flex", justifyContent: "flex-end", marginBottom: 20 }}>
          <a onClick={() => go("/forgot")} style={{ fontSize: 13, color: "var(--ink-soft)", textDecoration: "underline", cursor: "pointer" }}>Forgot password?</a>
        </div>

        {error && (
          <div style={{ background: "#fee2e2", color: "#b91c1c", borderRadius: 10, padding: "10px 14px", fontSize: 13, marginBottom: 16 }}>
            {error}
          </div>
        )}

        <button type="submit" disabled={loading} className="btn btn-primary" style={{
          width: "100%", justifyContent: "center", padding: "14px 22px", fontSize: 15, opacity: loading ? .6 : 1,
        }}>{loading ? "Signing in…" : "Sign in →"}</button>
      </form>
    </AuthShell>
  );
};

// SIGNUP
const SignupScreen = ({ go, setSession, session }) => {
  const [role, setRole] = React.useState(session.role || "parent");
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [error, setError] = React.useState("");
  const [loading, setLoading] = React.useState(false);

  const submit = async (e) => {
    e?.preventDefault?.();
    setError("");
    if (password.length < 8) { setError("Password must be at least 8 characters."); return; }
    setLoading(true);
    try {
      const res = await apiFetch("/auth/signup", {
        method: "POST",
        body: JSON.stringify({ name, email, password, role, phone }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) { setError(data.error || "Sign up failed"); setLoading(false); return; }
      // Carry the email/role forward to the OTP step.
      setSession({ ...session, role, email });
      go("/otp");
    } catch {
      setError("Could not reach server. Try again.");
      setLoading(false);
    }
  };

  return (
    <AuthShell tagline="Start your adventure." accent="var(--moss)">
      <div className="mono" style={{ fontSize: 11, color: "var(--ink-mute)", letterSpacing: "0.06em" }}>STEP 1 OF 3 · CREATE ACCOUNT</div>
      <h1 className="display" style={{ fontSize: 36, margin: "6px 0 8px", letterSpacing: "-0.03em" }}>Get started</h1>
      <p style={{ color: "var(--ink-soft)", margin: "0 0 22px", fontSize: 14 }}>
        Already have an account? <a onClick={() => go("/login")} style={{ color: "var(--coral)", fontWeight: 700, cursor: "pointer" }}>Sign in →</a>
      </p>

      <div className="mono" style={{ fontSize: 11, color: "var(--ink-soft)", marginBottom: 10 }}>I'M A…</div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 22 }}>
        <RoleCard icon={I.user({ size: 18 })} name="Parent" desc="Sign up your child, track progress, message teachers" color="var(--coral)" selected={role === "parent"} onClick={() => setRole("parent")} />
        <RoleCard icon={I.book({ size: 18 })} name="Teacher" desc="Apply to teach. We'll review and onboard you" color="var(--sky)" selected={role === "teacher"} onClick={() => setRole("teacher")} />
      </div>

      <form onSubmit={submit}>
        <Field label={role === "teacher" ? "Full name" : "Parent name"} value={name} onChange={(e) => setName(e.target.value)} placeholder="Your name" required />
        <Field label="Email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@home.in" required />
        <Field label="Phone" type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+91 …" />
        <Field label="Password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="At least 8 characters" required />

        {error && (
          <div style={{ background: "#fee2e2", color: "#b91c1c", borderRadius: 10, padding: "10px 14px", fontSize: 13, margin: "4px 0 14px" }}>{error}</div>
        )}

        <label style={{ display: "flex", alignItems: "flex-start", gap: 10, margin: "8px 0 18px", fontSize: 13, color: "var(--ink-soft)", cursor: "pointer", lineHeight: 1.5 }}>
          <input type="checkbox" defaultChecked style={{ width: 16, height: 16, marginTop: 2 }} />
          I agree to EpiqMinds's <a style={{ color: "var(--coral)", fontWeight: 700 }}>Terms</a> and <a style={{ color: "var(--coral)", fontWeight: 700 }}>Privacy</a>.
        </label>

        <button type="submit" disabled={loading} className="btn btn-primary" style={{ width: "100%", justifyContent: "center", padding: "14px 22px", fontSize: 15, opacity: loading ? 0.6 : 1 }}>
          {loading ? "Creating account…" : "Continue → verify email"}
        </button>
      </form>
    </AuthShell>
  );
};

// OTP
const OtpScreen = ({ go, session, setSession }) => {
  const [digits, setDigits] = React.useState(["", "", "", "", "", ""]);
  const refs = React.useRef([]);
  const onInput = (i, v) => {
    const d = v.replace(/[^0-9]/g, "").slice(0, 1);
    const next = [...digits]; next[i] = d; setDigits(next);
    if (d && i < 5) refs.current[i + 1]?.focus();
  };
  const filled = digits.every(d => d);
  const [error, setError] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const submit = async (e) => {
    e?.preventDefault?.();
    setError("");
    setLoading(true);
    try {
      const res = await apiFetch("/auth/verify-email", {
        method: "POST",
        body: JSON.stringify({ email: session.email, code: digits.join("") }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) { setError(data.error || "Invalid or expired code"); setLoading(false); return; }
      // Server has set the session cookies; mark us authenticated.
      setSession({ authed: true, ...data.user });
      const role = data.user.role;
      if (role === "parent" || role === "teacher") go("/onboarding");
      else go(`/app/${role}`);
    } catch {
      setError("Could not reach server. Try again.");
      setLoading(false);
    }
  };

  return (
    <AuthShell tagline="Quick — check your email." accent="var(--sky)">
      <div className="mono" style={{ fontSize: 11, color: "var(--ink-mute)", letterSpacing: "0.06em" }}>STEP 2 OF 3 · VERIFY</div>
      <h1 className="display" style={{ fontSize: 36, margin: "6px 0 8px", letterSpacing: "-0.03em" }}>Enter the code</h1>
      <p style={{ color: "var(--ink-soft)", margin: "0 0 28px", fontSize: 14, lineHeight: 1.5 }}>
        We sent a 6-digit code to <b>{session.email || "you@home.in"}</b>.<br/>
        It expires in 10 minutes.
      </p>

      <form onSubmit={submit}>
        <div style={{ display: "flex", gap: 10, marginBottom: 22, justifyContent: "space-between" }}>
          {digits.map((d, i) => (
            <input key={i} ref={el => refs.current[i] = el} value={d}
              onChange={e => onInput(i, e.target.value)}
              onKeyDown={e => { if (e.key === "Backspace" && !d && i > 0) refs.current[i-1]?.focus(); }}
              maxLength={1} inputMode="numeric"
              style={{
                width: 54, height: 64, textAlign: "center",
                fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 28,
                border: "var(--border)", borderRadius: 14,
                background: d ? "var(--paper-card)" : "var(--paper-deep)",
                color: "var(--ink)", outline: "none",
                boxShadow: d ? "var(--sh-2)" : "var(--sh-1)",
              }}/>
          ))}
        </div>

        {error && (
          <div style={{ background: "#fee2e2", color: "#b91c1c", borderRadius: 10, padding: "10px 14px", fontSize: 13, marginBottom: 14 }}>{error}</div>
        )}

        <button type="submit" disabled={loading || !filled} className="btn btn-primary" style={{
          width: "100%", justifyContent: "center", padding: "14px 22px", fontSize: 15,
          opacity: filled && !loading ? 1 : 0.6,
        }}>{loading ? "Verifying…" : "Verify & continue →"}</button>

        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 18, fontSize: 13, color: "var(--ink-soft)" }}>
          <a onClick={() => go("/signup")} style={{ cursor: "pointer", textDecoration: "underline" }}>← Change email</a>
          <a style={{ cursor: "pointer", color: "var(--coral)", fontWeight: 700 }}>Resend code</a>
        </div>
      </form>
    </AuthShell>
  );
};

// ONBOARDING — branches on role
const OnboardingScreen = ({ go, session, setSession }) => {
  const role = session.role || "parent";
  const [step, setStep] = React.useState(0);
  const [child, setChild] = React.useState({ name: "", age: "", pronouns: "she/her", experience: "some" });
  const [submitting, setSubmitting] = React.useState(false);
  const [obError, setObError] = React.useState("");

  if (role === "teacher") {
    const finish = () => { setSession({ ...session, authed: true }); go("/app/teacher"); };
    return (
      <AuthShell tagline="Tell us about your teaching." accent="var(--plum)">
        <div className="mono" style={{ fontSize: 11, color: "var(--ink-mute)" }}>STEP 3 OF 3 · TEACHER PROFILE</div>
        <h1 className="display" style={{ fontSize: 36, margin: "6px 0 8px", letterSpacing: "-0.03em" }}>You're almost in.</h1>
        <p style={{ color: "var(--ink-soft)", margin: "0 0 22px", fontSize: 14 }}>
          Our team reviews every teacher in 48 hrs. While we do, you can explore your dashboard.
        </p>
        <Field label="Years teaching K-12" defaultValue="6"/>
        <Field label="Languages you can teach" defaultValue="Python, Scratch, JavaScript"/>
        <Field label="Time zone" defaultValue="Asia/Kolkata (IST)"/>
        <div style={{ marginBottom: 18 }}>
          <label style={{ display: "block", fontSize: 11, fontWeight: 700, color: "var(--ink-soft)", fontFamily: "var(--font-mono)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 6 }}>Short bio</label>
          <textarea defaultValue="6 years teaching computer science to middle-schoolers. I love finding the moment a kid says 'wait, I can make this do anything?'"
            style={{ width: "100%", padding: 14, border: "var(--border)", borderRadius: 16, background: "var(--paper-card)", fontSize: 14, fontFamily: "var(--font-ui)", outline: "none", color: "var(--ink)", minHeight: 90, resize: "vertical" }}/>
        </div>
        <button onClick={finish} className="btn btn-primary" style={{ width: "100%", justifyContent: "center", padding: "14px 22px", fontSize: 15 }}>
          Submit & enter EpiqMinds →
        </button>
      </AuthShell>
    );
  }

  // PARENT onboarding — 2 sub-steps
  const childLabel = child.name.trim() || "your child";
  if (step === 0) {
    const goNext = () => {
      setObError("");
      if (!child.name.trim()) { setObError("Please enter your child's name."); return; }
      setStep(1);
    };
    return (
      <AuthShell tagline="Tell us about your kid." accent="var(--coral)">
        <div className="mono" style={{ fontSize: 11, color: "var(--ink-mute)" }}>STEP 3A OF 3 · ADD YOUR CHILD</div>
        <h1 className="display" style={{ fontSize: 36, margin: "6px 0 8px", letterSpacing: "-0.03em" }}>Who's coding?</h1>
        <p style={{ color: "var(--ink-soft)", margin: "0 0 22px", fontSize: 14 }}>
          You can add more children later. We use this to match them to the right teacher and starting level.
        </p>

        <Field label="Child's first name" value={child.name} onChange={e => setChild(c => ({ ...c, name: e.target.value }))} placeholder="e.g. Maya" required/>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="Age" type="number" min="2" max="18" value={child.age} onChange={e => setChild(c => ({ ...c, age: e.target.value }))} placeholder="9"/>
          <div style={{ marginBottom: 14 }}>
            <label style={{ display: "block", fontSize: 11, fontWeight: 700, color: "var(--ink-soft)", fontFamily: "var(--font-mono)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 6 }}>Pronouns</label>
            <select value={child.pronouns} onChange={e => setChild(c => ({ ...c, pronouns: e.target.value }))} style={{ width: "100%", padding: "13px 18px", border: "var(--border)", borderRadius: "var(--r-pill)", background: "var(--paper-card)", fontSize: 15, fontFamily: "var(--font-ui)", outline: "none", color: "var(--ink)" }}>
              <option>she/her</option><option>he/him</option><option>they/them</option><option>prefer not to say</option>
            </select>
          </div>
        </div>

        <div className="mono" style={{ fontSize: 11, color: "var(--ink-soft)", margin: "10px 0 8px" }}>EXPERIENCE WITH CODING</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginBottom: 22 }}>
          {[
            ["never", "Never coded", "🌱"],
            ["some", "Tried Scratch", "🧩"],
            ["lots", "Real code", "🚀"],
          ].map(([id, label, em]) => {
            const sel = child.experience === id;
            return (
            <button key={id} type="button" onClick={() => setChild(c => ({ ...c, experience: id }))} style={{
              padding: 14, border: "var(--border)", borderRadius: 14,
              background: sel ? "var(--coral)" : "var(--paper-card)",
              color: sel ? "white" : "var(--ink)",
              cursor: "pointer", textAlign: "center",
              boxShadow: sel ? "var(--sh-3)" : "var(--sh-1)",
              fontWeight: 700, fontSize: 13, fontFamily: "var(--font-ui)",
            }}>
              <div style={{ fontSize: 22 }}>{em}</div>
              {label}
            </button>
          );})}
        </div>

        {obError && <div style={{ background: "#fee2e2", color: "#b91c1c", borderRadius: 10, padding: "10px 14px", fontSize: 13, marginBottom: 14 }}>{obError}</div>}

        <button onClick={goNext} className="btn btn-primary" style={{ width: "100%", justifyContent: "center", padding: "14px 22px", fontSize: 15 }}>
          Continue →
        </button>
      </AuthShell>
    );
  }

  // Step 1: pick track + schedule, then create the child for real.
  const finish = async () => {
    if (submitting) return;
    setObError(""); setSubmitting(true);
    try {
      const res = await apiFetch("/parent/children", {
        method: "POST",
        body: JSON.stringify({
          name: child.name.trim(),
          age: child.age ? Number(child.age) : undefined,
          pronouns: child.pronouns,
          experience: child.experience,
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) { setObError(data.error || "Could not save your child's profile."); setSubmitting(false); return; }
      // Refresh the session so studentId/links populate, then enter the app.
      const fresh = await authApi.me().catch(() => null);
      setSession(fresh ? { authed: true, ...fresh } : { ...session, authed: true });
      go("/app/parent");
    } catch {
      setObError("Could not reach server. Try again.");
      setSubmitting(false);
    }
  };
  return (
    <AuthShell tagline="One more thing." accent="var(--coral)">
      <div className="mono" style={{ fontSize: 11, color: "var(--ink-mute)" }}>STEP 3B OF 3 · PICK A TRACK</div>
      <h1 className="display" style={{ fontSize: 36, margin: "6px 0 8px", letterSpacing: "-0.03em" }}>What should {childLabel} start with?</h1>
      <p style={{ color: "var(--ink-soft)", margin: "0 0 22px", fontSize: 14 }}>
        We picked one based on age. Your teacher can change tracks anytime.
      </p>

      <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 18 }}>
        {[
          { id: "scratch", name: "Scratch Quest", age: "6–8", color: "var(--moss)", desc: "Drag-and-drop blocks, first games" },
          { id: "python", name: "Python Pilot", age: "8–11", color: "var(--coral)", desc: "Real syntax, turtle graphics, projects", reco: true },
          { id: "web", name: "Web Builder", age: "10–13", color: "var(--sky)", desc: "HTML, CSS, JavaScript, a deployed site" },
        ].map(t => (
          <div key={t.id} style={{
            padding: 16, border: "var(--border)", borderRadius: 18,
            background: t.reco ? "var(--paper-card)" : "var(--paper-card)",
            boxShadow: t.reco ? "var(--sh-3)" : "var(--sh-1)",
            display: "flex", alignItems: "center", gap: 14, cursor: "pointer",
            outline: t.reco ? "3px solid var(--coral)" : "none",
            outlineOffset: -3,
          }}>
            <div style={{
              width: 44, height: 44, borderRadius: 12, background: t.color, color: "white",
              border: "var(--border)", display: "grid", placeItems: "center",
            }}>{I.book({ size: 18 })}</div>
            <div style={{ flex: 1 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16 }}>{t.name}</div>
                {t.reco && <span className="chip" style={{ background: "var(--coral)", color: "white", borderColor: "var(--coral-deep)", fontSize: 10, padding: "2px 8px" }}>RECOMMENDED</span>}
              </div>
              <div style={{ fontSize: 12, color: "var(--ink-mute)" }}>Ages {t.age} · {t.desc}</div>
            </div>
            <div style={{
              width: 22, height: 22, borderRadius: "50%",
              border: "var(--border)",
              background: t.reco ? "var(--coral)" : "transparent",
              display: "grid", placeItems: "center", color: "white",
            }}>{t.reco && I.check({ size: 14 })}</div>
          </div>
        ))}
      </div>

      <div className="mono" style={{ fontSize: 11, color: "var(--ink-soft)", marginBottom: 8 }}>PREFERRED CLASS SCHEDULE</div>
      <div style={{ display: "flex", gap: 6, marginBottom: 18 }}>
        {["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d, i) => (
          <button key={d} style={{
            flex: 1, padding: "10px 0", borderRadius: 10,
            border: "var(--border)", cursor: "pointer", fontWeight: 700, fontSize: 12,
            background: [0, 2, 4].includes(i) ? "var(--moss)" : "var(--paper-card)",
            color: [0, 2, 4].includes(i) ? "white" : "var(--ink)",
            fontFamily: "var(--font-ui)",
          }}>{d}</button>
        ))}
      </div>

      {obError && <div style={{ background: "#fee2e2", color: "#b91c1c", borderRadius: 10, padding: "10px 14px", fontSize: 13, marginBottom: 14 }}>{obError}</div>}

      <div style={{ display: "flex", gap: 10 }}>
        <button onClick={() => setStep(0)} disabled={submitting} className="btn btn-ghost" style={{ padding: "12px 18px" }}>← Back</button>
        <button onClick={finish} disabled={submitting} className="btn btn-primary" style={{ flex: 1, justifyContent: "center", padding: "14px 22px", fontSize: 15, opacity: submitting ? 0.6 : 1 }}>
          {submitting ? "Setting up…" : "Finish & enter EpiqMinds →"}
        </button>
      </div>
    </AuthShell>
  );
};

// FORGOT
const ForgotScreen = ({ go }) => {
  const [email, setEmail] = React.useState("");
  const [sent, setSent] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const submit = async (e) => {
    e?.preventDefault?.();
    setLoading(true);
    try {
      // Always succeeds (server never reveals whether the account exists).
      await apiFetch("/auth/forgot", { method: "POST", body: JSON.stringify({ email }) });
    } catch {
      /* ignore */
    }
    setSent(true);
    setLoading(false);
  };
  return (
    <AuthShell tagline="No worries." accent="var(--gold)">
      <div className="mono" style={{ fontSize: 11, color: "var(--ink-mute)" }}>RESET</div>
      <h1 className="display" style={{ fontSize: 36, margin: "6px 0 8px", letterSpacing: "-0.03em" }}>Forgot password</h1>
      {sent ? (
        <p style={{ color: "var(--ink-soft)", margin: "0 0 22px", fontSize: 14, lineHeight: 1.5 }}>
          If an account exists for <b>{email}</b>, a reset link is on its way. Check your inbox.
        </p>
      ) : (
        <form onSubmit={submit}>
          <p style={{ color: "var(--ink-soft)", margin: "0 0 22px", fontSize: 14 }}>Enter your email and we'll send a reset link.</p>
          <Field label="Email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@home.in" required />
          <button type="submit" disabled={loading} className="btn btn-primary" style={{ width: "100%", justifyContent: "center", padding: "14px 22px", fontSize: 15, opacity: loading ? 0.6 : 1 }}>
            {loading ? "Sending…" : "Send reset link →"}
          </button>
        </form>
      )}
      <div style={{ marginTop: 18, fontSize: 13, textAlign: "center" }}>
        <a onClick={() => go("/login")} style={{ cursor: "pointer", color: "var(--ink-soft)", textDecoration: "underline" }}>← Back to sign in</a>
      </div>
    </AuthShell>
  );
};

Object.assign(window, { LoginScreen, SignupScreen, OtpScreen, OnboardingScreen, ForgotScreen });

