import { a as __spreadArray, b as __awaiter, c as __generator, _ as __assign } from './bundle-B8Grfnrx.js';
import { u as useStore, c as createStore, s as shimExports } from './bundle-C4OmfIXk.js';
import React__default, { useEffect, createContext, useState, useCallback, useRef, useContext, useMemo } from 'react';
import { GroupChannelHandler } from '@sendbird/chat/groupChannel';
import { u as uuidv4 } from './bundle-CTkGIdt8.js';
import { c as compareIds } from './bundle-Djq12iSf.js';
import { c as classnames } from './bundle-CDcu1I4f.js';
import { U as UserProfileProvider } from './bundle-BYqblmEM.js';
import { u as useSendbird } from './bundle-I25ah_Bv.js';

function useSetChannel(_a) {
    var _this = this;
    var channelUrl = _a.channelUrl, sdk = _a.sdk, logger = _a.logger, initialized = _a.initialized, _b = _a.dependencies, dependencies = _b === void 0 ? [] : _b;
    var _c = useChannelSettings().actions, setChannel = _c.setChannel, setInvalid = _c.setInvalid, setLoading = _c.setLoading;
    useEffect(function () {
        var controller = new AbortController();
        var signal = controller.signal;
        var fetchChannel = function () { return __awaiter(_this, void 0, void 0, function () {
            var groupChannel, error_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, 3, 4]);
                        if (!channelUrl) {
                            logger.warning('ChannelSettings: channel url is required');
                            setLoading(false);
                            return [2 /*return*/];
                        }
                        if (!initialized || !sdk) {
                            logger.warning('ChannelSettings: SDK is not initialized');
                            setLoading(false);
                            return [2 /*return*/];
                        }
                        if (!sdk.groupChannel) {
                            logger.warning('ChannelSettings: GroupChannelModule is not specified in the SDK');
                            setLoading(false);
                            return [2 /*return*/];
                        }
                        setLoading(true);
                        return [4 /*yield*/, sdk.groupChannel.getChannel(channelUrl)];
                    case 1:
                        groupChannel = _a.sent();
                        if (!signal.aborted) {
                            logger.info('ChannelSettings | useSetChannel: fetched group channel', groupChannel);
                            setChannel(groupChannel);
                        }
                        return [3 /*break*/, 4];
                    case 2:
                        error_1 = _a.sent();
                        if (!signal.aborted) {
                            logger.error('ChannelSettings | useSetChannel: failed fetching channel', error_1);
                            setInvalid(true);
                        }
                        return [3 /*break*/, 4];
                    case 3:
                        if (!signal.aborted) {
                            setLoading(false);
                        }
                        return [7 /*endfinally*/];
                    case 4: return [2 /*return*/];
                }
            });
        }); };
        fetchChannel();
        return function () { return controller.abort(); }; // Cleanup with AbortController
    }, __spreadArray([channelUrl, initialized, sdk], dependencies, true));
}

var useChannelHandler = function (_a) {
    var sdk = _a.sdk, channelUrl = _a.channelUrl, logger = _a.logger, forceUpdateUI = _a.forceUpdateUI, _b = _a.dependencies, dependencies = _b === void 0 ? [] : _b;
    useEffect(function () {
        if (!sdk || !sdk.groupChannel) {
            logger.warning('ChannelSettings: SDK or GroupChannelModule is not available');
            return;
        }
        var newChannelHandlerId = uuidv4();
        var channelHandler = new GroupChannelHandler({
            onUserLeft: function (channel, user) {
                if (compareIds(channel === null || channel === void 0 ? void 0 : channel.url, channelUrl)) {
                    logger.info('ChannelSettings: onUserLeft', { channel: channel, user: user });
                    forceUpdateUI();
                }
            },
            onUserBanned: function (channel, user) {
                if (compareIds(channel === null || channel === void 0 ? void 0 : channel.url, channelUrl) && channel.isGroupChannel()) {
                    logger.info('ChannelSettings: onUserBanned', { channel: channel, user: user });
                    forceUpdateUI();
                }
            },
        });
        sdk.groupChannel.addGroupChannelHandler(newChannelHandlerId, channelHandler);
        return function () {
            if (sdk.groupChannel && newChannelHandlerId) {
                logger.info('ChannelSettings: Removing message receiver handler', newChannelHandlerId);
                sdk.groupChannel.removeGroupChannelHandler(newChannelHandlerId);
            }
        };
    }, __spreadArray([sdk, channelUrl, logger], dependencies, true));
    return null;
};

