"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderMemberPortalWidget = void 0;
exports.default = MemberPortalWidgetElement;
const contexts_1 = require("../../contexts/index.js");
const hooks_1 = require("../../hooks/index.js");
const react_1 = __importStar(require("react"));
const react_dom_1 = require("react-dom");
const react_i18next_1 = require("react-i18next");
const react_router_dom_1 = require("react-router-dom");
const BEButton_1 = __importDefault(require("../../components/generic/BEButton"));
const Icon_1 = __importStar(require("../../components/generic/Icon/Icon"));
const SmallSpinner_1 = __importDefault(require("../../components/generic/loader/SmallSpinner"));
const AuthenticatedUserModal_1 = require("../../components/generic/modal/SigninModal/AuthenticatedUserModal");
const UnauthenticatedUserModal_1 = require("../../components/generic/modal/SigninModal/UnauthenticatedUserModal");
const AccountRoutes_1 = require("../../pages/account/AccountRoutes");
const Translation_1 = require("../../translations/Translation");
const Color_1 = require("../../util/Color");
const MemberPortalWidget_1 = require("./MemberPortalWidget");
function MemberPortalWidgetElement({ engine }) {
    const engineConfig = engine.getConfig();
    const { roomstayMember } = (0, react_1.useContext)(contexts_1.RoomstayMemberContext);
    const { loading } = (0, react_1.useContext)(contexts_1.AuthenticationContext);
    const { t } = (0, react_i18next_1.useTranslation)();
    const [loginModalOpen, setLoginModalOpen] = (0, react_1.useState)(false);
    const loginAnchorEl = (0, react_1.useRef)(null);
    const { hotel } = (0, hooks_1.useCurrentHotel)();
    const location = (0, react_router_dom_1.useLocation)();
    const closeLoginClickHandler = () => {
        setLoginModalOpen(false);
    };
    const onLoginClickHandler = () => {
        setLoginModalOpen(true);
    };
    (0, react_1.useEffect)(() => {
        var _a;
        if (roomstayMember) {
            (_a = engineConfig.onSignedIn) === null || _a === void 0 ? void 0 : _a.call(engineConfig, roomstayMember);
        }
    }, [roomstayMember]);
    // Detect changes to the roomstay path
    (0, react_1.useEffect)(() => {
        var _a;
        const href = window.location.href.split('#');
        const checkoutUrl = ((_a = engineConfig.groupWidgetConfig) === null || _a === void 0 ? void 0 : _a.checkoutUrl) || (hotel === null || hotel === void 0 ? void 0 : hotel.checkoutUrl);
        // Only redirect if the hash contains an account route path
        const isAccountRoute = href.length > 1 &&
            Object.values(AccountRoutes_1.AccountRoutes).some((route) => {
                return location.pathname.startsWith(route.path);
            });
        // Ensure the user is redirected to the checkout if a member portal account link is clicked
        if (isAccountRoute && checkoutUrl && href[0] !== checkoutUrl) {
            // Add Member portal flag to URL to ensure member portal in enabled when the user lands in the checkout
            const params = new URLSearchParams(window.location.search);
            params.set(MemberPortalWidget_1.MemberPortalWidget.MEMBER_PORTAL_PARAM, true.toString());
            // Redirected to the checkout
            const url = new URL(checkoutUrl, window.location.origin);
            url.hash = location.pathname + '?' + params.toString();
            window.location.href = url.toString();
        }
    }, [location, engineConfig.groupWidgetConfig]);
    const buttonElement = (0, react_1.useMemo)(() => {
        if (engineConfig.renderInput) {
            return (react_1.default.createElement("div", { ref: loginAnchorEl, onClick: onLoginClickHandler }, engineConfig.renderInput(roomstayMember, loading)));
        }
        else {
            return (react_1.default.createElement("div", { ref: loginAnchorEl, style: { width: 'fit-content' } }, roomstayMember ? (react_1.default.createElement(BEButton_1.default, { isLoading: loading, size: "small", className: engineConfig.buttonClass, onClick: onLoginClickHandler, stopIconAnimation: true },
                roomstayMember.forename,
                " ",
                roomstayMember.surname,
                react_1.default.createElement("span", { className: "u-white u-pad-left--light", style: { marginRight: -13 } },
                    react_1.default.createElement(Icon_1.default, { icon: Icon_1.IconType.ArrowDown2, size: "1.3em", color: Color_1.Color.DarkGrey })))) : (react_1.default.createElement(BEButton_1.default, { isLoading: loading, size: "small", className: engineConfig.buttonClass, onClick: onLoginClickHandler, stopIconAnimation: true },
                t(Translation_1.Translation.Navigation.SignIn.SignIn),
                react_1.default.createElement("span", { className: "u-white u-pad-left--light", style: { marginRight: -13 } },
                    react_1.default.createElement(Icon_1.default, { icon: Icon_1.IconType.ArrowDown2, size: "1.3em", color: Color_1.Color.DarkGrey }))))));
        }
    }, [engineConfig.renderInput, roomstayMember, loading]);
    const authProps = {
        open: loginModalOpen,
        anchorEl: loginAnchorEl.current,
        menuItems: engineConfig.authMenuItem,
        placement: engineConfig.overlayPlacement || 'bottom-end',
        fallbackPlacements: engineConfig.fallbackPlacements,
        onClose: closeLoginClickHandler,
        onSignedOut: engineConfig.onSignedOut,
    };
    const unauthProps = {
        open: loginModalOpen,
        anchorEl: loginAnchorEl.current,
        placement: engineConfig.overlayPlacement || 'bottom-end',
        fallbackPlacements: engineConfig.fallbackPlacements,
        onClose: closeLoginClickHandler,
    };
    return (react_1.default.createElement(react_1.default.Fragment, null,
        buttonElement,
        react_1.default.createElement(react_1.Suspense, { fallback: SmallSpinner_1.default }, roomstayMember ? react_1.default.createElement(AuthenticatedUserModal_1.AuthenticatedUserModal, Object.assign({}, authProps)) : react_1.default.createElement(UnauthenticatedUserModal_1.UnauthenticatedUserModal, Object.assign({}, unauthProps)))));
}
const renderMemberPortalWidget = (container, engine) => {
    var _a, _b, _c, _d, _e;
    const config = engine.getConfig();
    const companyConfig = config.company;
    const company = {
        companyId: companyConfig.companyId,
        name: ((_a = config.groupWidgetConfig) === null || _a === void 0 ? void 0 : _a.name) || '',
        logo: ((_b = config.groupWidgetConfig) === null || _b === void 0 ? void 0 : _b.logo) || '',
        logoLink: ((_c = config.groupWidgetConfig) === null || _c === void 0 ? void 0 : _c.logoLink) || '',
        companyShort: companyConfig.companyShort,
        colors: companyConfig.colors,
        selectedHotel: config.hotel,
        hotels: ((_d = config.groupWidgetConfig) === null || _d === void 0 ? void 0 : _d.hotels) || (config.hotel ? [config.hotel] : []),
        privacyPolicyUrl: (_e = config.groupWidgetConfig) === null || _e === void 0 ? void 0 : _e.privacyPolicyUrl,
    };
    (0, react_dom_1.render)(react_1.default.createElement(react_1.Suspense, { fallback: react_1.default.createElement(react_1.default.Fragment, null) },
        react_1.default.createElement(react_router_dom_1.HashRouter, { future: {
                v7_startTransition: false,
                v7_relativeSplatPath: false,
            } },
            react_1.default.createElement(contexts_1.BookingEngineContextWrapper, { engine: engine },
                react_1.default.createElement(contexts_1.CompanyContextWrapper, { configCompany: company },
                    react_1.default.createElement(contexts_1.AuthenticationContextProvider, null,
                        react_1.default.createElement(MemberPortalWidgetElement, { engine: engine })))))), container);
};
exports.renderMemberPortalWidget = renderMemberPortalWidget;
//# sourceMappingURL=MemberPortalWidgetElement.js.map