"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScrollPlaybackVideo = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const rangeMap_1 = require("../utils/rangeMap");
const ArticleRectContext_1 = require("../provider/ArticleRectContext");
const sdk_1 = require("@cntrl-site/sdk");
const ScrollPlaybackVideo = ({ sectionId, src, playbackParams, style, className }) => {
    const [containerElement, setContainerElement] = (0, react_1.useState)(null);
    const [time, setTime] = (0, react_1.useState)(0);
    const articleRectObserver = (0, react_1.useContext)(ArticleRectContext_1.ArticleRectContext);
    (0, react_1.useEffect)(() => {
        if (!playbackParams || !articleRectObserver)
            return;
        return articleRectObserver.on('scroll', () => {
            const scrollPos = articleRectObserver.getSectionScroll(sectionId);
            const time = (0, rangeMap_1.rangeMap)(scrollPos, playbackParams.from, playbackParams.to, 0, 1, true);
            setTime(toFixed(time));
        });
    }, [playbackParams === null || playbackParams === void 0 ? void 0 : playbackParams.from, playbackParams === null || playbackParams === void 0 ? void 0 : playbackParams.to, time]);
    const scrollVideoManager = (0, react_1.useMemo)(() => {
        if (!containerElement)
            return null;
        const manager = new sdk_1.ScrollPlaybackVideoManager({
            src,
            videoContainer: containerElement
        });
        return manager;
    }, [containerElement, src]);
    (0, react_1.useEffect)(() => {
        return () => {
            scrollVideoManager === null || scrollVideoManager === void 0 ? void 0 : scrollVideoManager.destroy();
        };
    }, [scrollVideoManager]);
    (0, react_1.useEffect)(() => {
        if (scrollVideoManager && time >= 0 && time <= 1) {
            scrollVideoManager.setTargetTimePercent(time);
        }
    }, [time, scrollVideoManager]);
    return (0, jsx_runtime_1.jsx)("div", { className: className, style: style, ref: setContainerElement });
};
exports.ScrollPlaybackVideo = ScrollPlaybackVideo;
function toFixed(num) {
    return Number(num.toFixed(3));
}
