import { p as proxyCustomElement, H, e as createEvent, h, c as Host } from './p-ae373651.js';
import { e as defaultIconPack, i as useLanguage } from './p-5b3a7f00.js';
import { S as SyncWithStore } from './p-070aa695.js';
import { d as defineCustomElement$d } from './p-a3bf84d7.js';
import { d as defineCustomElement$c } from './p-85587a5c.js';
import { d as defineCustomElement$b } from './p-5644d937.js';
import { d as defineCustomElement$a } from './p-3e0452c4.js';
import { d as defineCustomElement$9 } from './p-60d401f8.js';
import { d as defineCustomElement$8 } from './p-549ab58f.js';
import { d as defineCustomElement$7 } from './p-241583c3.js';
import { d as defineCustomElement$6 } from './p-0304f83a.js';
import { d as defineCustomElement$5 } from './p-02d63986.js';
import { d as defineCustomElement$4 } from './p-10552fa5.js';
import { d as defineCustomElement$3 } from './p-7dd3acf5.js';
import { d as defineCustomElement$2 } from './p-e6245534.js';
import { d as defineCustomElement$1 } from './p-51b6f520.js';

const rtkChatMessagesUiPaginatedCss = ":host{display:flex;flex-direction:column;--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-900, 26 26 26) / var(--tw-bg-opacity));flex:1 0 0px}";
const RtkChatMessagesUiPaginatedStyle0 = rtkChatMessagesUiPaginatedCss;

var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
        r = Reflect.decorate(decorators, target, key, desc);
    else
        for (var i = decorators.length - 1; i >= 0; i--)
            if (d = decorators[i])
                r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
