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 __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;
};
import { SurveyQuestionBranchingType, SurveyQuestionType, SurveyType, } from '../posthog-surveys-types';
import { window as _window, document as _document } from '../utils/globals';
import { style, defaultSurveyAppearance, sendSurveyEvent, dismissedSurveyEvent, createShadow, getContrastingTextColor, SurveyContext, getDisplayOrderQuestions, getSurveySeenKey, } from './surveys/surveys-utils';
import * as Preact from 'preact';
import { createWidgetShadow, createWidgetStyle } from './surveys-widget';
import { useState, useEffect, useRef, useContext, useMemo } from 'preact/hooks';
import { isNumber } from '../utils/type-utils';
import { ConfirmationMessage } from './surveys/components/ConfirmationMessage';
import { OpenTextQuestion, LinkQuestion, RatingQuestion, MultipleChoiceQuestion, } from './surveys/components/QuestionTypes';
// We cast the types here which is dangerous but protected by the top level generateSurveys call
var window = _window;
var document = _document;
var handleWidget = function (posthog, survey) {
    var shadow = createWidgetShadow(survey);
    var surveyStyleSheet = style(survey.appearance);
    shadow.appendChild(Object.assign(document.createElement('style'), { innerText: surveyStyleSheet }));
    Preact.render(<FeedbackWidget key={'feedback-survey'} posthog={posthog} survey={survey}/>, shadow);
};
export var callSurveys = function (posthog, forceReload) {
    if (forceReload === void 0) { forceReload = false; }
    posthog === null || posthog === void 0 ? void 0 : posthog.getActiveMatchingSurveys(function (surveys) {
        var nonAPISurveys = surveys.filter(function (survey) { return survey.type !== 'api'; });
        nonAPISurveys.forEach(function (survey) {
            var _a, _b, _c, _d, _e, _f, _g;
            if (survey.type === SurveyType.Widget) {
                if (((_a = survey.appearance) === null || _a === void 0 ? void 0 : _a.widgetType) === 'tab' &&
                    document.querySelectorAll(".PostHogWidget".concat(survey.id)).length === 0) {
                    handleWidget(posthog, survey);
                }
                if (((_b = survey.appearance) === null || _b === void 0 ? void 0 : _b.widgetType) === 'selector' && ((_c = survey.appearance) === null || _c === void 0 ? void 0 : _c.widgetSelector)) {
                    var selectorOnPage = document.querySelector(survey.appearance.widgetSelector);
                    if (selectorOnPage) {
                        if (document.querySelectorAll(".PostHogWidget".concat(survey.id)).length === 0) {
                            handleWidget(posthog, survey);
                        }
                        else if (document.querySelectorAll(".PostHogWidget".concat(survey.id)).length === 1) {
                            // we have to check if user selector already has a survey listener attached to it because we always have to check if it's on the page or not
                            if (!selectorOnPage.getAttribute('PHWidgetSurveyClickListener')) {
                                var surveyPopup_1 = (_e = (_d = document
                                    .querySelector(".PostHogWidget".concat(survey.id))) === null || _d === void 0 ? void 0 : _d.shadowRoot) === null || _e === void 0 ? void 0 : _e.querySelector(".survey-form");
                                selectorOnPage.addEventListener('click', function () {
                                    if (surveyPopup_1) {
                                        surveyPopup_1.style.display =
                                            surveyPopup_1.style.display === 'none' ? 'block' : 'none';
                                        surveyPopup_1.addEventListener('PHSurveyClosed', function () { return (surveyPopup_1.style.display = 'none'); });
                                    }
                                });
                                selectorOnPage.setAttribute('PHWidgetSurveyClickListener', 'true');
                            }
                        }
                    }
                }
            }
            // with event based surveys, we need to show the next survey without reloading the page.
            // A simple check for div elements with the class name pattern of PostHogSurvey_xyz doesn't work here
            // because preact leaves behind the div element for any surveys responded/dismissed with a <style> node.
            // To alleviate this, we check the last div in the dom and see if it has any elements other than a Style node.
            // if the last PostHogSurvey_xyz div has only one style node, we can show the next survey in the queue
            // without reloading the page.
            var surveyPopups = document.querySelectorAll("div[class^=PostHogSurvey]");
            var canShowSurvey = surveyPopups.length > 0
                ? ((_f = surveyPopups[surveyPopups.length - 1].shadowRoot) === null || _f === void 0 ? void 0 : _f.childElementCount) === 1
                : true;
            if (survey.type === SurveyType.Popover && canShowSurvey) {
                var surveyWaitPeriodInDays = (_g = survey.conditions) === null || _g === void 0 ? void 0 : _g.seenSurveyWaitPeriodInDays;
                var lastSeenSurveyDate = localStorage.getItem("lastSeenSurveyDate");
                if (surveyWaitPeriodInDays && lastSeenSurveyDate) {
                    var today = new Date();
                    var diff = Math.abs(today.getTime() - new Date(lastSeenSurveyDate).getTime());
                    var diffDaysFromToday = Math.ceil(diff / (1000 * 3600 * 24));
                    if (diffDaysFromToday < surveyWaitPeriodInDays) {
                        return;
                    }
                }
                if (!localStorage.getItem(getSurveySeenKey(survey))) {
                    var shadow = createShadow(style(survey === null || survey === void 0 ? void 0 : survey.appearance), survey.id);
                    Preact.render(<SurveyPopup key={'popover-survey'} posthog={posthog} survey={survey}/>, shadow);
                }
            }
        });
    }, forceReload);
};
export var renderSurveysPreview = function (_a) {
    var _b, _c;
    var survey = _a.survey, parentElement = _a.parentElement, previewPageIndex = _a.previewPageIndex, forceDisableHtml = _a.forceDisableHtml;
    var surveyStyleSheet = style(survey.appearance);
    var styleElement = Object.assign(document.createElement('style'), { innerText: surveyStyleSheet });
    // Remove previously attached <style>
    Array.from(parentElement.children).forEach(function (child) {
        if (child instanceof HTMLStyleElement) {
            parentElement.removeChild(child);
        }
    });
    parentElement.appendChild(styleElement);
    var textColor = getContrastingTextColor(((_b = survey.appearance) === null || _b === void 0 ? void 0 : _b.backgroundColor) || defaultSurveyAppearance.backgroundColor || 'white');
    Preact.render(<SurveyPopup key="surveys-render-preview" survey={survey} forceDisableHtml={forceDisableHtml} style={{
            position: 'relative',
            right: 0,
            borderBottom: "1px solid ".concat((_c = survey.appearance) === null || _c === void 0 ? void 0 : _c.borderColor),
            borderRadius: 10,
            color: textColor,
        }} previewPageIndex={previewPageIndex}/>, parentElement);
};
export var renderFeedbackWidgetPreview = function (_a) {
    var _b;
    var survey = _a.survey, root = _a.root, forceDisableHtml = _a.forceDisableHtml;
    var widgetStyleSheet = createWidgetStyle((_b = survey.appearance) === null || _b === void 0 ? void 0 : _b.widgetColor);
    var styleElement = Object.assign(document.createElement('style'), { innerText: widgetStyleSheet });
    root.appendChild(styleElement);
    Preact.render(<FeedbackWidget key={'feedback-render-preview'} forceDisableHtml={forceDisableHtml} survey={survey} readOnly={true}/>, root);
};
// This is the main exported function
export function generateSurveys(posthog) {
    // NOTE: Important to ensure we never try and run surveys without a window environment
    if (!document || !window) {
        return;
    }
    callSurveys(posthog, true);
    // recalculate surveys every 3 seconds to check if URL or selectors have changed
    setInterval(function () {
        callSurveys(posthog, false);
    }, 3000);
}
export function SurveyPopup(_a) {
    var _b, _c, _d;
    var survey = _a.survey, forceDisableHtml = _a.forceDisableHtml, posthog = _a.posthog, style = _a.style, previewPageIndex = _a.previewPageIndex;
    var _e = __read(useState(true), 2), isPopupVisible = _e[0], setIsPopupVisible = _e[1];
    var _f = __read(useState(false), 2), isSurveySent = _f[0], setIsSurveySent = _f[1];
    var shouldShowConfirmation = isSurveySent || previewPageIndex === survey.questions.length;
    var isPreviewMode = Number.isInteger(previewPageIndex);
    var confirmationBoxLeftStyle = (style === null || style === void 0 ? void 0 : style.left) && isNumber(style === null || style === void 0 ? void 0 : style.left) ? { left: style.left - 40 } : {};
    // Ensure the popup stays in the same position for the preview
    if (isPreviewMode) {
        style = style || {};
        style.left = 'unset';
        style.right = 'unset';
        style.transform = 'unset';
    }
    useEffect(function () {
        var _a;
        if (isPreviewMode || !posthog) {
            return;
        }
        window.dispatchEvent(new Event('PHSurveyShown'));
        posthog.capture('survey shown', {
            $survey_name: survey.name,
            $survey_id: survey.id,
            $survey_iteration: survey.current_iteration,
            $survey_iteration_start_date: survey.current_iteration_start_date,
            sessionRecordingUrl: (_a = posthog.get_session_replay_url) === null || _a === void 0 ? void 0 : _a.call(posthog),
        });
        localStorage.setItem("lastSeenSurveyDate", new Date().toISOString());
        window.addEventListener('PHSurveyClosed', function () {
            setIsPopupVisible(false);
        });
        window.addEventListener('PHSurveySent', function () {
            var _a, _b;
            if (!((_a = survey.appearance) === null || _a === void 0 ? void 0 : _a.displayThankYouMessage)) {
                return setIsPopupVisible(false);
            }
            setIsSurveySent(true);
            if ((_b = survey.appearance) === null || _b === void 0 ? void 0 : _b.autoDisappear) {
                setTimeout(function () {
                    setIsPopupVisible(false);
                }, 5000);
            }
        });
    }, []);
    return isPopupVisible ? (<SurveyContext.Provider value={{
            isPreviewMode: isPreviewMode,
            previewPageIndex: previewPageIndex,
            handleCloseSurveyPopup: function () { return dismissedSurveyEvent(survey, posthog, isPreviewMode); },
        }}>
            {!shouldShowConfirmation ? (<Questions survey={survey} forceDisableHtml={!!forceDisableHtml} posthog={posthog} styleOverrides={style}/>) : (<ConfirmationMessage header={((_b = survey.appearance) === null || _b === void 0 ? void 0 : _b.thankYouMessageHeader) || 'Thank you!'} description={((_c = survey.appearance) === null || _c === void 0 ? void 0 : _c.thankYouMessageDescription) || ''} forceDisableHtml={!!forceDisableHtml} contentType={(_d = survey.appearance) === null || _d === void 0 ? void 0 : _d.thankYouMessageDescriptionContentType} appearance={survey.appearance || defaultSurveyAppearance} styleOverrides={__assign(__assign({}, style), confirmationBoxLeftStyle)} onClose={function () { return setIsPopupVisible(false); }}/>)}
        </SurveyContext.Provider>) : (<></>);
}
var getQuestionComponent = function (_a) {
    var _b, _c;
    var question = _a.question, forceDisableHtml = _a.forceDisableHtml, displayQuestionIndex = _a.displayQuestionIndex, appearance = _a.appearance, onSubmit = _a.onSubmit;
    var questionComponents = (_b = {},
        _b[SurveyQuestionType.Open] = OpenTextQuestion,
        _b[SurveyQuestionType.Link] = LinkQuestion,
        _b[SurveyQuestionType.Rating] = RatingQuestion,
        _b[SurveyQuestionType.SingleChoice] = MultipleChoiceQuestion,
        _b[SurveyQuestionType.MultipleChoice] = MultipleChoiceQuestion,
        _b);
    var commonProps = {
        question: question,
        forceDisableHtml: forceDisableHtml,
        appearance: appearance,
        onSubmit: onSubmit,
    };
    var additionalProps = (_c = {},
        _c[SurveyQuestionType.Open] = {},
        _c[SurveyQuestionType.Link] = {},
        _c[SurveyQuestionType.Rating] = { displayQuestionIndex: displayQuestionIndex },
        _c[SurveyQuestionType.SingleChoice] = { displayQuestionIndex: displayQuestionIndex },
        _c[SurveyQuestionType.MultipleChoice] = { displayQuestionIndex: displayQuestionIndex },
        _c);
    var Component = questionComponents[question.type];
    var componentProps = __assign(__assign({}, commonProps), additionalProps[question.type]);
    return <Component {...componentProps}/>;
};
export function Questions(_a) {
    var _b, _c;
    var survey = _a.survey, forceDisableHtml = _a.forceDisableHtml, posthog = _a.posthog, styleOverrides = _a.styleOverrides;
    var textColor = getContrastingTextColor(((_b = survey.appearance) === null || _b === void 0 ? void 0 : _b.backgroundColor) || defaultSurveyAppearance.backgroundColor);
    var _d = __read(useState({}), 2), questionsResponses = _d[0], setQuestionsResponses = _d[1];
    var _e = useContext(SurveyContext), isPreviewMode = _e.isPreviewMode, previewPageIndex = _e.previewPageIndex;
    var _f = __read(useState(previewPageIndex || 0), 2), currentQuestionIndex = _f[0], setCurrentQuestionIndex = _f[1];
    var surveyQuestions = useMemo(function () { return getDisplayOrderQuestions(survey); }, [survey]);
    // Sync preview state
    useEffect(function () {
        setCurrentQuestionIndex(previewPageIndex !== null && previewPageIndex !== void 0 ? previewPageIndex : 0);
    }, [previewPageIndex]);
    var onNextButtonClick = function (_a) {
        var _b, _c;
        var res = _a.res, originalQuestionIndex = _a.originalQuestionIndex, displayQuestionIndex = _a.displayQuestionIndex;
        if (!posthog) {
            return;
        }
        var responseKey = originalQuestionIndex === 0 ? "$survey_response" : "$survey_response_".concat(originalQuestionIndex);
        setQuestionsResponses(__assign(__assign({}, questionsResponses), (_b = {}, _b[responseKey] = res, _b)));
        var nextStep = posthog.getNextSurveyStep(survey, displayQuestionIndex, res);
        if (nextStep === SurveyQuestionBranchingType.ConfirmationMessage) {
            sendSurveyEvent(__assign(__assign({}, questionsResponses), (_c = {}, _c[responseKey] = res, _c)), survey, posthog);
        }
        else {
            setCurrentQuestionIndex(nextStep);
        }
    };
    return (<form className="survey-form" style={__assign({ color: textColor, borderColor: (_c = survey.appearance) === null || _c === void 0 ? void 0 : _c.borderColor }, styleOverrides)}>
            {surveyQuestions.map(function (question, displayQuestionIndex) {
            var originalQuestionIndex = question.originalQuestionIndex;
            var isVisible = isPreviewMode
                ? currentQuestionIndex === originalQuestionIndex
                : currentQuestionIndex === displayQuestionIndex;
            return (isVisible && (<div>
                            {getQuestionComponent({
                    question: question,
                    forceDisableHtml: forceDisableHtml,
                    displayQuestionIndex: displayQuestionIndex,
                    appearance: survey.appearance || defaultSurveyAppearance,
                    onSubmit: function (res) {
                        return onNextButtonClick({
                            res: res,
                            originalQuestionIndex: originalQuestionIndex,
                            displayQuestionIndex: displayQuestionIndex,
                        });
                    },
                })}
                        </div>));
        })}
        </form>);
}
export function FeedbackWidget(_a) {
    var _b, _c;
    var survey = _a.survey, forceDisableHtml = _a.forceDisableHtml, posthog = _a.posthog, readOnly = _a.readOnly;
    var _d = __read(useState(false), 2), showSurvey = _d[0], setShowSurvey = _d[1];
    var _e = __read(useState({}), 2), styleOverrides = _e[0], setStyle = _e[1];
    var widgetRef = useRef(null);
    useEffect(function () {
        var _a, _b, _c;
        if (readOnly || !posthog) {
            return;
        }
        if (((_a = survey.appearance) === null || _a === void 0 ? void 0 : _a.widgetType) === 'tab') {
            if (widgetRef.current) {
                var widgetPos = widgetRef.current.getBoundingClientRect();
                var style_1 = {
                    top: '50%',
                    left: parseInt("".concat(widgetPos.right - 360)),
                    bottom: 'auto',
                    borderRadius: 10,
                    borderBottom: "1.5px solid ".concat(((_b = survey.appearance) === null || _b === void 0 ? void 0 : _b.borderColor) || '#c9c6c6'),
                };
                setStyle(style_1);
            }
        }
        if (((_c = survey.appearance) === null || _c === void 0 ? void 0 : _c.widgetType) === 'selector') {
            var widget = document.querySelector(survey.appearance.widgetSelector || '');
            widget === null || widget === void 0 ? void 0 : widget.addEventListener('click', function () {
                setShowSurvey(!showSurvey);
            });
            widget === null || widget === void 0 ? void 0 : widget.setAttribute('PHWidgetSurveyClickListener', 'true');
        }
    }, []);
    return (<>
            {((_b = survey.appearance) === null || _b === void 0 ? void 0 : _b.widgetType) === 'tab' && (<div className="ph-survey-widget-tab" ref={widgetRef} onClick={function () { return !readOnly && setShowSurvey(!showSurvey); }} style={{ color: getContrastingTextColor(survey.appearance.widgetColor) }}>
                    <div className="ph-survey-widget-tab-icon"></div>
                    {((_c = survey.appearance) === null || _c === void 0 ? void 0 : _c.widgetLabel) || ''}
                </div>)}
            {showSurvey && (<SurveyPopup key={'feedback-widget-survey'} posthog={posthog} survey={survey} forceDisableHtml={forceDisableHtml} style={styleOverrides}/>)}
        </>);
}
//# sourceMappingURL=surveys.jsx.map