"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TermsCheckbox = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
/*
 *  This file is part of CoCalc: Copyright © 2022 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
const static_markdown_1 = __importDefault(require("@cocalc/frontend/editors/slate/static-markdown"));
const misc_1 = require("@cocalc/util/misc");
const antd_1 = require("antd");
const logo_square_1 = __importDefault(require("components/logo-square"));
const A_1 = __importDefault(require("components/misc/A"));
const loading_1 = __importDefault(require("components/share/loading"));
const post_1 = __importDefault(require("lib/api/post"));
const use_customize_1 = __importDefault(require("lib/use-customize"));
const react_1 = require("react");
const react_google_recaptcha_v3_1 = require("react-google-recaptcha-v3");
const shared_1 = require("./shared");
const sso_1 = __importStar(require("./sso"));
const LINE = { margin: "15px 0" };
function SignUp(props) {
    const { reCaptchaKey } = (0, use_customize_1.default)();
    return ((0, jsx_runtime_1.jsx)(react_google_recaptcha_v3_1.GoogleReCaptchaProvider, { reCaptchaKey: reCaptchaKey, children: (0, jsx_runtime_1.jsx)(SignUp0, { ...props }) }));
}
exports.default = SignUp;
function SignUp0({ requiresToken, minimal, onSuccess }) {
    const { anonymousSignup, siteName, emailSignup, accountCreationInstructions, reCaptchaKey, } = (0, use_customize_1.default)();
    const [terms, setTerms] = (0, react_1.useState)(false);
    const [email, setEmail] = (0, react_1.useState)("");
    const [registrationToken, setRegistrationToken] = (0, react_1.useState)("");
    const [password, setPassword] = (0, react_1.useState)("");
    const [firstName, setFirstName] = (0, react_1.useState)("");
    const [lastName, setLastName] = (0, react_1.useState)("");
    const [signingUp, setSigningUp] = (0, react_1.useState)(false);
    const [issues, setIssues] = (0, react_1.useState)({});
    const submittable = (0, react_1.useRef)(false);
    const { executeRecaptcha } = (0, react_google_recaptcha_v3_1.useGoogleReCaptcha)();
    const { strategies } = (0, use_customize_1.default)();
    // Sometimes the user if this component knows requiresToken and sometimes they don't.
    // If they don't, we have to make an API call to figure it out.
    const [requiresToken2, setRequiresToken2] = (0, react_1.useState)(requiresToken);
    (0, react_1.useEffect)(() => {
        if (requiresToken2 === undefined) {
            (async () => {
                try {
                    setRequiresToken2(await (0, post_1.default)("/auth/requires-token"));
                }
                catch (err) { }
            })();
        }
    }, []);
    // based on email: if user has to sign up via SSO, this will tell which strategy to use.
    const requiredSSO = (0, sso_1.useRequiredSSO)(strategies, email);
    if (requiresToken2 === undefined || strategies == null) {
        return (0, jsx_runtime_1.jsx)(loading_1.default, {});
    }
    submittable.current = !!(terms &&
        requiredSSO == null &&
        (!requiresToken2 || registrationToken) &&
        email &&
        (0, misc_1.is_valid_email_address)(email) &&
        password &&
        firstName &&
        lastName);
    async function signUp() {
        if (!submittable.current)
            return;
        if (signingUp)
            return;
        setIssues({});
        try {
            setSigningUp(true);
            let reCaptchaToken;
            if (reCaptchaKey) {
                if (!executeRecaptcha) {
                    throw Error("Please wait a few seconds, then try again.");
                }
                reCaptchaToken = await executeRecaptcha("signup");
            }
            const result = await (0, post_1.default)("/auth/sign-up", {
                terms,
                email,
                password,
                firstName,
                lastName,
                registrationToken,
                reCaptchaToken,
            });
            if (result.issues && (0, misc_1.len)(result.issues) > 0) {
                setIssues(result.issues);
            }
            else {
                onSuccess?.();
            }
        }
        catch (err) {
            setIssues({ error: `${err}` });
        }
        finally {
            setSigningUp(false);
        }
    }
    if (!emailSignup && strategies.length == 0) {
        return ((0, jsx_runtime_1.jsx)(antd_1.Alert, { style: { margin: "30px 15%" }, type: "error", showIcon: true, message: "No Account Creation Allowed", description: (0, jsx_runtime_1.jsxs)("div", { style: { fontSize: "14pt", marginTop: "20px" }, children: [(0, jsx_runtime_1.jsx)("b", { children: "There is no method enabled for creating an account on this server." }), anonymousSignup && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsx)("br", {}), "However, you can still", " ", (0, jsx_runtime_1.jsxs)(A_1.default, { href: "/auth/try", children: ["try ", siteName, " without creating an account."] })] }))] }) }));
    }
    return ((0, jsx_runtime_1.jsxs)("div", { style: { margin: "30px", minHeight: "50vh" }, children: [!minimal && ((0, jsx_runtime_1.jsxs)("div", { style: { textAlign: "center", marginBottom: "15px" }, children: [(0, jsx_runtime_1.jsx)(logo_square_1.default, { style: { width: "100px", height: "100px", marginBottom: "15px" }, priority: true }), (0, jsx_runtime_1.jsxs)("h1", { children: ["Create a ", siteName, " Account"] }), accountCreationInstructions && ((0, jsx_runtime_1.jsx)(static_markdown_1.default, { value: accountCreationInstructions }))] })), (0, jsx_runtime_1.jsxs)("div", { style: shared_1.LOGIN_STYLE, children: [(0, jsx_runtime_1.jsx)(TermsCheckbox, { onChange: setTerms, checked: terms, style: {
                            marginTop: "10px",
                            marginBottom: terms ? "10px" : undefined,
                            fontSize: "12pt",
                            color: "#666",
                        } }), (0, jsx_runtime_1.jsxs)("form", { children: [issues.reCaptcha && ((0, jsx_runtime_1.jsx)(antd_1.Alert, { style: LINE, type: "error", showIcon: true, message: issues.reCaptcha, description: (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: "You may have to contact the site administrator." }) })), issues.registrationToken && ((0, jsx_runtime_1.jsx)(antd_1.Alert, { style: LINE, type: "error", showIcon: true, message: issues.registrationToken, description: (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: "You may have to contact the site administrator for a registration token." }) })), terms && requiresToken2 && ((0, jsx_runtime_1.jsxs)("div", { style: LINE, children: [(0, jsx_runtime_1.jsx)("p", { children: "Registration Token" }), (0, jsx_runtime_1.jsx)(antd_1.Input, { style: { fontSize: "12pt" }, value: registrationToken, placeholder: "Enter your secret registration token", onChange: (e) => setRegistrationToken(e.target.value) })] })), terms && ((0, jsx_runtime_1.jsx)(EmailOrSSO, { email: email, setEmail: setEmail, signUp: signUp, strategies: strategies, hideSSO: requiredSSO != null })), (0, jsx_runtime_1.jsx)(sso_1.RequiredSSO, { strategy: requiredSSO }), issues.email && ((0, jsx_runtime_1.jsx)(antd_1.Alert, { style: LINE, type: "error", showIcon: true, message: issues.email, description: (0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: ["Choose a different email address,", " ", (0, jsx_runtime_1.jsx)(A_1.default, { href: "/auth/sign-in", children: "sign in" }), ", or", " ", (0, jsx_runtime_1.jsx)(A_1.default, { href: "/auth/password-reset", children: "reset your password" }), "."] }) })), terms && email && requiredSSO == null && ((0, jsx_runtime_1.jsxs)("div", { style: LINE, children: [(0, jsx_runtime_1.jsx)("p", { children: "Password" }), (0, jsx_runtime_1.jsx)(antd_1.Input.Password, { style: { fontSize: "12pt" }, value: password, placeholder: "Password", autoComplete: "new-password", onChange: (e) => setPassword(e.target.value), onPressEnter: signUp })] })), issues.password && ((0, jsx_runtime_1.jsx)(antd_1.Alert, { style: LINE, type: "error", showIcon: true, message: issues.email })), terms && email && requiredSSO == null && password?.length >= 6 && ((0, jsx_runtime_1.jsxs)("div", { style: LINE, children: [(0, jsx_runtime_1.jsx)("p", { children: "First name" }), (0, jsx_runtime_1.jsx)(antd_1.Input, { style: { fontSize: "12pt" }, placeholder: "First name", value: firstName, onChange: (e) => setFirstName(e.target.value), onPressEnter: signUp })] })), terms && email && password && requiredSSO == null && firstName && ((0, jsx_runtime_1.jsxs)("div", { style: LINE, children: [(0, jsx_runtime_1.jsx)("p", { children: "Last name" }), (0, jsx_runtime_1.jsx)(antd_1.Input, { style: { fontSize: "12pt" }, placeholder: "Last name", value: lastName, onChange: (e) => setLastName(e.target.value), onPressEnter: signUp })] }))] }), (0, jsx_runtime_1.jsx)("div", { style: LINE, children: (0, jsx_runtime_1.jsxs)(antd_1.Button, { shape: "round", size: "large", disabled: !submittable.current || signingUp, type: "primary", style: { width: "100%", marginTop: "15px" }, onClick: signUp, children: [!terms
                                    ? "Agree to the terms"
                                    : requiresToken2 && !registrationToken
                                        ? "Enter the secret registration token"
                                        : !email
                                            ? "How will you sign in?"
                                            : requiredSSO != null
                                                ? "You must sign up via SSO"
                                                : !password || password.length < 6
                                                    ? "Choose password with at least 6 characters"
                                                    : !firstName
                                                        ? "Enter your first name above"
                                                        : !lastName
                                                            ? "Enter your last name above"
                                                            : !(0, misc_1.is_valid_email_address)(email)
                                                                ? "Enter a valid email address above"
                                                                : signingUp
                                                                    ? ""
                                                                    : "Sign Up!", signingUp && ((0, jsx_runtime_1.jsx)("span", { style: { marginLeft: "15px" }, children: (0, jsx_runtime_1.jsx)(loading_1.default, { children: "Signing Up..." }) }))] }) }), issues.error && ((0, jsx_runtime_1.jsx)(antd_1.Alert, { style: LINE, type: "error", showIcon: true, message: issues.error }))] }), !minimal && ((0, jsx_runtime_1.jsxs)("div", { style: {
                    ...shared_1.LOGIN_STYLE,
                    backgroundColor: "white",
                    margin: "30px auto",
                    padding: "15px",
                }, children: ["Already have an account? ", (0, jsx_runtime_1.jsx)(A_1.default, { href: "/auth/sign-in", children: "Sign In" }), anonymousSignup && ((0, jsx_runtime_1.jsxs)("div", { style: { marginTop: "15px" }, children: ["Don't want to provide any information?", (0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsxs)(A_1.default, { href: "/auth/try", children: ["Try ", siteName, " without creating an account."] })] }))] }))] }));
}
function EmailOrSSO(props) {
    const { email, setEmail, signUp, strategies = [], hideSSO = false } = props;
    const { emailSignup } = (0, use_customize_1.default)();
    function renderSSO() {
        if (strategies.length == 0)
            return;
        const emailStyle = email
            ? { textAlign: "right", marginBottom: "20px" }
            : {};
        const style = {
            display: hideSSO ? "none" : "block",
            ...emailStyle,
        };
        return ((0, jsx_runtime_1.jsx)("div", { style: { textAlign: "center", margin: "20px 0" }, children: (0, jsx_runtime_1.jsx)(sso_1.default, { size: email ? 24 : undefined, style: style }) }));
    }
    return ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("p", { children: hideSSO
                    ? "Sign up using your single sign-on provider"
                    : strategies.length > 0 && emailSignup
                        ? "Sign up using either your email address or a single sign-on provider."
                        : emailSignup
                            ? "Enter the email address you will use to sign in."
                            : "Sign up using a single sign-on provider." }), renderSSO(), emailSignup && ((0, jsx_runtime_1.jsx)("p", { children: (0, jsx_runtime_1.jsx)(antd_1.Input, { style: { fontSize: "12pt" }, placeholder: "Email address", autoComplete: "username", value: email, onChange: (e) => setEmail(e.target.value), onPressEnter: signUp }) }))] }));
}
function TermsCheckbox({ checked, onChange, style, }) {
    return ((0, jsx_runtime_1.jsxs)(antd_1.Checkbox, { checked: checked, style: style, onChange: (e) => onChange?.(e.target.checked), children: ["I agree to the", " ", (0, jsx_runtime_1.jsx)(A_1.default, { external: true, href: "/policies/terms", children: "Terms of Service" }), "."] }));
}
exports.TermsCheckbox = TermsCheckbox;
//# sourceMappingURL=sign-up.js.map