"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.YANDEX_FORM_SECTION = exports.YANDEX_FORM_ORIGIN = void 0;
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const React = tslib_1.__importStar(require("react"));
const localeContext_1 = require("../../context/localeContext/index.js");
const mobileContext_1 = require("../../context/mobileContext/index.js");
const hooks_1 = require("../../hooks/index.js");
const common_1 = require("../../models/common.js");
const utils_1 = require("../../utils/index.js");
const constants_1 = require("../constants.js");
exports.YANDEX_FORM_ORIGIN = 'https://forms.yandex.ru';
exports.YANDEX_FORM_SECTION = 'surveys';
const CONTAINER_ID = 'pc-yandex-form-container';
const b = (0, utils_1.block)('yandex-form');
const YandexForm = (props) => {
    const { onLoad, id, params, className, theme, containerId = CONTAINER_ID, headerHeight = constants_1.HEADER_HEIGHT, onSubmit, analyticsEvents, customFormOrigin, customFormSection, } = props;
    const formContainerRef = React.useRef(null);
    const iframeRef = React.useRef();
    const yaFormOrigin = customFormOrigin || exports.YANDEX_FORM_ORIGIN;
    const yaFormSection = customFormSection || exports.YANDEX_FORM_SECTION;
    const handleAnalytics = (0, hooks_1.useAnalytics)(common_1.DefaultEventNames.YandexFormSubmit);
    const isMobile = React.useContext(mobileContext_1.MobileContext);
    const locale = React.useContext(localeContext_1.LocaleContext);
    const updateFormIframe = React.useCallback((container) => {
        const queryParams = new URLSearchParams(location.search);
        const url = location.origin + location.pathname;
        queryParams.set('url', url);
        queryParams.set('iframe', '1');
        if (locale?.lang) {
            queryParams.set('lang', locale.lang);
        }
        queryParams.set('theme', theme || 'cloud-www');
        if (isMobile) {
            queryParams.set('media-type', 'mobile');
        }
        if (params) {
            Object.keys(params).forEach((param) => {
                queryParams.set(param, params[param]);
            });
        }
        const src = `${yaFormOrigin}/${yaFormSection}/${id}/?${queryParams}`;
        if (iframeRef.current) {
            iframeRef.current.src = src;
        }
        else {
            iframeRef.current = document.createElement('iframe');
            iframeRef.current.src = src;
            iframeRef.current.id = containerId;
            iframeRef.current.name = `form${id}`;
            iframeRef.current.setAttribute('loading', 'lazy');
            iframeRef.current.frameBorder = '0';
            iframeRef.current.scrolling = 'no';
            iframeRef.current.width = '100%';
            container.appendChild(iframeRef.current);
        }
    }, [locale.lang, theme, isMobile, yaFormOrigin, yaFormSection, id, containerId, params]);
    const handleSubmit = React.useCallback(() => {
        if (formContainerRef && formContainerRef.current) {
            const { top } = formContainerRef.current.getBoundingClientRect();
            window.scrollBy(0, top - headerHeight);
        }
        handleAnalytics(analyticsEvents);
        if (onSubmit) {
            onSubmit();
        }
    }, [handleAnalytics, analyticsEvents, onSubmit, headerHeight]);
    const handleMessage = React.useCallback(({ origin, data }) => {
        if (origin !== yaFormOrigin) {
            return;
        }
        try {
            const parsed = JSON.parse(data);
            const height = parsed['iframe-height'];
            const { message, name, redirectUrl } = parsed;
            if (name !== `form${id}`) {
                return;
            }
            if (iframeRef.current && height && !message) {
                iframeRef.current.height = `${height}px`;
                onLoad?.();
            }
            if (message === 'sent' || redirectUrl) {
                // event with redirectUrl is comming when form with redirect is used
                // otherwise, message: 'sent' is not comming on such sort of forms
                // to catch this event and handle analytics redirectUrl is added to condition
                handleSubmit();
            }
        }
        catch (error) {
            return;
        }
    }, [yaFormOrigin, id, onLoad, handleSubmit]);
    const addIframe = React.useCallback(() => {
        const container = formContainerRef.current;
        if (container) {
            updateFormIframe(container);
            window.addEventListener('message', handleMessage, { passive: true });
        }
    }, [updateFormIframe, handleMessage]);
    React.useEffect(() => {
        addIframe();
        // Crunch for mobile chrome in lite mode
        // https://support.google.com/chrome/answer/2392284?co=GENIE.Platform%3DAndroid&oco=1
        setTimeout(() => onLoad?.(), 1000);
        return () => window.removeEventListener('message', handleMessage);
    }, [id, addIframe, handleMessage, onLoad]);
    return (0, jsx_runtime_1.jsx)("div", { ref: formContainerRef, className: b(null, className) });
};
exports.default = YandexForm;
//# sourceMappingURL=YandexForm.js.map
