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 { SurveyQuestionType, SurveyType } from '../posthog-surveys-types';
import { window as _window, document as _document } from '../utils/globals';
import { style, defaultSurveyAppearance, sendSurveyEvent, createShadow, getContrastingTextColor, SurveyContext, getDisplayOrderQuestions, } 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("seenSurvey_".concat(survey.id))) {
                    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 (survey, parentElement, previewPageIndex) {
    var _a, _b;
    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(((_a = survey.appearance) === null || _a === void 0 ? void 0 : _a.backgroundColor) || defaultSurveyAppearance.backgroundColor || 'white');
    Preact.render(<SurveyPopup key="surveys-render-preview" survey={survey} style={{
            position: 'relative',
            right: 0,
            borderBottom: "1px solid ".concat((_b = survey.appearance) === null || _b === void 0 ? void 0 : _b.borderColor),
            borderRadius: 10,
            color: textColor,
        }} previewPageIndex={previewPageIndex}/>, parentElement);
};
export var renderFeedbackWidgetPreview = function (survey, root) {
    var _a;
    var widgetStyleSheet = createWidgetStyle((_a = survey.appearance) === null || _a === void 0 ? void 0 : _a.widgetColor);
    var styleElement = Object.assign(document.createElement('style'), { innerText: widgetStyleSheet });
    root.appendChild(styleElement);
    Preact.render(<FeedbackWidget key={'feedback-render-preview'} 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;
    var survey = _a.survey, posthog = _a.posthog, style = _a.style, previewPageIndex = _a.previewPageIndex;
    var _d = __read(useState(true), 2), isPopupVisible = _d[0], setIsPopupVisible = _d[1];
    var _e = __read(useState(false), 2), isSurveySent = _e[0], setIsSurveySent = _e[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,
            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 closeSurveyPopup(survey, posthog, isPreviewMode); },
        }}>
            {!shouldShowConfirmation ? (<Questions survey={survey} 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) || ''} 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, 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,
        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, 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;
        var isLastDisplayedQuestion = displayQuestionIndex === survey.questions.length - 1;
        var responseKey = originalQuestionIndex === 0 ? "$survey_response" : "$survey_response_".concat(originalQuestionIndex);
        if (isLastDisplayedQuestion) {
            return sendSurveyEvent(__assign(__assign({}, questionsResponses), (_b = {}, _b[responseKey] = res, _b)), survey, posthog);
        }
        else {
            setQuestionsResponses(__assign(__assign({}, questionsResponses), (_c = {}, _c[responseKey] = res, _c)));
            setCurrentQuestionIndex(displayQuestionIndex + 1);
        }
    };
    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,
                    displayQuestionIndex: displayQuestionIndex,
                    appearance: survey.appearance || defaultSurveyAppearance,
                    onSubmit: function (res) {
                        return onNextButtonClick({
                            res: res,
                            originalQuestionIndex: originalQuestionIndex,
                            displayQuestionIndex: displayQuestionIndex,
                        });
                    },
                })}
                        </div>));
        })}
        </form>);
}
var closeSurveyPopup = function (survey, posthog, isPreviewMode) {
    var _a;
    var _b;
    if (isPreviewMode || !posthog) {
        return;
    }
    posthog.capture('survey dismissed', {
        $survey_name: survey.name,
        $survey_id: survey.id,
        sessionRecordingUrl: (_b = posthog.get_session_replay_url) === null || _b === void 0 ? void 0 : _b.call(posthog),
        $set: (_a = {},
            _a["$survey_dismissed/".concat(survey.id)] = true,
            _a),
    });
    localStorage.setItem("seenSurvey_".concat(survey.id), 'true');
    window.dispatchEvent(new Event('PHSurveyClosed'));
};
export function FeedbackWidget(_a) {
    var _b, _c;
    var survey = _a.survey, 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} style={styleOverrides}/>)}
        </>);
}
//# sourceMappingURL=surveys.jsx.map