"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Check, X, Loader2, MailCheck, Eye, EyeOff } from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import { USERNAME_RE, SITE_NAME } from "@/lib/constants";
import DiscordButton from "@/components/DiscordButton";
import GoogleButton from "@/components/GoogleButton";

declare global {
  interface Window {
    turnstile?: {
      render: (container: HTMLElement, options: {
        sitekey: string;
        action: string;
        callback: (token: string) => void;
        "expired-callback": () => void;
        "error-callback": () => void;
      }) => string;
      reset: (widgetId?: string) => void;
      remove: (widgetId: string) => void;
    };
  }
}

export default function SignupForm({
  initialUsername,
  discordSignup,
  initialReferralCode = "",
}: {
  initialUsername: string;
  initialReferralCode?: string;
  discordSignup?: { email: string; avatarUrl?: string } | null;
}) {
  const router = useRouter();
  const supabase = useMemo(() => createClient(), []);
  const isDiscord = Boolean(discordSignup);

  const [username, setUsername] = useState(initialUsername);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [status, setStatus] = useState<"idle" | "checking" | "free" | "taken" | "invalid" | "rate_limited" | "error">("idle");
  const checkCacheRef = useRef<Map<string, { available: boolean; reserved?: boolean }>>(new Map());
  const [reservedName, setReservedName] = useState(false);
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");
  const [loading, setLoading] = useState(false);
  const [signupId, setSignupId] = useState("");
  const [verificationCode, setVerificationCode] = useState("");
  const [turnstileToken, setTurnstileToken] = useState("");
  const [referralCode, setReferralCode] = useState(initialReferralCode);
  const [showReferral, setShowReferral] = useState(Boolean(initialReferralCode));
  const [acceptedTerms, setAcceptedTerms] = useState(false);
  const [transferMigration, setTransferMigration] = useState<{ sourceUsername: string; chosenHandle?: string } | null>(null);
  const [turnstileError, setTurnstileError] = useState("");
  const turnstileContainer = useRef<HTMLDivElement>(null);
  const turnstileWidgetId = useRef<string | null>(null);
  const turnstileSiteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || "";

  useEffect(() => {
    const clean = username.trim().toLowerCase();
    if (!clean) return setStatus("idle");
    if (!USERNAME_RE.test(clean)) return setStatus("invalid");

    if (checkCacheRef.current.has(clean)) {
      const cached = checkCacheRef.current.get(clean)!;
      setStatus(cached.available ? "free" : "taken");
      setReservedName(Boolean(cached.reserved));
      return;
    }

    let active = true;
    setStatus("checking");
    const t = setTimeout(async () => {
      try {
        const response = await fetch(`/api/sys/id/check?username=${encodeURIComponent(clean)}&_t=${Date.now()}`, { cache: "no-store" });
        const result = await response.json();
        if (active) {
          if (result?.username && result.username !== clean) {
            return;
          }
          if (response.status === 429 || result?.rateLimited) {
            setStatus("rate_limited");
          } else if (!response.ok || !result?.ok) {
            setStatus("error");
          } else {
            checkCacheRef.current.set(clean, { available: Boolean(result.available), reserved: Boolean(result.reserved) });
            setStatus(result.available ? "free" : "taken");
            setReservedName(Boolean(result?.reserved));
          }
        }
      } catch {
        if (active) setStatus("error");
      }
    }, 350);
    return () => { active = false; clearTimeout(t); };
  }, [username, supabase]);

  useEffect(() => {
    const pendingSignupId = window.sessionStorage.getItem("pendingEmailSignupId");
    const pendingEmail = window.sessionStorage.getItem("pendingEmailSignupAddress");
    if (pendingSignupId && pendingEmail) {
      setSignupId(pendingSignupId);
      setEmail(pendingEmail);
      setNotice(`Enter the verification code sent to ${pendingEmail}.`);
    }

    // Detect pending guns.lol transfer session
    try {
      const transferRaw = window.sessionStorage.getItem("sinss_transfer_session");
      if (transferRaw) {
        const parsed = JSON.parse(transferRaw);
        if (parsed.sourceUsername) {
          setTransferMigration({
            sourceUsername: parsed.sourceUsername,
            chosenHandle: parsed.chosenHandle,
          });
          if (parsed.chosenHandle && !username) {
            setUsername(parsed.chosenHandle);
          }
        }
      }
    } catch {
      // Ignore sessionStorage parsing error
    }
  }, []);

  useEffect(() => {
    if (signupId || !turnstileSiteKey || !turnstileContainer.current) return;
    let cancelled = false;
    let script = document.getElementById("cloudflare-turnstile-script") as HTMLScriptElement | null;

    const renderWidget = () => {
      if (cancelled || !window.turnstile || !turnstileContainer.current || turnstileWidgetId.current) return;
      turnstileWidgetId.current = window.turnstile.render(turnstileContainer.current, {
        sitekey: turnstileSiteKey,
        action: "signup",
        callback: (token) => {
          setTurnstileToken(token);
          setTurnstileError("");
        },
        "expired-callback": () => {
          setTurnstileToken("");
          setTurnstileError("Verification expired. Please complete it again.");
        },
        "error-callback": () => {
          setTurnstileToken("");
          setTurnstileError("Could not load verification. Refresh the page and try again.");
        },
      });
    };

    let checkInterval: NodeJS.Timeout | null = null;
    if (window.turnstile) {
      renderWidget();
    } else {
      if (!script) {
        script = document.createElement("script");
        script.id = "cloudflare-turnstile-script";
        script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
        script.async = true;
        script.defer = true;
        document.head.appendChild(script);
      }
      script.addEventListener("load", renderWidget);
      script.addEventListener("error", () => {
        if (!cancelled) setTurnstileError("Could not load verification. Check your connection and try again.");
      }, { once: true });

      // Fallback polling in case the script load event already fired
      checkInterval = setInterval(() => {
        if (cancelled) return;
        if (window.turnstile && !turnstileWidgetId.current && turnstileContainer.current) {
          renderWidget();
          if (checkInterval) clearInterval(checkInterval);
        }
      }, 200);
    }

    return () => {
      cancelled = true;
      if (checkInterval) clearInterval(checkInterval);
      if (turnstileWidgetId.current && window.turnstile) {
        window.turnstile.remove(turnstileWidgetId.current);
        turnstileWidgetId.current = null;
      }
    };
  }, [signupId, turnstileSiteKey]);

  const submit = async () => {
    setError("");
    setNotice("");
    window.sessionStorage.removeItem("pendingDiscordSignup");

    if (!USERNAME_RE.test(username)) return setError("Username: 1–20 lowercase letters, numbers, or _");
    if (status !== "free") return setError(status === "error" ? "Could not check this name. Try again." : "Wait for the name availability check to finish.");
    if (!email.trim()) return setError("Enter an email.");
    if (email.includes("+")) return setError("Email aliases (using '+') are not permitted. Please use your primary email address.");
    if (password.length < 6) return setError("Password must be at least 6 characters.");
    if (!acceptedTerms) return setError("You must accept the Terms of Service to create an account.");
    if (!turnstileSiteKey) return setError("Signup verification is not configured. Please contact the site owner.");
    if (!turnstileToken) return setError("Complete the verification challenge before continuing.");

    setLoading(true);
    try {
      const response = await fetch("/api/sys/id/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password, username, turnstileToken, referralCode, acceptedTerms: true }),
      });
      const result = await response.json();
      if (result.signupId) {
        setSignupId(result.signupId);
        window.sessionStorage.setItem("pendingEmailSignupId", result.signupId);
        window.sessionStorage.setItem("pendingEmailSignupAddress", email.trim().toLowerCase());
      }
      if (!response.ok && !result.signupId) return setError(result.error || "Signup failed. Please try again.");
      if (response.ok) {
        setNotice(`A 6-digit verification code was sent to ${email.trim().toLowerCase()}. It expires in 10 minutes.`);
      } else {
        setNotice("Your account was created, but the verification email could not be sent.");
        setError(result.error || "You can request another code.");
      }
    } catch {
      setError("Could not start signup. Check your connection and try again.");
    } finally {
      setLoading(false);
      setTurnstileToken("");
      if (turnstileWidgetId.current) window.turnstile?.reset(turnstileWidgetId.current);
    }
  };

  const submitDiscord = async () => {
    setError("");
    setNotice("");
    const ds = discordSignup;
    if (!ds) return setError("Start again with Discord.");

    if (!USERNAME_RE.test(username)) return setError("Username: 1–20 lowercase letters, numbers, or _");
    if (status !== "free") return setError(status === "error" ? "Could not check this name. Try again." : "Wait for the name availability check to finish.");
    if (!acceptedTerms) return setError("You must accept the Terms of Service to create an account.");

    setLoading(true);
    try {
      const response = await fetch("/api/discord/signup/complete", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, acceptedTerms: true, referralCode: referralCode.trim() }),
      });
      const result = await response.json().catch(() => ({}));
      if (result.ok && !result.signupId) {
        window.sessionStorage.removeItem("pendingDiscordSignup");
        router.replace("/dashboard");
        router.refresh();
        return;
      }
      if (result.signupId) {
        setSignupId(result.signupId);
        window.sessionStorage.setItem("pendingEmailSignupId", result.signupId);
        window.sessionStorage.setItem("pendingEmailSignupAddress", ds.email.toLowerCase());
        window.sessionStorage.setItem("pendingDiscordSignup", "1");
      }
      if (!response.ok && !result.signupId) return setError(result.error || "Could not create your page. Please try again.");
      if (response.ok) {
        setNotice(`A 6-digit verification code was sent to ${ds.email.toLowerCase()}. It expires in 10 minutes.`);
      } else {
        setNotice("Your page was created, but the verification email could not be sent.");
        setError(result.error || "You can request another code.");
      }
    } catch {
      setError("Could not create your page. Check your connection and try again.");
    } finally {
      setLoading(false);
    }
  };

  const useEmailInstead = async () => {
    setError("");
    setLoading(true);
    try {
      await fetch("/api/discord/signup/clear", { method: "POST" });
    } catch {
      // The cookie may already be gone; fall through and reload anyway.
    }
    window.sessionStorage.removeItem("pendingEmailSignupId");
    window.sessionStorage.removeItem("pendingEmailSignupAddress");
    window.sessionStorage.removeItem("pendingDiscordSignup");
    window.location.assign(initialUsername ? `/signup?username=${encodeURIComponent(initialUsername)}` : "/signup");
  };

  const verifyCode = async () => {
    setError("");
    if (!signupId) return setError("Start signup again to request a verification code.");
    if (!/^[0-9]{6}$/.test(verificationCode.trim())) return setError("Enter the 6-digit code from your email.");
    setLoading(true);
    try {
      const response = await fetch("/api/sys/id/confirm", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ signupId, code: verificationCode.trim() }),
      });
      const result = await response.json();
      if (!response.ok) return setError(result.error || "Could not verify your email.");

      if (window.sessionStorage.getItem("pendingDiscordSignup") === "1") {
        // Discord-created account: no typed password exists, so the server
        // establishes the session from the signed pending cookie instead.
        try {
          const sessionResponse = await fetch("/api/discord/signup/complete", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ action: "session" }),
          });
          const sessionResult = await sessionResponse.json().catch(() => ({}));
          if (!sessionResponse.ok || !sessionResult.ok) {
            if (sessionResult.error) setError(sessionResult.error);
            window.sessionStorage.removeItem("pendingDiscordSignup");
            return;
          }
        } catch {
          setError("Could not sign you in automatically. Try logging in with Discord.");
          window.sessionStorage.removeItem("pendingDiscordSignup");
          return;
        }
        window.sessionStorage.removeItem("pendingEmailSignupId");
        window.sessionStorage.removeItem("pendingEmailSignupAddress");
        window.sessionStorage.removeItem("pendingDiscordSignup");
        router.replace("/dashboard");
        router.refresh();
        return;
      }

      const { error: loginError } = await supabase.auth.signInWithPassword({
        email: email.trim().toLowerCase(),
        password,
      });
      setPassword("");
      if (loginError) {
        window.sessionStorage.removeItem("pendingEmailSignupId");
        window.sessionStorage.removeItem("pendingEmailSignupAddress");
        setSignupId("");
        router.replace(`/login?verified=true&email=${encodeURIComponent(email.trim().toLowerCase())}`);
        return;
      }
      window.sessionStorage.removeItem("pendingEmailSignupId");
      window.sessionStorage.removeItem("pendingEmailSignupAddress");
      router.replace("/dashboard");
      router.refresh();
    } catch {
      setError("Could not verify your email. Check your connection and try again.");
    } finally {
      setLoading(false);
    }
  };

  const resendCode = async () => {
    setError("");
    if (!signupId) return setError("Start signup again to request a verification code.");
    setLoading(true);
    try {
      const response = await fetch("/api/sys/id/dispatch", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ signupId }),
      });
      const result = await response.json();
      if (!response.ok) return setError(result.error || "Could not resend the verification code.");
      setNotice(`A new verification code was sent to ${email.trim().toLowerCase()}.`);
    } catch {
      setError("Could not resend the verification code. Check your connection and try again.");
    } finally {
      setLoading(false);
    }
  };

  const changeEmail = async () => {
    setError("");
    setLoading(true);
    try {
      const response = await fetch("/api/sys/id/abort", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ signupId }),
      });
      const result = await response.json();
      if (!response.ok) {
        setError(result.error || "Could not restart signup. Please try again.");
        return;
      }

      window.sessionStorage.removeItem("pendingEmailSignupId");
      window.sessionStorage.removeItem("pendingEmailSignupAddress");
      window.sessionStorage.removeItem("pendingDiscordSignup");
      setSignupId("");
      setVerificationCode("");
      setNotice("Update your email address and try again.");
    } catch {
      setError("Could not restart signup. Check your connection and try again.");
    } finally {
      setLoading(false);
    }
  };

  const usernameField = (
    <>
      <label className="lbl">Username</label>
      <div style={{ position: "relative" }}>
        <span style={prefix}>{SITE_NAME}/</span>
        <input
          className="field"
          style={{ paddingLeft: 76 }}
          value={username}
          onChange={(e) => { setError(""); setUsername(e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, "")); }}
          onKeyDown={(e) => e.key === "Enter" && (isDiscord ? submitDiscord() : submit())}
          placeholder="yourname"
          autoFocus
        />
        <span style={hint}>
          {status === "checking" && <Loader2 size={16} className="spin" style={{ color: "var(--auth-muted, #1a0a0a)" }} />}
          {status === "free" && <Check size={16} style={{ color: "var(--auth-good, #de8383)" }} />}
          {(status === "taken" || status === "invalid" || status === "rate_limited") && <X size={16} style={{ color: "var(--auth-bad, #f8d6d6)" }} />}
        </span>
      </div>
      <div style={{ minHeight: 18, fontSize: 12, marginTop: 5, color: status === "free" ? "var(--auth-good, #de8383)" : "var(--auth-bad, #f8d6d6)" }}>
        {status === "free" && "Available ✓"}
        {status === "taken" && (reservedName ? "Reserved for the site" : "Already claimed")}
        {status === "invalid" && "1–20 lowercase letters, numbers, or _"}
        {status === "rate_limited" && "Checking too fast. Please wait a moment."}
        {status === "error" && "Could not check availability. Try again."}
      </div>
    </>
  );

  return (
    <main style={shell}>
      <div style={card}>
        <div style={{ display: "flex", justifyContent: "center", marginBottom: 20 }}>
          <Link href="/" aria-label={`${SITE_NAME} home`} style={{ display: "inline-flex", alignItems: "center", gap: 9, textDecoration: "none", color: "var(--auth-text, #000)", fontWeight: 600, fontSize: 20 }}>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src="/addons/logo.svg" alt="" width={26} height={26} />
            <span>{SITE_NAME}</span>
          </Link>
        </div>
        {transferMigration && (
          <div
            style={{
              padding: "8px 14px",
              borderRadius: 8,
              background: "rgba(255, 255, 255, 0.08)",
              border: "1px solid rgba(255, 255, 255, 0.2)",
              color: "#ffffff",
              fontSize: 12,
              marginBottom: 16,
              textAlign: "center",
              lineHeight: 1.4,
            }}
          >
            Migrating profile from <strong>guns.lol/@{transferMigration.sourceUsername}</strong>. Content will be confirmed on your first login.
          </div>
        )}
        <h1 style={title}>Claim your name</h1>

        {!signupId && !discordSignup && (
          <>
            <DiscordButton mode="signup" />
            <GoogleButton mode="signup" />
            <div style={dividerRow}>
              <div style={dividerLine} /> or email <div style={dividerLine} />
            </div>
          </>
        )}

        {!signupId ? (
          discordSignup ? (
            <>
              <div style={discordIdentity}>
                {discordSignup.avatarUrl ? (
                  <img src={discordSignup.avatarUrl} alt="" width={36} height={36} style={{ borderRadius: "50%", objectFit: "cover", flexShrink: 0 }} />
                ) : null}
                <div style={{ minWidth: 0 }}>
                  <strong style={{ display: "block", fontSize: 13 }}>Signed in with Discord</strong>
                  <span style={{ fontSize: 12, color: "var(--auth-muted, #1a0a0a)", wordBreak: "break-all" }}>{discordSignup.email}</span>
                </div>
              </div>
              {usernameField}
              <p style={{ fontSize: 12, color: "var(--auth-dim, #180808)", marginTop: 4, lineHeight: 1.5 }}>
                Pick a handle for your page — this Discord account becomes your login.
              </p>
            </>
          ) : (
            <>
              {usernameField}
            <label className="lbl" style={{ marginTop: 8 }}>Email</label>
            <input className="field" type="email" value={email} onChange={(e) => setEmail(e.target.value)} />

            <label className="lbl" style={{ marginTop: 14 }}>Password</label>
            <div style={{ position: "relative" }}>
              <input
                className="field"
                type={showPassword ? "text" : "password"}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                style={{ paddingRight: 40 }}
                onKeyDown={(e) => e.key === "Enter" && submit()}
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                aria-label={showPassword ? "Hide password" : "Show password"}
                title={showPassword ? "Hide password" : "Show password"}
                style={{
                  position: "absolute",
                  right: 10,
                  top: "50%",
                  transform: "translateY(-50%)",
                  background: "none",
                  border: "none",
                  color: "var(--auth-muted, #0e0505)",
                  cursor: "pointer",
                  padding: 4,
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                }}
              >
                {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
              </button>
            </div>

            {showReferral || referralCode ? (
              <>
                <label className="lbl" style={{ marginTop: 12 }}>Referral code <span style={{ color: "var(--auth-dim, #280b0b)", fontWeight: 400 }}>(optional)</span></label>
                <input className="field" type="text" maxLength={20} value={referralCode} onChange={(e) => setReferralCode(e.target.value.toUpperCase())} placeholder="e.g. ALICEAB12CD" />
              </>
            ) : (
              <div style={{ marginTop: 8 }}>
                <button
                  type="button"
                  onClick={() => setShowReferral(true)}
                  style={{
                    background: "none",
                    border: "none",
                    color: "var(--auth-muted, #0e0505)",
                    fontSize: 12,
                    cursor: "pointer",
                    padding: "2px 0",
                    textDecoration: "underline",
                    textUnderlineOffset: 3,
                  }}
                >
                  Have a referral code?
                </button>
              </div>
            )}

            <div ref={turnstileContainer} style={{ display: "flex", justifyContent: "center", minHeight: turnstileSiteKey ? 65 : 0, marginTop: turnstileSiteKey ? 14 : 0 }} />
            {turnstileError && <p style={{ color: "var(--auth-bad, #f8d6d6)", fontSize: 12, margin: "8px 0 0" }}>{turnstileError}</p>}
            {!turnstileSiteKey && <p style={{ color: "var(--auth-bad, #f8d6d6)", fontSize: 12, margin: "8px 0 0" }}>Signup verification is not configured.</p>}
            </>
          )
        ) : (
          <>
            <p style={{ color: "var(--auth-sub, #3a0606)", fontSize: 14, lineHeight: 1.6, margin: "0 0 18px" }}>
              Enter the 6-digit code we emailed to <strong>{email.trim().toLowerCase()}</strong>.
            </p>
            <label className="lbl">Verification code</label>
            <input
              className="field"
              type="text"
              inputMode="numeric"
              autoComplete="one-time-code"
              maxLength={6}
              value={verificationCode}
              onChange={(event) => setVerificationCode(event.target.value.replace(/\D/g, "").slice(0, 6))}
              onKeyDown={(event) => event.key === "Enter" && verifyCode()}
              autoFocus
            />
          </>
        )}

        {notice && (
          <p style={{ color: "var(--auth-good, #de8383)", fontSize: 13, marginTop: 12, display: "flex", gap: 8, alignItems: "center" }}>
            <MailCheck size={16} /> {notice}
          </p>
        )}
        {error && <p style={{ color: "var(--auth-bad, #f8d6d6)", fontSize: 13, marginTop: 12 }}>{error}</p>}

          {signupId ? (
            <>
              <button className="btn" onClick={verifyCode} disabled={loading || verificationCode.length !== 6} style={{ background: "var(--auth-accent, #ffffff)", color: "var(--auth-accent-text, #604a4a)", width: "100%", marginTop: 18 }}>
                {loading ? "Verifying…" : "Verify email"}
              </button>
              <button type="button" className="btn" onClick={resendCode} disabled={loading} style={{ background: "transparent", color: "var(--auth-accent, #ebbdbd)", width: "100%", marginTop: 8, border: "1px solid var(--auth-line, rgba(0, 0, 0, .1))" }}>
                Resend code
              </button>
              <button type="button" className="btn" onClick={isDiscord ? useEmailInstead : changeEmail} disabled={loading} style={{ background: "transparent", color: "var(--auth-dim, #1f0707)", width: "100%", marginTop: 8, border: "1px solid var(--auth-line, rgba(0, 0, 0, .1))" }}>
                {loading ? "Please wait…" : (isDiscord ? "Start over with a different account" : "Wrong email? Go back and change it")}
              </button>
            </>
          ) : (
            <>
              <label
                style={{
                  display: "flex",
                  alignItems: "flex-start",
                  gap: 10,
                  marginTop: 18,
                  cursor: "pointer",
                  userSelect: "none",
                  fontSize: 13,
                  color: "var(--auth-sub, #3a0606)",
                  lineHeight: 1.45,
                }}
              >
                <input
                  type="checkbox"
                  checked={acceptedTerms}
                  onChange={(e) => {
                    setAcceptedTerms(e.target.checked);
                    if (error && error.toLowerCase().includes("terms")) setError("");
                  }}
                  style={{
                    marginTop: 2,
                    width: 16,
                    height: 16,
                    accentColor: "var(--auth-accent, #ffffff)",
                    borderRadius: 4,
                    cursor: "pointer",
                    flexShrink: 0,
                  }}
                />
                <span>
                  I agree to the{" "}
                  <Link
                    href="/terms"
                    target="_blank"
                    rel="noopener noreferrer"
                    style={{
                      color: "var(--auth-accent, #ffffff)",
                      textDecoration: "underline",
                      textUnderlineOffset: 2,
                    }}
                    onClick={(e) => e.stopPropagation()}
                  >
                    Terms of Service
                  </Link>{" "}
                  and{" "}
                  <Link
                    href="/privacy"
                    target="_blank"
                    rel="noopener noreferrer"
                    style={{
                      color: "var(--auth-accent, #ffffff)",
                      textDecoration: "underline",
                      textUnderlineOffset: 2,
                    }}
                    onClick={(e) => e.stopPropagation()}
                  >
                    Privacy Policy
                  </Link>
                </span>
              </label>

              <button
                className="btn"
                onClick={isDiscord ? submitDiscord : submit}
                disabled={loading || status !== "free" || !acceptedTerms || (!isDiscord && (!turnstileSiteKey || !turnstileToken))}
                style={{
                  background: "var(--auth-accent, #ffffff)",
                  color: "var(--auth-accent-text, #604a4a)",
                  width: "100%",
                  marginTop: 14,
                  opacity: loading || status !== "free" || !acceptedTerms || (!isDiscord && (!turnstileSiteKey || !turnstileToken)) ? 0.6 : 1,
                  cursor: loading || status !== "free" || !acceptedTerms ? "not-allowed" : "pointer",
                }}
              >
                {loading ? "Creating…" : "Create my page"}
              </button>
            </>
          )}

        <p style={{ margin: "12px 0 0", fontSize: 12, color: "var(--auth-dim, #180808)", textAlign: "center" }}>
          We use limited account-security signals to help review abuse. <Link href="/privacy" style={{ color: "var(--lp-blue, #ffffff)" }}>Read the privacy notice</Link>.
        </p>

        <p style={{ marginTop: 18, fontSize: 14, color: "var(--auth-muted, #1a0a0a)", textAlign: "center" }}>
          Already have one? <Link href="/login" style={{ fontWeight: 600 }}>Log in</Link>
        </p>
      </div>
      <style>{`.spin{animation:spin 1s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}`}</style>
    </main>
  );
}

