"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 __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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PersonalizationContainer = void 0;
var react_1 = __importStar(require("react"));
var sdk_1 = require("@builder6/sdk");
var react_2 = require("react");
var builder_blocks_component_1 = require("../components/builder-blocks.component");
var filter_with_custom_targeting_1 = require("../functions/filter-with-custom-targeting");
var builder_store_1 = require("../store/builder-store");
function PersonalizationContainer(props) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
    var isBeingHydrated = Boolean(sdk_1.Builder.isBrowser && ((_a = window.__hydrated) === null || _a === void 0 ? void 0 : _a[(_b = props.builderBlock) === null || _b === void 0 ? void 0 : _b.id]));
    var rootRef = (0, react_1.useRef)(null);
    var _x = (0, react_2.useState)(isBeingHydrated), isClient = _x[0], setIsClient = _x[1];
    var _y = (0, react_2.useState)(0), update = _y[0], setUpdate = _y[1];
    var builderStore = (0, react_1.useContext)(builder_store_1.BuilderStoreContext);
    (0, react_2.useEffect)(function () {
        var _a;
        setIsClient(true);
        var subscriber = sdk_1.builder.userAttributesChanged.subscribe(function () {
            setUpdate(update + 1);
        });
        var unsubs = [function () { return subscriber.unsubscribe(); }];
        if (!(sdk_1.Builder.isEditing || sdk_1.Builder.isPreviewing)) {
            var variant_1 = filteredVariants[0];
            // fire a custom event to update the personalization container
            (_a = rootRef.current) === null || _a === void 0 ? void 0 : _a.dispatchEvent(new CustomEvent('builder.variantLoaded', {
                detail: {
                    variant: variant_1 || 'default',
                    content: builderStore.content,
                },
                bubbles: true,
            }));
            // add an intersection observer to fire a builder.variantDisplayed event when the container is in the viewport
            var observer_1 = new IntersectionObserver(function (entries) {
                entries.forEach(function (entry) {
                    var _a;
                    if (entry.isIntersecting) {
                        (_a = rootRef.current) === null || _a === void 0 ? void 0 : _a.dispatchEvent(new CustomEvent('builder.variantDisplayed', {
                            detail: {
                                variant: variant_1 || 'default',
                                content: builderStore.content,
                            },
                            bubbles: true,
                        }));
                    }
                });
            });
            observer_1.observe(rootRef.current);
            unsubs.push(function () { return observer_1.disconnect(); });
        }
        return function () {
            unsubs.forEach(function (fn) { return fn(); });
        };
    }, []);
    if (sdk_1.Builder.isServer) {
        return (react_1.default.createElement(react_1.default.Fragment, null,
            react_1.default.createElement("div", __assign({}, props.attributes, { 
                // same as the client side styles for hydration matching
                style: __assign({ opacity: 1, transition: 'opacity 0.2s ease-in-out' }, (_c = props.attributes) === null || _c === void 0 ? void 0 : _c.style), className: "builder-personalization-container ".concat(props.attributes.className) }), (_d = props.variants) === null || _d === void 0 ? void 0 :
                _d.map(function (variant, index) {
                    var _a, _b;
                    return (react_1.default.createElement("template", { key: index, "data-variant-id": ((_a = props.builderBlock) === null || _a === void 0 ? void 0 : _a.id) + index },
                        react_1.default.createElement(builder_blocks_component_1.BuilderBlocks, { blocks: variant.blocks, parentElementId: (_b = props.builderBlock) === null || _b === void 0 ? void 0 : _b.id, dataPath: "component.options.variants.".concat(index, ".blocks"), child: true })));
                }),
                react_1.default.createElement("script", { id: "variants-script-".concat((_e = props.builderBlock) === null || _e === void 0 ? void 0 : _e.id), dangerouslySetInnerHTML: {
                        __html: getPersonalizationScript(props.variants, ((_f = props.builderBlock) === null || _f === void 0 ? void 0 : _f.id) || 'none', (_g = props.builderState.state) === null || _g === void 0 ? void 0 : _g.locale),
                    } }),
                react_1.default.createElement(builder_blocks_component_1.BuilderBlocks, { blocks: (_h = props.builderBlock) === null || _h === void 0 ? void 0 : _h.children, parentElementId: (_j = props.builderBlock) === null || _j === void 0 ? void 0 : _j.id, dataPath: "this.children", child: true })),
            react_1.default.createElement("script", { dangerouslySetInnerHTML: {
                    __html: "\n         window.__hydrated = window.__hydrated || {};\n         window.__hydrated['".concat((_k = props.builderBlock) === null || _k === void 0 ? void 0 : _k.id, "'] = true;\n        ").replace(/\s+/g, ' '),
                } })));
    }
    var filteredVariants = (props.variants || []).filter(function (variant) {
        var _a;
        return (0, filter_with_custom_targeting_1.filterWithCustomTargeting)(__assign(__assign({}, (((_a = props.builderState.state) === null || _a === void 0 ? void 0 : _a.locale) ? { locale: props.builderState.state.locale } : {})), sdk_1.builder.getUserAttributes()), variant.query, variant.startDate, variant.endDate);
    });
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement("div", __assign({ ref: rootRef }, props.attributes, { style: __assign({ opacity: isClient ? 1 : 0, transition: 'opacity 0.2s ease-in-out' }, (_l = props.attributes) === null || _l === void 0 ? void 0 : _l.style), className: "builder-personalization-container ".concat(props.attributes.className, " ").concat(isClient ? '' : 'builder-personalization-container-loading') }), sdk_1.Builder.isEditing &&
            typeof props.previewingIndex === 'number' &&
            props.previewingIndex < (((_m = props.variants) === null || _m === void 0 ? void 0 : _m.length) || 0) ? (react_1.default.createElement(builder_blocks_component_1.BuilderBlocks, { blocks: (_p = (_o = props.variants) === null || _o === void 0 ? void 0 : _o[props.previewingIndex]) === null || _p === void 0 ? void 0 : _p.blocks, parentElementId: (_q = props.builderBlock) === null || _q === void 0 ? void 0 : _q.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: (_r = props.builderBlock) === null || _r === void 0 ? void 0 : _r.children, parentElementId: (_s = props.builderBlock) === null || _s === void 0 ? void 0 : _s.id, dataPath: "this.children", child: true })) : (
            // Show the variant matching the current user attributes
            react_1.default.createElement(builder_blocks_component_1.BuilderBlocks, { blocks: (_t = filteredVariants[0]) === null || _t === void 0 ? void 0 : _t.blocks, parentElementId: (_u = props.builderBlock) === null || _u === void 0 ? void 0 : _u.id, dataPath: "component.options.variants.".concat((_v = props.variants) === null || _v === void 0 ? void 0 : _v.indexOf(filteredVariants[0]), ".blocks"), child: true }))),
        react_1.default.createElement("script", { dangerouslySetInnerHTML: {
                __html: "\n         window.__hydrated = window.__hydrated || {};\n         window.__hydrated['".concat((_w = props.builderBlock) === null || _w === void 0 ? void 0 : _w.id, "'] = true;\n        ").replace(/\s+/g, ' '),
            } })));
}
exports.PersonalizationContainer = PersonalizationContainer;
sdk_1.Builder.registerComponent(PersonalizationContainer, {
    name: 'PersonalizationContainer',
    noWrap: true,
    friendlyName: 'Dynamic Container',
    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',
                    localized: false,
                },
                {
                    name: 'query',
                    friendlyName: 'Targeting rules',
                    type: 'BuilderQuery',
                    defaultValue: [],
                    localized: false,
                },
                {
                    name: 'startDate',
                    type: 'date',
                    localized: false,
                },
                {
                    name: 'endDate',
                    type: 'date',
                    localized: false,
                },
                {
                    name: 'blocks',
                    type: 'UiBlocks',
                    hideFromUI: true,
                    defaultValue: [],
                },
            ],
        },
    ],
});
function getPersonalizationScript(variants, blockId, locale) {
    return "\n      (function() {\n        function getCookie(name) {\n          var nameEQ = name + \"=\";\n          var ca = document.cookie.split(';');\n          for(var i=0;i < ca.length;i++) {\n              var c = ca[i];\n              while (c.charAt(0)==' ') c = c.substring(1,c.length);\n              if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);\n          }\n          return null;\n        }\n        function removeVariants() {\n          variants.forEach(function (template, index) {\n            document.querySelector('template[data-variant-id=\"' + \"".concat(blockId, "\" + index + '\"]').remove();\n          });\n          document.getElementById('variants-script-").concat(blockId, "').remove();\n        }\n\n        var attributes = JSON.parse(getCookie(\"").concat(sdk_1.Builder.attributesCookieName, "\") || \"{}\");\n        ").concat(locale ? "attributes.locale = \"".concat(locale, "\";") : '', "\n        var variants = ").concat(JSON.stringify(variants === null || variants === void 0 ? void 0 : variants.map(function (v) { return ({ query: v.query, startDate: v.startDate, endDate: v.endDate }); })), ";\n        var winningVariantIndex = variants.findIndex(function(variant) {\n          return filterWithCustomTargeting(\n            attributes,\n            variant.query,\n            variant.startDate,\n            variant.endDate\n          );\n        });\n        var isDebug = location.href.includes('builder.debug=true');\n        if (isDebug) {\n          console.debug('PersonalizationContainer', {\n            attributes: attributes,\n            variants: variants,\n            winningVariantIndex: winningVariantIndex,\n            });\n        }\n        if (winningVariantIndex !== -1) {\n          var winningVariant = document.querySelector('template[data-variant-id=\"' + \"").concat(blockId, "\" + winningVariantIndex + '\"]');\n          if (winningVariant) {\n            var parentNode = winningVariant.parentNode;\n            var newParent = parentNode.cloneNode(false);\n            newParent.appendChild(winningVariant.content.firstChild);\n            parentNode.parentNode.replaceChild(newParent, parentNode);\n            if (isDebug) {\n              console.debug('PersonalizationContainer', 'Winning variant Replaced:', winningVariant);\n            }\n          }\n        } else if (variants.length > 0) {\n          removeVariants();\n        }\n        ").concat(filter_with_custom_targeting_1.filterWithCustomTargetingScript, "\n      })();\n    ").replace(/\s+/g, ' ');
}
//# sourceMappingURL=PersonalizationContainer.js.map