import { Host, h, Fragment } from "@stencil/core";
import { configStore, deviceModeStore, messagesStore, profilePanelStore, selectedChatStore, selectedMessageToReplyStore, translateStore, userStore } from "../../store/store";
import { getMessagePicture, getOrFetchTranslation, handleGetChatMessages, scrollToMessage, serviceUpdateMessageItems } from "../../store/message";
import { displayDateTime, displayTime, isToday } from "../../utils/dayjs";
import { Icon } from "../internal-component/icon";
import { ZTagOrStatusItem } from "../internal-component/z-tag-or-status-item";
import { useTranslation } from "../../utils/utils";
import { handleError } from "../../store/dialog";
import { persistMessage, updateMessageSyncState } from "../../utils/cache";
import { getChatName } from "../../store/chat";
import { MAX_DISPLAY_READS_BY, MESSAGE_PAGE_LIMIT } from "../../utils/constant";
import { errorSymbolIcon } from "../../utils/icon-svg";
import { getSenderName, openWindow } from "../../utils/func";
export class MessageItem {
    item;
    replyMessage;
    isLoading = false;
    showError = false;
    focusRequested;
    componentShouldUpdate(newValue, oldValue, propName) {
        // Only check the item prop
        if (propName !== 'item')
            return true;
        if (!newValue || !oldValue)
            return true;
        // Only update if key properties changed
        return (newValue.id !== oldValue.id ||
            newValue.text !== oldValue.text ||
            newValue.translatedText !== oldValue.translatedText ||
            newValue.isSending !== oldValue.isSending ||
            newValue.type !== oldValue.type ||
            newValue.error_data !== oldValue.error_data ||
            newValue.menu_list !== oldValue.menu_list ||
            newValue.buttons !== oldValue.buttons);
    }
    async componentWillLoad() {
        const { text, translatedText } = this.item;
        const translationSettings = configStore.get('translationSettings');
        const selectedChat = selectedChatStore.get('selectedChat');
        if (text) {
            const isAutoTranslate = translationSettings.is_auto &&
                selectedChat.language !== translationSettings.target_language &&
                !translationSettings.exclude_languages.includes(selectedChat.language);
            if (!translatedText && this.item && this.item.id) {
                this.handleTranslateMessages(this.item.id, !isAutoTranslate);
            }
        }
    }
    handleTranslateMessages = async (messageId, skipFetch = false) => {
        try {
            this.isLoading = true;
            const messages = messagesStore.get('messages');
            const idx = messages.findIndex(message => message.id === messageId);
            if (idx !== -1) {
                const selectedChat = selectedChatStore.get('selectedChat');
                const selectedChatId = selectedChat ? selectedChat.id : '';
                const translatedResponse = await getOrFetchTranslation({
                    chat_id: selectedChatId,
                    message_ids: [messageId],
                    skipFetch,
                });
                const translatedText = translatedResponse.messages.find(message => message.id === messageId);
                if (translatedText) {
                    const translatedMessages = translateStore.get('translatedMessages');
                    translateStore.set('translatedMessages', {
                        ...translatedMessages,
                        [messageId]: translatedText.text,
                    });
                    const updatedMessage = {
                        ...messages[idx],
                        translatedText: translatedText.text,
                    };
                    serviceUpdateMessageItems({ updateMessages: [updatedMessage] });
                    // Persist translated message to cache so it's not lost on reload
                    if (updatedMessage.id && !updatedMessage.isSending && selectedChatId) {
                        persistMessage(selectedChatId, updatedMessage).then(() => updateMessageSyncState(selectedChatId));
                    }
                }
            }
        }
        catch (error) {
            handleError(error, 'Failed to translate chat message');
        }
        finally {
            this.isLoading = false;
        }
    };
    renderTimestamp = (date) => h("span", null, isToday(date) ? displayTime(date) : displayDateTime(date));
    renderActivityChips = () => {
        const from = this.item ? this.item.from : null;
        const to = this.item ? this.item.to : null;
        const item = this.item ? this.item.item : null;
        const renderChip = (chip) => chip && h(ZTagOrStatusItem, { item: { id: '', name: chip.name, color: chip.color, sequence: 0 } });
        return (h("div", { class: "message-item-activity-log-chip" }, from && renderChip(from), (this.item ? this.item.action : '') === 'change' && h("span", { class: "text-xs text-theme-gray" }, "\u2192"), to && renderChip(to), item && renderChip(item)));
    };
    getActionText = (t) => {
        if (!this.item)
            return '';
        const { action, sender } = this.item;
        const type = (this.item.from ? this.item.from.type : '') || (this.item.to ? this.item.to.type : '') || (this.item.item ? this.item.item.type : '');
        const base = t('profile_tab.activity_action')
            .replace('{action}', t(`${action}`))
            .replace('{type}', t(`${type}`))
            .toLowerCase();
        return `${getSenderName(sender)} ${base}`;
    };
    handleShowProfile = () => {
        if (deviceModeStore.get('mode') !== 'desktop') {
            profilePanelStore.set('isShowProfile', true);
        }
    };
    handleJumpToMessage = async (messageId) => {
        try {
            const topMessageRange = Math.ceil(MESSAGE_PAGE_LIMIT / 3);
            const messageIndex = messagesStore.get('messages').findIndex(message => message.id === messageId);
            const isTopMessage = messageIndex !== -1 ? messageIndex < topMessageRange : false;
            if (isTopMessage) {
                this.isLoading = true;
                messagesStore.set('jumpMessageId', messageId);
                await handleGetChatMessages({ next: messagesStore.get('newer')?.next });
            }
            const isSuccessScroll = scrollToMessage({ messageId });
            if (isTopMessage && isSuccessScroll) {
                setTimeout(() => {
                    messagesStore.set('jumpMessageId', undefined);
                }, 300);
            }
            if (!isSuccessScroll) {
                this.isLoading = true;
                await handleGetChatMessages({ startMessageId: messageId });
                setTimeout(() => {
                    const isSuccessScroll = scrollToMessage({ messageId });
                    if (isSuccessScroll) {
                        setTimeout(() => {
                            messagesStore.set('jumpMessageId', undefined);
                        }, 300);
                    }
                }, 500);
            }
        }
        catch (error) {
            handleError(error, 'Failed to load Chat Messages');
        }
        finally {
            this.isLoading = false;
        }
    };
    getErrorMessage = () => {
        const errorData = this.item.error_data;
        if (typeof errorData === 'string')
            return errorData;
        if (!errorData)
            return '';
        if (errorData.errorMessage) {
            try {
                const parsed = JSON.parse(errorData.errorMessage);
                if (parsed?.message)
                    return parsed.message;
            }
            catch (e) {
                // Fallback to raw errorMessage
                handleError(e, 'Failed to getErrorMessage');
            }
            return errorData.errorMessage;
        }
        const { error, message } = errorData;
        const errorMsg = typeof error === 'object' ? error?.message : error;
        return errorMsg || message || '';
    };
    handleViewAdsPost = () => {
        const { referral } = this.item;
        const postId = referral?.ads_context_data?.post_id;
        if (!postId)
            return;
        const selectedChat = selectedChatStore.get('selectedChat');
        if (!selectedChat)
            return;
        const connectionList = configStore.get('connectionList');
        const connectionId = selectedChat.connection.id;
        const connection = connectionList.find(conn => {
            if (conn.type === 'zwiz') {
                return conn.channels.some(channel => channel.id === connectionId);
            }
            return conn.id === connectionId;
        });
        if (!connection)
            return;
        let pageId = '';
        if (connection.type === 'facebook') {
            pageId = connection.page_id;
        }
        else if (connection.type === 'zwiz') {
            const selectedChannel = connection.channels.find(ch => ch.id === connectionId);
            pageId = selectedChannel?.channel_id;
        }
        if (!pageId)
            return;
        openWindow(`https://www.facebook.com/${pageId}/posts/${postId}`);
    };
    handleViewFeedPost = () => {
        const { feed } = this.item;
        if (!feed?.post_id || !feed?.comment_id)
            return;
        const [post1, post2] = feed.post_id.split('_');
        const [, comment] = feed.comment_id.split('_');
        openWindow(`https://www.facebook.com/${post1}/posts/${post2}?comment_id=${comment}`);
    };
    renderReferral() {
        if (this.item.type !== 'referral' || !this.item.referral)
            return null;
        const { referral, message_at } = this.item;
        const { ads_context_data } = referral;
        if (!ads_context_data)
            return null;
        const { post_id } = ads_context_data;
        const t = useTranslation();
        return (h("div", { class: "message-item-referral-wrapper" }, h("span", { class: "message-item-referral-text" }, this.renderTimestamp(message_at), "\u00A0:\u00A0", t('chat_tab.referral_message_sent_from_ads')), post_id && (h("span", { class: "message-item-referral-link", onClick: this.handleViewAdsPost }, t('chat_tab.view_ads')))));
    }
    renderFeed() {
        if (this.item.type !== 'feed' || !this.item.feed)
            return null;
        const { message_at } = this.item;
        const t = useTranslation();
        return (h("div", { class: "message-item-referral-wrapper" }, h("span", { class: "message-item-referral-text" }, this.renderTimestamp(message_at), "\u00A0:\u00A0", t('chat_tab.feed_message_sent_from_post')), h("span", { class: "message-item-referral-link", onClick: this.handleViewFeedPost }, t('chat_tab.view_post'))));
    }
    render() {
        const t = useTranslation();
        const { sender, message_at, reply_message, text } = this.item;
        const numberFormatter = Intl.NumberFormat();
        const translationSettings = configStore.get('translationSettings');
        const selectedChat = selectedChatStore.get('selectedChat');
        const readsMap = messagesStore.get('readsMap');
        const isUser = sender.type === 'user';
        const isUUID = (id) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id);
        const isDisabledReply = (selectedChat ? selectedChat.channel : '') === 'instagram' || isUUID(this.item.message_id);
        const isSummarized = this.item.type === 'summarized_chat' || this.item.event_type === 'summarized_chat';
        const isActivityLog = this.item.type === 'activity_log' || this.item.event_type === 'activity_log';
        const isUserEvent = this.item.type === 'zwiz_user_event' || this.item.event_type === 'zwiz_user_event';
        const isReferral = this.item.type === 'referral' || this.item.event_type === 'referral';
        const isFeed = this.item.type === 'feed' || this.item.event_type === 'feed';
        const isZptDebug = this.item.type === 'zpt-debug' || this.item.event_type === 'zpt-debug';
        const isZptUnanswered = this.item.type === 'zpt-unanswered' || this.item.event_type === 'zpt-unanswered';
        const isBroadcast = this.item.event_type === 'zwiz-broadcast' || this.item.event_type === 'zwiz-broadcast-mm';
        const isFollow = this.item.type === 'follow';
        const isUnfollow = this.item.type === 'unfollow';
        const isDisplayTranslate = 
        // selectedChat.language !== null &&
        // selectedChat.language !== translationSettings.target_language &&
        // !translationSettings.exclude_languages.includes(selectedChat.language) &&
        (this.item ? (this.item.text ? this.item.text.length : 0) : 0) > 0 &&
            !translationSettings.is_auto;
        const menuItems = [
            ...(isDisabledReply
                ? []
                : [
                    {
                        label: t('chat_tab.reply'),
                        value: 'reply',
                        onClick: () => {
                            selectedMessageToReplyStore.set('selectedMessageToReply', this.item);
                            this.focusRequested.emit();
                        },
                    },
                ]),
            ...(isDisplayTranslate
                ? [
                    {
                        label: t('translate'),
                        value: 'translate',
                        onClick: () => this.handleTranslateMessages(this.item.id),
                    },
                ]
                : []),
        ];
        const _readers = readsMap[this.item.id] || [];
        return (h(Host, { key: '180f819bc9fde6dfac84236752ebd134749e7e42' }, h("div", { key: '4bcb89b35faca1d178c5c49b7c9342bdb20d45dd', id: `message-${this.item.id}`, class: "message-item" }, isSummarized ? (h("div", { class: "message-item-summarized-wrapper" }, h("span", { class: "message-item-summarized-time" }, this.renderTimestamp(message_at), "\u00A0:\u00A0", t('chat_tab.summary')), h("div", { class: "message-item-summarized-text" }, text))) : isFollow || isUnfollow ? (h("div", { class: "message-item-user-event-wrapper" }, h("span", { class: "message-item-user-event-time" }, this.renderTimestamp(message_at)), h("div", { class: "message-item-user-event-text" }, isUnfollow ? t('chat_tab.line_blocked') : this.item.follow?.isUnblocked ? t('chat_tab.line_unblocked') : t('chat_tab.line_add_friend')))) : isUserEvent ? (h("div", { class: "message-item-user-event-wrapper" }, h("span", { class: "message-item-user-event-time" }, this.renderTimestamp(message_at)), h("div", { class: "message-item-user-event-text" }, h(Icon, { name: "CircleCheck", addClass: "message-item-user-event-icon" }), "\u0E2A\u0E48\u0E07\u00A0", this.item.event_name, "\u00A0Event\u00A0\u0E2A\u0E33\u0E40\u0E23\u0E47\u0E08!", this.item.value ? h(Fragment, null, h("br", null), "\u0E22\u0E2D\u0E14\u0E40\u0E07\u0E34\u0E19\u00A0", numberFormatter.format(this.item.value || 0)) : null))) : isActivityLog ? (h("div", { id: `message-content-${this.item.id}`, tabIndex: -1, class: "message-item-activity-log-wrapper" }, h("div", { class: `message-item-activity-log-action ${(deviceModeStore.get('mode') === 'mobile' && (this.item ? this.item.from : null)) ? 'flex-col' : 'flex-row'}` }, h("span", { class: "message-item-activity-log-timestamp" }, this.renderTimestamp(message_at), "\u00A0:\u00A0"), h("div", { class: "message-item-activity-log-text", title: this.getActionText(t) }, this.getActionText(t)), this.renderActivityChips()))) : isZptDebug ? (h("div", { class: "message-item-summarized-wrapper" }, h("span", { class: "message-item-summarized-time" }, this.renderTimestamp(message_at), "\u00A0:\u00A0", t('chat_tab.zpt_debug_mode')), h("div", { class: "message-item-summarized-text" }, text))) : isZptUnanswered ? (h("div", { class: "message-item-summarized-wrapper" }, h("span", { class: "message-item-summarized-time" }, this.renderTimestamp(message_at), "\u00A0:\u00A0ZPT"), h("div", { class: "message-item-summarized-text flex flex-row items-center justify-center gap-2" }, h(Icon, { name: "TriangleAlert", addClass: "size-5 text-white fill-yellow-500" }), h("span", { class: "text-sm" }, t('chat_tab.zpt_unanswered_mode'))))) : isReferral ? (this.renderReferral()) : isFeed ? (this.renderFeed()) : (h(Fragment, null, h("div", { class: `message-item-content-wrapper ${isUser ? 'justify-start' : 'justify-end'}` }, isUser && getMessagePicture(sender, selectedChat) && (h("div", { class: "message-item-content-avatar-wrapper", onClick: this.handleShowProfile }, h("z-tooltip", { text: getSenderName(sender), position: "right" }, h("z-avatar", { pictureUrl: getMessagePicture(sender, selectedChat), size: "small" })))), h("div", { class: "message-item-content-reply-wrapper" }, reply_message && (h("div", { class: `message-item-content-reply-jump-to-message ${isUser ? 'justify-start' : 'justify-end'} text-theme-gray`, onClick: () => this.handleJumpToMessage(reply_message.id) }, h(Icon, { name: "Reply", addClass: "size-3 text-theme-gray" }), "\u00A0", ['admin', 'connection'].includes(sender.type) ? t('you') : getChatName(selectedChat), "\u00A0", t('chat_tab.replied_to'), "\u00A0", reply_message.sender.type === 'admin' ? (sender.type === 'admin' ? t('chat_tab.yourself') : t('you')) : getChatName(selectedChat))), h("div", { class: `message-item-content-message-wrapper ${isUser ? 'justify-start' : 'justify-end'}` }, !isUser && this.item.isSending && h(Icon, { name: "LoaderCircle", addClass: "message-item-content-message-loading text-theme-gray" }), !isUser && menuItems.length > 0 && (h("menu-list", { menuItems: menuItems, referenceSelector: `menu-${this.item.id}`, iconName: "EllipsisVertical" })), h("message-content", { item: this.item, onJumpChat: () => this.handleJumpToMessage(reply_message.id) }), isUser && menuItems.length > 0 && (h("div", { class: "flex flex-row gap-1 items-center" }, this.item.error_data &&
            h("div", { onClick: () => this.showError = !this.showError }, h(Icon, { name: "Info", addClass: "size-4 text-red-500 cursor-pointer" })), h("menu-list", { menuItems: menuItems, position: "bottom-start", referenceSelector: `menu-${this.item.id}`, iconName: "EllipsisVertical" })))))), h("div", { class: `message-item-content-misc ${isUser ? 'mb-2.5 justify-start pl-10' : 'mb-0.5 justify-end'} text-theme-gray ${isUser ? 'text-left' : 'text-right'}` }, !isUser && (this.item.translatedText || translateStore.get('translatedMessages')[this.item.id]) && h(Icon, { name: "Languages", addClass: "size-3 text-theme-gray" }), "\u00A0", isUser ? getSenderName(sender) : (isBroadcast ? t('chat_tab.broadcast') : getSenderName(this.item.sender)), "\u00A0", this.renderTimestamp(message_at), "\u00A0"), this.item.error_data && (() => {
            const errorMessage = this.getErrorMessage();
            return (h("div", null, h("div", { class: `message-item-content-error-wrapper ${isUser ? 'justify-start' : 'justify-end'}` }, h("div", { class: "cursor-pointer", onClick: () => this.showError = !this.showError }, errorSymbolIcon()), this.showError &&
                h("span", { class: `message-item-content-error-text ${isUser ? 'text-left' : 'text-right'}`, title: errorMessage }, errorMessage)), this.showError &&
                errorMessage.includes('https://developers.facebook.com/docs/messenger-platform/policy-overview') &&
                h("div", { class: `message-item-content-error-wrapper ${isUser ? 'justify-start' : 'justify-end'}` }, h("br", null), h("span", { class: `message-item-content-error-text ${isUser ? 'text-left' : 'text-right'}` }, t('you_can_still_reply_via_the_meta_business_suite_inbox'), "\u00A0", h("a", { href: `https://business.facebook.com/latest/${userStore.get('user').user_id}`, target: "_blank", rel: "noopener noreferrer", onClick: (event) => {
                        event.preventDefault();
                        openWindow(`https://business.facebook.com/latest/${userStore.get('user').user_id}`);
                    }, class: "lowercase underline" }, t('here'))))));
        })(), _readers.length > 0 && (h("reads-popper", { readers: _readers, referenceSelector: `read-popper-ref-${this.item.id}` }, h("div", { class: "message-item-content-reader-wrapper" }, _readers
            .sort((a, b) => new Date(a.read_at).getTime() - new Date(b.read_at).getTime())
            .slice(0, MAX_DISPLAY_READS_BY)
            .map((reader, index) => (h("div", { title: reader.name, class: "message-item-content-reader-name bg-time-badge ring-[1px] ring-background", style: { zIndex: String(MAX_DISPLAY_READS_BY + 1 - index) } }, reader.picture_url
            ? h("z-avatar", { pictureUrl: reader.picture_url, size: "2x-small" })
            : reader.name[0]))), _readers.length > MAX_DISPLAY_READS_BY && (h("div", { class: "message-item-content-reader-name bg-selected relative ring-[1px] ring-background", style: { zIndex: '0' } }, h("span", { class: "text-sm text-primary absolute -top-[0.6em]" }, "...")))))))))));
    }
    static get is() { return "message-item"; }
    static get originalStyleUrls() {
        return {
            "$": ["message-item.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["message-item.css"]
        };
    }
    static get properties() {
        return {
            "item": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "ChatMessageItem",
                    "resolved": "{ id?: string; message_id?: string; sender: ChatSender; created_at: Date; updated_at: Date; message_at: Date; text: string; type?: MessageType; event_type?: MessageType; stickerId?: string; reply_message?: ChatMessageItem; attachments?: MessageAttachment[]; template?: ChatMessageTemplate; elements?: MessageElement; altText?: string; baseUrl?: string; baseSize?: { width: number; height: number; }; contents?: any; error_data?: string | MessageError; action?: \"remove\" | \"add\" | \"change\"; item?: ActivityLogItem; from?: ActivityLogItem; to?: ActivityLogItem; translatedText?: string; isSending?: boolean; menu_list?: QuickMessageTemplateMenuListItem[]; buttons?: QuickMessageTemplateButton[]; event_name?: BillingItemEvent; value?: string | number; currency?: string; file?: FileMessage; files?: FileMessage[]; isTranslateFromInput?: boolean; interactive?: InteractivePayload; sticker?: ChatSticker; referral?: TReferral; feed?: TFeed; location?: TLocation; mention?: TMention; follow?: { isUnblocked: boolean; }; postback?: { data: string; }; }",
                    "references": {
                        "ChatMessageItem": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::ChatMessageItem",
                            "referenceLocation": "ChatMessageItem"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            }
        };
    }
    static get states() {
        return {
            "replyMessage": {},
            "isLoading": {},
            "showError": {}
        };
    }
    static get events() {
        return [{
                "method": "focusRequested",
                "name": "focusRequested",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
}
