"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const contexts_1 = require("../../../contexts/index.js");
const events_1 = require("../../../events/index.js");
const hooks_1 = require("../../../hooks/index.js");
const react_1 = __importStar(require("react"));
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 Currency_1 = __importDefault(require("../../generic/Currency"));
const Headline_1 = __importDefault(require("../../generic/Headline"));
const SimpleModal_1 = __importDefault(require("../../generic/modal/SimpleModal"));
const TaxInclusionNotice_1 = require("../../generic/TaxInclusionNotice/TaxInclusionNotice");
const Text_1 = __importStar(require("../../generic/Text"));
const ImageGallerySlider_1 = __importDefault(require("./ImageGallerySlider"));
const LargeRateCard_1 = __importDefault(require("./LargeRateCard"));
const LargeRoomCard_1 = __importDefault(require("./LargeRoomCard"));
const useSignedInMember_1 = require("../../../hooks/useSignedInMember");
const RoomUpsellFeature_1 = __importDefault(require("../../../providers/feature/RoomUpsellFeature"));
const Color_1 = require("../../../util/Color");
const DataLayer_1 = __importDefault(require("../../../util/DataLayer"));
const AvailableUpgradesModal = () => {
    const { t } = (0, react_i18next_1.useTranslation)();
    const { hotel } = (0, hooks_1.useCurrentHotel)();
    const { memberNumber } = (0, useSignedInMember_1.useSignedInMember)();
    const [isOpen, setIsOpen] = (0, react_1.useState)(false);
    const [row, setRow] = (0, react_1.useState)(null);
    const basketContext = (0, react_1.useContext)(contexts_1.BasketContext);
    const { on } = (0, hooks_1.useEvent)();
    const room = row === null || row === void 0 ? void 0 : row.getRoom();
    const selectedRate = row === null || row === void 0 ? void 0 : row.getRate();
    const [roomUpgrades, setRoomUpgrades] = (0, react_1.useState)([]);
    const [rateUpgrades, setRateUpgrades] = (0, react_1.useState)([]);
    // Determines whether a rate is eligible to be displayed in the Upsell modal.
    // A rate is eligible if:
    // - It has valid room data and a room code
    // - The room is not marked as `doNotUpsell`
    // - If `upsellRoomCodes` is empty then all rooms are allowed
    // - If `upsellRoomCodes` is defined then only rooms with matching codes are allowed
    const isEligibleUpsellRate = (rate) => {
        var _a, _b;
        const roomData = (_a = rate.getRoom) === null || _a === void 0 ? void 0 : _a.call(rate); // Room data of the rate being evaluated (used to check if this room can be upsold)
        const roomCode = roomData === null || roomData === void 0 ? void 0 : roomData.code;
        if (!room || !roomData || !roomCode || !!(roomData === null || roomData === void 0 ? void 0 : roomData.doNotUpsell))
            return false;
        // Important: defines which room codes are allowed for upsell based on the current basket room
        const upsellCodes = (_b = room.upsellRoomCodes) !== null && _b !== void 0 ? _b : [];
        return upsellCodes.length === 0 || upsellCodes.includes(roomCode);
    };
    (0, react_1.useEffect)(() => {
        let cancelled = false;
        on(events_1.AddToCartEvent, (event) => __awaiter(void 0, void 0, void 0, function* () {
            if (cancelled)
                return;
            setRow(event.basketRow);
            return true;
        }));
        return () => {
            cancelled = true;
        };
    }, []);
    (0, react_1.useEffect)(() => {
        let cancelled = false;
        if (row && selectedRate) {
            BookingAPI_1.default.Availability.fetchAvailabilityData(row, hotel === null || hotel === void 0 ? void 0 : hotel.hotelID, memberNumber, true).then((availableRooms) => __awaiter(void 0, void 0, void 0, function* () {
                var _a;
                if (cancelled)
                    return;
                const upsellEligibleRates = (_a = availableRooms === null || availableRooms === void 0 ? void 0 : availableRooms.flatMap((room) => { var _a, _b, _c; return (_c = (_b = (_a = room.getRates) === null || _a === void 0 ? void 0 : _a.call(room)) === null || _b === void 0 ? void 0 : _b.filter(isEligibleUpsellRate)) !== null && _c !== void 0 ? _c : []; })) !== null && _a !== void 0 ? _a : [];
                const roomUpsellsEnabled = (hotel === null || hotel === void 0 ? void 0 : hotel.enableRoomUpsells) || RoomUpsellFeature_1.default.isActive();
                const rateUpsellsEnabled = hotel === null || hotel === void 0 ? void 0 : hotel.enableRateUpsells;
                // Check for minimum stay opportunities
                const hasMinStayOpportunities = BookingAPI_1.default.Availability.hasMinStayUpsellOpportunities(row, hotel === null || hotel === void 0 ? void 0 : hotel.hotelID, memberNumber);
                const minStayUpsells = [];
                if (rateUpsellsEnabled && hasMinStayOpportunities) {
                    // Fetch extended availability for minimum stay upsells
                    const extendedRooms = yield BookingAPI_1.default.Availability.fetchMinimumStayExtensions(row, hotel === null || hotel === void 0 ? void 0 : hotel.hotelID, memberNumber);
                    if (extendedRooms && !cancelled) {
                        extendedRooms.forEach((room) => {
                            room.getRates().forEach((rate) => {
                                // We want to find rates where the user can extend the stay in their current room, for a lower price per night.
                                const wasAvailableForOriginalDates = upsellEligibleRates.find((r) => r.code === rate.code);
                                const isCheaperPerNight = rate.getAveragePrice() < selectedRate.getAveragePrice();
                                const requiresLongerStay = rate.minNightStayOverride && rate.minNightStayOverride > row.getNumberOfDays();
                                const isSameRoom = rate.getRoom().code === selectedRate.getRoom().code;
                                if (!wasAvailableForOriginalDates && isSameRoom && rate.isUpsellRate && isCheaperPerNight && requiresLongerStay) {
                                    minStayUpsells.push(rate);
                                }
                            });
                        });
                    }
                }
                if (cancelled)
                    return;
                // Find rate upgrades (same room, different rate)
                const rateUpgradeRoomRates = rateUpsellsEnabled
                    ? upsellEligibleRates
                        .filter((rate) => {
                        const isSameRoom = rate.getRoom().code === selectedRate.getRoom().code;
                        const isDifferentRate = rate.code !== selectedRate.code;
                        const isUpsellRate = rate.isUpsellRate === true;
                        const isMoreExpensive = rate.getAveragePrice() > selectedRate.getAveragePrice();
                        // Don't show rates with lower minimum stay requirements as upsells, because we might show a minimum
                        // stay upsell when the user has already chosen a rate with a longer minimum stay requirement.
                        // But, still show upsell rates that don't have a minimum night stay requirement.
                        const hasLowerMinStay = rate.minNightStayOverride && rate.minNightStayOverride < row.getNumberOfDays();
                        return isSameRoom && isDifferentRate && isUpsellRate && isMoreExpensive && !hasLowerMinStay;
                    })
                        .sort((a, b) => a.getAveragePrice() - b.getAveragePrice())
                        .slice(0, 3)
                    : [];
                // Combine regular rate upgrades with minimum stay upsells
                const allRateUpgrades = [...rateUpgradeRoomRates, ...minStayUpsells]
                    .sort((a, b) => {
                    // Prioritize minimum stay deals (rates with minNightStayOverride)
                    const aIsMinStay = !!(a.minNightStayOverride && a.minNightStayOverride > row.getNumberOfDays());
                    const bIsMinStay = !!(b.minNightStayOverride && b.minNightStayOverride > row.getNumberOfDays());
                    if (aIsMinStay && !bIsMinStay)
                        return -1;
                    if (!aIsMinStay && bIsMinStay)
                        return 1;
                    return a.getAveragePrice() - b.getAveragePrice();
                })
                    .slice(0, 3);
                // Find room upgrades (different room, same rate, higher price)
                const roomUpgradeRoomRates = roomUpsellsEnabled
                    ? upsellEligibleRates
                        .filter((rate) => {
                        const isDifferentRoom = rate.getRoom().code !== selectedRate.getRoom().code;
                        const isSameRate = rate.name === selectedRate.name;
                        const isMoreExpensive = rate.getAveragePrice() > selectedRate.getAveragePrice();
                        return isDifferentRoom && isSameRate && isMoreExpensive;
                    })
                        .sort((a, b) => a.getAveragePrice() - b.getAveragePrice())
                        .slice(0, 3)
                    : [];
                setRoomUpgrades(roomUpgradeRoomRates);
                setRateUpgrades(allRateUpgrades);
                const hasUpgrades = roomUpgradeRoomRates.length > 0 || allRateUpgrades.length > 0;
                if (!hasUpgrades && selectedRate) {
                    // Proceed as if user clicked the nav.
                    confirmRateOnClick();
                }
                else {
                    setIsOpen(hasUpgrades);
                }
            }));
        }
        return () => {
            cancelled = true;
        };
    }, [row, memberNumber]);
    const closeModal = () => {
        setIsOpen(false);
        setRow(null);
    };
    const cancelUpsell = () => {
        if (row) {
            DataLayer_1.default.instance.sendUpsellCancelled({ from: row.getStartDate(), to: row.getEndDate() }, row.getRate());
        }
        closeModal();
    };
    const confirmRateOnClick = (rate) => {
        if (row) {
            if (rate) {
                DataLayer_1.default.instance.sendUpsellConfirmed({ from: row.getStartDate(), to: row.getEndDate() }, row.getRate(), rate);
                const isUpsellActive = (hotel === null || hotel === void 0 ? void 0 : hotel.enableRoomUpsells) || RoomUpsellFeature_1.default.isActive() || (hotel === null || hotel === void 0 ? void 0 : hotel.enableRateUpsells);
                // Check if this is a minimum stay upsell that requires extending the checkout
                if (rate.minNightStayOverride && rate.minNightStayOverride > row.getNumberOfDays()) {
                    const newStartDate = row.getStartDate();
                    const newEndDate = newStartDate.add(rate.minNightStayOverride, 'days');
                    row.setStartDate(newStartDate);
                    row.setEndDate(newEndDate);
                }
                row.setRate(rate, isUpsellActive);
                basketContext.updateBasketRow(row);
                closeModal();
            }
            else {
                cancelUpsell();
            }
        }
    };
    const roomUpsellsEnabled = (hotel === null || hotel === void 0 ? void 0 : hotel.enableRoomUpsells) || RoomUpsellFeature_1.default.isActive();
    const rateUpsellsEnabled = hotel === null || hotel === void 0 ? void 0 : hotel.enableRateUpsells;
    const allowedUpgrades = [...rateUpgrades, ...roomUpgrades].slice(0, 3);
    const upsellsEnabled = (roomUpsellsEnabled || rateUpsellsEnabled) && allowedUpgrades.length > 0;
    return upsellsEnabled && row ? (react_1.default.createElement(SimpleModal_1.default, { open: isOpen, onClose: cancelUpsell, title: t(Translation_1.Translation.Step.Room.AvailableUpgrades) },
        react_1.default.createElement("div", { className: "upgrades-room-modal" },
            react_1.default.createElement("div", { className: "current-room-block container" },
                react_1.default.createElement("div", { className: "u-flex u-flex-flex-start row" },
                    react_1.default.createElement("div", { className: "image-wrapper col-md-3 col-12" },
                        react_1.default.createElement(ImageGallerySlider_1.default, { images: (room === null || room === void 0 ? void 0 : room.getImages()) || [] })),
                    react_1.default.createElement("div", { className: "u-flex info-block col-md-7 col-sm-9" },
                        react_1.default.createElement("div", null,
                            react_1.default.createElement(Text_1.default, { color: Color_1.Color.DarkGrey, bold: true }, t(Translation_1.Translation.Step.Room.CurrentSelectedRoom)),
                            react_1.default.createElement(Headline_1.default, { bold: true }, room === null || room === void 0 ? void 0 : room.name),
                            react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small, color: Color_1.Color.DarkGrey }, selectedRate === null || selectedRate === void 0 ? void 0 : selectedRate.name)),
                        react_1.default.createElement("div", null,
                            react_1.default.createElement("div", { className: "room-details--content-price flex-row" },
                                react_1.default.createElement(Headline_1.default, { bold: true },
                                    react_1.default.createElement(Currency_1.default, { hideDecimals: true }, selectedRate === null || selectedRate === void 0 ? void 0 : selectedRate.getAveragePrice())),
                                react_1.default.createElement(Text_1.default, { color: Color_1.Color.DarkGrey, inline: true },
                                    "/",
                                    t(Translation_1.Translation.Misc.Night))),
                            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.Grey, className: "u-nowrap" },
                                    react_1.default.createElement(TaxInclusionNotice_1.TaxInclusionNotice, { rate: selectedRate }))))),
                    react_1.default.createElement("div", { className: "u-flex u-flex-align-center col-md-2 col-sm-3" },
                        react_1.default.createElement(BEButton_1.default, { wide: true, filled: true, primary: true, onClick: () => confirmRateOnClick() }, t(Translation_1.Translation.Step.Room.Confirm))))),
            react_1.default.createElement("div", { className: "container", style: { backgroundColor: Color_1.Color.Snow } },
                react_1.default.createElement("div", { className: "u-pad-top u-marg-bottom" },
                    react_1.default.createElement("div", { className: "u-marg-bottom--heavy" },
                        react_1.default.createElement(Headline_1.default, { bold: true }, t(Translation_1.Translation.Step.Room.CheckOutOtherOptions))),
                    react_1.default.createElement("div", { className: "row no-gutters" }, allowedUpgrades.map((rate) => {
                        const isRateUpgrade = rate.getRoom().code === (selectedRate === null || selectedRate === void 0 ? void 0 : selectedRate.getRoom().code);
                        const key = `room-${rate.getRoom().code}-${rate.code}`;
                        return (react_1.default.createElement("div", { className: "col-md-6 col-xl-4 u-marg-bottom u-pad-left--light u-pad-right--light", key: key }, selectedRate &&
                            (isRateUpgrade ? (react_1.default.createElement(LargeRateCard_1.default, { selectedRate: selectedRate, rate: rate, onSelectRate: () => confirmRateOnClick(rate), startDate: row.getStartDate() })) : (react_1.default.createElement(LargeRoomCard_1.default, { selectedRate: selectedRate, rate: rate, onSelectRate: () => confirmRateOnClick(rate) })))));
                    }))))))) : null;
};
exports.default = AvailableUpgradesModal;
//# sourceMappingURL=AvailableUpgradesModal.js.map