import { _ as __assign, d as __rest } from './bundle-B8Grfnrx.js';
import React__default, { useContext, useCallback, useMemo, useRef, useEffect } from 'react';
import { GroupChannelFilter } from '@sendbird/chat/groupChannel';
import { useGroupChannelList as useGroupChannelList$1, useGroupChannelHandler } from '@sendbird/uikit-tools';
import { U as UserProfileProvider } from './bundle-BYqblmEM.js';
import { u as useOnlineStatus, a as useMarkAsDeliveredScheduler } from './bundle-WsWZ-SJW.js';
import { s as shimExports, u as useStore, c as createStore } from './bundle-C4OmfIXk.js';
import { n as noop } from './bundle-CDcu1I4f.js';
import { u as useSendbird } from './bundle-I25ah_Bv.js';
import { u as useDeepCompareEffect } from './bundle-C5Pz6wMm.js';

var useGroupChannelList = function () {
    var store = useContext(GroupChannelListContext);
    if (!store)
        throw new Error('useGroupChannelList must be used within a GroupChannelListProvider');
    var setGroupChannels = useCallback(function (channels) {
        store.setState(function (state) { return (__assign(__assign({}, state), { groupChannels: channels })); }, true);
    }, []);
    var state = shimExports.useSyncExternalStore(store.subscribe, store.getState);
    var actions = useMemo(function () { return ({
        setGroupChannels: setGroupChannels,
    }); }, [setGroupChannels]);
    return { state: state, actions: actions };
};

var GroupChannelListContext = React__default.createContext(null);
var initialState = {
    className: '',
    selectedChannelUrl: '',
    disableAutoSelect: false,
    allowProfileEdit: false,
    isTypingIndicatorEnabled: false,
    isMessageReceiptStatusEnabled: false,
    onChannelSelect: function () { },
    onChannelCreated: function () { },
    onThemeChange: noop,
    onCreateChannelClick: noop,
    onBeforeCreateChannel: null,
    onUserProfileUpdated: noop,
    typingChannelUrls: [],
    refreshing: false,
    initialized: false,
    groupChannels: [],
    refresh: null,
    loadMore: null,
    scrollRef: { current: null },
};
/**
 * @returns {ReturnType<typeof createStore<GroupChannelListState>>}
 */
