'use strict';

var React = require('react');
var useSendbirdStateContext = require('../useSendbirdStateContext.js');
var LocalizationContext = require('./bundle-6SzyBwQ5.js');
var ChannelList_context = require('./bundle-zGSEOOdl.js');
var ui_MessageStatus = require('./bundle-Pzvqu5yR.js');
var _tslib = require('./bundle-DhtZdKsr.js');
var groupChannel = require('@sendbird/chat/groupChannel');
var uikitTools = require('@sendbird/uikit-tools');
var UserProfileContext = require('./bundle-TPy0gj60.js');
var useMarkAsDeliveredScheduler = require('./bundle-fzSiKesI.js');
var utils = require('./bundle-Y-_KhZFq.js');
var useLongPress = require('./bundle-2hJhRu5W.js');
var MediaQueryContext = require('./bundle-6zBNmPOP.js');
var index = require('./bundle-nox41MG6.js');
var TypingIndicator = require('./bundle-5UyAossc.js');
var ui_Badge = require('../ui/Badge.js');
var ui_ChannelAvatar = require('../ui/ChannelAvatar.js');
var ui_Icon = require('../ui/Icon.js');
var ui_Label = require('./bundle-VxcYXhwp.js');
var ui_MentionUserLabel = require('../ui/MentionUserLabel.js');
var ui_Modal = require('./bundle-6L4HCLmb.js');
var ui_TextButton = require('../ui/TextButton.js');

