// ============== misc pages: role detail, password reset, accept invite ==============

function RoleDetailPage({ publicId, go }) {
  const [role, setRole] = React.useState(null);
  const [err, setErr] = React.useState("");

  React.useEffect(() => {
    window.W3J_API.apiFetch(`/roles/by-public-id/${publicId}`, { auth: false })
      .then((r) => setRole(window.W3J.normalizeRole(r)))
      .catch((ex) => setErr(ex.status === 404 ? "Role not found or no longer open." : ex.message));
  }, [publicId]);

  if (err) {
    return (
      <main>
        <section className="page-hero">
          <div className="shell">
            <Eyebrow>404 · Role unavailable</Eyebrow>
            <h1 style={{ marginTop: 24 }}><em>Not found.</em></h1>
            <p className="lede" style={{ marginTop: 28 }}>{err}</p>
            <div style={{ marginTop: 24 }}>
              <Btn kind="primary" onClick={() => go("jobs")}>Browse open roles</Btn>
            </div>
          </div>
        </section>
      </main>
    );
  }
  if (!role) {
    return <main><section className="section"><div className="shell"><p className="lede">Loading…</p></div></section></main>;
  }

  return (
    <main>
      <section className="page-hero">
        <div className="shell">
          <Eyebrow>{role.id} · {role.cat}{role.chain ? ` · ${role.chain}` : ""}</Eyebrow>
          <h1 style={{ marginTop: 16 }}>{role.title}</h1>
          <div className="lede" style={{ marginTop: 16 }}>{role.company} · {role.remote}</div>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 20 }}>
            {role.chain && <span className="chip chip--solid">{role.chain}</span>}
            {role.stack.map((s) => <span className="chip" key={s}>{s}</span>)}
            <span className="chip">{role.level}</span>
          </div>
        </div>
      </section>

      <section className="section section--tight">
        <div className="shell role-detail-grid">
          <div>
            {role.description && (<><h3 className="h3">About the role</h3>
              <p style={{ whiteSpace: "pre-wrap", color: "var(--fg-dim)", marginTop: 12 }}>{role.description}</p></>)}
            {role.requirements?.length > 0 && (
              <><h3 className="h3" style={{ marginTop: 32 }}>What we're looking for</h3>
              <ul className="bullets">{role.requirements.map((s, i) => <li key={i}>{s}</li>)}</ul></>
            )}
            {role.offer?.length > 0 && (
              <><h3 className="h3" style={{ marginTop: 32 }}>What's on offer</h3>
              <ul className="bullets">{role.offer.map((s, i) => <li key={i}>{s}</li>)}</ul></>
            )}
          </div>
          <aside className="role-aside">
            <div className="kv-grid" style={{ gridTemplateColumns: "1fr" }}>
              <div className="kv"><div className="kv-key">Total comp</div><div className="kv-val">${role.min}–${role.max}k</div></div>
              <div className="kv"><div className="kv-key">Location</div><div className="kv-val" style={{ fontSize: 16, fontWeight: 400 }}>{role.remote}</div></div>
              <div className="kv"><div className="kv-key">Seniority</div><div className="kv-val" style={{ fontSize: 16, fontWeight: 400 }}>{role.level}</div></div>
              <div className="kv"><div className="kv-key">Type</div><div className="kv-val" style={{ fontSize: 16, fontWeight: 400 }}>{role.type}</div></div>
              {role.chain && <div className="kv"><div className="kv-key">Chain</div><div className="kv-val" style={{ fontSize: 16, fontWeight: 400 }}>{role.chain}</div></div>}
            </div>
            <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 12 }}>
              <Btn kind="primary" onClick={() => go("jobs", { id: role.id })}>Apply for this role</Btn>
              <Btn kind="ghost" onClick={() => go("jobs")}>Back to all roles</Btn>
            </div>
          </aside>
        </div>
      </section>
    </main>
  );
}

function ResetPasswordPage({ token, go }) {
  const [password, setPassword] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");

  const submit = async (e) => {
    e.preventDefault();
    setBusy(true); setErr("");
    try {
      const tokens = await window.W3J_API.apiFetch("/auth/reset-password", {
        method: "POST", body: { token, new_password: password }, auth: false,
      });
      window.W3J_API.tokens.set(tokens);
      go("dashboard");
    } catch (ex) {
      setErr(ex.message);
    } finally { setBusy(false); }
  };

  if (!token) {
    return (
      <main>
        <section className="page-hero">
          <div className="shell">
            <Eyebrow>Reset password</Eyebrow>
            <h1 style={{ marginTop: 16 }}>Missing reset <em>token.</em></h1>
            <p className="lede" style={{ marginTop: 16 }}>Use the link from your reset email, or request a new one.</p>
            <div style={{ marginTop: 24 }}><Btn kind="primary" onClick={() => go("forgot")}>Request a new link</Btn></div>
          </div>
        </section>
      </main>
    );
  }

  return (
    <main>
      <section className="page-hero">
        <div className="shell">
          <Eyebrow>Reset password</Eyebrow>
          <h1 style={{ marginTop: 16 }}>Choose a <em>new password.</em></h1>
        </div>
      </section>
      <section className="section">
        <div className="shell" style={{ maxWidth: 520 }}>
          <form className="form-grid" onSubmit={submit}>
            <div className="form-section">
              <label className="field">
                <span className="field-label">New password</span>
                <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={10} autoFocus />
                <span className="field-hint">Minimum 10 characters.</span>
              </label>
              {err && <div className="form-error">{err}</div>}
              <button type="submit" className="btn btn--primary" disabled={busy}>
                {busy ? "…" : "Set new password"} <Icon.Arrow />
              </button>
            </div>
          </form>
        </div>
      </section>
    </main>
  );
}

