'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index$1 = require('./index-2e5758b6.js');
const uiStore = require('./ui-store-583d205a.js');
const date = require('./date-61ffcd0a.js');
const scroll = require('./scroll-c6404609.js');
const index = require('./index-3f8e5441.js');

const rtkChatMessagesUiCss = ":host{line-height:initial;font-family:var(--rtk-font-family, sans-serif);font-feature-settings:normal;font-variation-settings:normal}p{margin:var(--rtk-space-0, 0px);padding:var(--rtk-space-0, 0px)}.scrollbar{scrollbar-width:thin;scrollbar-color:var(--rtk-scrollbar-color, rgb(var(--rtk-colors-background-600, 60 60 60)))\n    var(--rtk-scrollbar-background, transparent)}.scrollbar::-webkit-scrollbar{height:var(--rtk-space-1\\.5, 6px);width:var(--rtk-space-1\\.5, 6px);border-radius:9999px;background-color:var(--rtk-scrollbar-background, transparent)}.scrollbar::-webkit-scrollbar-thumb{border-radius:9999px;background-color:var(--rtk-scrollbar-color, rgb(var(--rtk-colors-background-600, 60 60 60)))}:host{position:relative;display:flex;flex-direction:column;--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-900, 26 26 26) / var(--tw-bg-opacity));word-break:break-word}.chat-container{box-sizing:border-box;display:flex;flex-direction:column;padding-top:var(--rtk-space-4, 16px);padding-bottom:var(--rtk-space-4, 16px);flex:1 0 0px;overflow-y:scroll}.chat-container .spacer{flex:1 1 auto}.chat-container .chat{flex:0 0 auto}.file-picker{display:none}.chat .head{margin-bottom:var(--rtk-space-2, 8px);display:flex;align-items:center}.chat .head .name{margin-right:var(--rtk-space-2, 8px);font-size:12px;font-weight:700}.chat .head .time{font-size:12px;color:rgb(var(--rtk-colors-text-800, 255 255 255 / 0.76))}.chat .body{overflow-wrap:break-word;line-height:1.5}.chat .body .emoji{font-size:24px}p{margin:var(--rtk-space-0, 0px);line-height:1.5}rtk-message-view{margin-top:var(--rtk-space-2, 8px);display:block;padding-left:var(--rtk-space-2, 8px);padding-right:var(--rtk-space-2, 8px);color:rgb(var(--rtk-colors-text-900, 255 255 255 / 0.88));box-sizing:border-box}rtk-message-view::part(message){flex-grow:1}*[is-continued] rtk-message-view{margin-top:var(--rtk-space-1, 4px)}.pinned .message-wrapper{position:relative}.pinned .pin-button{position:absolute;right:var(--rtk-space-4, 16px);top:calc(var(--rtk-space-4, 16px) * -1);display:flex;border-radius:var(--rtk-border-radius-sm, 4px);--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-600, 60 60 60) / var(--tw-bg-opacity))}.pinned .pin-button:hover rtk-button{--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-brand-600, 13 81 253) / var(--tw-bg-opacity))}.pinned rtk-message-view{--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-700, 44 44 44) / var(--tw-bg-opacity));padding-top:var(--rtk-space-1, 4px);padding-bottom:var(--rtk-space-1, 4px)}a{--tw-text-opacity:1;color:rgba(var(--rtk-colors-brand-300, 73 124 253) / var(--tw-text-opacity));text-decoration-line:none}a:hover{text-decoration-line:underline}.new-chat-marker{display:flex;width:100%;align-items:center;gap:var(--rtk-space-2, 8px);--tw-text-opacity:1;color:rgba(var(--rtk-colors-brand-300, 73 124 253) / var(--tw-text-opacity))}.new-chat-marker::before{content:'';height:1px;flex:1 1 0%;background-color:rgba(var(--rtk-colors-brand-300, 73 124 253) / 0.5)}.show-new-messages-ctr{pointer-events:none;display:flex;justify-content:flex-end;padding:var(--rtk-space-3, 12px);z-index:0;margin-top:calc(var(--rtk-space-14, 56px) * -1)}.show-new-messages{pointer-events:auto;--tw-translate-y:var(--rtk-space-16, 64px);transform:translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));opacity:0;transition-property:color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter;transition-timing-function:cubic-bezier(0.4, 0, 0.2, 1);transition-duration:150ms}.show-new-messages.active{--tw-translate-y:var(--rtk-space-0, 0px);transform:translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));opacity:1}";
const RtkChatMessagesUiStyle0 = rtkChatMessagesUiCss;

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;
};
let hasShownDeprecationWarning = false;
const RtkChatMessagesUi = class {
    constructor(hostRef) {
        index$1.registerInstance(this, hostRef);
        this.onPinMessage = index$1.createEvent(this, "pinMessage", 7);
        this.stateUpdate = index$1.createEvent(this, "rtkStateUpdate", 7);
        this.observingEl = [];
        this.autoScrollEnabled = true;
        /** Chat Messages */
        this.messages = [];
        /** Can current user pin/unpin messages */
        this.canPinMessages = false;
        /** Icon pack */
        this.iconPack = uiStore.defaultIconPack;
        /** Language */
        this.t = uiStore.useLanguage();
        this.now = new Date();
        this.showLatestMessageButton = false;
        this.onScroll = (e) => {
            const target = e.target;
            index$1.writeTask(() => {
                const { scrollTop, clientHeight, scrollHeight } = target;
                const fromTop = scrollTop + clientHeight;
                if (fromTop + 10 >= scrollHeight) {
                    // at bottom
                    this.autoScrollEnabled = true;
                    this.showLatestMessageButton = false;
                }
                else {
                    // not at bottom
                    this.autoScrollEnabled = false;
                }
            });
        };
        this.scrollToBottom = () => {
            scroll.smoothScrollToBottom(this.$chat);
        };
        this.observeMessage = (el) => {
            if (el) {
                this.observingEl.push(el);
            }
            try {
                this.intersectionObserver.observe(el);
            }
            catch (_a) { }
        };
        this.getMessageActions = (message) => {
            const actions = [];
            if (!message.pinned && this.canPinMessages) {
                actions.push({
                    id: 'pin_message',
                    label: this.t('pin'),
                    icon: this.iconPack.pin,
                });
            }
            return actions;
        };
        this.onMessageActionHandler = (actionId, message) => {
            switch (actionId) {
                case 'pin_message':
                    this.onPinMessage.emit(message);
                    break;
            }
        };
    }
    connectedCallback() {
        var _a;
        if (index$1.Build.isDev && !hasShownDeprecationWarning) {
            hasShownDeprecationWarning = true;
            // eslint-disable-next-line no-console
            console.warn('[realtimekit-ui] `rtk-chat-messages-ui` is deprecated and will be removed in a future release. Use `rtk-chat-messages-ui-paginated` instead.');
        }
        this.lastReadTimestamp = (_a = uiStore.chatUnreadTimestamps['everyone']) !== null && _a !== void 0 ? _a : new Date('0001-01-01T00:00:00Z');
        this.intersectionObserver = new IntersectionObserver((entries) => {
            if (!document.hasFocus())
                return;
            index$1.writeTask(() => {
                for (const entry of entries) {
                    if (entry.isIntersecting) {
                        const currTimestamp = parseInt(entry.target.getAttribute('data-timestamp'));
                        if (currTimestamp > this.lastReadTimestamp.getTime()) {
                            // this.lastReadTimestamp = new Date();
                            uiStore.chatUnreadTimestamps[this.selectedGroup] = new Date();
                        }
                    }
                }
            });
        });
        // update current time every minute
        const updateNow = () => {
            this.now = new Date();
            this.timeout = setTimeout(() => {
                if (this.request != null) {
                    this.request = requestAnimationFrame(updateNow);
                }
            }, 60 * 1000);
        };
        this.request = requestAnimationFrame(updateNow);
        this.chatChanged(this.messages);
    }
    componentDidLoad() {
        this.$chat.addEventListener('scroll', this.onScroll);
        this.$chat.scrollTop = this.$chat.scrollHeight;
    }
    componentDidRender() {
        if (this.autoScrollEnabled) {
            scroll.smoothScrollToBottom(this.$chat);
        }
        else if (this.autoScrollEnabled == null) {
            // scroll to bottom on first render
            scroll.smoothScrollToBottom(this.$chat, false);
        }
    }
    chatChanged(messages) {
        if (this.$chat == null)
            return;
        if (this.autoScrollEnabled || this.$chat.clientHeight === this.$chat.scrollHeight)
            return;
        for (let i = messages.length - 1; i >= 0; i--) {
            if (messages[i].message.time > this.lastReadTimestamp &&
                messages[i].message.userId !== this.selfUserId) {
                // show latest message button when you have new messages
                // and chat container is scrollable and autoscroll is not enabled
                this.showLatestMessageButton = true;
                break;
            }
        }
    }
    selectedBucketChanged() {
        this.autoScrollEnabled = undefined;
        this.observingEl.forEach((el) => {
            this.intersectionObserver.unobserve(el);
        });
        this.observingEl = [];
    }
    disconnectedCallback() {
        this.$chat.removeEventListener('scroll', this.onScroll);
        this.intersectionObserver.disconnect();
        clearTimeout(this.timeout);
        cancelAnimationFrame(this.request);
    }
    render() {
        var _a;
        let prevMessage = null;
        let reachedFirstUnread = false;
        return (index$1.h(index$1.Host, { key: '5fa9062dc2937e4eb9d1210808a91c430a54535d' }, index$1.h("div", { key: '6a45ba033904cc222f4461262049d71c801a8b7c', class: "chat-container scrollbar", ref: (el) => (this.$chat = el), part: "container" }, index$1.h("div", { key: 'f9cfd2960e08ddf5f024cce91f9aa6f247ebe54f', class: "spacer", part: "spacer" }), index$1.h("div", { key: 'ec66c68f1d3876be4767279fe25022ca6994f1a0', class: "chat", part: "chat" }, (_a = this.messages) === null || _a === void 0 ? void 0 : _a.map((item) => {
            if (item.type === 'chat') {
                const { message } = item;
                const isSelfMessage = message.userId === this.selfUserId;
                const isUnread = !isSelfMessage &&
                    !this.autoScrollEnabled &&
                    !reachedFirstUnread &&
                    message.time > this.lastReadTimestamp;
                if (isUnread)
                    reachedFirstUnread = isUnread;
                const isContinued = !isUnread &&
                    message.userId === (prevMessage === null || prevMessage === void 0 ? void 0 : prevMessage.userId) &&
                    date.differenceInMinutes(message.time, prevMessage === null || prevMessage === void 0 ? void 0 : prevMessage.time) < 2;
                prevMessage = message;
                return (index$1.h("div", { "is-continued": isContinued, key: item.message.id, ref: this.observeMessage, "data-timestamp": message.time.getTime(), class: message.pinned ? 'pinned' : '' }, isUnread && (index$1.h("div", { class: "new-chat-marker", part: "new-chat-marker" }, this.t('chat.new'))), index$1.h("div", { class: "message-wrapper" }, index$1.h("rtk-message-view", { time: message.time, actions: this.getMessageActions(message), authorName: message.displayName, hideAuthorName: true, hideAvatar: true, hideMetadata: true, viewType: 'incoming', variant: "bubble", onAction: (event) => this.onMessageActionHandler(event.detail, message) }, !isContinued && (index$1.h("div", { class: "head" }, index$1.h("div", { class: "name" }, message.displayName), !!message.time && (index$1.h("div", { class: "time", title: date.formatDateTime(message.time) }, date.elapsedDuration(message.time, new Date(Date.now())))))), index$1.h("div", { class: "body" }, message.type === 'text' && (index$1.h("rtk-text-message-view", { text: message.message, isMarkdown: true })), message.type === 'file' && (index$1.h("rtk-file-message-view", { name: message.name, url: message.link, size: message.size })), message.type === 'image' && (index$1.h("rtk-image-message-view", { url: message.link, onPreview: () => {
                        this.stateUpdate.emit({ image: message });
                    } })))), message.pinned && (index$1.h("div", { class: "pin-button", part: "pin-button" }, index$1.h("rtk-tooltip", { label: this.t('unpin') }, index$1.h("rtk-button", { kind: "icon", variant: "ghost", onClick: () => this.onMessageActionHandler('pin_message', message), disabled: !this.canPinMessages }, index$1.h("rtk-icon", { icon: this.iconPack.pin, size: "sm" }))))))));
            }
            return null;
        }))), index$1.h("div", { key: 'eae0a23fbe7ba44722539e98ac74eb1406bbc162', class: "show-new-messages-ctr" }, index$1.h("rtk-button", { key: '05c860848174c514a28bb475157c2d81c78538ff', class: {
                'show-new-messages': true,
                active: this.showLatestMessageButton,
            }, kind: "icon", part: "show-new-messages", onClick: this.scrollToBottom }, index$1.h("rtk-icon", { key: '99b6ad3515cfbdf400cb96ca9cc2bbfd83a7deb9', icon: this.iconPack.chevron_down })))));
    }
    static get watchers() { return {
        "messages": ["chatChanged"],
        "selectedGroup": ["selectedBucketChanged"]
    }; }
};
__decorate([
    index.SyncWithStore()
], RtkChatMessagesUi.prototype, "iconPack", void 0);
__decorate([
    index.SyncWithStore()
], RtkChatMessagesUi.prototype, "t", void 0);
RtkChatMessagesUi.style = RtkChatMessagesUiStyle0;

exports.rtk_chat_messages_ui = RtkChatMessagesUi;
