window.createOnboardingLandingModule = function createOnboardingLandingModule(deps) {
  const { useState, useEffect } = React;
  const {
    apiRequest,
    safeText,
    isEndpointUnavailableError,
    BrandHomeLink,
    SiteHeaderNav,
    trackVisitorEvent,
  } = deps || {};

  const OnboardingLanding = ({
    authToken,
    setAuthToken,
    tenantId,
    setTenantId,
    tenantStatus,
    setTenantStatus,
    onboardingError,
    setOnboardingError,
    onboardingBusy,
    setOnboardingBusy,
    detachedMode,
    setDetachedMode,
    onCreditInfoChange,
    onContinue,
  }) => {
    const [authMode, setAuthMode] = useState("register");
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [couponCode, setCouponCode] = useState("BETALIST");
    const [registrationKey, setRegistrationKey] = useState(localStorage.getItem("approx_registration_key") || "");
    const [agentLineReady, setAgentLineReady] = useState(false);
    const [statusLine, setStatusLine] = useState("");
    const [didSubmit, setDidSubmit] = useState(false);
    const [copiedSkillLine, setCopiedSkillLine] = useState(false);
    const prettyState = (s) => {
      const value = String(s || "pending").trim();
      if (value === "workspace_pending_agent") return "Pending agent";
      if (value === "workspace_active") return "Active";
      return value.replace(/_/g, " ");
    };
    const activeRegistrationKey = registrationKey.trim();
    const deriveDisplayName = (value) => {
      const localPart = String(value || "").trim().toLowerCase().split("@")[0] || "user";
      const parts = localPart
        .split(/[^a-z0-9]+/g)
        .map((item) => item.trim())
        .filter(Boolean)
        .slice(0, 3);
      if (!parts.length) return "User";
      return parts.map((item) => item.charAt(0).toUpperCase() + item.slice(1)).join(" ");
    };

    const setupAccount = async () => {
      const cleanEmail = email.trim().toLowerCase();
      if (!cleanEmail || !cleanEmail.includes("@")) {
        setOnboardingError("Valid email is required.");
        return;
      }
      if ((password || "").length < 8) {
        setOnboardingError("Password must be at least 8 characters.");
        return;
      }
      if (authMode === "register" && !String(name || "").trim()) {
        setOnboardingError("Name is required.");
        return;
      }
      setOnboardingBusy(true);
      setOnboardingError("");
      setAgentLineReady(false);
      setDidSubmit(false);
      setStatusLine(authMode === "register" ? "Creating account..." : "Signing in...");
      if (typeof trackVisitorEvent === "function") {
        trackVisitorEvent(authMode === "register" ? "signup_submit" : "login_submit", {
          surface: "onboarding",
          email_domain: safeText(cleanEmail.split("@")[1], ""),
          coupon_code: authMode === "register" ? String(couponCode || "").trim().toUpperCase() : "",
        });
      }

      try {
        let token = "";
        let authPayload = null;
        if (authMode === "register") {
          try {
            const userData = await apiRequest("/users/register", {
              method: "POST",
              body: {
                email: cleanEmail,
                password,
                name: String(name || "").trim() || deriveDisplayName(cleanEmail),
                coupon_code: String(couponCode || "").trim(),
              },
            });
            authPayload = userData;
            token = userData.access_token || "";
            setRegistrationKey(safeText(userData?.registration_key, ""));
          } catch (err) {
            const message = safeText(err?.message, "");
            if (message.toLowerCase().includes("email already exists")) {
              const loginData = await apiRequest("/users/login", {
                method: "POST",
                body: {
                  email: cleanEmail,
                  password,
                  ...(activeRegistrationKey ? { registration_key: activeRegistrationKey } : {}),
                },
              });
              authPayload = loginData;
              token = loginData.access_token || "";
              setStatusLine("User already exists. Logged in successfully.");
            } else {
              throw err;
            }
          }
        } else {
          const loginData = await apiRequest("/users/login", {
            method: "POST",
            body: {
              email: cleanEmail,
              password,
            },
          });
          authPayload = loginData;
          token = loginData.access_token || "";
        }
        if (!token) throw new Error("Authentication did not return an access token.");
        setAuthToken(token);
        if (typeof onCreditInfoChange === "function") {
          onCreditInfoChange(authPayload?.query_credit || null);
        }

        setTenantId("default");
        setTenantStatus("workspace_pending_agent");
        const issuedRegistrationKey = safeText(authPayload?.registration_key, activeRegistrationKey);
        if (issuedRegistrationKey) {
          setRegistrationKey(issuedRegistrationKey);
          localStorage.setItem("approx_registration_key", issuedRegistrationKey);
        }
        setStatusLine(
          authMode === "register"
            ? "Registration successful. Your agent key is ready."
            : "Login successful.",
        );
        setAgentLineReady(true);
        setDidSubmit(true);
        setDetachedMode(false);
      } catch (err) {
        if (isEndpointUnavailableError(err)) {
          const localTenant = `local_${deriveDisplayName(cleanEmail).toLowerCase().replace(/[^a-z0-9]+/g, "_")}_${Date.now()}`;
          setAuthToken(`local_token_${Date.now()}`);
          setTenantId(localTenant);
          setTenantStatus("workspace_pending_agent");
          setDetachedMode(true);
          setOnboardingError("");
          setStatusLine("Backend is offline. Frontend is running in detached mode.");
          setAgentLineReady(true);
          setDidSubmit(true);
        } else {
          setOnboardingError(safeText(err?.message, "Registration flow failed."));
          setStatusLine("");
        }
      } finally {
        setOnboardingBusy(false);
      }
    };

    const skillLink = `${window.location.origin}/Skill.md${activeRegistrationKey ? `?registration_key=${encodeURIComponent(activeRegistrationKey)}` : ""}`;
    const skillCommandLine = `Register to Approxination using this skill: ${skillLink}`;

    return (
      <div
        className="w-screen h-screen overflow-y-auto bg-[#ffffff] text-[#24292f]"
        style={{ fontFamily: '"Helvetica Neue", Helvetica, Arial, sans-serif' }}
      >
        <header className="px-6 py-4 z-10 border-b border-[#d0d7de] shrink-0 bg-[#f6f8fa]">
          <div className="max-w-7xl mx-auto w-full flex justify-between items-center">
            <div className="flex items-center gap-6">
              <BrandHomeLink className="h-5 w-auto" />
              <SiteHeaderNav />
            </div>
            <div className="flex items-center gap-4 text-sm font-semibold text-[#57606a]">
              Account
            </div>
          </div>
        </header>
        <div className="max-w-4xl mx-auto px-6 py-12 space-y-8">
          <div className="space-y-4 border-b border-[#d0d7de] pb-8">
            <BrandHomeLink className="h-10 md:h-12 w-auto" />
            <div className="space-y-2">
              <h1 className="text-3xl md:text-4xl font-bold tracking-tight text-[#0f172a]">
                Create your account or sign in to use the API.
              </h1>
              <p className="text-sm md:text-base text-[#57606a] max-w-2xl">
                Keep it simple: create an account, get your agent key, connect your agent, and start using Approxination.
              </p>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <div className="border border-[#d0d7de] bg-[#f6f8fa] rounded-xl p-4">
                <div className="text-[11px] font-semibold uppercase tracking-wide text-[#57606a]">Step 1</div>
                <div className="mt-1 text-sm font-semibold text-[#24292f]">Create account</div>
                <div className="mt-1 text-xs text-[#57606a]">Use email and password to register or log in.</div>
              </div>
              <div className="border border-[#d0d7de] bg-[#f6f8fa] rounded-xl p-4">
                <div className="text-[11px] font-semibold uppercase tracking-wide text-[#57606a]">Step 2</div>
                <div className="mt-1 text-sm font-semibold text-[#24292f]">Get agent key</div>
                <div className="mt-1 text-xs text-[#57606a]">We generate your registration key after account creation.</div>
              </div>
              <div className="border border-[#d0d7de] bg-[#f6f8fa] rounded-xl p-4">
                <div className="text-[11px] font-semibold uppercase tracking-wide text-[#57606a]">Step 3</div>
                <div className="mt-1 text-sm font-semibold text-[#24292f]">Connect agent</div>
                <div className="mt-1 text-xs text-[#57606a]">Use that key to activate your agent and start querying.</div>
              </div>
            </div>
          </div>

          {onboardingError && (
            <div className="border border-[#d1242f] bg-[#ffebe9] text-[#cf222e] px-4 py-3 text-sm rounded-md">
              {onboardingError}
            </div>
          )}

          <div className="border border-[#d0d7de] bg-[#f6f8fa] rounded-2xl p-6 md:p-7 space-y-4 shadow-sm">
            <div className="flex gap-2">
              <button
                onClick={() => {
                  setAuthMode("register");
                  setDidSubmit(false);
                  setStatusLine("");
                }}
                className={`px-3 py-1.5 border rounded-md text-xs font-semibold transition-colors ${
                  authMode === "register"
                    ? "bg-[#24292f] text-white border-[#24292f]"
                    : "bg-white text-[#24292f] border-[#d0d7de] hover:bg-[#f3f4f6]"
                }`}
              >
                Register
              </button>
              <button
                onClick={() => {
                  setAuthMode("login");
                  setDidSubmit(false);
                  setStatusLine("");
                }}
                className={`px-3 py-1.5 border rounded-md text-xs font-semibold transition-colors ${
                  authMode === "login"
                    ? "bg-[#24292f] text-white border-[#24292f]"
                    : "bg-white text-[#24292f] border-[#d0d7de] hover:bg-[#f3f4f6]"
                }`}
              >
                Login
              </button>
            </div>

            <div className="space-y-1">
              <div className="text-xs font-semibold tracking-wide text-[#57606a]">
                {authMode === "register" ? "Create account" : "Sign in"}
              </div>
              <p className="text-sm text-[#57606a]">
                {authMode === "register"
                  ? "Register with your name, email, password, and optional coupon code."
                  : "Log in with your email and password."}
              </p>
            </div>

            {authMode === "register" && (
              <input
                className="w-full border border-[#d0d7de] rounded-md p-3 text-sm bg-white focus:outline-none focus:border-[#24292f] focus:ring-1 focus:ring-[#24292f]"
                placeholder="Name"
                value={name}
                onChange={(e) => setName(e.target.value)}
              />
            )}
            {authMode === "register" && (
              <input
                className="w-full border border-[#d0d7de] rounded-md p-3 text-sm bg-white focus:outline-none focus:border-[#24292f] focus:ring-1 focus:ring-[#24292f]"
                placeholder="Coupon code"
                value={couponCode}
                onChange={(e) => setCouponCode(e.target.value)}
              />
            )}
            <input
              className="w-full border border-[#d0d7de] rounded-md p-3 text-sm bg-white focus:outline-none focus:border-[#24292f] focus:ring-1 focus:ring-[#24292f]"
              placeholder="Email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
            <input
              type="password"
              className="w-full border border-[#d0d7de] rounded-md p-3 text-sm bg-white focus:outline-none focus:border-[#24292f] focus:ring-1 focus:ring-[#24292f]"
              placeholder="Password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />

            <button
              disabled={onboardingBusy}
              onClick={setupAccount}
              className="w-full px-4 py-3 bg-[#2da44e] text-white text-sm font-semibold rounded-md hover:bg-[#2c974b] disabled:opacity-50 transition-colors"
            >
              {onboardingBusy ? "Processing..." : authMode === "register" ? "Create account" : "Sign in"}
            </button>

            <div className="text-xs text-[#57606a]">
              {statusLine ||
                (didSubmit
                  ? `Workspace: ${prettyState(tenantStatus)}`
                  : authMode === "register"
                    ? "Register with your name, email, and password. We will generate your agent key."
                    : "Log in with email and password.")}
            </div>
          </div>

          {didSubmit && (
            <div className="border border-[#d0d7de] bg-white rounded-2xl p-6 md:p-7 space-y-5 shadow-sm">
              <div className="space-y-2">
                <div className="text-sm font-semibold text-[#24292f]">Connect your agent</div>
                <p className="text-sm text-[#57606a]">
                  Use this registration key to activate your agent so the workspace is fully ready for querying and credits.
                </p>
              </div>

              {activeRegistrationKey ? (
                <>
                  <div className="space-y-2">
                    <div className="text-xs font-semibold uppercase tracking-wide text-[#57606a]">Your registration key</div>
                    <input
                      readOnly
                      value={activeRegistrationKey}
                      className="w-full border border-[#d0d7de] rounded-md p-3 text-sm font-mono bg-[#f6f8fa] focus:outline-none"
                      onFocus={(e) => e.target.select()}
                    />
                  </div>
                  <div className="flex gap-2">
                    <input
                      readOnly
                      value={skillCommandLine}
                      className="w-full border border-[#d0d7de] rounded-md p-3 text-xs font-mono bg-[#f6f8fa] focus:outline-none"
                      onFocus={(e) => e.target.select()}
                    />
                    <button
                      onClick={async () => {
                        try {
                          await navigator.clipboard?.writeText(skillCommandLine);
                          setCopiedSkillLine(true);
                          setTimeout(() => setCopiedSkillLine(false), 1500);
                        } catch (_err) {
                          setCopiedSkillLine(false);
                        }
                      }}
                      className="px-4 py-2 border border-[#d0d7de] rounded-md text-xs font-semibold text-[#24292f] hover:bg-[#f3f4f6]"
                    >
                      {copiedSkillLine ? "Copied" : "Copy"}
                    </button>
                  </div>
                  <div className="text-xs text-[#57606a]">
                    Open this link in OpenClaw to register and connect the agent with the same key.
                  </div>
                </>
              ) : (
                <div className="border border-[#d0d7de] bg-[#f6f8fa] rounded-md p-3 text-xs text-[#57606a]">
                  No registration key is saved yet. Create an account first, or log in to an account that already has a linked key.
                </div>
              )}

              <div className="flex flex-wrap gap-3 items-center">
                <button
                  onClick={onContinue}
                  className="px-5 py-2 bg-[#24292f] text-white text-xs font-semibold rounded-md hover:bg-[#111111] disabled:opacity-50"
                  disabled={!didSubmit}
                >
                  Continue to app
                </button>
              </div>

              <div className="text-xs text-[#57606a]">
                You can continue now. Full agent connection details are available from your profile page inside the app.
              </div>
            </div>
          )}
          
        </div>
      </div>
    );
  };

  return { OnboardingLanding };
};