function ForgotPasswordPage({ go }) {
  const [email, setEmail] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [sent, setSent] = React.useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setBusy(true);
    try {
      await window.W3J_API.apiFetch("/auth/forgot-password", { method: "POST", body: { email }, auth: false });
      setSent(true);
    } catch {
      setSent(true); // never reveal account existence
    } finally { setBusy(false); }
  };

  return (
    <main>
      <section className="page-hero">
        <div className="shell">
          <Eyebrow>Forgot password</Eyebrow>
          <h1 style={{ marginTop: 16 }}>{sent ? <>Check your <em>inbox.</em></> : <><em>Recover</em> your account.</>}</h1>
          <p className="lede" style={{ marginTop: 16, maxWidth: 540 }}>
            {sent
              ? "If an account exists for that email, we just sent a reset link. The link expires in 30 minutes."
              : "Enter the email tied to your account. We'll send a one-time reset link."}
          </p>
        </div>
      </section>
      {!sent && (
        <section className="section">
          <div className="shell" style={{ maxWidth: 520 }}>
            <form className="form-grid" onSubmit={submit}>
              <div className="form-section">
                <label className="field"><span className="field-label">Email</span>
                  <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required autoFocus /></label>
                <button type="submit" className="btn btn--primary" disabled={busy}>
                  {busy ? "…" : "Send reset link"} <Icon.Arrow />
                </button>
              </div>
            </form>
          </div>
        </section>
      )}
    </main>
  );
}

function AcceptInvitePage({ token, go }) {
  const [info, setInfo] = React.useState(null);
  const [err, setErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [form, setForm] = React.useState({ full_name: "", password: "" });

  React.useEffect(() => {
    if (!token) { setErr("Missing invite token."); return; }
    window.W3J_API.apiFetch(`/auth/invite/${token}`, { auth: false })
      .then(setInfo).catch((ex) => setErr(ex.message));
  }, [token]);

  const submit = async (e) => {
    e.preventDefault();
    setBusy(true); setErr("");
    try {
      const tokens = await window.W3J_API.apiFetch("/auth/accept-invite", {
        method: "POST", body: { token, full_name: form.full_name, password: form.password }, auth: false,
      });
      window.W3J_API.tokens.set(tokens);
      go("admin");
    } catch (ex) {
      setErr(ex.message);
    } finally { setBusy(false); }
  };

  if (err) {
    return (
      <main>
        <section className="page-hero">
          <div className="shell">
            <Eyebrow>Invite</Eyebrow>
            <h1 style={{ marginTop: 16 }}>Invite <em>unavailable.</em></h1>
            <p className="lede" style={{ marginTop: 16 }}>{err}</p>
          </div>
        </section>
      </main>
    );
  }
  if (!info) return <main><section className="section"><div className="shell"><p className="lede">Loading invite…</p></div></section></main>;

  return (
    <main>
      <section className="page-hero">
        <div className="shell">
          <Eyebrow>Recruiter invite</Eyebrow>
          <h1 style={{ marginTop: 16 }}>Welcome to <em>Web3JOE.</em></h1>
          <p className="lede" style={{ marginTop: 16 }}>
            Joining as <strong>{info.email}</strong>. Set a password and you're in.
          </p>
        </div>
      </section>
      <section className="section">
        <div className="shell" style={{ maxWidth: 520 }}>
          <form className="form-grid" onSubmit={submit}>
            <div className="form-section">
              <label className="field"><span className="field-label">Full name</span>
                <input value={form.full_name} onChange={(e) => setForm((f) => ({ ...f, full_name: e.target.value }))} required maxLength={160} autoFocus /></label>
              <label className="field"><span className="field-label">Password</span>
                <input type="password" value={form.password} onChange={(e) => setForm((f) => ({ ...f, password: e.target.value }))} required minLength={10} />
                <span className="field-hint">Minimum 10 characters.</span></label>
              <button type="submit" className="btn btn--primary" disabled={busy}>
                {busy ? "…" : "Create my account"} <Icon.Arrow />
              </button>
            </div>
          </form>
        </div>
      </section>
    </main>
  );
}

window.RoleDetailPage = RoleDetailPage;
window.ResetPasswordPage = ResetPasswordPage;
window.ForgotPasswordPage = ForgotPasswordPage;
window.AcceptInvitePage = AcceptInvitePage;
