"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RenderPeritext = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const Chrome_1 = require("./Chrome");
const context_1 = require("./context");
const sync_store_1 = require("../../../util/events/sync-store");
const RenderPeritext = ({ ctx, children }) => {
    const value = React.useMemo(() => ({
        ctx,
        score: new sync_store_1.ValueSyncStore(0),
        scoreDelta: new sync_store_1.ValueSyncStore(0),
        lastVisScore: new sync_store_1.ValueSyncStore(0),
    }), [ctx]);
    React.useEffect(() => {
        const dom = ctx?.dom;
        if (!dom || !value)
            return;
        let lastNow = 0;
        const listener = (event) => {
            const now = Date.now();
            const timeDiff = now - lastNow;
            let delta = 0;
            switch (event.detail.ev?.type) {
                case 'delete':
                case 'insert':
                case 'format':
                case 'marker': {
                    delta = timeDiff < 30 ? 10 : timeDiff < 70 ? 5 : timeDiff < 150 ? 2 : timeDiff <= 1000 ? 1 : -1;
                    break;
                }
                default: {
                    delta = timeDiff <= 1000 ? 0 : -1;
                    break;
                }
            }
            if (delta)
                value.score.next(delta >= 0 ? value.score.value + delta : 0);
            value.scoreDelta.next(delta);
            lastNow = now;
        };
        dom.et.addEventListener('change', listener);
        return () => {
            dom.et.removeEventListener('change', listener);
        };
    }, [ctx?.dom, value]);
    return (React.createElement(context_1.context.Provider, { value: value },
        React.createElement(Chrome_1.Chrome, null, children)));
};
exports.RenderPeritext = RenderPeritext;
//# sourceMappingURL=RenderPeritext.js.map