var useGroupChannelListStore = function () {
    return useStore(GroupChannelListContext, function (state) { return state; }, initialState);
};
var GroupChannelListManager = function (_a) {
    var _b, _c, _d, _e, _f, _g;
    var _h = _a.className, className = _h === void 0 ? '' : _h, _j = _a.selectedChannelUrl, selectedChannelUrl = _j === void 0 ? '' : _j, _k = _a.disableAutoSelect, disableAutoSelect = _k === void 0 ? false : _k, channelListQueryParams = _a.channelListQueryParams, onThemeChange = _a.onThemeChange, onChannelSelect = _a.onChannelSelect, onChannelCreated = _a.onChannelCreated, onCreateChannelClick = _a.onCreateChannelClick, onBeforeCreateChannel = _a.onBeforeCreateChannel, onUserProfileUpdated = _a.onUserProfileUpdated, props = __rest(_a, ["className", "selectedChannelUrl", "disableAutoSelect", "channelListQueryParams", "onThemeChange", "onChannelSelect", "onChannelCreated", "onCreateChannelClick", "onBeforeCreateChannel", "onUserProfileUpdated"]);
    var sendbirdState = useSendbird().state;
    var config = sendbirdState.config, stores = sendbirdState.stores;
    var _l = useGroupChannelList(), state = _l.state, actions = _l.actions;
    var updateState = useGroupChannelListStore().updateState;
    var sdkStore = stores.sdkStore;
    var sdk = sdkStore.sdk;
    var isConnected = useOnlineStatus(sdk, config.logger);
    var scheduler = useMarkAsDeliveredScheduler({ isConnected: isConnected }, config);
    var scrollRef = useRef(null);
    var channelListDataSource = useGroupChannelList$1(sdk, {
        collectionCreator: getCollectionCreator(sdk, channelListQueryParams),
        markAsDelivered: function (channels) { return channels.forEach(scheduler.push); },
        onChannelsDeleted: function (channelUrls) {
            channelUrls.forEach(function (url) {
                if (url === selectedChannelUrl)
                    onChannelSelect(null);
            });
        },
        onChannelsUpdated: function () {
            actions.setGroupChannels(groupChannels);
        },
    });
    var refreshing = channelListDataSource.refreshing, initialized = channelListDataSource.initialized, groupChannels = channelListDataSource.groupChannels, refresh = channelListDataSource.refresh, loadMore = channelListDataSource.loadMore;
    // SideEffect: Auto select channel
    useEffect(function () {
        var _a;
        if (!disableAutoSelect && stores.sdkStore.initialized && initialized) {
            if (!selectedChannelUrl)
                onChannelSelect((_a = groupChannels[0]) !== null && _a !== void 0 ? _a : null);
        }
    }, [disableAutoSelect, stores.sdkStore.initialized, initialized, selectedChannelUrl]);
    // Recreates the GroupChannelCollection when `channelListQueryParams` change
    useEffect(function () {
        refresh === null || refresh === void 0 ? void 0 : refresh();
    }, [
        Object.keys(channelListQueryParams !== null && channelListQueryParams !== void 0 ? channelListQueryParams : {}).sort()
            .map(function (key) { return "".concat(key, "=").concat(encodeURIComponent(JSON.stringify(channelListQueryParams[key]))); })
            .join('&'),
    ]);
    var typingChannelUrls = state.typingChannelUrls;
    useGroupChannelHandler(sdk, {
        onTypingStatusUpdated: function (channel) {
            var _a;
            var channelList = typingChannelUrls.filter(function (channelUrl) { return channelUrl !== channel.url; });
            if (((_a = channel.getTypingUsers()) === null || _a === void 0 ? void 0 : _a.length) > 0) {
                updateState({
                    typingChannelUrls: (channelList.concat(channel.url)),
                });
            }
            else {
                updateState({
                    typingChannelUrls: (channelList),
                });
            }
        },
    });
    var allowProfileEdit = (_c = (_b = props.allowProfileEdit) !== null && _b !== void 0 ? _b : config.allowProfileEdit) !== null && _c !== void 0 ? _c : true;
    var isTypingIndicatorEnabled = (_e = (_d = props.isTypingIndicatorEnabled) !== null && _d !== void 0 ? _d : config.groupChannelList.enableTypingIndicator) !== null && _e !== void 0 ? _e : false;
    var isMessageReceiptStatusEnabled = (_g = (_f = props.isMessageReceiptStatusEnabled) !== null && _f !== void 0 ? _f : config.groupChannelList.enableMessageReceiptStatus) !== null && _g !== void 0 ? _g : false;
    var eventHandlers = useMemo(function () { return ({
        onChannelSelect: onChannelSelect,
        onChannelCreated: onChannelCreated,
        onThemeChange: onThemeChange,
        onCreateChannelClick: onCreateChannelClick,
        onBeforeCreateChannel: onBeforeCreateChannel,
        onUserProfileUpdated: onUserProfileUpdated,
    }); }, [
        onChannelSelect,
        onChannelCreated,
        onThemeChange,
        onCreateChannelClick,
        onBeforeCreateChannel,
        onUserProfileUpdated,
    ]);
    var configurations = useMemo(function () { return ({
        className: className,
        selectedChannelUrl: selectedChannelUrl,
        disableAutoSelect: disableAutoSelect,
        allowProfileEdit: allowProfileEdit,
        isTypingIndicatorEnabled: isTypingIndicatorEnabled,
        isMessageReceiptStatusEnabled: isMessageReceiptStatusEnabled,
        typingChannelUrls: typingChannelUrls,
        refreshing: refreshing,
        initialized: initialized,
        refresh: refresh,
        loadMore: loadMore,
    }); }, [
        className,
        selectedChannelUrl,
        disableAutoSelect,
        allowProfileEdit,
        isTypingIndicatorEnabled,
        isMessageReceiptStatusEnabled,
        typingChannelUrls,
        refreshing,
        initialized,
        scrollRef,
    ]);
    useDeepCompareEffect(function () {
        updateState(__assign(__assign(__assign({}, eventHandlers), configurations), { groupChannels: groupChannels }));
    }, [
        configurations,
        eventHandlers,
        groupChannels.map(function (groupChannel) { return groupChannel.serialize(); }),
    ]);
    return null;
};
var createGroupChannelListStore = function () { return createStore(initialState); };
var InternalGroupChannelListProvider = function (_a) {
    var children = _a.children;
    var storeRef = useRef(createGroupChannelListStore());
    return (React__default.createElement(GroupChannelListContext.Provider, { value: storeRef.current }, children));
};
var GroupChannelListProvider = function (props) {
    var children = props.children, className = props.className;
    return (React__default.createElement(InternalGroupChannelListProvider, null,
        React__default.createElement(GroupChannelListManager, __assign({}, props)),
        React__default.createElement(UserProfileProvider, __assign({}, props),
            React__default.createElement("div", { className: "sendbird-channel-list ".concat(className) }, children))));
};
// Keep this function for backward compatibility.
var useGroupChannelListContext = function () {
    var _a = useGroupChannelList(), state = _a.state, actions = _a.actions;
    return __assign(__assign({}, state), actions);
};
function getCollectionCreator(sdk, channelListQueryParams) {
    return function (defaultParams) {
        var params = __assign(__assign({}, defaultParams), channelListQueryParams);
        return sdk.groupChannel.createGroupChannelCollection(__assign(__assign({}, params), { filter: new GroupChannelFilter(params) }));
    };
}

export { GroupChannelListContext as G, useGroupChannelListStore as a, GroupChannelListManager as b, GroupChannelListProvider as c, useGroupChannelListContext as d, useGroupChannelList as u };
//# sourceMappingURL=bundle-Bc6hXWJF.js.map