const RtkChatMessagesUiPaginated = /*@__PURE__*/ proxyCustomElement(class RtkChatMessagesUiPaginated extends H {
    constructor() {
        super();
        this.__registerHost();
        this.__attachShadow();
        this.editMessageInit = createEvent(this, "editMessageInit", 7);
        this.onPinMessage = createEvent(this, "pinMessage", 7);
        this.onEditMessage = createEvent(this, "editMessage", 7);
        this.onDeleteMessage = createEvent(this, "deleteMessage", 7);
        this.stateUpdate = createEvent(this, "rtkStateUpdate", 7);
        /** Icon pack */
        this.iconPack = defaultIconPack;
        /** Language */
        this.t = useLanguage();
        this.permissionsChanged = false;
        this.pageSize = 25;
        this.permissionsUpdateListener = () => {
            this.permissionsChanged = !this.permissionsChanged;
        };
        this.getChatMessages = async (timestamp, size, reversed) => {
            if (this.privateChatRecipient) {
                try {
                    const messages = await this.meeting.chat.fetchPrivateMessages({
                        timestamp,
                        limit: size,
                        direction: reversed ? 'before' : 'after',
                        userId: this.privateChatRecipient.userId,
                    });
                    return messages;
                }
                catch (err) {
                    return [];
                }
            }
            try {
                const messages = await this.meeting.chat.fetchPublicMessages({
                    timestamp,
                    limit: size,
                    direction: reversed ? 'before' : 'after',
                });
                return messages;
            }
            catch (err) {
                return [];
            }
        };
        this.createChatNodes = (data) => {
            /**
             * NOTE(callmetarush): When between pages the message's isContinued
             * will fail in current implementation
             */
            return data.map((message, idx) => {
                var _a, _b;
                const isContinued = message.userId === ((_a = data[idx - 1]) === null || _a === void 0 ? void 0 : _a.userId);
                // FIXME(ikabra): Socket sends private messages sent to the recipient as a part of public messages
                if (!this.privateChatRecipient && ((_b = message.targetUserIds) === null || _b === void 0 ? void 0 : _b.length) > 0)
                    return;
                return this.createChatNode(message, isContinued);
            });
        };
        this.disconnectMeeting = (meeting) => {
            var _a, _b;
            (_a = meeting === null || meeting === void 0 ? void 0 : meeting.chat) === null || _a === void 0 ? void 0 : _a.removeListener('chatUpdate', this.chatUpdateListener);
            (_b = this.meeting) === null || _b === void 0 ? void 0 : _b.self.permissions.removeListener('permissionsUpdate', this.permissionsUpdateListener);
        };
        this.getMessageActions = (message) => {
            var _a;
            const actions = [];
            const messageBelongsToSelf = message.userId === this.meeting.self.userId;
            const isPrivateMessage = ((_a = message.targetUserIds) === null || _a === void 0 ? void 0 : _a.length) > 0;
            if (!isPrivateMessage) {
                actions.push({
                    id: 'pin_message',
                    label: message.pinned ? this.t('unpin') : this.t('pin'),
                    icon: this.iconPack.pin,
                });
            }
            if (messageBelongsToSelf) {
                actions.push({
                    id: 'edit_message',
                    label: this.t('chat.edit_msg'),
                    icon: this.iconPack.edit,
                });
                actions.push({
                    id: 'delete_message',
                    label: this.t('chat.delete_msg'),
                    icon: this.iconPack.delete,
                });
            }
            return actions;
        };
        this.onMessageActionHandler = (actionId, message) => {
            switch (actionId) {
                case 'pin_message':
                    this.onPinMessage.emit(message);
                    break;
                case 'edit_message':
                    this.onEditMessage.emit(message);
                    break;
                case 'delete_message':
                    this.onDeleteMessage.emit(message);
                    break;
            }
        };
        this.createChatNode = (message, isContinued) => {
            var _a, _b, _c, _d;
            let displayPicture;
            if (this.meeting.meta.viewType === 'CHAT') {
                displayPicture = (_a = this.meeting.participants.all
                    .toArray()
                    .find((p) => p.userId === message.userId)) === null || _a === void 0 ? void 0 : _a.picture;
            }
            else {
                if (this.meeting.self.userId === message.userId) {
                    displayPicture = this.meeting.self.picture;
                }
                else {
                    displayPicture =
                        (_c = (_b = this.meeting.participants.joined
                            .toArray()
                            .find((member) => member.userId === message.userId)) === null || _b === void 0 ? void 0 : _b.picture) !== null && _c !== void 0 ? _c : (_d = this.meeting.participants.waitlisted.toArray().find((p) => p.userId === message.userId)) === null || _d === void 0 ? void 0 : _d.picture;
                }
            }
            const isSelf = message.userId === this.meeting.self.userId;
            const viewType = isSelf ? 'outgoing' : 'incoming';
            return (h("div", null, h("div", { class: "message-wrapper", id: message.id }, h("rtk-message-view", { messageType: message.type, pinned: message.pinned, isEdited: message.isEdited, time: message.time, actions: this.getMessageActions(message), authorName: message.displayName, isSelf: isSelf, avatarUrl: displayPicture, hideAuthorName: isContinued, viewType: viewType, variant: "bubble", onAction: (event) => this.onMessageActionHandler(event.detail, message) }, h("div", null, h("div", { class: "body" }, message.type === 'text' && (h("rtk-text-message-view", { text: message.message, isMarkdown: true })), message.type === 'file' && (h("rtk-file-message-view", { name: message.name, url: message.link, size: message.size })), message.type === 'image' && (h("rtk-image-message-view", { url: message.link, onPreview: () => {
                    this.stateUpdate.emit({ image: message });
                } }))))))));
        };
        this.chatUpdateListener = (data) => {
            var _a, _b, _c;
            // if private message and not for privateChatRecipient, ignore
            // if private message and public chat selected, ignore
            if (((_a = data.message.targetUserIds) === null || _a === void 0 ? void 0 : _a.length) > 0 &&
                !data.message.targetUserIds.includes((_b = this.privateChatRecipient) === null || _b === void 0 ? void 0 : _b.userId))
                return;
            // if public message and private chat selected, ignore
            if (this.privateChatRecipient && ((_c = data.message.targetUserIds) === null || _c === void 0 ? void 0 : _c.length) === 0) {
                return;
            }
            if (data.action === 'add') {
                this.$paginatedListRef.onNewNode(data.message);
            }
            else if (data.action === 'delete') {
                this.$paginatedListRef.onNodeDelete(data.message.id);
            }
            else if (data.action === 'edit') {
                this.$paginatedListRef.onNodeUpdate(data.message.id, data.message);
            }
        };
    }
    componentDidLoad() {
        const slotted = this.host.shadowRoot.querySelector('slot');
        if (!slotted)
            return;
        this.children = slotted.assignedElements()[0];
    }
    connectedCallback() {
        this.meetingChanged(this.meeting);
    }
    async onPinnedMessageSelect(event) {
        var _a, _b;
        const message = event.detail;
        if (!message)
            return;
        await ((_b = (_a = this.$paginatedListRef) === null || _a === void 0 ? void 0 : _a.reset) === null || _b === void 0 ? void 0 : _b.call(_a, message.timeMs + 1));
    }
    disconnectedCallback() {
        this.disconnectMeeting(this.meeting);
    }
    privateChatRecipientChanged() {
        var _a;
        (_a = this.$paginatedListRef) === null || _a === void 0 ? void 0 : _a.reset();
    }
    meetingChanged(meeting, oldMeeting) {
        var _a;
        if (oldMeeting != undefined)
            this.disconnectMeeting(oldMeeting);
        if (meeting && !meeting.chat)
            return;
        if (meeting != null) {
            (_a = meeting.chat) === null || _a === void 0 ? void 0 : _a.addListener('chatUpdate', this.chatUpdateListener);
            meeting.self.permissions.addListener('permissionsUpdate', this.permissionsUpdateListener);
        }
        this.permissionsUpdateListener();
    }
    render() {
        return (h(Host, { key: '8862788879d34ba9474f6970251df29c4ac2064d' }, h("rtk-paginated-list", { key: 'cb0965c8bc5118408e943872b04d9fa7b6b9c970', ref: (el) => (this.$paginatedListRef = el), pageSize: this.pageSize, pagesAllowed: 3, fetchData: this.getChatMessages, createNodes: this.createChatNodes, emptyListLabel: this.t('chat.empty_chat') }, h("slot", { key: '7b1686d75404515a2bc018b9e40918612b826136' }))));
    }
    get host() { return this; }
    static get watchers() { return {
        "privateChatRecipient": ["privateChatRecipientChanged"],
        "meeting": ["meetingChanged"]
    }; }
    static get style() { return RtkChatMessagesUiPaginatedStyle0; }
}, [1, "rtk-chat-messages-ui-paginated", {
        "meeting": [16],
        "size": [513],
        "iconPack": [16],
        "t": [16],
        "privateChatRecipient": [16],
        "children": [32],
        "permissionsChanged": [32]
    }, [[8, "rtkPinnedMessageSelect", "onPinnedMessageSelect"]], {
        "privateChatRecipient": ["privateChatRecipientChanged"],
        "meeting": ["meetingChanged"]
    }]);
