import { Host, h } from "@stencil/core";
import { deviceModeStore, translateStore } from "../../store/store";
import { Icon } from "../internal-component/icon";
import { useTranslation } from "../../utils/utils";
import { ZTextWithLink } from "../internal-component/z-text-with-link";
import { MediaSkeleton } from "../internal-component/media-skeleton";
import { truncateText } from "../../utils/helpers";
const INTERACTIVE_MESSAGE_TYPES = ['image', 'video', 'audio', 'file', 'location', 'sticker', 'attachments', 'imagemap'];
export class MessageContent {
    item;
    isReply = false;
    jumpChat;
    seeTranslate = false;
    isClamped = false;
    showMore = false;
    errorUrls = new Set();
    loadedUrls = new Set();
    contentEl;
    disposeTranslateListener;
    lineClamp = 20;
    checkClamped = () => {
        if (!this.contentEl)
            return;
        this.contentEl.classList.remove(`line-clamp-${this.lineClamp}`);
        const fullHeight = this.contentEl.scrollHeight;
        this.contentEl.classList.add(`line-clamp-${this.lineClamp}`);
        const clampedHeight = this.contentEl.clientHeight;
        this.isClamped = fullHeight > clampedHeight + 1;
    };
    componentDidLoad() {
        this.checkClamped();
        window.addEventListener('resize', this.checkClamped);
    }
    async componentWillLoad() {
        if (this.item.translatedText) {
            this.seeTranslate = true;
        }
        // Watch for translations from the store
        this.disposeTranslateListener = translateStore.onChange('translatedMessages', (translatedMessages) => {
            const translatedText = translatedMessages[this.item.id];
            if (translatedText && translatedText.trim() !== '' && !this.seeTranslate) {
                this.seeTranslate = true;
            }
        });
    }
    disconnectedCallback() {
        window.removeEventListener('resize', this.checkClamped);
        if (this.disposeTranslateListener)
            this.disposeTranslateListener();
    }
    handleError = (url) => {
        this.errorUrls = new Set([...this.errorUrls, url]);
    };
    handleLoad = (url) => {
        this.loadedUrls = new Set([...this.loadedUrls, url]);
    };
    handleJumpChat = () => {
        this.jumpChat.emit();
    };
    renderReplyQuickMessage(replyMessage, isUser, t) {
        if (!(replyMessage && replyMessage.type))
            return null;
        const iconClass = `size-4 ${isUser ? 'text-black' : 'text-white'}`;
        const attachments = replyMessage.attachments || [];
        const template = replyMessage.template || null;
        const templateType = template ? template.type : '';
        const isMenuList = attachments.some((attachment) => attachment.payload && (attachment.payload.template_type === 'generic' || !!attachment.payload.generic)) || templateType === 'carousel';
        const isButton = attachments.some((attachment) => (attachment.payload ? attachment.payload.template_type : '') === 'button') || templateType === 'buttons';
        if (isMenuList) {
            return (h("div", { class: "message-content-reply-quick" }, h(Icon, { name: "SquareMenu", addClass: iconClass }), h("span", { class: "message-content-reply-quick-label" }, t('quick_message.menu_list'))));
        }
        if (isButton) {
            return (h("div", { class: "message-content-reply-quick" }, h(Icon, { name: "Touchpad", addClass: iconClass }), h("span", { class: "message-content-reply-quick-label" }, t('quick_message.button'))));
        }
        return null;
    }
    renderActionButton(button, key, isUser, extraClasses = '') {
        if (!button)
            return null;
        const className = ['message-content-action-button', extraClasses, !isUser ? 'message-content-action-button-admin' : ''].filter(Boolean).join(' ');
        const actionValue = (button.action || '').trim();
        const maxChar = 15;
        if (button.action_type === 'url' && actionValue) {
            return (h("a", { key: key, href: actionValue, target: "_blank", rel: "noopener noreferrer", class: className }, h("span", { class: "message-content-action-button-label" }, button.text || '-'), h("span", { class: "message-content-action-button-action", title: actionValue }, truncateText(actionValue, maxChar))));
        }
        if (button.action_type === 'tel' && actionValue) {
            const telHref = actionValue.startsWith('tel:') ? actionValue : `tel:${actionValue}`;
            return (h("a", { key: key, href: telHref, class: className }, h("span", { class: "message-content-action-button-label" }, button.text || '-'), h("span", { class: "message-content-action-button-action", title: actionValue }, truncateText(actionValue, maxChar))));
        }
        return (h("div", { key: key, class: className }, h("span", { class: "message-content-action-button-label" }, button.text || '-'), h("span", { class: "message-content-action-button-action", title: actionValue }, truncateText(actionValue, maxChar) || '-')));
    }
    renderButtons(isUser) {
        if (this.item.type !== 'button')
            return null;
        const buttons = this.item.isSending ? this.item.buttons || [] : this.item.buttons || [];
        if (buttons.length === 0)
            return null;
        return h("div", { class: "message-content-buttons" }, buttons.map((button, index) => this.renderActionButton(button, (button ? button.id : '') || `${index}`, isUser)));
    }
    renderMenuList(isUser) {
        if (this.item.type !== 'menu_list' && this.item.type !== 'interactive')
            return null;
        const menus = this.item.type === 'interactive' && this.item.interactive
            ? this.mapInteractiveToMenuList(this.item.interactive)
            : (this.item.menu_list || []);
        if (menus.length === 0)
            return null;
        return (h("div", { class: "message-content-menu-list" }, menus.map((menu, menuIndex) => (h("div", { class: "message-content-menu-card", key: (menu ? menu.id : '') || `${menuIndex}` }, (menu ? menu.file_url : '') && (h("div", { class: "message-content-menu-card-media" }, !this.loadedUrls.has(menu.file_url) && h(MediaSkeleton, null), h("img", { src: menu.file_url, alt: menu.title || 'menu-item', class: "message-content-menu-card-image", onError: () => this.handleError(menu.file_url), onLoad: () => this.handleLoad(menu.file_url), loading: "lazy" }))), h("div", { class: "message-content-menu-card-body" }, (menu ? menu.title : '') && h("h4", { class: "message-content-menu-card-title" }, menu.title), (menu ? menu.description : '') && h("p", { class: "message-content-menu-card-description" }, menu.description), (menu ? menu.buttons : []) && menu.buttons.length > 0 && (h("div", { class: "message-content-menu-card-buttons" }, menu.buttons.map((button, buttonIndex) => this.renderActionButton(button, `${(menu ? menu.id : '') || menuIndex}-${(button ? button.id : '') || buttonIndex}`, isUser, 'message-content-action-button-compact'))))))))));
    }
    renderActionElement(title, button, key, isUser, extraClasses = '') {
        if (!button)
            return null;
        const className = ['message-content-action-button', extraClasses, !isUser ? 'message-content-action-button-admin' : ''].filter(Boolean).join(' ');
        const actionValue = (button.text || '').trim();
        const maxChar = 15;
        return (h("div", { key: key, class: className }, h("span", { class: "message-content-action-button-label" }, title || button.text || '-'), h("span", { class: "message-content-action-button-action", title: actionValue }, truncateText(actionValue, maxChar) || '-')));
    }
    renderElements(isUser) {
        if (this.item.type !== 'qa_button_card')
            return null;
        const buttons = this.item.isSending ? this.item.elements.buttons || [] : this.item.elements.buttons || [];
        if (buttons.length === 0)
            return null;
        return h("div", { class: "message-content-buttons" }, buttons.map((button, index) => this.renderActionElement(this.item.elements.title, button, (button ? button.id : '') || `${index}`, isUser)));
    }
    renderReplyMessage(reply_message, isUser) {
        if (!reply_message)
            return null;
        const t = useTranslation();
        const replyQuickPreview = this.renderReplyQuickMessage(reply_message, isUser, t);
        const isMedia = ['image', 'sticker', 'file', 'audio', 'video', 'attachment', 'files'].includes(reply_message.type) || (reply_message.attachments && reply_message.attachments.length > 0);
        return (h("div", { class: `message-content-reply-wrapper ${isUser ? 'message-content-reply-wrapper-user' : 'message-content-reply-wrapper-admin'}`, onClick: () => this.handleJumpChat() }, h("div", { class: `message-content-reply-spacer ${isUser ? 'bg-black' : 'bg-white'}` }, "\u00A0\u00A0"), reply_message.text && h("span", { class: "message-content-reply-text" }, reply_message.text), isMedia && (replyQuickPreview ?? h("message-media", { item: reply_message }))));
    }
    mapInteractiveToMenuList(interactive) {
        const { header, body, footer, action } = interactive;
        const buttons = (action?.buttons || []).map((btn, index) => {
            const btnTitle = btn.reply?.title || '';
            const btnId = btn.reply?.id || '';
            let actionType = 'text';
            let actionValue = btnId;
            if (btnId.startsWith('url|')) {
                actionType = 'url';
                actionValue = btnId.substring(4);
            }
            else if (btnId.startsWith('tel|')) {
                actionType = 'tel';
                actionValue = btnId.substring(4);
            }
            else if (btnId.startsWith('pb|')) {
                actionType = 'text';
                actionValue = btnId.substring(3);
            }
            const resultBtn = {
                id: `${index}`,
                action_type: actionType,
                text: btnTitle,
                action: actionValue,
            };
            return resultBtn;
        });
        const menuList = [{
                id: `interactive-menu-${Date.now()}`,
                file_url: header?.image?.link,
                title: body?.text,
                description: footer?.text,
                buttons: buttons,
            }];
        return menuList;
    }
    renderLocation() {
        const location = this.item.location;
        if (!location)
            return null;
        const { latitude, longitude, address } = location;
        const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${latitude},${longitude}`;
        const delta = 0.005;
        const bbox = `${longitude - delta},${latitude - delta},${longitude + delta},${latitude + delta}`;
        const osmEmbedUrl = `https://www.openstreetmap.org/export/embed.html?bbox=${bbox}&layer=mapnik&marker=${latitude},${longitude}`;
        const coordinatesLabel = `${latitude.toFixed(6)}, ${longitude.toFixed(6)}`;
        return (h("div", { class: "message-content-location" }, h("div", { class: "message-content-location-map" }, h("iframe", { src: osmEmbedUrl, class: "message-content-location-map-iframe", loading: "lazy", referrerPolicy: "no-referrer", sandbox: "allow-popups allow-forms allow-same-origin allow-scripts allow-top-navigation allow-popups-to-escape-sandbox allow-downloads" }), h("a", { href: googleMapsUrl, target: "_blank", rel: "noopener noreferrer", class: "message-content-location-map-overlay", onClick: (e) => e.stopPropagation() }, h(Icon, { name: "ExternalLink", addClass: "size-3.5" }), h("span", null, "Open in Maps"))), address && h("p", { class: "message-content-location-address" }, address), h("p", { class: "message-content-location-coords" }, coordinatesLabel)));
    }
    renderToggleTranslateMessage() {
        const t = useTranslation();
        const isUser = this.item.sender.type === 'user';
        const translatedTextValue = this.item.translatedText || translateStore.get('translatedMessages')[this.item.id];
        if (translatedTextValue && this.item.text !== translatedTextValue) {
            const translateMeta = translateStore.get('translatedMessagesMeta')[this.item.id];
            const isTranslateFromInput = this.item.isTranslateFromInput || (translateMeta ? translateMeta.isTranslateFromInput : false);
            return h("p", { class: "message-content-translate-wrapper", onClick: () => (this.seeTranslate = !this.seeTranslate) }, h(Icon, { name: "Languages", addClass: `size-3 ${isUser ? 'text-primary' : 'text-primary'}` }), "\u00A0", h("span", { class: `underline ${isUser ? 'text-primary' : 'text-primary'}` }, this.seeTranslate
                ? t(isTranslateFromInput ? 'chat_tab.see_send_text' : 'chat_tab.see_original')
                : t(isTranslateFromInput ? 'chat_tab.see_original' : 'chat_tab.see_translated')));
        }
        return null;
    }
    render() {
        const t = useTranslation();
        const { sender, type, event_type, text, translatedText, reply_message, error_data, postback } = this.item;
        const displayText = text || postback?.data;
        const translatedTextValue = translatedText || translateStore.get('translatedMessages')[this.item.id];
        const isMobile = deviceModeStore.get('mode') === 'mobile';
        const isUser = sender.type === 'user';
        const isInteractiveType = type ? INTERACTIVE_MESSAGE_TYPES.includes(type) : false;
        const isZptAnswered = type === 'zpt-answered' || event_type === 'zpt-answered';
        const isLocation = type === 'location';
        const bubblePadding = type === 'menu_list' || type === 'interactive' ? 'p-3' : ['button', 'text', 'zwiz-broadcast', 'zwiz-broadcast-mm', 'zpt-answered', 'postback'].includes(type) || !type ? 'px-3 py-2' : 'p-2';
        const classBox = this.isReply
            ? `message-content-reply bg-paper text-theme-gray ${!isUser ? 'rounded-bl-[0]' : 'rounded-br-[0]'} ${isInteractiveType ? 'cursor-pointer' : ''} ${isMobile ? 'max-w-3xs' : 'max-w-sm'}`
            : `message-content ${bubblePadding} ${isZptAnswered ? 'message-content-zpt-answered' : isUser ? 'message-content-user' : 'message-content-admin'} ${isInteractiveType ? 'cursor-pointer' : ''} ${isMobile ? 'max-w-3xs' : 'max-w-sm'} ${error_data ? 'border-2 border-primary' : ''}`;
        const buttonsContent = this.renderButtons(isUser);
        const menuListContent = this.renderMenuList(isUser);
        const elementsContent = this.renderElements(isUser);
        return (h(Host, { key: 'c00fe33cf8a5d560697577a37e1289f2c580f668' }, h("div", { key: '45fa35c9fbced162b63730daba13fd0f24890088', id: `message-content-${this.item.id}`, tabIndex: -1, class: classBox }, reply_message && this.renderReplyMessage(reply_message, isUser), h("div", { key: '28504edb7d2891086045502687caa4c400b9cdfc', class: "message-content-text-wrapper" }, (['text', 'zwiz-broadcast', 'zwiz-broadcast-mm', 'zpt-answered'].includes(type) || displayText) && (h("p", { key: '053a4abf027bf4204f08a54d8fa298d8b2e67b5d', ref: el => (this.contentEl = el), class: `message-content-text ${this.showMore ? '' : `line-clamp-${this.lineClamp}`}` }, h(ZTextWithLink, { key: '1e984f99a3d5b864cd31553161ce7f0c504f08c9', text: this.seeTranslate ? translatedTextValue : displayText, mention: this.item.mention }))), this.renderToggleTranslateMessage(), this.isClamped && (h("div", { key: '2eebae191412ba83b1c3105e7472e3682f343a33', class: "message-content-clamp-wrapper mt-1", onClick: () => (this.showMore = !this.showMore) }, this.showMore ? t('chat_tab.hide') : t('chat_tab.see_all_text'))), buttonsContent, menuListContent, elementsContent, isLocation && this.renderLocation(), !['text', 'button', 'menu_list', 'flex', 'interactive', 'zwiz-broadcast', 'zwiz-broadcast-mm', 'zpt-answered', 'location', 'qa_button_card', 'postback'].includes(this.item.type) && h("message-media", { key: '308044629bf755910257cf5ac37354b4bcfeebac', item: this.item }), this.item.type === 'flex' && h("flex-message-render", { key: '87d8fd1c21ff3993618c480e67b289cc9a1ae4d1', flexJson: this.item.contents })))));
    }
    static get is() { return "message-content"; }
    static get originalStyleUrls() {
        return {
            "$": ["message-content.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["message-content.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": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "isReply": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "is-reply",
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "seeTranslate": {},
            "isClamped": {},
            "showMore": {},
            "errorUrls": {},
            "loadedUrls": {}
        };
    }
    static get events() {
        return [{
                "method": "jumpChat",
                "name": "jumpChat",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }];
    }
}
