"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useDanmuLanes = void 0;
const react_1 = require("react");
const LANE_GAP = 4;
const useDanmuLanes = (laneCount, containerWidth) => {
    const activeDanmu = (0, react_1.useRef)(new Map());
    const lanes = (0, react_1.useRef)(Array.from({ length: laneCount }, (_, i) => ({
        index: i,
        occupiedUntil: 0,
    })));
    const canFitInLane = (0, react_1.useCallback)((laneIndex) => {
        const now = Date.now();
        // find all active danmu in this lane
        const danmuInLane = Array.from(activeDanmu.current.values()).filter((d) => d.lane === laneIndex && d.endTime > now);
        if (danmuInLane.length === 0)
            return true;
        // check the most recent danmu in this lane
        const mostRecent = danmuInLane.reduce((latest, current) => current.startTime > latest.startTime ? current : latest);
        // calculate how far it has traveled
        const elapsed = now - mostRecent.startTime;
        const progress = elapsed / mostRecent.duration;
        const traveled = containerWidth * progress;
        // estimate width (assume ~8px per char, will be updated with actual width later)
        const estimatedWidth = mostRecent.width || 200;
        // check if there's enough space
        const spaceNeeded = estimatedWidth + LANE_GAP;
        const hasSpace = traveled >= spaceNeeded;
        return hasSpace;
    }, [containerWidth]);
    const assignLane = (0, react_1.useCallback)((messageId, duration, width) => {
        const now = Date.now();
        for (const lane of lanes.current) {
            if (canFitInLane(lane.index)) {
                const endTime = now + duration;
                activeDanmu.current.set(messageId, {
                    id: messageId,
                    lane: lane.index,
                    endTime,
                    startTime: now,
                    duration,
                    width,
                });
                return lane.index;
            }
        }
        return null;
    }, [lanes, canFitInLane]);
    const updateDanmuWidth = (0, react_1.useCallback)((messageId, width) => {
        const danmu = activeDanmu.current.get(messageId);
        if (danmu) {
            danmu.width = width;
        }
    }, []);
    const releaseLane = (0, react_1.useCallback)((messageId) => {
        const danmu = activeDanmu.current.get(messageId);
        if (danmu) {
            activeDanmu.current.delete(messageId);
        }
    }, []);
    const cleanup = (0, react_1.useCallback)(() => {
        const now = Date.now();
        for (const [id, danmu] of activeDanmu.current.entries()) {
            if (danmu.endTime <= now) {
                activeDanmu.current.delete(id);
            }
        }
    }, []);
    return {
        assignLane,
        updateDanmuWidth,
        releaseLane,
        cleanup,
    };
};
exports.useDanmuLanes = useDanmuLanes;
//# sourceMappingURL=use-danmu-lanes.js.map