var GroupChannelListContext = React.createContext(null);
var GroupChannelListProvider = function (props) {
    var 
    // Default
    children = props.children, _a = props.className, className = _a === void 0 ? '' : _a, selectedChannelUrl = props.selectedChannelUrl, 
    // Flags
    _b = props.allowProfileEdit, 
    // Flags
    allowProfileEdit = _b === void 0 ? true : _b, _c = props.disableAutoSelect, disableAutoSelect = _c === void 0 ? false : _c, _d = props.isTypingIndicatorEnabled, isTypingIndicatorEnabled = _d === void 0 ? false : _d, _e = props.isMessageReceiptStatusEnabled, isMessageReceiptStatusEnabled = _e === void 0 ? false : _e, 
    // Custom
    channelListQueryParams = props.channelListQueryParams, onThemeChange = props.onThemeChange, _f = props.onChannelSelect, onChannelSelect = _f === void 0 ? utils.noop : _f, _g = props.onChannelCreated, onChannelCreated = _g === void 0 ? utils.noop : _g, onCreateChannelClick = props.onCreateChannelClick, onBeforeCreateChannel = props.onBeforeCreateChannel, onUserProfileUpdated = props.onUserProfileUpdated, 
    // UserProfile
    disableUserProfile = props.disableUserProfile, renderUserProfile = props.renderUserProfile, onUserProfileMessage = props.onUserProfileMessage;
    var globalStore = useSendbirdStateContext.useSendbirdStateContext();
    var config = globalStore.config, stores = globalStore.stores;
    var sdkStore = stores.sdkStore;
    var _h = config.isTypingIndicatorEnabledOnChannelList, isTypingIndicatorEnabledOnChannelList = _h === void 0 ? false : _h, _j = config.isMessageReceiptStatusEnabledOnChannelList, isMessageReceiptStatusEnabledOnChannelList = _j === void 0 ? false : _j;
    var sdk = sdkStore.sdk;
    var isConnected = useMarkAsDeliveredScheduler.useOnlineStatus(sdk, config.logger);
    var scheduler = useMarkAsDeliveredScheduler.useMarkAsDeliveredScheduler({ isConnected: isConnected }, config);
    var channelListDataSource = uikitTools.useGroupChannelList(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);
            });
        },
    });
    var refreshing = channelListDataSource.refreshing, initialized = channelListDataSource.initialized, groupChannels = channelListDataSource.groupChannels, refresh = channelListDataSource.refresh, loadMore = channelListDataSource.loadMore;
    // SideEffect: Auto select channel
    React.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]);
    var _k = React.useState([]), typingChannelUrls = _k[0], setTypingChannelUrls = _k[1];
    uikitTools.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) {
                setTypingChannelUrls(channelList.concat(channel.url));
            }
            else {
                setTypingChannelUrls(channelList);
            }
        },
    });
    return (React.createElement(GroupChannelListContext.Provider, { value: {
            // Default
            className: className,
            selectedChannelUrl: selectedChannelUrl,
            // Flags
            allowProfileEdit: allowProfileEdit !== null && allowProfileEdit !== void 0 ? allowProfileEdit : config === null || config === void 0 ? void 0 : config.allowProfileEdit,
            disableAutoSelect: disableAutoSelect,
            isTypingIndicatorEnabled: isTypingIndicatorEnabled !== null && isTypingIndicatorEnabled !== void 0 ? isTypingIndicatorEnabled : isTypingIndicatorEnabledOnChannelList,
            isMessageReceiptStatusEnabled: isMessageReceiptStatusEnabled !== null && isMessageReceiptStatusEnabled !== void 0 ? isMessageReceiptStatusEnabled : isMessageReceiptStatusEnabledOnChannelList,
            // Essential
            onChannelSelect: onChannelSelect,
            onChannelCreated: onChannelCreated,
            // Partial props
            onThemeChange: onThemeChange,
            onCreateChannelClick: onCreateChannelClick,
            onBeforeCreateChannel: onBeforeCreateChannel,
            onUserProfileUpdated: onUserProfileUpdated,
            // Internal
            typingChannelUrls: typingChannelUrls,
            // ReturnType<UseGroupChannelList>
            refreshing: refreshing,
            initialized: initialized,
            groupChannels: groupChannels,
            refresh: refresh,
            loadMore: loadMore,
        } },
        React.createElement(UserProfileContext.UserProfileProvider, { disableUserProfile: disableUserProfile !== null && disableUserProfile !== void 0 ? disableUserProfile : config === null || config === void 0 ? void 0 : config.disableUserProfile, renderUserProfile: renderUserProfile !== null && renderUserProfile !== void 0 ? renderUserProfile : config === null || config === void 0 ? void 0 : config.renderUserProfile, onUserProfileMessage: onUserProfileMessage !== null && onUserProfileMessage !== void 0 ? onUserProfileMessage : config === null || config === void 0 ? void 0 : config.onUserProfileMessage },
            React.createElement("div", { className: "sendbird-channel-list ".concat(className) }, children))));
};
var useGroupChannelListContext = function () {
    var context = React.useContext(GroupChannelListContext);
    if (!context)
        throw new Error('GroupChannelListContext not found. Use within the GroupChannelList module.');
    return context;
};
function getCollectionCreator(sdk, channelListQueryParams) {
    return function (defaultParams) {
        var params = _tslib.__assign(_tslib.__assign({}, defaultParams), channelListQueryParams);
        return sdk.groupChannel.createGroupChannelCollection(_tslib.__assign(_tslib.__assign({}, params), { filter: new groupChannel.GroupChannelFilter(params) }));
    };
}

