import { Host, h } from "@stencil/core";
import dayjs from "dayjs";
import { createQuickMessageTemplate, deleteQuickMessageTemplate, getQuickMessageTemplates, updateQuickMessageTemplate } from "../../api/quick-message";
import { configStore, selectedChatStore } from "../../store/store";
import { useTranslation } from "../../utils/utils";
import { debounce } from "../../utils/helpers";
import { Icon } from "../internal-component/icon";
import { closeDialog, handleError, openDialog, handleError as showErrorDialog } from "../../store/dialog";
import { validateMessageTemplate } from "../../store/message";
import { getConnectionId } from "../../utils/func";
export class QuickMessageTemplateComponent {
    handleClose;
    value;
    isMaster = false;
    isZignal = true;
    searchTemplate = '';
    templates = [];
    showAddTemplateDialog = false;
    editingTemplate;
    dialogMode = 'create';
    isLoading = false;
    isLoadingMore = false;
    isSavingTemplate = false;
    deletingTemplateId;
    templatePendingDelete;
    totalTemplates = 0;
    totalPages = 0;
    isSelectZignal = true;
    isZwizSME = false;
    isZdesk = false;
    page = 1;
    pageSize = 10;
    loadMoreThreshold = 160;
    currentSearch = '';
    scrollContainer;
    debouncedSearch = debounce((value) => {
        void this.fetchTemplates({ search: value, reset: true });
    }, 500);
    templatesChange;
    sendTemplate;
    async componentWillLoad() {
        this.syncTemplatesFromProp(this.value);
        const selectedChat = selectedChatStore.get('selectedChat');
        if (selectedChat?.connection?.type === 'zwiz') {
            this.isSelectZignal = false;
            const connection = configStore.get('connectionList').find(con => con.id === selectedChat.connection.zwiz_connection?.id);
            if (connection && connection.type === 'zwiz') {
                if (connection.platform === 'sme')
                    this.isZwizSME = true;
                if (connection.platform === 'enterprise')
                    this.isZdesk = true;
            }
        }
        await this.fetchTemplates({ reset: true });
    }
    componentDidRender() {
        setTimeout(() => {
            this.autoLoadMoreIfNeeded();
        }, 0);
    }
    handleValueChange(newValue) {
        this.syncTemplatesFromProp(newValue);
    }
    syncTemplatesFromProp(value) {
        if (value === undefined || value === null) {
            this.setTemplates([], false);
            return;
        }
        const parsed = this.parseTemplateValue(value);
        this.setTemplates(parsed, false);
    }
    mergeWithExistingState(fetched) {
        if (this.templates.length === 0) {
            return fetched;
        }
        const expandedMap = new Map(this.templates.map(template => [template.id, template.isExpanded || false]));
        return fetched.map(template => ({
            ...template,
            isExpanded: expandedMap.get(template.id) || template.isExpanded || false,
        }));
    }
    appendTemplates(fetched) {
        if (fetched.length === 0) {
            return [...this.templates];
        }
        const next = [...this.templates];
        const indexMap = new Map(next.map((template, index) => [template.id, index]));
        fetched.forEach(template => {
            const existingIndex = indexMap.get(template.id);
            if (existingIndex !== undefined) {
                next[existingIndex] = {
                    ...template,
                    isExpanded: next[existingIndex].isExpanded || false,
                };
                return;
            }
            next.push({ ...template, isExpanded: template.isExpanded || false });
            indexMap.set(template.id, next.length - 1);
        });
        return next;
    }
    async fetchTemplates({ search, reset = true } = {}) {
        const businessId = configStore.get('businessId');
        const shopId = configStore.get('shopId');
        const selectedChat = selectedChatStore.get('selectedChat');
        if (!businessId || !shopId) {
            return;
        }
        if (reset ? this.isLoading : this.isLoadingMore) {
            return;
        }
        const normalizedSearch = search !== undefined ? search : this.currentSearch;
        const trimmedSearch = normalizedSearch ? normalizedSearch.trim() : '';
        const nextPage = reset ? 1 : this.page + 1;
        if (search !== undefined) {
            this.searchTemplate = normalizedSearch || '';
        }
        if (reset) {
            this.isLoading = true;
        }
        else {
            this.isLoadingMore = true;
        }
        try {
            const response = await getQuickMessageTemplates({
                search: trimmedSearch ? trimmedSearch : undefined,
                page: nextPage,
                limit: this.pageSize,
                connection_id: selectedChat ? getConnectionId() : undefined,
            });
            const normalized = this.cloneTemplates(response.templates || []);
            const nextTemplates = reset ? this.mergeWithExistingState(normalized) : this.appendTemplates(normalized);
            this.page = response.page > 0 ? response.page : nextPage;
            const resolvedTotalPages = response.total_pages > 0 ? response.total_pages : nextTemplates.length > 0 ? 1 : 0;
            this.totalPages = resolvedTotalPages;
            this.totalTemplates = response.total;
            this.currentSearch = trimmedSearch;
            this.setTemplates(nextTemplates);
        }
        catch (error) {
            showErrorDialog(error, '[quick-message-template] Failed to fetch templates');
        }
        finally {
            if (reset) {
                this.isLoading = false;
            }
            else {
                this.isLoadingMore = false;
            }
        }
    }
    async loadMoreTemplates() {
        if (this.isLoading || this.isLoadingMore) {
            return;
        }
        if (this.totalTemplates > 0 && this.templates.length >= this.totalTemplates) {
            return;
        }
        if (this.totalPages === 0 || this.page >= this.totalPages) {
            return;
        }
        await this.fetchTemplates({ reset: false });
    }
    handleScroll(event) {
        const target = event.target;
        if (!target) {
            return;
        }
        this.triggerLoadMoreIfNeeded(target);
    }
    async handleSearchSubmit(event) {
        if (event)
            event.preventDefault();
        await this.fetchTemplates({ search: this.searchTemplate, reset: true });
    }
    handleSearchInput(event) {
        const value = event.target.value;
        this.searchTemplate = value;
        this.debouncedSearch(value);
    }
    clearSearch() {
        if (!this.searchTemplate && !this.currentSearch) {
            return;
        }
        this.searchTemplate = '';
        if (!this.isLoading && !this.isLoadingMore) {
            void this.fetchTemplates({ search: '', reset: true });
        }
    }
    parseTemplateValue(value) {
        if (typeof value === 'string') {
            try {
                const deserialized = JSON.parse(value);
                return this.cloneTemplates(deserialized);
            }
            catch (error) {
                console.warn('[quick-message-template] Failed to parse templates value', error);
                return [];
            }
        }
        return this.cloneTemplates(value);
    }
    cloneTemplates(templates) {
        return (templates || []).map(template => {
            const rawContents = template.contents || [];
            const normalizedContents = rawContents.map(content => {
                const rawMenuList = content.menu_list || [];
                const menuList = rawMenuList.map(menu => ({
                    ...menu,
                    buttons: (menu.buttons || []).map(button => ({ ...button })),
                }));
                return {
                    ...content,
                    buttons: (content.buttons || []).map(button => ({ ...button })),
                    menu_list: menuList,
                };
            });
            return {
                ...template,
                contents: normalizedContents,
            };
        });
    }
    setTemplates(next, shouldEmit = true) {
        this.templates = next;
        if (shouldEmit) {
            const payload = this.cloneTemplates(next);
            this.templatesChange.emit(payload);
        }
    }
    canAttemptLoadMore() {
        if (this.isLoading || this.isLoadingMore) {
            return false;
        }
        if (this.totalTemplates > 0 && this.templates.length >= this.totalTemplates) {
            return false;
        }
        if (this.totalPages === 0 || this.page >= this.totalPages) {
            return false;
        }
        return true;
    }
    triggerLoadMoreIfNeeded(container) {
        if (!this.canAttemptLoadMore()) {
            return;
        }
        const remaining = container.scrollHeight - container.scrollTop - container.clientHeight;
        if (remaining < this.loadMoreThreshold) {
            void this.loadMoreTemplates();
        }
    }
    autoLoadMoreIfNeeded() {
        if (!this.scrollContainer) {
            return;
        }
        this.triggerLoadMoreIfNeeded(this.scrollContainer);
    }
    toggleTemplateExpansion(id) {
        this.setTemplates(this.templates.map(template => (template.id === id ? { ...template, isExpanded: !template.isExpanded } : template)));
    }
    filterTemplates() {
        const search = this.currentSearch.trim().toLowerCase();
        if (!search)
            return this.templates;
        return this.templates.filter(template => template.title.toLowerCase().includes(search));
    }
    handleTemplateAction(template, mode) {
        if (mode === 'create' || mode === 'edit' || mode === 'edit-send') {
            this.openTemplateDialog(template, mode);
            return;
        }
        if (mode === 'send') {
            const clonedTemplate = {
                ...template,
                contents: (template.contents || []).map(content => ({
                    ...content,
                    buttons: [...(content.buttons || [])],
                    menu_list: (content.menu_list || []).map(menu => ({
                        ...menu,
                        buttons: [...(menu.buttons || [])],
                    })),
                })),
            };
            const processedTemplate = this.processTemplate(clonedTemplate);
            if (!processedTemplate) {
                return;
            }
            if (processedTemplate.contents?.length > 0) {
                this.closeTemplateDialog();
                if (this.handleClose)
                    this.handleClose();
                this.sendTemplate.emit(processedTemplate);
            }
            else {
                handleError(null, 'Your template is empty, Please add content to your template');
            }
        }
    }
    renderTemplateContent(content) {
        switch (content.type) {
            case 'text':
                return (h("div", { class: "flex flex-col gap-2" }, h("p", { class: "text-surface whitespace-pre-line text-sm leading-relaxed" }, content.text)));
            case 'button':
                return (h("div", { class: "flex flex-col gap-2" }, h("p", { class: "text-surface whitespace-pre-line text-sm leading-relaxed" }, content.text), h("div", { class: "flex flex-col gap-1.5" }, content.buttons.length > 0 && (h("div", { class: "flex flex-col gap-2" }, content.buttons.map(button => (h("div", { class: "flex w-full flex-col items-center gap-1 rounded-xl px-3 py-2 text-sm font-medium text-white shadow-sm bg-primary truncate", key: button.id }, h("span", { class: "w-full text-center leading-tight truncate" }, button.text || '-'), h("span", { class: "w-full text-center text-xs leading-none opacity-80 truncate" }, button.action_type === 'text' ? '-' : button.action?.length > 15 ? button.action?.slice(0, 15) + '...' : button.action || '-')))))))));
            case 'image':
                return h("div", { class: "flex flex-wrap gap-3" }, (content.file_url || content.file.url) && this.renderImageMedia(content.file_url || content.file.url));
            case 'menu_list':
                return (h("div", { class: "flex gap-3 overflow-x-auto pb-1" }, content.menu_list.map(menu => (h("div", { class: "flex w-60 shrink-0 flex-col overflow-hidden rounded-[18px] border-[1.5px] shadow-sm border-primary bg-background", key: menu.id }, h("div", { class: "relative h-40 border-b-[1.5px] border-primary overflow-hidden" }, (menu.file_url || menu.file.url) ? (h("img", { src: menu.file_url || menu.file.url, alt: menu.title, class: "h-full w-full object-cover", loading: "lazy" })) : (h("div", { class: "flex h-full w-full items-center justify-center bg-background text-theme-gray opacity-60" }, h(Icon, { name: "Image", addClass: "size-10" })))), h("div", { class: "flex flex-col gap-2 px-4 py-4" }, menu.title && h("div", { class: "text-sm font-semibold leading-snug" }, menu.title), menu.description && h("div", { class: "text-xs leading-snug text-theme-gray" }, menu.description), menu.buttons.length > 0 && (h("div", { class: "flex flex-col gap-2" }, menu.buttons.map(button => (h("div", { class: "flex w-full flex-col items-center gap-1 rounded-xl px-3 py-2 text-sm font-medium text-white shadow-sm bg-primary", key: button.id }, h("span", { class: "w-full text-center leading-tight truncate" }, button.text || '-'), h("span", { class: "w-full text-center text-xs leading-none opacity-80 truncate" }, button.action_type === 'text' ? '-' : button.action?.length > 15 ? button.action.slice(0, 15) + '...' : button.action || '-'))))))))))));
            case 'video':
                return (h("video", { src: content.file_url || content.file.url, preload: "metadata", class: "h-[220px] object-cover rounded-xl", controls: true }, h("track", { kind: "captions", src: "", label: "English" })));
            default:
                return null;
        }
    }
    renderImageMedia(fileUrl) {
        return h("img", { src: fileUrl, alt: "", class: "h-[200px] w-[200px] rounded-xl border object-cover border-surface", loading: "lazy" });
    }
    closeTemplateDialog() {
        this.showAddTemplateDialog = false;
        this.editingTemplate = undefined;
        this.dialogMode = 'edit';
        this.isSavingTemplate = false;
    }
    openTemplateDialog(template, mode = 'edit') {
        this.editingTemplate = template ? { ...template } : undefined;
        this.dialogMode = mode;
        this.showAddTemplateDialog = true;
        this.isSavingTemplate = false;
    }
    processTemplate(template) {
        // remove empty menuList
        template.contents = template.contents.map(content => {
            if (content.type === 'menu_list') {
                content.menu_list = content.menu_list.filter(menu => menu.buttons.length > 0 || menu.file_url || menu.title || menu.description || menu.file);
            }
            return content;
        });
        // remove empty content
        template.contents = template.contents.filter(content => content.text || content.buttons.length > 0 || content.file_url || content.menu_list.length > 0 || content.file);
        for (const content of template.contents) {
            if (!validateMessageTemplate(content)) {
                return undefined;
            }
        }
        return template;
    }
    upsertTemplate(template, { closeDialog = true } = {}) {
        const withMeta = {
            ...template,
            isExpanded: (this.editingTemplate ? this.editingTemplate.id : undefined) === template.id ? this.editingTemplate.isExpanded : true,
        };
        const exists = this.templates.some(item => item.id === withMeta.id);
        const nextTemplates = exists ? this.templates.map(item => (item.id === withMeta.id ? withMeta : item)) : [...this.templates, withMeta];
        this.setTemplates(nextTemplates);
        if (closeDialog) {
            this.closeTemplateDialog();
        }
    }
    async handleTemplateSave(template) {
        const t = useTranslation();
        if (this.isSavingTemplate) {
            return;
        }
        const cloned = this.cloneTemplates([template]);
        const workingTemplate = cloned[0];
        if (!workingTemplate) {
            return;
        }
        const processedTemplate = this.processTemplate(workingTemplate);
        if (!processedTemplate) {
            return;
        }
        const isNewTemplate = !processedTemplate.id || processedTemplate.id.startsWith('template-');
        if (!isNewTemplate) {
            try {
                this.isSavingTemplate = true;
                const updated = await updateQuickMessageTemplate(processedTemplate);
                const [normalized] = this.cloneTemplates([updated]);
                this.upsertTemplate(normalized);
                openDialog({
                    open: true,
                    type: "SUCCESS" /* DIALOG_TYPE.SUCCESS */,
                    title: t('success'),
                    onCloseDialog: closeDialog,
                });
                void this.fetchTemplates({ reset: true });
            }
            catch (error) {
                showErrorDialog(error, '[quick-message-template] Failed to update template');
            }
            finally {
                this.isSavingTemplate = false;
            }
            return;
        }
        try {
            this.isSavingTemplate = true;
            const created = await createQuickMessageTemplate(processedTemplate);
            const [normalized] = this.cloneTemplates([created]);
            this.upsertTemplate(normalized);
            openDialog({
                open: true,
                type: "SUCCESS" /* DIALOG_TYPE.SUCCESS */,
                title: t('success'),
                onCloseDialog: closeDialog,
            });
            void this.fetchTemplates({ reset: true });
        }
        catch (error) {
            showErrorDialog(error, '[quick-message-template] Failed to create template');
        }
        finally {
            this.isSavingTemplate = false;
        }
    }
    requestDeleteTemplate(template) {
        if (!(template && template.id) || this.deletingTemplateId) {
            return;
        }
        this.templatePendingDelete = template;
        const t = useTranslation();
        const title = t('quick_message.delete_template_title');
        openDialog({
            open: true,
            type: "WARNING" /* DIALOG_TYPE.WARNING */,
            title,
            buttonName: t('confirm'),
            cancelButtonName: t('cancel'),
            onSubmitDialog: () => {
                this.confirmDeleteTemplate();
            },
            onCloseDialog: () => {
                this.templatePendingDelete = undefined;
            },
        });
    }
    async confirmDeleteTemplate() {
        const t = useTranslation();
        const template = this.templatePendingDelete;
        if (!(template && template.id) || this.deletingTemplateId) {
            this.templatePendingDelete = undefined;
            return;
        }
        this.deletingTemplateId = template.id;
        this.templatePendingDelete = undefined;
        try {
            await deleteQuickMessageTemplate(template.id);
            const remaining = this.templates.filter(item => item.id !== template.id);
            this.setTemplates(remaining);
            this.totalTemplates = Math.max(0, this.totalTemplates - 1);
            openDialog({
                open: true,
                type: "SUCCESS" /* DIALOG_TYPE.SUCCESS */,
                title: t('success'),
                onCloseDialog: closeDialog,
            });
            void this.fetchTemplates({ reset: true });
        }
        catch (error) {
            showErrorDialog(error, '[quick-message-template] Failed to delete template');
        }
        finally {
            this.deletingTemplateId = undefined;
        }
    }
    renderSelectPlatformButton(name, onClick, isSelected) {
        return (h("button", { class: `cursor-pointer inline-flex items-center rounded-full px-4 py-1 text-[10px] font-semibold ${isSelected ? 'text-white bg-primary' : 'text-primary border border-primary'}`, onClick: onClick }, name));
    }
    render() {
        const theme = configStore.get('theme');
        const t = useTranslation();
        const filteredTemplates = this.filterTemplates();
        const showBottomSpinner = (this.isLoading && filteredTemplates.length > 0) || this.isLoadingMore;
        const maxTemplateMessage = configStore.get('package').maxTemplateMessage;
        return (h(Host, { key: '8bbea9cb90b5753c6d43ee3092aa20005de3d7fa', class: "relative flex min-h-0 flex-1 flex-col gap-2", "data-theme": theme }, !this.isMaster && !this.isZignal && h("div", { key: '7335cbc51f59c0842fbb552d97c7bef2a4852cb9', class: "flex items-center gap-2" }, this.renderSelectPlatformButton('ZIGNAL', () => this.isSelectZignal = true, this.isSelectZignal), this.isZwizSME && this.renderSelectPlatformButton('ZWIZ.AI', () => this.isSelectZignal = false, !this.isSelectZignal), this.isZdesk && this.renderSelectPlatformButton('ZDESK', () => this.isSelectZignal = false, !this.isSelectZignal)), h("div", { key: 'e9a6b59cbeac02c322b63cf42c57a9134250fb6c', class: "flex flex-col min-h-0 flex-1" }, h("div", { key: 'e77ee20e30debaa4f7657afc3b64d5a72df6e0e9', class: this.isSelectZignal ? 'quick-message-template__panel' : 'quick-message-template__panel quick-message-template__panel--hidden' }, h("form", { key: '52b1ad500c227bea4a2a0c7e3f19d675920989c3', class: "relative w-full mb-2", onSubmit: event => this.handleSearchSubmit(event) }, h("input", { key: 'a87160bd12b17843d4cce5801822f47fd77aaa47', type: "text", class: "w-full border border-divider text-sm px-4 py-2 rounded-lg ring-primary focus:outline-none focus:border-primary bg-background text-surface", placeholder: t('quick_message.search_template'), value: this.searchTemplate, onInput: event => this.handleSearchInput(event) }), this.searchTemplate && (h("button", { key: '0226a2fbef702813ae431461669bf40036affadc', type: "button", class: "absolute inset-y-0 right-3 flex items-center text-xs opacity-70 transition-opacity hover:opacity-100", onClick: () => this.clearSearch() }, h(Icon, { key: '2175d354d7d029cd76ff0de87011d32025482492', name: "X", addClass: "size-4" }))), h("div", { key: 'fbb8df9b9337384575108c5b6bb07889d3d1c101', class: "flex flex-row justify-between items-center mt-2" }, h("span", { key: 'aa29236f9481b45dc352da8945d5762089a0ef07' }, t('quick_message.template_message_counter', { count: this.templates.length, max: maxTemplateMessage })), h("button", { key: '93397855973afaf16779f4bc727a700c38ec0ec3', type: "button", class: "quick-message-template__action-button flex ml-auto h-9 w-9 items-center justify-center rounded-lg cursor-pointer", onClick: () => this.openTemplateDialog(undefined, 'create'), "aria-label": t('quick_message.add_template'), disabled: this.templates.length >= maxTemplateMessage }, h(Icon, { key: 'c994c8313964d410fdf2cc80744858b87b7c5131', name: "Plus" })))), h("div", { key: '9534eaabe10b971c82aaec5014d74204a4a5d668', class: "flex flex-1 flex-col gap-3 overflow-y-auto min-h-0", ref: el => {
                this.scrollContainer = el ? el : undefined;
            }, onScroll: event => this.handleScroll(event) }, this.isLoading && filteredTemplates.length === 0 ? (h("div", { class: "flex flex-1 items-center justify-center py-10 text-sm text-slate-500" }, h(Icon, { name: "Loader2", addClass: "size-6 animate-spin" }))) : (h("div", { class: "flex flex-col gap-3" }, filteredTemplates.length === 0 && h("div", { class: "py-10 text-center text-sm text-slate-500" }, t('quick_message.template_empty')), filteredTemplates.map(template => {
            const lastUpdatedAt = template.last_updated_at || template.created_at || new Date();
            const formattedDate = dayjs(lastUpdatedAt).tz().format('DD/MM/YYYY HH:mm');
            const rawLastUpdatedBy = template.last_updated_by || template.created_by || '';
            const displayUpdatedBy = typeof rawLastUpdatedBy === 'string' && rawLastUpdatedBy.trim().length > 0 ? rawLastUpdatedBy : '-';
            return (h("div", { class: "quick-message-template__card border-primary rounded-2xl border-[1.5px] px-4 py-4 shadow-[0_8px_24px_rgba(15,23,42,0.08)]", key: template.id }, h("div", { class: "flex flex-col sm:flex-row items-start gap-3 sm:min-w-0" }, h("div", { class: "flex-1 flex flex-col gap-1.5 w-full overflow-hidden" }, h("div", { class: "text-base font-semibold truncate", title: template.title }, template.title), h("div", { class: "text-[11px] text-theme-gray" }, t('quick_message.updated_at').replace('{date}', formattedDate).replace('{by}', displayUpdatedBy))), h("div", { class: "flex gap-4 flex-row items-center self-end" }, this.isMaster && h("button", { type: "button", onClick: () => this.handleTemplateAction(template, 'edit'), "aria-label": t('edit') }, h(Icon, { name: "Pencil", addClass: "size-4 cursor-pointer text-primary" })), this.isMaster && h("button", { type: "button", "aria-label": t('delete'), onClick: () => this.requestDeleteTemplate(template), disabled: Boolean(this.deletingTemplateId), class: `${this.deletingTemplateId ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}` }, this.deletingTemplateId === template.id ? (h(Icon, { name: "Loader2", addClass: "size-4 animate-spin text-primary" })) : (h(Icon, { name: "Trash2", addClass: "size-4 text-primary" }))), !this.isMaster && (h("button", { type: "button", class: "inline-flex items-center justify-center rounded-full border px-4 py-2 text-xs font-semibold cursor-pointer border-primary text-primary", onClick: () => this.handleTemplateAction(template, 'edit-send') }, t('quick_message.edit_before_send'))), !this.isMaster && (h("button", { type: "button", class: "inline-flex items-center justify-center rounded-full px-4 py-2 text-xs font-semibold text-white cursor-pointer bg-primary", onClick: () => this.handleTemplateAction(template, 'send') }, t('quick_message.send_now'))), h("button", { type: "button", class: "quick-message-template__toggle inline-flex h-9 w-9 items-center justify-center rounded-full cursor-pointer", onClick: () => this.toggleTemplateExpansion(template.id) }, h(Icon, { name: template.isExpanded ? 'ChevronUp' : 'ChevronDown' })))), template.isExpanded && (h("div", { class: "mt-4 flex flex-col gap-2" }, template.contents && template.contents.length > 0 ? (template.contents.map(content => (h("div", { key: content.id, class: "border border-surface rounded-xl p-4" }, this.renderTemplateContent(content))))) : (h("div", { class: "border border-surface rounded-xl p-4 text-sm text-theme-gray" }, t('quick_message.no_reply')))))));
        }))), showBottomSpinner && (h("div", { key: '049d87444d47c1777a7d4c5d0278d74d164e040f', class: "flex justify-center py-4 text-sm text-slate-500" }, h(Icon, { key: '345fe10637f4a17f36691333202d02ea60dc2f84', name: "Loader2", addClass: "size-5 animate-spin" }))))), h("div", { key: 'c07c8cf06cca46e6abd6e71673336c60180cdd6f', class: this.isSelectZignal ? 'quick-message-template__panel quick-message-template__panel--hidden' : 'quick-message-template__panel' }, this.isZwizSME
            ? (h("zwiz-quick-message-modal", { onTemplateSent: (event) => {
                    console.log('Zwiz SME quick message modal sent event :>> ', event);
                    this.handleClose ? this.handleClose() : null;
                } }))
            : (this.isZdesk ?
                h("zdesk-quick-message-modal", { onTemplateSent: (event) => {
                        console.log('Zdesk quick message modal sent event :>> ', event);
                        this.handleClose ? this.handleClose() : null;
                    } }) : null))), this.showAddTemplateDialog && (h("quick-message-add-template", { key: 'd149839cc430333fec3031cbb7fa59eb5ab0cd5a', handleClose: () => this.closeTemplateDialog(), handleSave: template => this.handleTemplateSave(template), handleSend: template => this.handleTemplateAction(template, 'send'), initialTemplate: this.editingTemplate, mode: this.dialogMode, isSaving: this.isSavingTemplate }))));
    }
    static get is() { return "quick-message-template"; }
    static get originalStyleUrls() {
        return {
            "$": ["quick-message-template.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["quick-message-template.css"]
        };
    }
    static get properties() {
        return {
            "handleClose": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "() => void",
                    "resolved": "() => void",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "value": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string | QuickMessageTemplateModel[]",
                    "resolved": "QuickMessageTemplate[] | string",
                    "references": {
                        "QuickMessageTemplateModel": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::QuickMessageTemplate",
                            "referenceLocation": "QuickMessageTemplate"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "value"
            },
            "isMaster": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "is-master",
                "defaultValue": "false"
            },
            "isZignal": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "is-zignal",
                "defaultValue": "true"
            }
        };
    }
    static get states() {
        return {
            "searchTemplate": {},
            "templates": {},
            "showAddTemplateDialog": {},
            "editingTemplate": {},
            "dialogMode": {},
            "isLoading": {},
            "isLoadingMore": {},
            "isSavingTemplate": {},
            "deletingTemplateId": {},
            "templatePendingDelete": {},
            "totalTemplates": {},
            "totalPages": {},
            "isSelectZignal": {},
            "isZwizSME": {},
            "isZdesk": {}
        };
    }
    static get events() {
        return [{
                "method": "templatesChange",
                "name": "templatesChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "QuickMessageTemplateModel[]",
                    "resolved": "QuickMessageTemplate[]",
                    "references": {
                        "QuickMessageTemplateModel": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::QuickMessageTemplate",
                            "referenceLocation": "QuickMessageTemplate"
                        }
                    }
                }
            }, {
                "method": "sendTemplate",
                "name": "sendTemplate",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "QuickMessageTemplateModel",
                    "resolved": "{ id: string; title: string; contents: QuickMessageTemplateContent[]; created_at?: string | Date; created_by?: string; last_updated_at: string | Date; last_updated_by: string; isExpanded?: boolean; }",
                    "references": {
                        "QuickMessageTemplateModel": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::QuickMessageTemplate",
                            "referenceLocation": "QuickMessageTemplate"
                        }
                    }
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "value",
                "methodName": "handleValueChange"
            }];
    }
}
