// Reseller portal signup ("request access") page.
//
// Every signup lands as `pending` and needs explicit admin approval —
// there's no referral/invite code, no auto-approval. See
// src/routes/portal.ts for the matching backend logic (company dedup by
// normalized name, per-user approval gate).
//
// Reuses FieldBlock / DarkInput / LiveDot / CornerHairlines from
// reseller-login-page.jsx (loaded just before this file — see index.html).
//
// LIGHT/DARK TOGGLE: renders standalone, outside ResellerShell (no
// sidebar pre-signup) — same treatment as reseller-login-page.jsx: its
// own usePortalTheme(), its own data-portal-theme root, its own
// <PortalThemeStyles /> mount, its own toggle placed next to the
// "request access" eyebrow tag.

function ResellerSignupPage({ onNavigate }) {
  const [theme, toggleTheme] = usePortalTheme();
  const [name, setName] = useState("");
  const [companyName, setCompanyName] = useState("");
  const [email, setEmail] = useState("");
  const [address, setAddress] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  // idle → submitting → submitted (shows the "pending approval" card)
  const [status, setStatus] = useState("idle");
  const [error, setError] = useState("");

  const passwordsMatch = !confirmPassword || password === confirmPassword;
  const canSubmit =
    name.trim() && companyName.trim() && email.trim() &&
    password.length >= 10 && password === confirmPassword &&
    status !== "submitting";

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!canSubmit) return;
    setStatus("submitting");
    setError("");
    try {
      const res = await fetch("/api/portal/signup", {
        method: "POST",
        credentials: "same-origin",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: name.trim(),
          companyName: companyName.trim(),
          email: email.trim(),
          address: address.trim(),
          password,
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setError(data.error || "Something went wrong. Please try again.");
        setStatus("idle");
        return;
      }
      setStatus("submitted");
    } catch {
      setError("Couldn't reach the server. Check your connection and try again.");
      setStatus("idle");
    }
  };

  return (
    <section data-portal-theme={theme} style={{
      background: "var(--pt-bg)",
      color: "var(--pt-fg)",
      minHeight: "calc(100vh - 88px)",
      padding: "80px 36px 120px",
      display: "flex", alignItems: "center", justifyContent: "center",
      position: "relative",
    }}>
      <PortalThemeStyles />
      <CornerHairlines />

      <div style={{
        width: "100%", maxWidth: 520,
        position: "relative", zIndex: 2,
      }}>
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10,
          marginBottom: 32,
        }}>
          <div style={{
            display: "flex", alignItems: "center", gap: 10,
            fontFamily: "var(--font-body)", fontSize: 10,
            letterSpacing: "0.32em", textTransform: "uppercase",
            color: "var(--pt-fg-dimmer)", fontWeight: 500,
          }}>
            <LiveDot />
            <span>Reseller portal · request access</span>
          </div>
          <PortalThemeToggle theme={theme} onToggle={toggleTheme} compact />
        </div>

        <h1 style={{
          fontFamily: "var(--font-display)", fontWeight: 700,
          fontSize: "clamp(36px, 5.4vw, 56px)", lineHeight: 1,
          letterSpacing: "-0.005em", textTransform: "uppercase",
          margin: "0 0 18px", color: "var(--pt-fg)",
        }}>
          Request portal access.
        </h1>
        <p style={{
          fontFamily: "var(--font-body)", fontSize: 16,
          lineHeight: 1.5, color: "var(--pt-fg-4)",
          margin: "0 0 24px", maxWidth: 440,
        }}>
          Tell us about your business. Every request is reviewed by our channel team — you'll get
          an email once your account and company are approved.
        </p>

        {status === "submitted" ? (
          <SignupConfirmedCard onNavigate={onNavigate} />
        ) : (
          <form onSubmit={handleSubmit} style={{
            background: "var(--pt-surface)",
            border: "1px solid var(--pt-border-3)",
            backdropFilter: "blur(6px)",
            padding: "36px 36px 36px",
          }}>
            {error && (
              <div style={{
                background: "var(--pt-error-bg)",
                border: "1px solid var(--pt-error-border)",
                color: "var(--pt-error-text)",
                padding: "14px 16px",
                marginBottom: 22,
                fontFamily: "var(--font-body)", fontSize: 13.5, lineHeight: 1.5,
              }}>
                {error}
              </div>
            )}

            <FieldBlock label="Full name">
              <DarkInput
                type="text" autoComplete="name" required
                value={name} onChange={(e) => setName(e.target.value)}
                placeholder="Jane Smith"
              />
            </FieldBlock>

            <FieldBlock label="Company name">
              <DarkInput
                type="text" autoComplete="organization" required
                value={companyName} onChange={(e) => setCompanyName(e.target.value)}
                placeholder="Partner Security Ltd"
              />
            </FieldBlock>

            <FieldBlock label="Email">
              <DarkInput
                type="email" autoComplete="username" required
                value={email} onChange={(e) => setEmail(e.target.value)}
                placeholder="jane@partner.co.uk"
              />
            </FieldBlock>

            <FieldBlock label="Company address" hint="Optional, but helps us route your account manager correctly">
              <DarkInput
                type="text" autoComplete="street-address"
                value={address} onChange={(e) => setAddress(e.target.value)}
                placeholder="1 Example Street, London, UK"
              />
            </FieldBlock>

            <FieldBlock label="Password" hint="At least 10 characters" right={
              <button
                type="button"
                onClick={() => setShowPassword((v) => !v)}
                style={{
                  background: "none", border: "none", cursor: "pointer", padding: 0,
                  fontFamily: "var(--font-body)", fontSize: 10,
                  letterSpacing: "0.22em", textTransform: "uppercase",
                  color: "var(--pt-fg-dim)", fontWeight: 500,
                }}>
                {showPassword ? "Hide" : "Show"}
              </button>
            }>
              <DarkInput
                type={showPassword ? "text" : "password"}
                autoComplete="new-password" required minLength={10}
                value={password} onChange={(e) => setPassword(e.target.value)}
                placeholder="••••••••••••"
              />
            </FieldBlock>

            <FieldBlock
              label="Confirm password"
              hint={!passwordsMatch ? "Passwords don't match" : undefined}
            >
              <DarkInput
                type={showPassword ? "text" : "password"}
                autoComplete="new-password" required
                value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)}
                placeholder="••••••••••••"
                style={!passwordsMatch ? { borderColor: "var(--pt-error-border)" } : undefined}
              />
            </FieldBlock>

            <button
              type="submit"
              disabled={!canSubmit}
              style={{
                width: "100%", marginTop: 12,
                background: canSubmit ? "var(--pt-accent-bg)" : "var(--pt-accent-bg-disabled)",
                color: canSubmit ? "var(--pt-accent-fg)" : "var(--pt-accent-fg-disabled)",
                border: `1px solid ${canSubmit ? "var(--pt-accent-bg)" : "var(--pt-accent-bg-disabled)"}`,
                padding: "18px 22px",
                cursor: canSubmit ? "pointer" : "not-allowed",
                fontFamily: "var(--font-body)",
                fontSize: 13, fontWeight: 500,
                letterSpacing: "0.22em", textTransform: "uppercase",
                transition: "background 140ms, color 140ms",
              }}>
              {status === "submitting" ? "Submitting…" : "Request access →"}
            </button>

            <div style={{
              marginTop: 24, paddingTop: 22,
              borderTop: "1px solid var(--pt-border)",
              fontFamily: "var(--font-body)", fontSize: 12,
              letterSpacing: "0.14em", textTransform: "uppercase",
              textAlign: "center",
            }}>
              <button
                type="button"
                onClick={() => onNavigate("reseller-login")}
                style={{
                  background: "none", border: "none", padding: 0,
                  cursor: "pointer",
                  fontFamily: "inherit", fontSize: "inherit", letterSpacing: "inherit",
                  color: "var(--pt-fg-4)",
                  textDecoration: "underline",
                  textDecorationColor: "var(--pt-border-strong)",
                  textUnderlineOffset: 4,
                }}>Already have an account? Sign in →</button>
            </div>
          </form>
        )}
      </div>
    </section>
  );
}