var GroupChannelListItemView = function (_a) {
    var channel = _a.channel, tabIndex = _a.tabIndex, isTyping = _a.isTyping, isSelected = _a.isSelected, channelName = _a.channelName, _b = _a.isMessageStatusEnabled, isMessageStatusEnabled = _b === void 0 ? true : _b, _c = _a.onClick, onClick = _c === void 0 ? utils.noop : _c, _d = _a.onLeaveChannel, onLeaveChannel = _d === void 0 ? utils.noop : _d, renderChannelAction = _a.renderChannelAction;
    var config = useSendbirdStateContext.useSendbirdStateContext().config;
    var theme = config.theme, isMentionEnabled = config.isMentionEnabled, userId = config.userId;
    var _e = LocalizationContext.useLocalization(), dateLocale = _e.dateLocale, stringSet = _e.stringSet;
    var isMobile = MediaQueryContext.useMediaQueryContext().isMobile;
    var _f = React.useState(false), showMobileLeave = _f[0], setShowMobileLeave = _f[1];
    var onLongPress = useLongPress.useLongPress({
        onLongPress: function () {
            if (isMobile) {
                setShowMobileLeave(true);
            }
        },
        onClick: onClick,
    }, {
        delay: 1000,
    });
    return (React.createElement(React.Fragment, null,
        React.createElement("div", _tslib.__assign({ className: [
                'sendbird-channel-preview',
                isSelected ? 'sendbird-channel-preview--active' : '',
            ].join(' '), role: "link", tabIndex: tabIndex }, (isMobile ? _tslib.__assign({}, onLongPress) : { onClick: onClick })),
            React.createElement("div", { className: "sendbird-channel-preview__avatar" },
                React.createElement(ui_ChannelAvatar, { channel: channel, userId: userId, theme: theme })),
            React.createElement("div", { className: "sendbird-channel-preview__content" },
                React.createElement("div", { className: "sendbird-channel-preview__content__upper" },
                    React.createElement("div", { className: "sendbird-channel-preview__content__upper__header" },
                        (channel.isBroadcast || false) && (React.createElement("div", { className: "sendbird-channel-preview__content__upper__header__broadcast-icon" },
                            React.createElement(ui_Icon.default, { type: ui_Icon.IconTypes.BROADCAST, fillColor: ui_Icon.IconColors.SECONDARY, height: "16px", width: "16px" }))),
                        React.createElement(ui_Label.Label, { className: "sendbird-channel-preview__content__upper__header__channel-name", type: ui_Label.LabelTypography.SUBTITLE_2, color: ui_Label.LabelColors.ONBACKGROUND_1 }, channelName),
                        React.createElement(ui_Label.Label, { className: "sendbird-channel-preview__content__upper__header__total-members", type: ui_Label.LabelTypography.CAPTION_2, color: ui_Label.LabelColors.ONBACKGROUND_2 }, ui_MessageStatus.getTotalMembers(channel)),
                        (channel.isFrozen) && (React.createElement("div", { title: "Frozen", className: "sendbird-channel-preview__content__upper__header__frozen-icon" },
                            React.createElement(ui_Icon.default, { type: ui_Icon.IconTypes.FREEZE, fillColor: ui_Icon.IconColors.PRIMARY, height: 12, width: 12 })))),
                    !channel.isEphemeral && isMessageStatusEnabled && (React.createElement(ui_MessageStatus.MessageStatus, { className: "sendbird-channel-preview__content__upper__last-message-at", channel: channel, message: channel.lastMessage, isDateSeparatorConsidered: false })),
                    !channel.isEphemeral && !isMessageStatusEnabled && (React.createElement(ui_Label.Label, { className: "sendbird-channel-preview__content__upper__last-message-at", type: ui_Label.LabelTypography.CAPTION_3, color: ui_Label.LabelColors.ONBACKGROUND_2 }, ui_MessageStatus.getLastMessageCreatedAt({
                        channel: channel,
                        locale: dateLocale,
                        stringSet: stringSet,
                    })))),
                React.createElement("div", { className: "sendbird-channel-preview__content__lower" },
                    React.createElement(ui_Label.Label, { className: "sendbird-channel-preview__content__lower__last-message", type: ui_Label.LabelTypography.BODY_2, color: ui_Label.LabelColors.ONBACKGROUND_3 },
                        isTyping && (React.createElement(TypingIndicator.TypingIndicatorText, { members: channel.getTypingUsers() })),
                        !isTyping
                            && !index.isVoiceMessage(channel.lastMessage)
                            && ui_MessageStatus.getLastMessage(channel, stringSet),
                        !isTyping
                            && index.isVoiceMessage(channel.lastMessage)
                            && stringSet.VOICE_MESSAGE),
                    /**
                     * Do not show unread count for focused channel. This is because of the limitation where
                     * isScrollBottom and hasNext states needs to be added globally but they are from channel context
                     * so channel list cannot see them with the current architecture.
                     */
                    !isSelected && !channel.isEphemeral && (React.createElement("div", { className: "sendbird-channel-preview__content__lower__unread-message-count" },
                        isMentionEnabled && channel.unreadMentionCount > 0 ? (React.createElement(ui_MentionUserLabel, { className: "sendbird-channel-preview__content__lower__unread-message-count__mention", color: "purple" }, '@')) : null,
                        ui_MessageStatus.getChannelUnreadMessageCount(channel) ? ( // return number
                        React.createElement(ui_Badge, { count: ui_MessageStatus.getChannelUnreadMessageCount(channel) })) : null)))),
            !isMobile && (React.createElement("div", { className: "sendbird-channel-preview__action" }, renderChannelAction({ channel: channel })))),
        showMobileLeave && isMobile && (React.createElement(ui_Modal.Modal, { className: "sendbird-channel-preview__leave--mobile", titleText: channelName, hideFooter: true, isCloseOnClickOutside: true, onCancel: function () { return setShowMobileLeave(false); } },
            React.createElement(ui_TextButton, { onClick: function () {
                    onLeaveChannel();
                    setShowMobileLeave(false);
                }, className: "sendbird-channel-preview__leave-label--mobile" },
                React.createElement(ui_Label.Label, { type: ui_Label.LabelTypography.SUBTITLE_1, color: ui_Label.LabelColors.ONBACKGROUND_1 }, stringSet.CHANNEL_PREVIEW_MOBILE_LEAVE))))));
};

