"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PlayerProvider = void 0;
exports.withPlayerProvider = withPlayerProvider;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const context_1 = require("./context");
const player_store_1 = require("./player-store");
function randomUUID() {
    let dt = new Date().getTime();
    var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
        var r = (dt + Math.random() * 16) % 16 | 0;
        dt = Math.floor(dt / 16);
        return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
    });
    return uuid;
}
const PlayerProvider = ({ children, initialPlayers = [], defaultId = Math.random().toString(36).slice(8), }) => {
    const [players, setPlayers] = (0, react_1.useState)(() => {
        // Initialize with any initial player IDs provided
        const initialPlayerStores = {};
        for (const playerId of initialPlayers) {
            initialPlayerStores[playerId] = (0, player_store_1.makePlayerStore)(playerId);
        }
        // Always create at least one player by default
        if (initialPlayers.length === 0) {
            initialPlayerStores[defaultId] = (0, player_store_1.makePlayerStore)(defaultId);
        }
        return initialPlayerStores;
    });
    const createPlayer = (0, react_1.useCallback)((id) => {
        const playerId = id || randomUUID();
        const playerStore = (0, player_store_1.makePlayerStore)(playerId);
        setPlayers((prev) => ({
            ...prev,
            [playerId]: playerStore,
        }));
        return playerId;
    }, []);
    const removePlayer = (0, react_1.useCallback)((id) => {
        setPlayers((prev) => {
            // Don't remove the last player
            if (Object.keys(prev).length <= 1) {
                console.warn("Cannot remove the last player");
                return prev;
            }
            const newPlayers = { ...prev };
            delete newPlayers[id];
            return newPlayers;
        });
    }, []);
    const contextValue = (0, react_1.useMemo)(() => ({
        players,
        createPlayer,
        removePlayer,
    }), [players, createPlayer, removePlayer]);
    return ((0, jsx_runtime_1.jsx)(context_1.PlayerContext.Provider, { value: contextValue, children: children }));
};
exports.PlayerProvider = PlayerProvider;
// HOC to wrap components that need player context
function withPlayerProvider(Component) {
    return function WithPlayerProvider(props) {
        const { initialPlayers, ...componentProps } = props;
        return ((0, jsx_runtime_1.jsx)(exports.PlayerProvider, { initialPlayers: initialPlayers, children: (0, jsx_runtime_1.jsx)(Component, { ...componentProps }) }));
    };
}
//# sourceMappingURL=player-provider.js.map