"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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = InternalMemberSignInModal;
const contexts_1 = require("../../../contexts/index.js");
const events_1 = require("../../../events/index.js");
const hooks_1 = require("../../../hooks/index.js");
const Sentry = __importStar(require("@sentry/browser"));
const ErrorContext_1 = require("contexts/ErrorContext");
const react_1 = __importStar(require("react"));
const react_hook_form_1 = require("react-hook-form");
const react_i18next_1 = require("react-i18next");
const Translation_1 = require("translations/Translation");
const BookingAPI_1 = __importDefault(require("../../../api/BookingAPI"));
const BEButton_1 = __importDefault(require("../../generic/BEButton"));
const Headline_1 = __importDefault(require("../../generic/Headline"));
const Icon_1 = __importStar(require("../../generic/Icon/Icon"));
const InputGroup_1 = __importDefault(require("../../generic/InputGroup/InputGroup"));
const SimpleModal_1 = __importStar(require("../../generic/modal/SimpleModal"));
const Text_1 = __importStar(require("../../generic/Text"));
const TextBox_1 = __importDefault(require("../../generic/TextBox"));
const ForgotPasswordForm_1 = require("../../User/Forms/ForgotPasswordForm");
const SignInForm_1 = require("../../User/Forms/SignInForm");
const MemberPortalFeature_1 = __importDefault(require("../../../providers/feature/MemberPortalFeature"));
const ImageProvider_1 = __importStar(require("../../../providers/ImageProvider"));
const RoomstayThemeEngine_1 = __importDefault(require("../../../providers/RoomstayThemeEngine"));
const Color_1 = require("../../../util/Color");
const ScreenSize_1 = __importDefault(require("../../../util/ScreenSize"));
const Validation_1 = require("../../../util/Validation");
var EViewingScreen;
(function (EViewingScreen) {
    EViewingScreen["SignUp"] = "SignUp";
    EViewingScreen["SignIn"] = "SignIn";
    EViewingScreen["ForgotPassword"] = "ForgotPassword";
})(EViewingScreen || (EViewingScreen = {}));
function InternalMemberSignInModal(props) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j;
    const { t } = (0, react_i18next_1.useTranslation)();
    const context = (0, react_1.useContext)(contexts_1.BookingEngineContext);
    const ccx = (0, react_1.useContext)(contexts_1.CompanyContext);
    const { hotel } = (0, hooks_1.useCurrentHotel)();
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    const [showErrors, setShowErrors] = (0, react_1.useState)(false);
    const [viewingScreen, setViewingScreen] = (0, react_1.useState)(EViewingScreen.SignUp);
    const [captchaScriptLoaded, setCaptchaScriptLoaded] = (0, react_1.useState)(false);
    const [captchaRendered, setCaptchaRendered] = (0, react_1.useState)(false);
    const [reCaptchaSecret, setReCaptchaSecret] = (0, react_1.useState)(null);
    const [captchaError, setCaptchaError] = (0, react_1.useState)(null);
    const captchaRef = (0, react_1.useRef)(null);
    const shouldLoadCaptcha = !!((_a = hotel === null || hotel === void 0 ? void 0 : hotel.googleReCaptcha) === null || _a === void 0 ? void 0 : _a.loadForMembers) && !!((_b = hotel === null || hotel === void 0 ? void 0 : hotel.googleReCaptcha) === null || _b === void 0 ? void 0 : _b.siteKey);
    const MemberOnlyModalDefaultInputs = (0, react_1.useMemo)(() => {
        return {
            Lines: [
                {
                    Dimension: '2/2',
                    Inputs: [
                        {
                            name: 'FirstName',
                            type: 'TextBox',
                            placeholder: t(Translation_1.Translation.MemberOnlyPopup.Fields.FirstName),
                            isRequired: true,
                        },
                        {
                            name: 'LastName',
                            type: 'TextBox',
                            placeholder: t(Translation_1.Translation.MemberOnlyPopup.Fields.LastName),
                            isRequired: true,
                        },
                    ],
                },
                {
                    Dimension: '1',
                    Inputs: [
                        {
                            name: 'Email',
                            type: 'TextBox',
                            placeholder: t(Translation_1.Translation.MemberOnlyPopup.Fields.Email.Label),
                            isRequired: true,
                            validate: (input) => {
                                if (!input.match(Validation_1.EMAIL_REGEX)) {
                                    return t(Translation_1.Translation.MemberOnlyPopup.Fields.Email.Validation.Invalid);
                                }
                                return true;
                            },
                        },
                    ],
                },
            ],
        };
    }, []);
    const memberImage = (0, react_1.useMemo)(() => {
        if (props.image) {
            return props.image;
        }
        if (hotel === null || hotel === void 0 ? void 0 : hotel.heroImage) {
            return hotel === null || hotel === void 0 ? void 0 : hotel.heroImage;
        }
    }, [hotel === null || hotel === void 0 ? void 0 : hotel.heroImage]);
    const { raise } = (0, hooks_1.useEvent)();
    (0, react_1.useEffect)(() => {
        if (props.isOpen) {
            const event = new events_1.MemberOnlyModalViewEvent();
            raise(event);
        }
    }, [props.isOpen]);
    (0, react_1.useEffect)(() => {
        let cancelled = false;
        if (shouldLoadCaptcha) {
            RoomstayThemeEngine_1.default.loadScript('https://www.google.com/recaptcha/api.js', 'Google ReCaptcha').then(() => {
                const tryInitCaptcha = (retries = 0) => {
                    if (cancelled)
                        return;
                    try {
                        window.grecaptcha.ready(() => {
                            if (!cancelled) {
                                setCaptchaScriptLoaded(true);
                            }
                        });
                    }
                    catch (ex) {
                        console.log('Captcha not ready yet, retrying...', { attempt: retries + 1 });
                        if (retries < 10) {
                            setTimeout(() => tryInitCaptcha(retries + 1), 200);
                        }
                        else {
                            console.error('Failed to initialize reCAPTCHA after multiple attempts');
                        }
                    }
                };
                tryInitCaptcha();
            });
        }
        return () => {
            cancelled = true;
        };
    }, [hotel]);
    (0, react_1.useEffect)(() => {
        if (shouldLoadCaptcha && captchaScriptLoaded && (captchaRef === null || captchaRef === void 0 ? void 0 : captchaRef.current) && !captchaRendered && props.isOpen) {
            try {
                setTimeout(() => {
                    var _a;
                    const captchaCallback = (secret) => {
                        setReCaptchaSecret(secret);
                        setCaptchaError(undefined);
                    };
                    window.grecaptcha.render(captchaRef.current, {
                        sitekey: (_a = hotel.googleReCaptcha) === null || _a === void 0 ? void 0 : _a.siteKey,
                        callback: captchaCallback,
                    });
                    setCaptchaRendered(true);
                }, 5);
            }
            catch (ex) {
                console.log(ex);
                Sentry.captureException(ex);
            }
        }
    }, [props.isOpen, captchaScriptLoaded, captchaRef, captchaRef === null || captchaRef === void 0 ? void 0 : captchaRef.current, captchaRendered]);
    (0, react_1.useEffect)(() => {
        if (!props.isOpen) {
            setReCaptchaSecret(null);
            setCaptchaError(null);
            setCaptchaRendered(false);
        }
    }, [props.isOpen]);
    const getValidationClass = (name) => {
        if (errors && (formState.touchedFields[name] || showErrors)) {
            if (errors[name]) {
                return 'error';
            }
            else {
                return 'success';
            }
        }
    };
    const methods = (0, react_hook_form_1.useForm)({
        mode: 'onChange',
    });
    const { formState, register } = methods;
    const errors = methods.formState.errors;
    const onSubmit = () => __awaiter(this, void 0, void 0, function* () {
        if (shouldLoadCaptcha && (!reCaptchaSecret || reCaptchaSecret === '')) {
            setCaptchaError(t(Translation_1.Translation.MemberOnlyPopup.Errors.ReCaptcha.PleaseTick));
            return;
        }
        yield signUpMember();
    });
    const signUpMember = () => __awaiter(this, void 0, void 0, function* () {
        setIsLoading(true);
        const _a = methods.getValues(), { FirstName, LastName, Email } = _a, extra = __rest(_a, ["FirstName", "LastName", "Email"]);
        if (!FirstName || !LastName || !Email) {
            setIsLoading(false);
            ErrorContext_1.ErrorHandler.add({
                title: t(Translation_1.Translation.MemberOnlyPopup.Errors.RequiredFields.Title),
                message: t(Translation_1.Translation.MemberOnlyPopup.Errors.RequiredFields.Message),
            });
            return;
        }
        try {
            const extraFields = Object.keys(extra).map((extraFieldKey) => {
                return { name: extraFieldKey, value: extra[extraFieldKey] };
            });
            const response = yield BookingAPI_1.default.Member.addMember(FirstName, LastName, Email, extraFields, hotel === null || hotel === void 0 ? void 0 : hotel.hotelID, reCaptchaSecret);
            if (response.error) {
                setCaptchaError(t(Translation_1.Translation.MemberOnlyPopup.Errors.ReCaptcha.ValidationError));
            }
            else {
                yield ccx.signUserIn({ saveState: true, memberNumber: Email, firstName: FirstName, lastName: LastName, email: Email });
            }
        }
        catch (e) {
            ErrorContext_1.ErrorHandler.add({
                title: t(Translation_1.Translation.MemberOnlyPopup.Errors.SignupFailed.Title),
                message: t(Translation_1.Translation.MemberOnlyPopup.Errors.SignupFailed.Message),
            });
        }
        finally {
            setIsLoading(false);
        }
    });
    const modalInputs = (_c = hotel === null || hotel === void 0 ? void 0 : hotel.memberOnlySignupInputs) !== null && _c !== void 0 ? _c : MemberOnlyModalDefaultInputs;
    const loadingOnClose = () => {
        setIsLoading(false);
        setViewingScreen(EViewingScreen.SignUp);
        if (props.onClose) {
            props.onClose();
        }
    };
    const handleSignInClick = () => {
        setViewingScreen(EViewingScreen.SignIn);
    };
    const handleBackToSignUp = () => {
        setViewingScreen(EViewingScreen.SignUp);
    };
    const handleSignInSuccess = () => {
        var _a;
        (_a = props.onClose) === null || _a === void 0 ? void 0 : _a.call(props);
    };
    const handleForgotPasswordClick = () => {
        setViewingScreen(EViewingScreen.ForgotPassword);
    };
    const handleBackToSignIn = () => {
        setViewingScreen(EViewingScreen.SignIn);
    };
    const handlePasswordResetSuccess = () => {
        var _a;
        (_a = props.onClose) === null || _a === void 0 ? void 0 : _a.call(props);
    };
    const buttonOnClickHandler = () => __awaiter(this, void 0, void 0, function* () {
        yield methods.handleSubmit(onSubmit)();
        setShowErrors(true);
        return false;
    });
    const modalTitle = (_e = (_d = ccx === null || ccx === void 0 ? void 0 : ccx.memberOnlyModalPromotion) === null || _d === void 0 ? void 0 : _d.memberOnlyModalTitle) !== null && _e !== void 0 ? _e : t(Translation_1.Translation.MemberOnlyPopup.Headline, {
        companyShort: ccx === null || ccx === void 0 ? void 0 : ccx.companyShort,
    });
    const modalSubtitle = (_g = (_f = ccx === null || ccx === void 0 ? void 0 : ccx.memberOnlyModalPromotion) === null || _f === void 0 ? void 0 : _f.memberOnlyModalSubtitle) !== null && _g !== void 0 ? _g : t(Translation_1.Translation.MemberOnlyPopup.Subtitle);
    const modalButtonText = (_j = (_h = ccx === null || ccx === void 0 ? void 0 : ccx.memberOnlyModalPromotion) === null || _h === void 0 ? void 0 : _h.memberOnlyModalButtonText) !== null && _j !== void 0 ? _j : t(Translation_1.Translation.MemberOnlyPopup.SubmitButtonText);
    const modalPrimaryColor = (hotel === null || hotel === void 0 ? void 0 : hotel.memberOnlyModalUsePrimaryColor) ? Color_1.Color.Accent : Color_1.Color.Success;
    return (react_1.default.createElement(SimpleModal_1.default, { open: props.isOpen, onClose: loadingOnClose, size: SimpleModal_1.SimpleModalSize.Normal, alignCenter: true },
        react_1.default.createElement("div", { className: "row" },
            react_1.default.createElement("div", { className: "col-md-6 u-mh-none", style: {
                    background: 'url("' + (memberImage && ImageProvider_1.default.resizeImage(memberImage, ImageProvider_1.ImageSize.Original)) + '")',
                    backgroundRepeat: 'no-repeat',
                    backgroundPosition: 'center',
                    backgroundSize: 'cover',
                } }),
            react_1.default.createElement("div", { className: "col-md-6" },
                react_1.default.createElement("div", { className: "u-pad u-pad-heavy" },
                    viewingScreen === EViewingScreen.SignUp && (react_1.default.createElement(react_1.default.Fragment, null,
                        react_1.default.createElement("div", { className: "u-marg-bottom-half" },
                            react_1.default.createElement(Icon_1.default, { icon: Icon_1.IconType.Money, size: "24px", color: modalPrimaryColor, useColorAsBackground: hotel === null || hotel === void 0 ? void 0 : hotel.memberOnlyModalUsePrimaryColor, backgroundColor: Color_1.Color.SuccessTint })),
                        react_1.default.createElement("div", { className: "u-marg-bottom-half" },
                            react_1.default.createElement(Headline_1.default, { bold: true, color: modalPrimaryColor },
                                react_1.default.createElement("div", { style: { color: modalPrimaryColor }, dangerouslySetInnerHTML: {
                                        __html: modalTitle,
                                    } }))),
                        react_1.default.createElement("div", { className: "u-marg-bottom" },
                            react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small, color: Color_1.Color.DarkGrey },
                                react_1.default.createElement("span", { dangerouslySetInnerHTML: { __html: modalSubtitle } }))),
                        react_1.default.createElement(react_hook_form_1.FormProvider, Object.assign({}, methods),
                            react_1.default.createElement("div", null, modalInputs.Lines.map((inputLine, lineIndex) => {
                                return (react_1.default.createElement("div", { className: "u-marg-bottom-xxx", key: lineIndex },
                                    react_1.default.createElement(InputGroup_1.default, { dimensions: inputLine.Dimension }, inputLine.Inputs.map((input, inputIndex) => {
                                        switch (input.type) {
                                            case 'TextBox':
                                                return (react_1.default.createElement(TextBox_1.default, Object.assign({ key: inputIndex, wide: true, placeholder: input.placeholder, required: input.isRequired, validationStatus: getValidationClass(input.name) }, register(input.name, {
                                                    required: input.isRequired,
                                                    validate: input.validate,
                                                }))));
                                        }
                                    }))));
                            })),
                            react_1.default.createElement("div", { className: "u-marg-top--light", style: { marginBottom: '45px' } },
                                captchaScriptLoaded && (react_1.default.createElement(react_1.default.Fragment, null,
                                    captchaError && (react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Label, color: Color_1.Color.Alert }, captchaError)),
                                    react_1.default.createElement("div", { ref: captchaRef, className: "u-marg-bottom" }))),
                                react_1.default.createElement(BEButton_1.default, { size: "normal", filled: true, primary: hotel === null || hotel === void 0 ? void 0 : hotel.memberOnlyModalUsePrimaryColor, success: !(hotel === null || hotel === void 0 ? void 0 : hotel.memberOnlyModalUsePrimaryColor), isLoading: isLoading, stopIconAnimation: true, icon: context.screenSize > ScreenSize_1.default.Mobile ? Icon_1.IconType.ArrowRight : undefined, onClick: buttonOnClickHandler }, modalButtonText))),
                        react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Label, color: Color_1.Color.DarkGrey },
                            react_1.default.createElement("span", { dangerouslySetInnerHTML: { __html: t(Translation_1.Translation.MemberOnlyPopup.AgreeToReceiveDeals, { companyShort: ccx === null || ccx === void 0 ? void 0 : ccx.companyShort }) } })),
                        ' ',
                        react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Label, color: Color_1.Color.DarkGrey },
                            react_1.default.createElement("span", { dangerouslySetInnerHTML: { __html: t(Translation_1.Translation.MemberOnlyPopup.UnsubscribeAnytime) } })),
                        MemberPortalFeature_1.default.isActive() && (react_1.default.createElement("div", { className: "u-marg-top--light" },
                            react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Label, color: Color_1.Color.DarkGrey }, t(Translation_1.Translation.Step.Confirmation.AlreadyHaveAccount)),
                            ' ',
                            react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Label, color: Color_1.Color.DarkGrey },
                                react_1.default.createElement(BEButton_1.default, { isText: true, size: "tiny", textColor: modalPrimaryColor, onClick: handleSignInClick }, t(Translation_1.Translation.Navigation.SignIn.SignIn))))))),
                    viewingScreen === EViewingScreen.SignIn && (react_1.default.createElement(react_1.default.Fragment, null,
                        react_1.default.createElement("div", { className: "u-marg-bottom" },
                            react_1.default.createElement(BEButton_1.default, { isText: true, size: "small", icon: Icon_1.IconType.ArrowLeft, iconPosition: "left", onClick: handleBackToSignUp }, "Back to sign up")),
                        react_1.default.createElement(SignInForm_1.SignInForm, { onSignedIn: handleSignInSuccess, onForgotPassword: handleForgotPasswordClick }))),
                    viewingScreen === EViewingScreen.ForgotPassword && (react_1.default.createElement(react_1.default.Fragment, null,
                        react_1.default.createElement("div", { className: "u-marg-bottom" },
                            react_1.default.createElement(BEButton_1.default, { isText: true, size: "small", icon: Icon_1.IconType.ArrowLeft, iconPosition: "left", onClick: handleBackToSignIn }, "Back to sign in")),
                        react_1.default.createElement(ForgotPasswordForm_1.ForgotPasswordForm, { onPasswordReset: handlePasswordResetSuccess, onCancelled: handleBackToSignIn, onDone: handlePasswordResetSuccess }))))))));
}
//# sourceMappingURL=InternalMemberSignInModal.js.map