/* ──────────── Confirmation card, shown after a successful signup ──────────── */
// Originally a light contrast card floating on the old dark page — now
// that the page itself is light, this becomes a solid black card so the
// "success" moment still reads as a distinct, weighty callout rather
// than blending into the surrounding white page.
function SignupConfirmedCard({ onNavigate }) {
  return (
    <div style={{
      background: "var(--pt-contrast-bg)", color: "var(--pt-contrast-fg)",
      padding: "36px 36px 36px",
      border: "1px solid var(--pt-contrast-bg)",
    }}>
      <div style={{
        fontFamily: "var(--font-body)", fontSize: 11,
        letterSpacing: "0.22em", textTransform: "uppercase",
        color: "var(--pt-contrast-fg-dimmer)", marginBottom: 12, fontWeight: 500,
      }}>Request received</div>
      <h3 style={{
        fontFamily: "var(--font-display)", fontWeight: 700,
        fontSize: 24, letterSpacing: "0.005em",
        textTransform: "uppercase", margin: "0 0 16px",
        color: "var(--pt-contrast-fg)",
      }}>Thanks — you're on the list.</h3>
      <p style={{
        fontFamily: "var(--font-body)", fontSize: 15,
        lineHeight: 1.55, color: "var(--pt-contrast-fg-dim)",
        margin: "0 0 26px",
      }}>
        Your request has been sent to our channel team for review. We'll email you as soon as
        your account is approved — then you can sign in from the login page.
      </p>
      <button
        type="button"
        onClick={() => onNavigate("reseller-login")}
        style={{
          background: "var(--pt-contrast-fg)", color: "var(--pt-contrast-bg)",
          border: "1px solid var(--pt-contrast-fg)",
          padding: "16px 24px", cursor: "pointer",
          fontFamily: "var(--font-body)",
          fontSize: 13, fontWeight: 500,
          letterSpacing: "0.22em", textTransform: "uppercase",
        }}>Go to login →</button>
    </div>
  );
}

Object.assign(window, { ResellerSignupPage });
