// Create account page — matches the login layout (centered card, single column).
// New accounts start with status "pending" — admin must approve before bidding.

function AccessRequestPage({ onNav, onSignup }) {
  const [form, setForm] = React.useState({
    firstName: "", lastName: "", company: "",
    email: "", password: "", confirm: "",
  });
  const [submitted, setSubmitted] = React.useState(null);
  const [errors, setErrors] = React.useState({});
  const [busy, setBusy] = React.useState(false);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const validate = () => {
    const e = {};
    if (!form.firstName.trim()) e.firstName = "Required";
    if (!form.lastName.trim()) e.lastName = "Required";
    if (!form.company.trim()) e.company = "Required";
    if (!form.email.trim()) e.email = "Required";
    if (form.email && !/\S+@\S+\.\S+/.test(form.email)) e.email = "Enter a valid email";
    if (!form.password) e.password = "Required";
    if (form.password && form.password.length < 8) e.password = "Use 8+ characters";
    if (form.password !== form.confirm) e.confirm = "Passwords don't match";
    return e;
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const errs = validate();
    if (Object.keys(errs).length) { setErrors(errs); return; }
    setErrors({});
    setBusy(true);
    setTimeout(() => {
      const res = onSignup({
        firstName: form.firstName, lastName: form.lastName,
        company: form.company,
        email: form.email,
        password: form.password,
      });
      setBusy(false);
      if (res?.error) { setErrors({ email: res.error }); return; }
      setSubmitted(res.profile);
    }, 500);
  };

  if (submitted) {
    return (
      <div className="container" style={{ maxWidth: 880, padding: "64px 24px 96px" }}>
        <div style={{ display: "grid", placeItems: "center" }}>
          <div style={{
            width: "min(480px, 100%)",
            background: "var(--bg-elev)",
            border: "1px solid var(--line)",
            borderRadius: 16,
            padding: "36px 36px 30px",
            boxShadow: "0 1px 0 rgba(15,23,42,0.02), 0 12px 32px -16px rgba(15,23,42,0.08)",
            textAlign: "center",
          }}>
            <div style={{
              width: 56, height: 56, borderRadius: "50%",
              background: "rgba(245,158,11,0.12)",
              border: "1px solid rgba(245,158,11,0.30)",
              display: "grid", placeItems: "center", color: "#b45309",
              margin: "0 auto 20px",
            }}>
              <IcClock size={24} />
            </div>
            <div className="eyebrow" style={{ marginBottom: 10 }}>Application received</div>
            <h1 style={{ fontSize: 26, fontWeight: 600, letterSpacing: "-0.02em", margin: 0, marginBottom: 10 }}>
              Account pending review
            </h1>
            <p style={{ color: "var(--ink-2)", fontSize: 14, lineHeight: 1.6, margin: "0 auto 24px", maxWidth: "40ch" }}>
              You're signed in and can browse all inventory. Our team will review your application within 1–2 business days, and we'll email you when bidding is unlocked.
            </p>
            <div style={{
              background: "var(--bg-sunken)", border: "1px solid var(--line)",
              borderRadius: 10, padding: "14px 18px", marginBottom: 24, textAlign: "left",
            }}>
              {[
                ["Buyer ID", <span className="mono" style={{ fontWeight: 600 }}>{submitted.id}</span>],
                ["Name", submitted.name],
                ["Company", submitted.company || "—"],
                ["Status", <span className="pill pill-amber" style={{ padding: "2px 8px", fontSize: 11 }}>Pending review</span>],
              ].map(([k, v], i, arr) => (
                <div key={k} className="row between" style={{
                  padding: "8px 0", fontSize: 13,
                  borderBottom: i < arr.length - 1 ? "1px solid var(--line)" : "none",
                }}>
                  <span style={{ color: "var(--ink-3)" }}>{k}</span>
                  <span style={{ fontWeight: 500 }}>{v}</span>
                </div>
              ))}
            </div>
            <button className="btn btn-primary btn-lg btn-block" onClick={() => onNav("inventory")}>
              Browse inventory <IcArrow size={16} />
            </button>
            <button className="btn btn-ghost btn-sm" onClick={() => onNav("home")} style={{ marginTop: 10 }}>
              Return home
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="container" style={{ maxWidth: 880, padding: "64px 24px 96px" }}>
      <div style={{ display: "grid", placeItems: "center" }}>
        <div style={{
          width: "min(480px, 100%)",
          background: "var(--bg-elev)",
          border: "1px solid var(--line)",
          borderRadius: 16,
          padding: "36px 36px 32px",
          boxShadow: "0 1px 0 rgba(15,23,42,0.02), 0 12px 32px -16px rgba(15,23,42,0.08)",
        }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Invite-only marketplace</div>
          <h1 style={{ fontSize: 28, fontWeight: 600, letterSpacing: "-0.02em", margin: 0, marginBottom: 8 }}>
            Create your account
          </h1>
          <p style={{ fontSize: 14, color: "var(--ink-2)", lineHeight: 1.55, margin: "0 0 24px" }}>
            Browsing is open. Bidding unlocks once our team approves your buyer profile — typically within 1–2 business days.
          </p>

          <form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <ArField label="First name" required error={errors.firstName}>
                <input className="input" value={form.firstName}
                  onChange={(e) => set("firstName", e.target.value)}
                  autoComplete="given-name" autoFocus />
              </ArField>
              <ArField label="Last name" required error={errors.lastName}>
                <input className="input" value={form.lastName}
                  onChange={(e) => set("lastName", e.target.value)}
                  autoComplete="family-name" />
              </ArField>
            </div>
            <ArField label="Company" required error={errors.company}>
              <input className="input" value={form.company}
                onChange={(e) => set("company", e.target.value)}
                autoComplete="organization"
                placeholder="Northfield Interiors" />
            </ArField>
            <ArField label="Email" required error={errors.email}>
              <input className="input" type="email" value={form.email}
                onChange={(e) => set("email", e.target.value)}
                autoComplete="email" placeholder="you@company.com" />
            </ArField>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <ArField label="Password" required error={errors.password} hint="8+ characters">
                <input className="input" type="password" value={form.password}
                  onChange={(e) => set("password", e.target.value)}
                  autoComplete="new-password" />
              </ArField>
              <ArField label="Confirm" required error={errors.confirm}>
                <input className="input" type="password" value={form.confirm}
                  onChange={(e) => set("confirm", e.target.value)}
                  autoComplete="new-password" />
              </ArField>
            </div>

            <button type="submit" className="btn btn-primary btn-lg btn-block"
              disabled={busy} style={{ marginTop: 6 }}>
              {busy ? "Creating account…" : <>Create account <IcArrow size={16} /></>}
            </button>
            <div style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.5, textAlign: "center", marginTop: 4 }}>
              By creating an account you agree to our{" "}
              <a href="#" onClick={(e) => { e.preventDefault(); onNav("terms"); }} style={{ color: "var(--ink-2)" }}>buyer agreement</a>.
            </div>
          </form>

          <div className="row center gap-8" style={{ margin: "20px 0 16px", color: "var(--ink-3)" }}>
            <div style={{ flex: 1, height: 1, background: "var(--line)" }} />
            <span className="mono" style={{ fontSize: 11, letterSpacing: "0.1em" }}>ALREADY APPROVED</span>
            <div style={{ flex: 1, height: 1, background: "var(--line)" }} />
          </div>
          <button className="btn btn-secondary btn-lg btn-block" onClick={() => onNav("login")}>
            Sign in
          </button>
        </div>
      </div>
    </div>
  );
}

function ArField({ label, children, required, hint, error }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
      <label style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)" }}>
        {label}{required && <span style={{ color: "var(--ink-3)", marginLeft: 3 }}>*</span>}
      </label>
      {hint && <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{hint}</div>}
      {children}
      {error && <div style={{ fontSize: 12, color: "#b42318" }}>{error}</div>}
    </div>
  );
}

Object.assign(window, { AccessRequestPage });
