"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AUTOPLAY_ATTRIBUTES = void 0;
exports.getHeight = getHeight;
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const React = tslib_1.__importStar(require("react"));
const icons_1 = require("@gravity-ui/icons");
const uikit_1 = require("@gravity-ui/uikit");
const debounce_1 = tslib_1.__importDefault(require("lodash/debounce.js"));
const uuid_1 = require("uuid");
const useAnalytics_1 = require("../../gravity-blocks/hooks/useAnalytics.js");
const common_1 = require("../../models/common.js");
const utils_1 = require("../../utils/index.js");
const Image_1 = tslib_1.__importDefault(require("../Image/Image.js"));
const i18n_1 = require("./i18n/index.js");
const RECORD_URL = 'https://www.youtube.com/embed/';
const STREAM_URL = 'https://www.youtube.com/embed/live_stream?channel=';
const RECORD_RE = /[0-9A-Za-z_-]{11}/;
const STREAM_RE = /[0-9A-Za-z_-]{23,25}/;
const AUTOPLAY_DELAY = 300;
exports.AUTOPLAY_ATTRIBUTES = {
    autoplay: 1,
    mute: 1,
};
const NO_AUTOPLAY_ATTRIBUTES = {
    autoplay: 0,
};
const b = (0, utils_1.block)('VideoBlock');
function getYoutubeVideoSrc(stream, record) {
    if (!stream && !record) {
        return null;
    }
    const [videoLink, url, re] = stream
        ? [stream, STREAM_URL, STREAM_RE]
        : [record, RECORD_URL, RECORD_RE];
    const match = videoLink?.match(re);
    let src;
    if (match && match.length) {
        src = url + match[0];
    }
    return src;
}
function getHeight(width) {
    return (width / 16) * 9;
}
const VideoBlock = (props) => {
    const { stream, record, videoIframe, attributes, className, id, previewImg, playButton, playButtonId, height, fullscreen, analyticsEvents, autoplay, onImageLoad, } = props;
    const handleAnalytics = (0, useAnalytics_1.useAnalytics)(common_1.DefaultEventNames.VideoPreview);
    const src = videoIframe ? videoIframe : getYoutubeVideoSrc(stream, record);
    const ref = React.useRef(null);
    const [hidePreview, setHidePreview] = React.useState(false);
    const [currentHeight, setCurrentHeight] = React.useState(height || undefined);
    const fullId = React.useMemo(() => id || (0, uuid_1.v4)(), [id]);
    const buttonId = (0, uikit_1.useUniqId)();
    const [isPlaying, setIsPlaying] = React.useState(!previewImg);
    const iframeSrc = React.useMemo(() => {
        if (src && isPlaying) {
            try {
                const url = new URL(src);
                const searchParams = (0, utils_1.getPageSearchParams)({
                    ...(attributes || {}),
                    ...(previewImg || autoplay ? exports.AUTOPLAY_ATTRIBUTES : NO_AUTOPLAY_ATTRIBUTES),
                });
                searchParams.forEach((value, key) => {
                    url.searchParams.set(key, value);
                });
                return url.href;
            }
            catch {
                return src;
            }
        }
        return undefined;
    }, [attributes, autoplay, isPlaying, previewImg, src]);
    const onPreviewClick = React.useCallback(() => {
        handleAnalytics(analyticsEvents);
        setIsPlaying(true);
        setTimeout(() => setHidePreview(true), AUTOPLAY_DELAY);
    }, [handleAnalytics, analyticsEvents]);
    const { onKeyDown: onPreviewKeyDown } = (0, uikit_1.useActionHandlers)(onPreviewClick);
    React.useEffect(() => {
        const updateSize = (0, debounce_1.default)(() => {
            setCurrentHeight(ref.current ? Math.round(getHeight(ref.current.offsetWidth)) : undefined);
        }, 100);
        updateSize();
        window.addEventListener('resize', updateSize, { passive: true });
        return () => {
            window.removeEventListener('resize', updateSize);
        };
    }, [height]);
    const iframeContent = React.useMemo(() => {
        return ((0, jsx_runtime_1.jsx)("iframe", { id: fullId, src: iframeSrc, width: "100%", height: "100%", title: (0, i18n_1.i18n)('iframe-title'), frameBorder: "0", allowFullScreen: true, scrolling: "no", allow: "autoplay; fullscreen; encrypted-media; accelerometer; gyroscope; picture-in-picture; clipboard-write; web-share; screen-wake-lock", loading: "lazy" }));
    }, [fullId, iframeSrc]);
    React.useEffect(() => {
        setHidePreview(false);
    }, [src]);
    if (!src) {
        return null;
    }
    return ((0, jsx_runtime_1.jsxs)("div", { className: b(null, className), style: { height: currentHeight }, ref: ref, children: [iframeContent, previewImg && !hidePreview && !fullscreen && ((0, jsx_runtime_1.jsxs)("div", { className: b('preview'), onClick: onPreviewClick, onKeyDown: onPreviewKeyDown, role: "button", tabIndex: 0, "aria-labelledby": playButton ? playButtonId : buttonId, children: [(0, jsx_runtime_1.jsx)(Image_1.default, { src: previewImg, className: b('image'), containerClassName: b('image-wrapper'), onLoad: onImageLoad }), playButton || ((0, jsx_runtime_1.jsx)("button", { title: "Play", id: buttonId, className: b('button'), children: (0, jsx_runtime_1.jsx)(uikit_1.Icon, { className: b('icon'), data: icons_1.PlayFill, size: 24 }) }))] }))] }));
};
exports.default = VideoBlock;
//# sourceMappingURL=VideoBlock.js.map
