"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.filterWithCustomTargeting = void 0;
var react_1 = __importDefault(require("react"));
var sdk_1 = require("@builder.io/sdk");
var react_2 = require("react");
var builder_blocks_component_1 = require("../components/builder-blocks.component");
function PersonalizationContainer(props) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j;
    var _k = (0, react_2.useState)(false), isClient = _k[0], setIsClient = _k[1];
    (0, react_2.useEffect)(function () {
        setIsClient(true);
    }, []);
    var filteredVariants = (props.variants || []).filter(function (variant) {
        return filterWithCustomTargeting(sdk_1.builder.getUserAttributes(), variant.query, variant.startDate, variant.endDate);
    });
    return (react_1.default.createElement("div", __assign({ style: __assign({ opacity: isClient ? 1 : 0, transition: 'opacity 0.2s ease-in-out' }, props.attributes) }, props.attributes, { className: "builder-personalization-container ".concat(props.attributes.className, " ").concat(isClient ? '' : 'builder-personalization-container-loading') }), sdk_1.Builder.isEditing &&
        typeof props.previewingIndex === 'number' &&
        props.previewingIndex < (((_a = props.variants) === null || _a === void 0 ? void 0 : _a.length) || 0) ? (react_1.default.createElement(builder_blocks_component_1.BuilderBlocks, { blocks: (_c = (_b = props.variants) === null || _b === void 0 ? void 0 : _b[props.previewingIndex]) === null || _c === void 0 ? void 0 : _c.blocks, parentElementId: (_d = props.builderBlock) === null || _d === void 0 ? void 0 : _d.id, dataPath: "component.options.variants.".concat(props.previewingIndex, ".blocks"), child: true })) : // If editing the default or we're on the server and there are no matching variants show the default
        (sdk_1.Builder.isEditing && typeof props.previewingIndex !== 'number') ||
            !isClient ||
            !filteredVariants.length ? (react_1.default.createElement(builder_blocks_component_1.BuilderBlocks, { blocks: (_e = props.builderBlock) === null || _e === void 0 ? void 0 : _e.children, parentElementId: (_f = props.builderBlock) === null || _f === void 0 ? void 0 : _f.id, dataPath: "this.children", child: true })) : (
        // Show the variant matching the current user attributes
        react_1.default.createElement(builder_blocks_component_1.BuilderBlocks, { blocks: (_g = filteredVariants[0]) === null || _g === void 0 ? void 0 : _g.blocks, parentElementId: (_h = props.builderBlock) === null || _h === void 0 ? void 0 : _h.id, dataPath: "component.options.variants.".concat((_j = props.variants) === null || _j === void 0 ? void 0 : _j.indexOf(filteredVariants[0]), ".blocks"), child: true }))));
}
exports.default = PersonalizationContainer;
function filterWithCustomTargeting(userAttributes, query, startDate, endDate) {
    var item = {
        query: query,
        startDate: startDate,
        endDate: endDate,
    };
    var now = (userAttributes.date && new Date(userAttributes.date)) || new Date();
    if (item.startDate && new Date(item.startDate) > now) {
        return false;
    }
    else if (item.endDate && new Date(item.endDate) < now) {
        return false;
    }
    if (!item.query || !item.query.length) {
        return true;
    }
    return item.query.every(function (filter) {
        if (filter &&
            filter.property === 'urlPath' &&
            filter.value &&
            typeof filter.value === 'string' &&
            filter.value !== '/' &&
            filter.value.endsWith('/')) {
            filter.value = filter.value.slice(0, -1);
        }
        return objectMatchesQuery(userAttributes, filter);
    });
    function isNumber(val) {
        return typeof val === 'number';
    }
    function isString(val) {
        return typeof val === 'string';
    }
    function objectMatchesQuery(userattr, query) {
        var result = (function () {
            var property = query.property;
            var operator = query.operator;
            var testValue = query.value;
            // Check is query property is present in userAttributes. Proceed only if it is present.
            if (!(property && operator)) {
                return true;
            }
            if (Array.isArray(testValue)) {
                if (operator === 'isNot') {
                    return testValue.every(function (val) {
                        return objectMatchesQuery(userattr, { property: property, operator: operator, value: val });
                    });
                }
                return !!testValue.find(function (val) {
                    return objectMatchesQuery(userattr, { property: property, operator: operator, value: val });
                });
            }
            var value = userattr[property];
            if (Array.isArray(value)) {
                return value.includes(testValue);
            }
            switch (operator) {
                case 'is':
                    return value === testValue;
                case 'isNot':
                    return value !== testValue;
                case 'contains':
                    return (isString(value) || Array.isArray(value)) && value.includes(testValue);
                case 'startsWith':
                    return isString(value) && value.startsWith(testValue);
                case 'endsWith':
                    return isString(value) && value.endsWith(testValue);
                case 'greaterThan':
                    return isNumber(value) && isNumber(testValue) && value > testValue;
                case 'lessThan':
                    return isNumber(value) && isNumber(testValue) && value < testValue;
                case 'greaterThanOrEqualTo':
                    return isNumber(value) && isNumber(testValue) && value >= testValue;
                case 'lessThanOrEqualTo':
                    return isNumber(value) && isNumber(testValue) && value <= testValue;
            }
            return false;
        })();
        return result;
    }
}
exports.filterWithCustomTargeting = filterWithCustomTargeting;
sdk_1.Builder.registerComponent(PersonalizationContainer, {
    name: 'PersonalizationContainer',
    noWrap: true,
    image: 'https://cdn.builder.io/api/v1/image/assets%2FYJIGb4i01jvw0SRdL5Bt%2F37229ed30d8c41dfb10b8cca1992053a',
    canHaveChildren: true,
    inputs: [
        {
            name: 'variants',
            defaultValue: [],
            behavior: 'personalizationVariantList',
            type: 'list',
            subFields: [
                {
                    name: 'name',
                    type: 'text',
                },
                {
                    name: 'variants',
                    type: 'BuilderQuery',
                    defaultValue: [],
                },
                {
                    name: 'startDate',
                    type: 'date',
                },
                {
                    name: 'endDate',
                    type: 'date',
                },
                {
                    name: 'blocks',
                    type: 'UiBlocks',
                    hideFromUI: true,
                    defaultValue: [],
                },
            ],
        },
    ],
});
//# sourceMappingURL=PersonalizationContainer.js.map