const shell: React.CSSProperties = {
  minHeight: "100vh",
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  padding: 24,
  background: "radial-gradient(circle at 50% -10%, rgba(255, 255, 255, .12), var(--auth-shell, #08090b) 60%)",
  fontFamily: "Outfit, Arial, sans-serif",
};
const card: React.CSSProperties = {
  width: "min(400px, 100%)",
  background: "var(--auth-card, linear-gradient(140deg, #101217, #0c0d10))",
  border: "1px solid var(--auth-card-border, rgba(0, 0, 0, 0.08))",
  borderRadius: 16,
  padding: 28,
  boxShadow: "0 20px 50px rgba(0,0,0,.15)",
};
const title: React.CSSProperties = {
  fontFamily: "Unbounded, sans-serif",
  fontSize: 20,
  fontWeight: 500,
  letterSpacing: "-0.5px",
  margin: "0 0 20px",
  color: "var(--auth-text, #000)",
  textAlign: "center",
};
const prefix: React.CSSProperties = {
  position: "absolute",
  left: 12,
  top: "50%",
  transform: "translateY(-50%)",
  color: "var(--auth-muted, #1a0a0a)",
  fontSize: 13,
  pointerEvents: "none",
};
const hint: React.CSSProperties = {
  position: "absolute",
  right: 12,
  top: "50%",
  transform: "translateY(-50%)",
  display: "flex",
};
const dividerRow: React.CSSProperties = {
  display: "flex",
  alignItems: "center",
  gap: 10,
  margin: "16px 0",
  color: "var(--auth-muted, #000)",
  fontSize: 12,
};
const dividerLine: React.CSSProperties = {
  flex: 1,
  height: 1,
  background: "var(--auth-line, #2e2222)",
};
const discordIdentity: React.CSSProperties = {
  display: "flex",
  alignItems: "center",
  gap: 10,
  padding: "10px 12px",
  marginBottom: 16,
  border: "1px solid var(--auth-line, #2e2222)",
  borderRadius: 12,
  background: "rgba(242, 194, 194, 0.08)",
};