var ChannelSettingsContext = createContext(null);
var initialState = {
    // Props
    channelUrl: '',
    onCloseClick: undefined,
    onLeaveChannel: undefined,
    onChannelModified: undefined,
    onBeforeUpdateChannel: undefined,
    renderUserListItem: undefined,
    queries: {},
    overrideInviteUser: undefined,
    // Managed states
    channel: null,
    loading: false,
    invalidChannel: false,
    forceUpdateUI: function () { },
    setChannelUpdateId: function () { },
};
/**
 * @returns {ReturnType<typeof createStore<ChannelSettingsState>>}
 */
var useChannelSettingsStore = function () {
    return useStore(ChannelSettingsContext, function (state) { return state; }, initialState);
};
var ChannelSettingsManager = function (_a) {
    var _b;
    var channelUrl = _a.channelUrl, onCloseClick = _a.onCloseClick, onLeaveChannel = _a.onLeaveChannel, onChannelModified = _a.onChannelModified, overrideInviteUser = _a.overrideInviteUser, onBeforeUpdateChannel = _a.onBeforeUpdateChannel, queries = _a.queries, renderUserListItem = _a.renderUserListItem;
    var state = useSendbird().state;
    var config = state.config, stores = state.stores;
    var updateState = useChannelSettingsStore().updateState;
    var logger = config.logger;
    var _c = (_b = stores === null || stores === void 0 ? void 0 : stores.sdkStore) !== null && _b !== void 0 ? _b : {}, sdk = _c.sdk, initialized = _c.initialized;
    var _d = useState(function () { return uuidv4(); }), channelUpdateId = _d[0], setChannelUpdateId = _d[1];
    var forceUpdateUI = useCallback(function () { return setChannelUpdateId(uuidv4()); }, []);
    var dependencies = [channelUpdateId];
    useSetChannel({
        channelUrl: channelUrl,
        sdk: sdk,
        logger: logger,
        initialized: initialized,
        dependencies: dependencies,
    });
    useChannelHandler({
        sdk: sdk,
        channelUrl: channelUrl,
        logger: logger,
        forceUpdateUI: forceUpdateUI,
        dependencies: dependencies,
    });
    useEffect(function () {
        updateState({
            channelUrl: channelUrl,
            onCloseClick: onCloseClick,
            onLeaveChannel: onLeaveChannel,
            onChannelModified: onChannelModified,
            onBeforeUpdateChannel: onBeforeUpdateChannel,
            renderUserListItem: renderUserListItem,
            queries: queries,
            overrideInviteUser: overrideInviteUser,
            forceUpdateUI: forceUpdateUI,
            setChannelUpdateId: setChannelUpdateId,
        });
    }, [
        channelUrl,
        onCloseClick,
        onLeaveChannel,
        onChannelModified,
        onBeforeUpdateChannel,
        renderUserListItem,
        queries,
        overrideInviteUser,
        forceUpdateUI,
    ]);
    return null;
};
var createChannelSettingsStore = function () { return createStore(initialState); };
var InternalChannelSettingsProvider = function (_a) {
    var children = _a.children;
    var storeRef = useRef(createChannelSettingsStore());
    return (React__default.createElement(ChannelSettingsContext.Provider, { value: storeRef.current }, children));
};
var ChannelSettingsProvider = function (props) {
    var children = props.children, className = props.className;
    return (React__default.createElement(InternalChannelSettingsProvider, null,
        React__default.createElement(ChannelSettingsManager, __assign({}, props)),
        React__default.createElement(UserProfileProvider, __assign({}, props),
            React__default.createElement("div", { className: classnames('sendbird-channel-settings', className) }, children))));
};
var useChannelSettingsContext = function () {
    var _a = useChannelSettings(), state = _a.state, actions = _a.actions;
    return __assign(__assign({}, state), actions);
};

var useChannelSettings = function () {
    var store = useContext(ChannelSettingsContext);
    if (!store)
        throw new Error('useChannelSettings must be used within a ChannelSettingsProvider');
    var state = shimExports.useSyncExternalStore(store.subscribe, store.getState);
    var actions = useMemo(function () { return ({
        setChannel: function (channel) { return store.setState(function (state) { return (__assign(__assign({}, state), { channel: channel })); }); },
        setLoading: function (loading) { return store.setState(function (state) { return (__assign(__assign({}, state), { loading: loading })); }); },
        setInvalid: function (invalid) { return store.setState(function (state) { return (__assign(__assign({}, state), { invalidChannel: invalid })); }); },
    }); }, [store]);
    return { state: state, actions: actions };
};

export { ChannelSettingsProvider as C, useChannelSettings as a, useChannelSettingsContext as u };
//# sourceMappingURL=bundle-BkZBhjs8.js.map