var ChannelPreview = function (_a) {
    var _b, _c, _d, _e, _f, _g, _h;
    var channel = _a.channel, _j = _a.isActive, isActive = _j === void 0 ? false : _j, _k = _a.isTyping, isTyping = _k === void 0 ? false : _k, renderChannelAction = _a.renderChannelAction, onLeaveChannel = _a.onLeaveChannel, onClick = _a.onClick, tabIndex = _a.tabIndex;
    var sbState = useSendbirdStateContext.useSendbirdStateContext();
    var _l = ChannelList_context.useChannelListContext(), _m = _l.isTypingIndicatorEnabled, isTypingIndicatorEnabled = _m === void 0 ? false : _m, _o = _l.isMessageReceiptStatusEnabled, isMessageReceiptStatusEnabled = _o === void 0 ? false : _o;
    var stringSet = LocalizationContext.useLocalization().stringSet;
    var userId = (_d = (_c = (_b = sbState === null || sbState === void 0 ? void 0 : sbState.stores) === null || _b === void 0 ? void 0 : _b.userStore) === null || _c === void 0 ? void 0 : _c.user) === null || _d === void 0 ? void 0 : _d.userId;
    var isMessageStatusEnabled = isMessageReceiptStatusEnabled
        && (((_e = channel === null || channel === void 0 ? void 0 : channel.lastMessage) === null || _e === void 0 ? void 0 : _e.messageType) === 'user' || ((_f = channel === null || channel === void 0 ? void 0 : channel.lastMessage) === null || _f === void 0 ? void 0 : _f.messageType) === 'file')
        && ((_h = (_g = channel === null || channel === void 0 ? void 0 : channel.lastMessage) === null || _g === void 0 ? void 0 : _g.sender) === null || _h === void 0 ? void 0 : _h.userId) === userId;
    var channelName = ui_MessageStatus.getChannelTitle(channel, userId, stringSet);
    return (React.createElement(GroupChannelListItemView, { channel: channel, tabIndex: tabIndex, isTyping: isTypingIndicatorEnabled && isTyping, isSelected: isActive, channelName: channelName, isMessageStatusEnabled: isMessageStatusEnabled, onClick: onClick, onLeaveChannel: onLeaveChannel, renderChannelAction: renderChannelAction }));
};

exports.ChannelPreview = ChannelPreview;
exports.GroupChannelListItemView = GroupChannelListItemView;
exports.GroupChannelListProvider = GroupChannelListProvider;
exports.useGroupChannelListContext = useGroupChannelListContext;
//# sourceMappingURL=bundle-Y86Tvf8p.js.map