__decorate([
    SyncWithStore()
], RtkChatMessagesUiPaginated.prototype, "meeting", void 0);
__decorate([
    SyncWithStore()
], RtkChatMessagesUiPaginated.prototype, "iconPack", void 0);
__decorate([
    SyncWithStore()
], RtkChatMessagesUiPaginated.prototype, "t", void 0);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["rtk-chat-messages-ui-paginated", "rtk-avatar", "rtk-button", "rtk-file-message-view", "rtk-icon", "rtk-image-message-view", "rtk-markdown-view", "rtk-menu", "rtk-menu-item", "rtk-menu-list", "rtk-message-view", "rtk-paginated-list", "rtk-spinner", "rtk-text-message-view"];
    components.forEach(tagName => { switch (tagName) {
        case "rtk-chat-messages-ui-paginated":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, RtkChatMessagesUiPaginated);
            }
            break;
        case "rtk-avatar":
            if (!customElements.get(tagName)) {
                defineCustomElement$d();
            }
            break;
        case "rtk-button":
            if (!customElements.get(tagName)) {
                defineCustomElement$c();
            }
            break;
        case "rtk-file-message-view":
            if (!customElements.get(tagName)) {
                defineCustomElement$b();
            }
            break;
        case "rtk-icon":
            if (!customElements.get(tagName)) {
                defineCustomElement$a();
            }
            break;
        case "rtk-image-message-view":
            if (!customElements.get(tagName)) {
                defineCustomElement$9();
            }
            break;
        case "rtk-markdown-view":
            if (!customElements.get(tagName)) {
                defineCustomElement$8();
            }
            break;
        case "rtk-menu":
            if (!customElements.get(tagName)) {
                defineCustomElement$7();
            }
            break;
        case "rtk-menu-item":
            if (!customElements.get(tagName)) {
                defineCustomElement$6();
            }
            break;
        case "rtk-menu-list":
            if (!customElements.get(tagName)) {
                defineCustomElement$5();
            }
            break;
        case "rtk-message-view":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "rtk-paginated-list":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "rtk-spinner":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
        case "rtk-text-message-view":
            if (!customElements.get(tagName)) {
                defineCustomElement$1();
            }
            break;
    } });
}
defineCustomElement();

export { RtkChatMessagesUiPaginated as R, defineCustomElement as d };
