"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 __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderFeedbackWidgetPreview = exports.renderSurveysPreview = exports.SurveyManager = exports.getNextSurveyStep = void 0;
exports.generateSurveys = generateSurveys;
exports.useHideSurveyOnURLChange = useHideSurveyOnURLChange;
exports.usePopupVisibility = usePopupVisibility;
exports.SurveyPopup = SurveyPopup;
exports.Questions = Questions;
exports.FeedbackWidget = FeedbackWidget;
var preact_1 = require("preact");
var jsx_runtime_1 = require("preact/jsx-runtime");
var preact_2 = require("preact");
var hooks_1 = require("preact/hooks");
var posthog_surveys_types_1 = require("../posthog-surveys-types");
var utils_1 = require("../utils");
var globals_1 = require("../utils/globals");
var survey_utils_1 = require("../utils/survey-utils");
var core_1 = require("@posthog/core");
var constants_1 = require("../constants");
var uuidv7_1 = require("../uuidv7");
var ConfirmationMessage_1 = require("./surveys/components/ConfirmationMessage");
var QuestionHeader_1 = require("./surveys/components/QuestionHeader");
var QuestionTypes_1 = require("./surveys/components/QuestionTypes");
var surveys_extension_utils_1 = require("./surveys/surveys-extension-utils");
var survey_url_prefill_1 = require("../utils/survey-url-prefill");
var survey_branching_1 = require("../utils/survey-branching");
Object.defineProperty(exports, "getNextSurveyStep", { enumerable: true, get: function () { return survey_branching_1.getNextSurveyStep; } });
var survey_translations_1 = require("../utils/survey-translations");
// We cast the types here which is dangerous but protected by the top level generateSurveys call
var window = globals_1.window;
var document = globals_1.document;
var DISPATCH_FEEDBACK_WIDGET_EVENT = 'ph:show_survey_widget';
var WIDGET_LISTENER_ATTRIBUTE = 'PHWidgetSurveyClickListener';
var SURVEY_NEXT_TO_TRIGGER_PARAMS = {
    ESTIMATED_MIN_HEIGHT: 250,
    HORIZONTAL_PADDING: 20,
    TRIGGER_SPACING: 12,
};
function getNextToTriggerPosition(target, surveyWidth) {
    try {
        var buttonRect = target.getBoundingClientRect();
        var viewportHeight = window.innerHeight;
        var viewportWidth = window.innerWidth;
        var estimatedMinSurveyHeight = SURVEY_NEXT_TO_TRIGGER_PARAMS.ESTIMATED_MIN_HEIGHT;
        var buttonCenterX = buttonRect.left + buttonRect.width / 2;
        var left = buttonCenterX - surveyWidth / 2;
        var horizontalPadding = SURVEY_NEXT_TO_TRIGGER_PARAMS.HORIZONTAL_PADDING;
        if (left + surveyWidth > viewportWidth - horizontalPadding) {
            left = viewportWidth - surveyWidth - horizontalPadding;
        }
        if (left < horizontalPadding) {
            left = horizontalPadding;
        }
        var spacing = SURVEY_NEXT_TO_TRIGGER_PARAMS.TRIGGER_SPACING;
        var spaceBelow = viewportHeight - buttonRect.bottom;
        var spaceAbove = buttonRect.top;
        var showAbove = spaceBelow < estimatedMinSurveyHeight && spaceAbove > spaceBelow;
        return {
            position: 'fixed',
            top: showAbove ? 'auto' : "".concat(buttonRect.bottom + spacing, "px"),
            left: "".concat(left, "px"),
            right: 'auto',
            bottom: showAbove ? "".concat(viewportHeight - buttonRect.top + spacing, "px") : 'auto',
            zIndex: surveys_extension_utils_1.defaultSurveyAppearance.zIndex,
        };
    }
    catch (error) {
        survey_utils_1.SURVEY_LOGGER.warn('Failed to calculate trigger position:', error);
        return null;
    }
}
// Keep in sync with posthog/constants.py on main repo
var SURVEY_TARGETING_FLAG_PREFIX = 'survey-targeting-';
var SurveyManager = /** @class */ (function () {
    function SurveyManager(posthog) {
        var _this = this;
        this._surveyTimeouts = new Map();
        this._widgetSelectorListeners = new Map();
        this._prefillHandledSurveys = new Set();
        this.handlePageUnload = function () {
            var e_1, _a;
            // we don't use getSurveys to avoid adding extra API calls here.
            // if no surveys are cached, there's nothing to do anyways
            var surveys = _this._posthog.get_property(constants_1.SURVEYS);
            if (!surveys) {
                return;
            }
            try {
                for (var surveys_1 = __values(surveys), surveys_1_1 = surveys_1.next(); !surveys_1_1.done; surveys_1_1 = surveys_1.next()) {
                    var survey = surveys_1_1.value;
                    if ((0, surveys_extension_utils_1.isSurveyInProgress)(survey)) {
                        (0, surveys_extension_utils_1.sendSurveyAbandonedEvent)(survey, _this._posthog);
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (surveys_1_1 && !surveys_1_1.done && (_a = surveys_1.return)) _a.call(surveys_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
        };
        this.handlePopoverSurvey = function (surveyParam, options) {
            var _a, _b, _c, _d, _e;
            var _f = _this._translateSurveyForRendering(surveyParam), translatedSurvey = _f.survey, surveyLanguage = _f.language;
            // apply overrides for position / selector (needed for thumb surveys)
            var survey = (options === null || options === void 0 ? void 0 : options.position) || (options === null || options === void 0 ? void 0 : options.selector)
                ? __assign(__assign({}, translatedSurvey), { appearance: __assign(__assign(__assign({}, translatedSurvey.appearance), (options.position && { position: options.position })), (options.selector && { widgetSelector: options.selector })) }) : translatedSurvey;
            _this._clearSurveyTimeout(survey.id);
            var _g = options !== null && options !== void 0 ? options : {}, properties = _g.properties, initialResponses = _g.initialResponses;
            var hasPrefillData = initialResponses && Object.keys(initialResponses).length > 0;
            var isSurveyCompleted = hasPrefillData
                ? _this._handleInitialResponses(survey, initialResponses, properties, surveyLanguage)
                : false;
            // if the survey is done (from prefill) and there is no thank-you, we can break early
            if (isSurveyCompleted && !((_a = survey.appearance) === null || _a === void 0 ? void 0 : _a.displayThankYouMessage)) {
                return;
            }
            _this._addSurveyToFocus(survey);
            // Calculate position style for NextToTrigger positioning
            var positionStyle = {};
            if (((_b = survey.appearance) === null || _b === void 0 ? void 0 : _b.position) === posthog_surveys_types_1.SurveyPosition.NextToTrigger && ((_c = survey.appearance) === null || _c === void 0 ? void 0 : _c.widgetSelector)) {
                var targetElement = document.querySelector(survey.appearance.widgetSelector);
                if (targetElement) {
                    positionStyle =
                        getNextToTriggerPosition(targetElement, parseInt(((_d = survey.appearance) === null || _d === void 0 ? void 0 : _d.maxWidth) || surveys_extension_utils_1.defaultSurveyAppearance.maxWidth)) || {};
                }
            }
            var delaySeconds = ((_e = survey.appearance) === null || _e === void 0 ? void 0 : _e.surveyPopupDelaySeconds) || 0;
            var shadow = (0, surveys_extension_utils_1.retrieveSurveyShadow)(survey, _this._posthog).shadow;
            var surveyPopupProps = {
                posthog: _this._posthog,
                survey: survey,
                removeSurveyFromFocus: _this._removeSurveyFromFocus,
                properties: properties,
                style: positionStyle,
                isSurveyCompleted: isSurveyCompleted,
                skipShownEvent: options === null || options === void 0 ? void 0 : options.skipShownEvent,
                surveyLanguage: surveyLanguage,
            };
            if (delaySeconds <= 0) {
                return (0, preact_2.render)((0, jsx_runtime_1.jsx)(SurveyPopup, __assign({}, surveyPopupProps)), shadow);
            }
            var timeoutId = setTimeout(function () {
                // remove survey to keep `_surveyTimeouts` as a true list of "pending" surveys
                _this._surveyTimeouts.delete(survey.id);
                if (!(0, surveys_extension_utils_1.doesSurveyUrlMatch)(survey)) {
                    return _this._removeSurveyFromFocus(survey);
                }
                // rendering with surveyPopupDelaySeconds = 0 because we're already handling the timeout here
                (0, preact_2.render)((0, jsx_runtime_1.jsx)(SurveyPopup, __assign({}, surveyPopupProps, { survey: __assign(__assign({}, survey), { appearance: __assign(__assign({}, survey.appearance), { surveyPopupDelaySeconds: 0 }) }) })), shadow);
            }, delaySeconds * 1000);
            _this._surveyTimeouts.set(survey.id, timeoutId);
        };
        this._handleWidget = function (survey) {
            var _a = _this._translateSurveyForRendering(survey), translatedSurvey = _a.survey, surveyLanguage = _a.language;
            // Ensure widget container exists if it doesn't
            var _b = (0, surveys_extension_utils_1.retrieveSurveyShadow)(translatedSurvey, _this._posthog), shadow = _b.shadow, isNewlyCreated = _b.isNewlyCreated;
            // If the widget is already rendered, do nothing. Otherwise the widget will be re-rendered every second
            if (!isNewlyCreated) {
                return;
            }
            (0, preact_2.render)((0, jsx_runtime_1.jsx)(FeedbackWidget, { posthog: _this._posthog, survey: translatedSurvey, surveyLanguage: surveyLanguage }, survey.id), shadow);
        };
        this._removeWidgetSelectorListener = function (survey) {
            _this._removeSurveyFromDom(survey);
            var existing = _this._widgetSelectorListeners.get(survey.id);
            if (existing) {
                existing.element.removeEventListener('click', existing.listener);
                existing.element.removeAttribute(WIDGET_LISTENER_ATTRIBUTE);
                _this._widgetSelectorListeners.delete(survey.id);
                survey_utils_1.SURVEY_LOGGER.info("Removed click listener for survey ".concat(survey.id));
            }
        };
        this._manageWidgetSelectorListener = function (survey, selector) {
            var currentElement = document.querySelector(selector);
            var existingListenerData = _this._widgetSelectorListeners.get(survey.id);
            if (!currentElement) {
                if (existingListenerData) {
                    _this._removeWidgetSelectorListener(survey);
                }
                return;
            }
            _this._handleWidget(survey);
            if (existingListenerData) {
                // Listener exists, check if element changed
                if (currentElement !== existingListenerData.element) {
                    survey_utils_1.SURVEY_LOGGER.info("Selector element changed for survey ".concat(survey.id, ". Re-attaching listener."));
                    _this._removeWidgetSelectorListener(survey);
                    // Continue to attach listener to the new element below
                }
                else {
                    // Element is the same, listener already attached, do nothing
                    return;
                }
            }
            // Element found, and no listener attached (or it was just removed from old element)
            if (!currentElement.hasAttribute(WIDGET_LISTENER_ATTRIBUTE)) {
                var listener = function (event) {
                    var _a, _b;
                    event.stopPropagation(); // Prevent bubbling
                    var positionStyles = ((_a = survey.appearance) === null || _a === void 0 ? void 0 : _a.position) === posthog_surveys_types_1.SurveyPosition.NextToTrigger
                        ? getNextToTriggerPosition(event.currentTarget, parseInt(((_b = survey.appearance) === null || _b === void 0 ? void 0 : _b.maxWidth) || surveys_extension_utils_1.defaultSurveyAppearance.maxWidth))
                        : {};
                    window.dispatchEvent(new CustomEvent(DISPATCH_FEEDBACK_WIDGET_EVENT, {
                        detail: { surveyId: survey.id, position: positionStyles },
                    }));
                };
                (0, utils_1.addEventListener)(currentElement, 'click', listener);
                currentElement.setAttribute(WIDGET_LISTENER_ATTRIBUTE, 'true');
                _this._widgetSelectorListeners.set(survey.id, { element: currentElement, listener: listener, survey: survey });
                survey_utils_1.SURVEY_LOGGER.info("Attached click listener for feedback button survey ".concat(survey.id));
            }
        };
        this.renderPopover = function (survey) {
            var _a = _this._translateSurveyForRendering(survey), translatedSurvey = _a.survey, surveyLanguage = _a.language;
            var shadow = (0, surveys_extension_utils_1.retrieveSurveyShadow)(translatedSurvey, _this._posthog).shadow;
            (0, preact_2.render)((0, jsx_runtime_1.jsx)(SurveyPopup, { posthog: _this._posthog, survey: translatedSurvey, removeSurveyFromFocus: _this._removeSurveyFromFocus, surveyLanguage: surveyLanguage }), shadow);
        };
        this.renderSurvey = function (survey, selector, properties) {
            var _a, _b;
            var _c = _this._translateSurveyForRendering(survey), translatedSurvey = _c.survey, surveyLanguage = _c.language;
            var isSurveyCompleted = false;
            if ((_b = (_a = _this._posthog.config) === null || _a === void 0 ? void 0 : _a.surveys) === null || _b === void 0 ? void 0 : _b.prefillFromUrl) {
                isSurveyCompleted = _this._handleUrlPrefill(translatedSurvey, surveyLanguage);
            }
            (0, preact_2.render)((0, jsx_runtime_1.jsx)(SurveyPopup, { posthog: _this._posthog, survey: translatedSurvey, removeSurveyFromFocus: _this._removeSurveyFromFocus, isPopup: false, properties: properties, isSurveyCompleted: isSurveyCompleted, surveyLanguage: surveyLanguage }), selector);
        };
        this.getActiveMatchingSurveys = function (callback, forceReload) {
            var _a, _b;
            if (forceReload === void 0) { forceReload = false; }
            (_b = (_a = _this._posthog) === null || _a === void 0 ? void 0 : _a.surveys) === null || _b === void 0 ? void 0 : _b.getSurveys(function (surveys) {
                var targetingMatchedSurveys = surveys.filter(function (survey) {
                    var eligibility = _this.checkSurveyEligibility(survey);
                    return (eligibility.eligible &&
                        _this._isSurveyConditionMatched(survey) &&
                        _this._hasActionOrEventTriggeredSurvey(survey) &&
                        _this._checkFlags(survey));
                });
                callback(targetingMatchedSurveys);
            }, forceReload);
        };
        this.callSurveysAndEvaluateDisplayLogic = function (forceReload) {
            if (forceReload === void 0) { forceReload = false; }
            _this.getActiveMatchingSurveys(function (surveys) {
                var inAppSurveysWithDisplayLogic = surveys.filter(function (survey) { return survey.type === posthog_surveys_types_1.SurveyType.Popover || survey.type === posthog_surveys_types_1.SurveyType.Widget; });
                // Create a queue of surveys sorted by their appearance delay.  We will evaluate the display logic
                // for each survey in the queue in order, and only display one survey at a time.
                var inAppSurveysQueue = _this._sortSurveysByAppearanceDelay(inAppSurveysWithDisplayLogic);
                // Keep track of surveys processed this cycle to remove listeners for inactive ones
                var activeSelectorSurveys = new Set();
                inAppSurveysQueue.forEach(function (survey) {
                    var _a, _b, _c, _d;
                    // Widget Type Logic
                    if (survey.type === posthog_surveys_types_1.SurveyType.Widget) {
                        if (((_a = survey.appearance) === null || _a === void 0 ? void 0 : _a.widgetType) === posthog_surveys_types_1.SurveyWidgetType.Tab) {
                            _this._handleWidget(survey);
                            return;
                        }
                        // For selector widget types, we need to manage the listener attachment/detachment dynamically
                        if (((_b = survey.appearance) === null || _b === void 0 ? void 0 : _b.widgetType) === posthog_surveys_types_1.SurveyWidgetType.Selector &&
                            ((_c = survey.appearance) === null || _c === void 0 ? void 0 : _c.widgetSelector)) {
                            activeSelectorSurveys.add(survey.id);
                            _this._manageWidgetSelectorListener(survey, (_d = survey.appearance) === null || _d === void 0 ? void 0 : _d.widgetSelector);
                        }
                    }
                    // Popover Type Logic (only one shown at a time)
                    if ((0, core_1.isNull)(_this._surveyInFocus) && survey.type === posthog_surveys_types_1.SurveyType.Popover) {
                        _this.handlePopoverSurvey(survey);
                    }
                });
                // Clean up listeners for surveys that are no longer active or matched
                _this._widgetSelectorListeners.forEach(function (_a) {
                    var survey = _a.survey;
                    if (!activeSelectorSurveys.has(survey.id)) {
                        _this._removeWidgetSelectorListener(survey);
                    }
                });
            }, forceReload);
        };
        this._addSurveyToFocus = function (survey) {
            if (!(0, core_1.isNull)(_this._surveyInFocus)) {
                survey_utils_1.SURVEY_LOGGER.error("Survey ".concat(_this._surveyInFocus, " already in focus. Cannot add survey ").concat(survey.id, "."));
            }
            _this._surveyInFocus = survey.id;
        };
        this._removeSurveyFromFocus = function (survey) {
            if (_this._surveyInFocus !== survey.id) {
                survey_utils_1.SURVEY_LOGGER.error("Survey ".concat(survey.id, " is not in focus. Cannot remove survey ").concat(survey.id, "."));
            }
            _this._clearSurveyTimeout(survey.id);
            _this._surveyInFocus = null;
            _this._removeSurveyFromDom(survey);
        };
        this._posthog = posthog;
        // This is used to track the survey that is currently in focus. We only show one survey at a time.
        this._surveyInFocus = null;
    }
    SurveyManager.prototype._clearSurveyTimeout = function (surveyId) {
        var timeout = this._surveyTimeouts.get(surveyId);
        if (timeout) {
            clearTimeout(timeout);
            this._surveyTimeouts.delete(surveyId);
        }
    };
    /**
     * cancel a "pending" survey, i.e. one that is waiting to be displayed in
     * the _surveyTimeouts queue
     */
    SurveyManager.prototype.cancelSurvey = function (surveyId) {
        // only works for surveys in the _surveyTimeouts queue...
        if (!this._surveyTimeouts.has(surveyId)) {
            return;
        }
        survey_utils_1.SURVEY_LOGGER.info("Cancelled pending survey ".concat(surveyId));
        this._clearSurveyTimeout(surveyId);
        // release focus - it was claimed when the delay timer started.
        // "focus" != "survey is displayed"
        if (this._surveyInFocus === surveyId) {
            this._surveyInFocus = null;
        }
    };
    /**
     * Sorts surveys by their appearance delay in ascending order. If a survey does not have an appearance delay,
     * it is considered to have a delay of 0.
     * @param surveys
     * @returns The surveys sorted by their appearance delay
     */
    SurveyManager.prototype._sortSurveysByAppearanceDelay = function (surveys) {
        return surveys.sort(function (a, b) {
            var _a, _b;
            var isSurveyInProgressA = (0, surveys_extension_utils_1.isSurveyInProgress)(a);
            var isSurveyInProgressB = (0, surveys_extension_utils_1.isSurveyInProgress)(b);
            if (isSurveyInProgressA && !isSurveyInProgressB) {
                return -1; // a comes before b (in progress surveys first)
            }
            if (!isSurveyInProgressA && isSurveyInProgressB) {
                return 1; // a comes after b (in progress surveys first)
            }
            var aIsAlways = a.schedule === posthog_surveys_types_1.SurveySchedule.Always;
            var bIsAlways = b.schedule === posthog_surveys_types_1.SurveySchedule.Always;
            if (aIsAlways && !bIsAlways) {
                return 1; // a comes after b
            }
            if (!aIsAlways && bIsAlways) {
                return -1; // a comes before b
            }
            // If both are Always or neither is Always, sort by delay
            return (((_a = a.appearance) === null || _a === void 0 ? void 0 : _a.surveyPopupDelaySeconds) || 0) - (((_b = b.appearance) === null || _b === void 0 ? void 0 : _b.surveyPopupDelaySeconds) || 0);
        });
    };
    SurveyManager.prototype._translateSurveyForRendering = function (survey) {
        // Rendering entry points accept the raw API survey. The translation helper is idempotent,
        // but keeping this central avoids each entry point growing its own language rules.
        return (0, survey_translations_1.applySurveyTranslationForUser)(survey, this._posthog);
    };
    SurveyManager.prototype._handleUrlPrefill = function (survey, surveyLanguage) {
        // Only handle prefill once per survey session to avoid overwriting in-progress responses
        if (this._prefillHandledSurveys.has(survey.id)) {
            return false;
        }
        var params = (0, survey_url_prefill_1.extractPrefillParamsFromUrl)(window.location.search).params;
        if (Object.keys(params).length === 0) {
            return false;
        }
        survey_utils_1.SURVEY_LOGGER.info('[Survey Prefill] Detected URL prefill parameters');
        var result = this._processPrefillData(survey, params, surveyLanguage);
        if (!result) {
            return false;
        }
        var responses = result.responses, submissionId = result.submissionId, isSurveyCompleted = result.isSurveyCompleted, skippedResponses = result.skippedResponses;
        /**
         * auto-submit some survey events on pageload only if:
         * 1) survey is complete, OR
         * 2) partial responses are enabled AND the skipped questions were set to auto-submit
         */
        var shouldAutoSubmitPrefilled = Object.keys(skippedResponses).length > 0 && survey.enable_partial_responses;
        if (shouldAutoSubmitPrefilled || isSurveyCompleted) {
            (0, surveys_extension_utils_1.sendSurveyEvent)({
                responses: isSurveyCompleted ? responses : skippedResponses,
                survey: survey,
                surveySubmissionId: submissionId,
                posthog: this._posthog,
                isSurveyCompleted: isSurveyCompleted,
                surveyLanguage: surveyLanguage,
            });
        }
        // Mark this survey as having been prefilled
        this._prefillHandledSurveys.add(survey.id);
        return isSurveyCompleted;
    };
    /**
     * process prefilled responses for non-hosted surveys
     *
     * @returns boolean, true if the survey is completed
     */
    SurveyManager.prototype._handleInitialResponses = function (survey, initialResponses, properties, surveyLanguage) {
        var e_2, _a;
        var prefillParams = {};
        try {
            for (var _b = __values(Object.entries(initialResponses)), _c = _b.next(); !_c.done; _c = _b.next()) {
                var _d = __read(_c.value, 2), indexStr = _d[0], value = _d[1];
                var index = parseInt(indexStr);
                prefillParams[index] = (0, core_1.isArray)(value) ? value.map(String) : [String(value)];
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_2) throw e_2.error; }
        }
        survey_utils_1.SURVEY_LOGGER.info('[Survey] Processing initial responses');
        var result = this._processPrefillData(survey, prefillParams, surveyLanguage);
        if (!result) {
            return false;
        }
        var responses = result.responses, submissionId = result.submissionId, isSurveyCompleted = result.isSurveyCompleted;
        // always capture immediately
        (0, surveys_extension_utils_1.sendSurveyEvent)({
            responses: responses,
            survey: survey,
            surveySubmissionId: submissionId,
            posthog: this._posthog,
            isSurveyCompleted: isSurveyCompleted,
            properties: properties,
            surveyLanguage: surveyLanguage,
        });
        return isSurveyCompleted;
    };
    SurveyManager.prototype._processPrefillData = function (survey, prefillParams, surveyLanguage) {
        try {
            var responses = (0, survey_url_prefill_1.convertPrefillToResponses)(survey, prefillParams);
            if (Object.keys(responses).length === 0) {
                survey_utils_1.SURVEY_LOGGER.warn('[Survey Prefill] No valid responses after conversion');
                return null;
            }
            var submissionId = (0, uuidv7_1.uuidv7)();
            // calculate which question to start at based on prefilled questions
            var prefilledIndices = Object.keys(prefillParams).map(function (k) { return parseInt(k, 10); });
            var _a = (0, survey_url_prefill_1.calculatePrefillStartIndex)(survey, prefilledIndices, responses), startQuestionIndex = _a.startQuestionIndex, skippedResponses = _a.skippedResponses;
            var isSurveyCompleted = startQuestionIndex >= survey.questions.length;
            (0, surveys_extension_utils_1.setInProgressSurveyState)(survey, {
                surveySubmissionId: submissionId,
                responses: responses,
                lastQuestionIndex: startQuestionIndex,
                surveyLanguage: surveyLanguage,
            });
            survey_utils_1.SURVEY_LOGGER.info('[Survey Prefill] Stored prefilled responses in localStorage');
            return { responses: responses, submissionId: submissionId, startQuestionIndex: startQuestionIndex, isSurveyCompleted: isSurveyCompleted, skippedResponses: skippedResponses };
        }
        catch (error) {
            survey_utils_1.SURVEY_LOGGER.error('[Survey Prefill] Error handling prefill:', error);
            return null;
        }
    };
    SurveyManager.prototype._isSurveyFeatureFlagEnabled = function (flagKey, flagVariant) {
        var _a, _b;
        if (flagVariant === void 0) { flagVariant = undefined; }
        if (!flagKey) {
            return true;
        }
        var isFeatureEnabled = !!((_a = this._posthog.featureFlags) === null || _a === void 0 ? void 0 : _a.isFeatureEnabled(flagKey, {
            send_event: !flagKey.startsWith(SURVEY_TARGETING_FLAG_PREFIX),
        }));
        var flagVariantCheck = true;
        if (flagVariant) {
            var flagVariantValue = (_b = this._posthog.featureFlags) === null || _b === void 0 ? void 0 : _b.getFeatureFlag(flagKey, { send_event: false });
            flagVariantCheck = flagVariantValue === flagVariant || flagVariant === 'any';
        }
        return isFeatureEnabled && flagVariantCheck;
    };
    SurveyManager.prototype._isSurveyConditionMatched = function (survey) {
        if (!survey.conditions) {
            return true;
        }
        return (0, surveys_extension_utils_1.doesSurveyUrlMatch)(survey) && (0, surveys_extension_utils_1.doesSurveyDeviceTypesMatch)(survey) && (0, surveys_extension_utils_1.doesSurveyMatchSelector)(survey);
    };
    SurveyManager.prototype._internalFlagCheckSatisfied = function (survey) {
        return ((0, surveys_extension_utils_1.canActivateRepeatedly)(survey) ||
            this._isSurveyFeatureFlagEnabled(survey.internal_targeting_flag_key) ||
            (0, surveys_extension_utils_1.isSurveyInProgress)(survey));
    };
    SurveyManager.prototype.checkSurveyEligibility = function (survey) {
        var _a, _b;
        var eligibility = { eligible: true, reason: undefined };
        if (!(0, survey_utils_1.isSurveyRunning)(survey)) {
            eligibility.eligible = false;
            eligibility.reason = "Survey is not running. It was completed on ".concat(survey.end_date);
            return eligibility;
        }
        if (!survey_utils_1.IN_APP_SURVEY_TYPES.includes(survey.type)) {
            eligibility.eligible = false;
            eligibility.reason = "Surveys of type ".concat(survey.type, " are never eligible to be shown in the app");
            return eligibility;
        }
        var linkedFlagVariant = (_a = survey.conditions) === null || _a === void 0 ? void 0 : _a.linkedFlagVariant;
        if (!this._isSurveyFeatureFlagEnabled(survey.linked_flag_key, linkedFlagVariant)) {
            eligibility.eligible = false;
            if (!linkedFlagVariant) {
                eligibility.reason = "Survey linked feature flag is not enabled";
            }
            else {
                eligibility.reason = "Survey linked feature flag is not enabled for variant ".concat(linkedFlagVariant);
            }
            return eligibility;
        }
        if (!this._isSurveyFeatureFlagEnabled(survey.targeting_flag_key)) {
            eligibility.eligible = false;
            eligibility.reason = "Survey targeting feature flag is not enabled";
            return eligibility;
        }
        if (!this._internalFlagCheckSatisfied(survey)) {
            eligibility.eligible = false;
            eligibility.reason =
                'Survey internal targeting flag is not enabled and survey cannot activate repeatedly and survey is not in progress';
            return eligibility;
        }
        if (!(0, surveys_extension_utils_1.hasWaitPeriodPassed)((_b = survey.conditions) === null || _b === void 0 ? void 0 : _b.seenSurveyWaitPeriodInDays)) {
            eligibility.eligible = false;
            eligibility.reason = "Survey wait period has not passed";
            return eligibility;
        }
        if ((0, surveys_extension_utils_1.getSurveySeen)(survey)) {
            eligibility.eligible = false;
            eligibility.reason = "Survey has already been seen and it can't be activated again";
            return eligibility;
        }
        return eligibility;
    };
    /**
     * Surveys can be activated by events or actions. This method checks if the survey has events and actions,
     * and if so, it checks if the survey has been activated.
     * @param survey
     */
    SurveyManager.prototype._hasActionOrEventTriggeredSurvey = function (survey) {
        var _a, _b;
        if (!(0, survey_utils_1.doesSurveyActivateByEvent)(survey) && !(0, survey_utils_1.doesSurveyActivateByAction)(survey)) {
            // If survey doesn't depend on events/actions, it's considered "triggered" by default
            return true;
        }
        var surveysActivatedByEventsOrActions = (_b = (_a = this._posthog.surveys) === null || _a === void 0 ? void 0 : _a._surveyEventReceiver) === null || _b === void 0 ? void 0 : _b.getSurveys();
        return !!(surveysActivatedByEventsOrActions === null || surveysActivatedByEventsOrActions === void 0 ? void 0 : surveysActivatedByEventsOrActions.includes(survey.id));
    };
    SurveyManager.prototype._checkFlags = function (survey) {
        var _this = this;
        var _a;
        if (!((_a = survey.feature_flag_keys) === null || _a === void 0 ? void 0 : _a.length)) {
            return true;
        }
        return survey.feature_flag_keys.every(function (_a) {
            var key = _a.key, value = _a.value;
            if (!key || !value) {
                return true;
            }
            return _this._isSurveyFeatureFlagEnabled(value);
        });
    };
    SurveyManager.prototype._removeSurveyFromDom = function (survey) {
        try {
            var shadowContainer = document.querySelector((0, surveys_extension_utils_1.getSurveyContainerClass)(survey, true));
            if (shadowContainer === null || shadowContainer === void 0 ? void 0 : shadowContainer.shadowRoot) {
                (0, preact_2.render)(null, shadowContainer.shadowRoot);
            }
            shadowContainer === null || shadowContainer === void 0 ? void 0 : shadowContainer.remove();
        }
        catch (error) {
            survey_utils_1.SURVEY_LOGGER.warn("Failed to remove survey ".concat(survey.id, " from DOM:"), error);
        }
    };
    // Expose internal state and methods for testing
    SurveyManager.prototype.getTestAPI = function () {
        return {
            addSurveyToFocus: this._addSurveyToFocus,
            removeSurveyFromFocus: this._removeSurveyFromFocus,
            surveyInFocus: this._surveyInFocus,
            surveyTimeouts: this._surveyTimeouts,
            handleWidget: this._handleWidget,
            handlePopoverSurvey: this.handlePopoverSurvey,
            manageWidgetSelectorListener: this._manageWidgetSelectorListener,
            sortSurveysByAppearanceDelay: this._sortSurveysByAppearanceDelay,
            checkFlags: this._checkFlags.bind(this),
            isSurveyFeatureFlagEnabled: this._isSurveyFeatureFlagEnabled.bind(this),
        };
    };
    return SurveyManager;
}());
exports.SurveyManager = SurveyManager;
var DEFAULT_PREVIEW_POSITION_STYLES = {
    position: 'relative',
    left: 'unset',
    right: 'unset',
    top: 'unset',
    bottom: 'unset',
    transform: 'unset',
};
var renderSurveysPreview = function (_a) {
    var survey = _a.survey, parentElement = _a.parentElement, previewPageIndex = _a.previewPageIndex, forceDisableHtml = _a.forceDisableHtml, onPreviewSubmit = _a.onPreviewSubmit, onPreviewBack = _a.onPreviewBack, _b = _a.positionStyles, positionStyles = _b === void 0 ? DEFAULT_PREVIEW_POSITION_STYLES : _b;
    var currentStyle = parentElement.querySelector('style[data-ph-survey-style]');
    if (currentStyle) {
        currentStyle.remove();
    }
    var stylesheet = (0, surveys_extension_utils_1.getSurveyStylesheet)();
    if (stylesheet) {
        parentElement.appendChild(stylesheet);
        (0, surveys_extension_utils_1.addSurveyCSSVariablesToElement)(parentElement, survey.type, survey.appearance);
    }
    (0, preact_2.render)((0, jsx_runtime_1.jsx)(SurveyPopup, { survey: survey, forceDisableHtml: forceDisableHtml, style: positionStyles, onPreviewSubmit: onPreviewSubmit, onPreviewBack: onPreviewBack, previewPageIndex: previewPageIndex, removeSurveyFromFocus: function () { } }), parentElement);
};
exports.renderSurveysPreview = renderSurveysPreview;
var renderFeedbackWidgetPreview = function (_a) {
    var survey = _a.survey, root = _a.root, forceDisableHtml = _a.forceDisableHtml;
    var stylesheet = (0, surveys_extension_utils_1.getSurveyStylesheet)();
    if (stylesheet) {
        root.appendChild(stylesheet);
        (0, surveys_extension_utils_1.addSurveyCSSVariablesToElement)(root, survey.type, survey.appearance);
    }
    (0, preact_2.render)((0, jsx_runtime_1.jsx)(FeedbackWidget, { forceDisableHtml: forceDisableHtml, survey: survey, readOnly: true }), root);
};
exports.renderFeedbackWidgetPreview = renderFeedbackWidgetPreview;
// This is the main exported function
function generateSurveys(posthog, isSurveysEnabled) {
    // NOTE: Important to ensure we never try and run surveys without a window environment
    if (!document || !window) {
        return;
    }
    var surveyManager = new SurveyManager(posthog);
    if (posthog.config.disable_surveys_automatic_display) {
        survey_utils_1.SURVEY_LOGGER.info('Surveys automatic display is disabled. Skipping call surveys and evaluate display logic.');
        return surveyManager;
    }
    // NOTE: The `generateSurveys` function used to accept just a single parameter, without any `isSurveysEnabled` parameter.
    // To keep compatibility with old clients, we'll consider `undefined` the same as `true`
    if (isSurveysEnabled === false) {
        survey_utils_1.SURVEY_LOGGER.info('There are no surveys to load or Surveys is disabled in the project settings.');
        return surveyManager;
    }
    surveyManager.callSurveysAndEvaluateDisplayLogic(true);
    var intervalId;
    var startInterval = function () {
        if (!(0, core_1.isUndefined)(intervalId)) {
            return;
        }
        intervalId = setInterval(function () {
            surveyManager.callSurveysAndEvaluateDisplayLogic(false);
        }, 1000);
    };
    var stopInterval = function () {
        if (!(0, core_1.isUndefined)(intervalId)) {
            clearInterval(intervalId);
            intervalId = undefined;
        }
    };
    startInterval();
    (0, utils_1.addEventListener)(document, 'visibilitychange', function () {
        if (document.hidden) {
            stopInterval();
        }
        else {
            surveyManager.callSurveysAndEvaluateDisplayLogic(false);
            startInterval();
        }
    });
    return surveyManager;
}
/**
 * This hook handles URL-based survey visibility after the initial mount.
 * The initial URL check is handled by the `getActiveMatchingSurveys` method in  the `PostHogSurveys` class,
 * which ensures the URL matches before displaying a survey for the first time.
 * That is the method that is called every second to see if there's a matching survey.
 *
 * This separation of concerns means:
 * 1. Initial URL matching is done by `getActiveMatchingSurveys` before displaying the survey
 * 2. Subsequent URL changes are handled here to hide the survey as the user navigates
 */
function useHideSurveyOnURLChange(_a) {
    var survey = _a.survey, _b = _a.removeSurveyFromFocus, removeSurveyFromFocus = _b === void 0 ? function () { } : _b, setSurveyVisible = _a.setSurveyVisible, _c = _a.isPreviewMode, isPreviewMode = _c === void 0 ? false : _c;
    (0, hooks_1.useEffect)(function () {
        var _a;
        if (isPreviewMode || !((_a = survey.conditions) === null || _a === void 0 ? void 0 : _a.url)) {
            return;
        }
        var checkUrlMatch = function () {
            var _a;
            var isSurveyTypeWidget = survey.type === posthog_surveys_types_1.SurveyType.Widget;
            var doesSurveyMatchUrlCondition = (0, surveys_extension_utils_1.doesSurveyUrlMatch)(survey);
            var isSurveyWidgetTypeTab = ((_a = survey.appearance) === null || _a === void 0 ? void 0 : _a.widgetType) === posthog_surveys_types_1.SurveyWidgetType.Tab && isSurveyTypeWidget;
            if (doesSurveyMatchUrlCondition) {
                if (isSurveyWidgetTypeTab) {
                    survey_utils_1.SURVEY_LOGGER.info("Showing survey ".concat(survey.id, " because it is a feedback button tab and URL matches"));
                    setSurveyVisible(true);
                }
                return;
            }
            survey_utils_1.SURVEY_LOGGER.info("Hiding survey ".concat(survey.id, " because URL does not match"));
            setSurveyVisible(false);
            return removeSurveyFromFocus(survey);
        };
        // Listen for browser back/forward browser history changes
        (0, utils_1.addEventListener)(window, 'popstate', checkUrlMatch);
        // Listen for hash changes, for SPA frameworks that use hash-based routing
        // The hashchange event is fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol).
        (0, utils_1.addEventListener)(window, 'hashchange', checkUrlMatch);
        // Listen for SPA navigation
        var originalPushState = window.history.pushState;
        var originalReplaceState = window.history.replaceState;
        window.history.pushState = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            originalPushState.apply(this, args);
            checkUrlMatch();
        };
        window.history.replaceState = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            originalReplaceState.apply(this, args);
            checkUrlMatch();
        };
        return function () {
            window.removeEventListener('popstate', checkUrlMatch);
            window.removeEventListener('hashchange', checkUrlMatch);
            window.history.pushState = originalPushState;
            window.history.replaceState = originalReplaceState;
        };
    }, [isPreviewMode, survey, removeSurveyFromFocus, setSurveyVisible]);
}
function usePopupVisibility(survey, posthog, millisecondDelay, isPreviewMode, removeSurveyFromFocus, isPopup, surveyContainerRef, skipShownEvent, surveyLanguage) {
    var _a = __read((0, hooks_1.useState)(isPreviewMode || millisecondDelay === 0 || survey.type === posthog_surveys_types_1.SurveyType.ExternalSurvey), 2), isPopupVisible = _a[0], setIsPopupVisible = _a[1];
    var _b = __read((0, hooks_1.useState)(false), 2), isSurveySent = _b[0], setIsSurveySent = _b[1];
    var hidePopupWithViewTransition = function () {
        var removeDOMAndHidePopup = function () {
            if (isPopup) {
                removeSurveyFromFocus(survey);
            }
            setIsPopupVisible(false);
        };
        if (!document.startViewTransition) {
            removeDOMAndHidePopup();
            return;
        }
        var transition = document.startViewTransition(function () {
            var _a;
            (_a = surveyContainerRef === null || surveyContainerRef === void 0 ? void 0 : surveyContainerRef.current) === null || _a === void 0 ? void 0 : _a.remove();
        });
        transition.finished.then(function () {
            setTimeout(function () {
                removeDOMAndHidePopup();
            }, 100);
        });
    };
    var handleSurveyClosed = function (event) {
        if (event.detail.surveyId !== survey.id) {
            return;
        }
        hidePopupWithViewTransition();
    };
    (0, hooks_1.useEffect)(function () {
        if (!posthog) {
            survey_utils_1.SURVEY_LOGGER.error('usePopupVisibility hook called without a PostHog instance.');
            return;
        }
        if (isPreviewMode) {
            return;
        }
        var handleSurveySent = function (event) {
            var _a, _b;
            if (event.detail.surveyId !== survey.id) {
                return;
            }
            if (!((_a = survey.appearance) === null || _a === void 0 ? void 0 : _a.displayThankYouMessage)) {
                return hidePopupWithViewTransition();
            }
            setIsSurveySent(true);
            if ((_b = survey.appearance) === null || _b === void 0 ? void 0 : _b.autoDisappear) {
                setTimeout(function () {
                    hidePopupWithViewTransition();
                }, 5000);
            }
        };
        var showSurvey = function () {
            var _a, _b;
            var _c;
            // check if the url is still matching, necessary for delayed surveys, as the URL may have changed
            if (!(0, surveys_extension_utils_1.doesSurveyUrlMatch)(survey)) {
                return;
            }
            setIsPopupVisible(true);
            window.dispatchEvent(new Event('PHSurveyShown'));
            if (!skipShownEvent) {
                posthog.capture(posthog_surveys_types_1.SurveyEventName.SHOWN, __assign(__assign((_a = {}, _a[posthog_surveys_types_1.SurveyEventProperties.SURVEY_NAME] = survey.name, _a[posthog_surveys_types_1.SurveyEventProperties.SURVEY_ID] = survey.id, _a[posthog_surveys_types_1.SurveyEventProperties.SURVEY_ITERATION] = survey.current_iteration, _a[posthog_surveys_types_1.SurveyEventProperties.SURVEY_ITERATION_START_DATE] = survey.current_iteration_start_date, _a), (surveyLanguage && (_b = {}, _b[posthog_surveys_types_1.SurveyEventProperties.SURVEY_LANGUAGE] = surveyLanguage, _b))), { sessionRecordingUrl: (_c = posthog.get_session_replay_url) === null || _c === void 0 ? void 0 : _c.call(posthog) }));
            }
            localStorage.setItem('lastSeenSurveyDate', new Date().toISOString());
        };
        (0, utils_1.addEventListener)(window, 'PHSurveyClosed', handleSurveyClosed);
        (0, utils_1.addEventListener)(window, 'PHSurveySent', handleSurveySent);
        if (millisecondDelay > 0) {
            // This path is only used for direct usage of SurveyPopup,
            // not for surveys managed by SurveyManager
            var timeoutId_1 = setTimeout(showSurvey, millisecondDelay);
            return function () {
                clearTimeout(timeoutId_1);
                window.removeEventListener('PHSurveyClosed', handleSurveyClosed);
                window.removeEventListener('PHSurveySent', handleSurveySent);
            };
        }
        else {
            // This is the path used for surveys managed by SurveyManager
            showSurvey();
            return function () {
                window.removeEventListener('PHSurveyClosed', handleSurveyClosed);
                window.removeEventListener('PHSurveySent', handleSurveySent);
            };
        }
    }, []);
    useHideSurveyOnURLChange({
        survey: survey,
        removeSurveyFromFocus: removeSurveyFromFocus,
        setSurveyVisible: setIsPopupVisible,
        isPreviewMode: isPreviewMode,
    });
    return { isPopupVisible: isPopupVisible, isSurveySent: isSurveySent, setIsPopupVisible: setIsPopupVisible, hidePopupWithViewTransition: hidePopupWithViewTransition };
}
function getTabPositionStyles(position) {
    if (position === void 0) { position = posthog_surveys_types_1.SurveyTabPosition.Right; }
    switch (position) {
        case posthog_surveys_types_1.SurveyTabPosition.Top:
            return { top: '0', left: '50%', transform: 'translateX(-50%)' };
        case posthog_surveys_types_1.SurveyTabPosition.Left:
            return { top: '50%', left: '0', transform: 'rotate(90deg) translateY(-100%)', transformOrigin: 'left top' };
        case posthog_surveys_types_1.SurveyTabPosition.Bottom: // bottom center
            return { bottom: '0', left: '50%', transform: 'translateX(-50%)' };
        default:
        case posthog_surveys_types_1.SurveyTabPosition.Right:
            // not perfectly centered vertically, to avoid a "breaking" change
            return {
                top: '50%',
                right: '0',
                transform: 'rotate(-90deg) translateY(-100%)',
                transformOrigin: 'right top',
            };
    }
}
function SurveyPopup(_a) {
    var _b, _c, _d, _e, _f, _g;
    var survey = _a.survey, forceDisableHtml = _a.forceDisableHtml, posthog = _a.posthog, _h = _a.style, style = _h === void 0 ? {} : _h, previewPageIndex = _a.previewPageIndex, _j = _a.removeSurveyFromFocus, removeSurveyFromFocus = _j === void 0 ? function () { } : _j, _k = _a.isPopup, isPopup = _k === void 0 ? true : _k, _l = _a.onPreviewSubmit, onPreviewSubmit = _l === void 0 ? function () { } : _l, _m = _a.onPreviewBack, onPreviewBack = _m === void 0 ? function () { } : _m, _o = _a.onPopupSurveyDismissed, onPopupSurveyDismissed = _o === void 0 ? function () { } : _o, _p = _a.onCloseConfirmationMessage, onCloseConfirmationMessage = _p === void 0 ? function () { } : _p, properties = _a.properties, isSurveyCompleted = _a.isSurveyCompleted, skipShownEvent = _a.skipShownEvent, surveyLanguage = _a.surveyLanguage;
    var surveyContainerRef = (0, hooks_1.useRef)(null);
    var isPreviewMode = Number.isInteger(previewPageIndex);
    // NB: The client-side code passes the millisecondDelay in seconds, but setTimeout expects milliseconds, so we multiply by 1000
    var surveyPopupDelayMilliseconds = ((_b = survey.appearance) === null || _b === void 0 ? void 0 : _b.surveyPopupDelaySeconds)
        ? survey.appearance.surveyPopupDelaySeconds * 1000
        : 0;
    var _q = usePopupVisibility(survey, posthog, surveyPopupDelayMilliseconds, isPreviewMode, removeSurveyFromFocus, isPopup, surveyContainerRef, skipShownEvent, surveyLanguage), isPopupVisible = _q.isPopupVisible, isSurveySent = _q.isSurveySent, hidePopupWithViewTransition = _q.hidePopupWithViewTransition;
    /**
     * show confirmation if:
     * 1) isSurveySent is true (completed via normal flow)
     * 2) we're on the preview page for it
     * 3) the target start question (from prefill) is >= the length of the survey
     */
    var shouldShowConfirmation = isSurveySent || previewPageIndex === survey.questions.length || isSurveyCompleted === true;
    var surveyContextValue = (0, hooks_1.useMemo)(function () {
        var getInProgressSurvey = (0, surveys_extension_utils_1.getInProgressSurveyState)(survey);
        var surveySubmissionId = (getInProgressSurvey === null || getInProgressSurvey === void 0 ? void 0 : getInProgressSurvey.surveySubmissionId) || (0, uuidv7_1.uuidv7)();
        return {
            isPreviewMode: isPreviewMode,
            previewPageIndex: previewPageIndex,
            onPopupSurveyDismissed: function () {
                if (surveyLanguage) {
                    (0, surveys_extension_utils_1.dismissedSurveyEvent)(survey, posthog, isPreviewMode, surveyLanguage);
                }
                else {
                    (0, surveys_extension_utils_1.dismissedSurveyEvent)(survey, posthog, isPreviewMode);
                }
                onPopupSurveyDismissed();
            },
            isPopup: isPopup || false,
            surveySubmissionId: surveySubmissionId,
            onPreviewSubmit: onPreviewSubmit,
            onPreviewBack: onPreviewBack,
            posthog: posthog,
            properties: properties,
            surveyLanguage: surveyLanguage,
        };
    }, [
        isPreviewMode,
        previewPageIndex,
        isPopup,
        posthog,
        survey,
        onPopupSurveyDismissed,
        onPreviewSubmit,
        onPreviewBack,
        properties,
        surveyLanguage,
    ]);
    if (!isPopupVisible) {
        return null;
    }
    return ((0, jsx_runtime_1.jsx)(surveys_extension_utils_1.SurveyContext.Provider, { value: surveyContextValue, children: (0, jsx_runtime_1.jsx)("div", { className: "ph-survey", style: __assign(__assign({}, (0, surveys_extension_utils_1.getPopoverPosition)(survey.type, (_c = survey.appearance) === null || _c === void 0 ? void 0 : _c.position, (_d = survey.appearance) === null || _d === void 0 ? void 0 : _d.widgetType)), style), ref: surveyContainerRef, children: !shouldShowConfirmation ? ((0, jsx_runtime_1.jsx)(Questions, { survey: survey, forceDisableHtml: !!forceDisableHtml, posthog: posthog })) : ((0, jsx_runtime_1.jsx)(ConfirmationMessage_1.ConfirmationMessage, { header: ((_e = survey.appearance) === null || _e === void 0 ? void 0 : _e.thankYouMessageHeader) || 'Thank you!', description: ((_f = survey.appearance) === null || _f === void 0 ? void 0 : _f.thankYouMessageDescription) || '', forceDisableHtml: !!forceDisableHtml, contentType: (_g = survey.appearance) === null || _g === void 0 ? void 0 : _g.thankYouMessageDescriptionContentType, appearance: survey.appearance || surveys_extension_utils_1.defaultSurveyAppearance, onClose: function () {
                    hidePopupWithViewTransition();
                    onCloseConfirmationMessage();
                } })) }) }));
}
function Questions(_a) {
    var _b, _c;
    var survey = _a.survey, forceDisableHtml = _a.forceDisableHtml, posthog = _a.posthog;
    // Initialize responses from localStorage or empty object
    var _d = __read((0, hooks_1.useState)(function () {
        var inProgressSurveyData = (0, surveys_extension_utils_1.getInProgressSurveyState)(survey);
        if (inProgressSurveyData === null || inProgressSurveyData === void 0 ? void 0 : inProgressSurveyData.responses) {
            survey_utils_1.SURVEY_LOGGER.info('Survey is already in progress, filling in initial responses');
        }
        return (inProgressSurveyData === null || inProgressSurveyData === void 0 ? void 0 : inProgressSurveyData.responses) || {};
    }), 2), questionsResponses = _d[0], setQuestionsResponses = _d[1];
    var _e = (0, hooks_1.useContext)(surveys_extension_utils_1.SurveyContext), previewPageIndex = _e.previewPageIndex, onPopupSurveyDismissed = _e.onPopupSurveyDismissed, isPopup = _e.isPopup, onPreviewSubmit = _e.onPreviewSubmit, onPreviewBack = _e.onPreviewBack, surveySubmissionId = _e.surveySubmissionId, isPreviewMode = _e.isPreviewMode, properties = _e.properties, surveyLanguage = _e.surveyLanguage;
    var _f = __read((0, hooks_1.useState)(function () {
        var inProgressSurveyData = (0, surveys_extension_utils_1.getInProgressSurveyState)(survey);
        return previewPageIndex || (inProgressSurveyData === null || inProgressSurveyData === void 0 ? void 0 : inProgressSurveyData.lastQuestionIndex) || 0;
    }), 2), currentQuestionIndex = _f[0], setCurrentQuestionIndex = _f[1];
    var _g = __read((0, hooks_1.useState)(function () {
        var _a;
        var inProgressSurveyData = (0, surveys_extension_utils_1.getInProgressSurveyState)(survey);
        return (_a = inProgressSurveyData === null || inProgressSurveyData === void 0 ? void 0 : inProgressSurveyData.visitedIndices) !== null && _a !== void 0 ? _a : [];
    }), 2), visitedIndices = _g[0], setVisitedIndices = _g[1];
    var surveyQuestions = (0, hooks_1.useMemo)(function () { return (0, surveys_extension_utils_1.getDisplayOrderQuestions)(survey); }, [survey]);
    // Sync preview state
    (0, hooks_1.useEffect)(function () {
        if (isPreviewMode && !(0, core_1.isUndefined)(previewPageIndex)) {
            setCurrentQuestionIndex(previewPageIndex);
        }
    }, [previewPageIndex, isPreviewMode]);
    var onNextButtonClick = function (_a) {
        var _b;
        var res = _a.res, displayQuestionIndex = _a.displayQuestionIndex, questionId = _a.questionId;
        if (!posthog) {
            survey_utils_1.SURVEY_LOGGER.error('onNextButtonClick called without a PostHog instance.');
            return;
        }
        if (!questionId) {
            survey_utils_1.SURVEY_LOGGER.error('onNextButtonClick called without a questionId.');
            return;
        }
        var responseKey = (0, surveys_extension_utils_1.getSurveyResponseKey)(questionId);
        var newResponses = __assign(__assign({}, questionsResponses), (_b = {}, _b[responseKey] = res, _b));
        setQuestionsResponses(newResponses);
        var nextStep = (0, survey_branching_1.getNextSurveyStep)(survey, displayQuestionIndex, res);
        var isSurveyCompleted = nextStep === posthog_surveys_types_1.SurveyQuestionBranchingType.End;
        var newVisitedIndices = __spreadArray(__spreadArray([], __read(visitedIndices), false), [displayQuestionIndex], false);
        if (!isSurveyCompleted) {
            setVisitedIndices(newVisitedIndices);
            setCurrentQuestionIndex(nextStep);
            (0, surveys_extension_utils_1.setInProgressSurveyState)(survey, {
                surveySubmissionId: surveySubmissionId,
                responses: newResponses,
                lastQuestionIndex: nextStep,
                visitedIndices: newVisitedIndices,
                surveyLanguage: surveyLanguage,
            });
        }
        // If partial responses are enabled, send the survey sent event with with the responses,
        // otherwise only send the event when the survey is completed
        if (survey.enable_partial_responses || isSurveyCompleted) {
            // Only emit responses for questions actually on the path the user took. This prunes
            // ghost answers from branches the user abandoned by backing up and choosing differently.
            var visitedResponseKeys_1 = new Set(newVisitedIndices
                .map(function (i) { var _a; return (_a = surveyQuestions[i]) === null || _a === void 0 ? void 0 : _a.id; })
                .filter(function (id) { return !!id; })
                .map(function (id) { return (0, surveys_extension_utils_1.getSurveyResponseKey)(id); }));
            var responsesOnPath = Object.fromEntries(Object.entries(newResponses).filter(function (_a) {
                var _b = __read(_a, 1), key = _b[0];
                return visitedResponseKeys_1.has(key);
            }));
            (0, surveys_extension_utils_1.sendSurveyEvent)({
                responses: responsesOnPath,
                survey: survey,
                surveySubmissionId: surveySubmissionId,
                isSurveyCompleted: isSurveyCompleted,
                posthog: posthog,
                properties: properties,
                surveyLanguage: surveyLanguage,
            });
        }
    };
    var onBackButtonClick = function () {
        // In preview mode the parent owns navigation (via previewPageIndex), so delegate to it.
        if (isPreviewMode) {
            onPreviewBack();
            return;
        }
        if (visitedIndices.length === 0) {
            return;
        }
        var previousIndex = visitedIndices[visitedIndices.length - 1];
        var newVisitedIndices = visitedIndices.slice(0, -1);
        setVisitedIndices(newVisitedIndices);
        setCurrentQuestionIndex(previousIndex);
        (0, surveys_extension_utils_1.setInProgressSurveyState)(survey, {
            surveySubmissionId: surveySubmissionId,
            responses: questionsResponses,
            lastQuestionIndex: previousIndex,
            visitedIndices: newVisitedIndices,
            surveyLanguage: surveyLanguage,
        });
    };
    var canGoBack = !!((_b = survey.appearance) === null || _b === void 0 ? void 0 : _b.allowGoBack) && (isPreviewMode ? (previewPageIndex !== null && previewPageIndex !== void 0 ? previewPageIndex : 0) > 0 : visitedIndices.length > 0);
    var currentQuestion = surveyQuestions.at(currentQuestionIndex);
    if (!currentQuestion) {
        return null;
    }
    var renderCancelButton = isPopup && ((_c = survey.appearance) === null || _c === void 0 ? void 0 : _c.hideCancelButton) !== true;
    return ((0, jsx_runtime_1.jsxs)("form", { className: "survey-form", name: "surveyForm", children: [renderCancelButton && ((0, jsx_runtime_1.jsx)(QuestionHeader_1.Cancel, { onClick: function () {
                    onPopupSurveyDismissed();
                } })), (0, jsx_runtime_1.jsx)("div", { className: "survey-box", "data-question-index": currentQuestionIndex, children: getQuestionComponent({
                    question: currentQuestion,
                    forceDisableHtml: forceDisableHtml,
                    displayQuestionIndex: currentQuestionIndex,
                    appearance: survey.appearance || surveys_extension_utils_1.defaultSurveyAppearance,
                    onSubmit: function (res) {
                        return onNextButtonClick({
                            res: res,
                            displayQuestionIndex: currentQuestionIndex,
                            questionId: currentQuestion.id,
                        });
                    },
                    onPreviewSubmit: onPreviewSubmit,
                    initialValue: currentQuestion.id
                        ? questionsResponses[(0, surveys_extension_utils_1.getSurveyResponseKey)(currentQuestion.id)]
                        : undefined,
                    canGoBack: canGoBack,
                    onBack: onBackButtonClick,
                }) })] }));
}
function FeedbackWidget(_a) {
    var _b, _c, _d, _e, _f, _g, _h;
    var survey = _a.survey, forceDisableHtml = _a.forceDisableHtml, posthog = _a.posthog, readOnly = _a.readOnly, surveyLanguage = _a.surveyLanguage;
    var _j = __read((0, hooks_1.useState)(true), 2), isFeedbackButtonVisible = _j[0], setIsFeedbackButtonVisible = _j[1];
    var _k = __read((0, hooks_1.useState)(false), 2), showSurvey = _k[0], setShowSurvey = _k[1];
    var _l = __read((0, hooks_1.useState)({}), 2), styleOverrides = _l[0], setStyleOverrides = _l[1];
    var toggleSurvey = function () {
        setShowSurvey(!showSurvey);
    };
    (0, hooks_1.useEffect)(function () {
        var _a;
        if (!posthog) {
            survey_utils_1.SURVEY_LOGGER.error('FeedbackWidget called without a PostHog instance.');
            return;
        }
        if (readOnly) {
            return;
        }
        if (((_a = survey.appearance) === null || _a === void 0 ? void 0 : _a.widgetType) === 'tab') {
            setStyleOverrides({
                top: '50%',
                bottom: 'auto',
            });
        }
        var handleShowSurvey = function (event) {
            var _a;
            var customEvent = event;
            // Check if the event is for this specific survey instance
            if (((_a = customEvent.detail) === null || _a === void 0 ? void 0 : _a.surveyId) === survey.id) {
                survey_utils_1.SURVEY_LOGGER.info("Received show event for feedback button survey ".concat(survey.id));
                setStyleOverrides(customEvent.detail.position || {});
                toggleSurvey();
            }
        };
        (0, utils_1.addEventListener)(window, DISPATCH_FEEDBACK_WIDGET_EVENT, handleShowSurvey);
        // Cleanup listener on component unmount
        return function () {
            window.removeEventListener(DISPATCH_FEEDBACK_WIDGET_EVENT, handleShowSurvey);
        };
    }, [
        posthog,
        readOnly,
        survey.id,
        (_b = survey.appearance) === null || _b === void 0 ? void 0 : _b.widgetType,
        (_c = survey.appearance) === null || _c === void 0 ? void 0 : _c.widgetSelector,
        (_d = survey.appearance) === null || _d === void 0 ? void 0 : _d.borderColor,
    ]);
    useHideSurveyOnURLChange({
        survey: survey,
        setSurveyVisible: setIsFeedbackButtonVisible,
    });
    if (!isFeedbackButtonVisible) {
        return null;
    }
    var resetShowSurvey = function () {
        // hide the feedback button after answering or closing the survey if it's not always show
        if (survey.schedule !== posthog_surveys_types_1.SurveySchedule.Always) {
            setIsFeedbackButtonVisible(false);
        }
        // important so our view transition has time to run
        setTimeout(function () {
            setShowSurvey(false);
        }, 200);
    };
    return ((0, jsx_runtime_1.jsxs)(preact_2.Fragment, { children: [((_e = survey.appearance) === null || _e === void 0 ? void 0 : _e.widgetType) === 'tab' && ((0, jsx_runtime_1.jsx)("button", { className: "ph-survey-widget-tab ".concat(((_f = survey.appearance) === null || _f === void 0 ? void 0 : _f.tabPosition) === posthog_surveys_types_1.SurveyTabPosition.Top ? 'widget-tab-top' : ''), onClick: toggleSurvey, disabled: readOnly, style: getTabPositionStyles((_g = survey.appearance) === null || _g === void 0 ? void 0 : _g.tabPosition), children: ((_h = survey.appearance) === null || _h === void 0 ? void 0 : _h.widgetLabel) || '' })), showSurvey && ((0, jsx_runtime_1.jsx)(SurveyPopup, { posthog: posthog, survey: survey, forceDisableHtml: forceDisableHtml, style: styleOverrides, onPopupSurveyDismissed: resetShowSurvey, onCloseConfirmationMessage: resetShowSurvey, surveyLanguage: surveyLanguage }))] }));
}
var getQuestionComponent = function (_a) {
    var question = _a.question, forceDisableHtml = _a.forceDisableHtml, displayQuestionIndex = _a.displayQuestionIndex, appearance = _a.appearance, onSubmit = _a.onSubmit, onPreviewSubmit = _a.onPreviewSubmit, initialValue = _a.initialValue, canGoBack = _a.canGoBack, onBack = _a.onBack;
    var baseProps = {
        forceDisableHtml: forceDisableHtml,
        appearance: appearance,
        onPreviewSubmit: function (res) {
            onPreviewSubmit(res);
        },
        onSubmit: function (res) {
            onSubmit(res);
        },
        initialValue: initialValue,
        displayQuestionIndex: displayQuestionIndex,
        canGoBack: canGoBack,
        onBack: onBack,
    };
    switch (question.type) {
        case posthog_surveys_types_1.SurveyQuestionType.Open:
            return (0, preact_1.createElement)(QuestionTypes_1.OpenTextQuestion, __assign({}, baseProps, { question: question, key: question.id }));
        case posthog_surveys_types_1.SurveyQuestionType.Link:
            return (0, preact_1.createElement)(QuestionTypes_1.LinkQuestion, __assign({}, baseProps, { question: question, key: question.id }));
        case posthog_surveys_types_1.SurveyQuestionType.Rating:
            return (0, preact_1.createElement)(QuestionTypes_1.RatingQuestion, __assign({}, baseProps, { question: question, key: question.id }));
        case posthog_surveys_types_1.SurveyQuestionType.SingleChoice:
        case posthog_surveys_types_1.SurveyQuestionType.MultipleChoice:
            return (0, preact_1.createElement)(QuestionTypes_1.MultipleChoiceQuestion, __assign({}, baseProps, { question: question, key: question.id }));
        default:
            survey_utils_1.SURVEY_LOGGER.error("Unsupported question type: ".concat(question.type));
            return null;
    }
};
//# sourceMappingURL=surveys.js.map