import { Host, h } from "@stencil/core";
import dayjs from "dayjs";
import { createQuickMessageLibraryFiles, deleteQuickMessageLibraryFile, getQuickMessageLibraryFiles, updateQuickMessageLibraryFileName } from "../../api/quick-message";
import { configStore, storageUsageStore } from "../../store/store";
import { useTranslation } from "../../utils/utils";
import { Icon } from "../internal-component/icon";
import { MediaSkeleton } from "../internal-component/media-skeleton";
import { uploadFileService } from "../../utils/upload";
import { handleError as showErrorDialog, openDialog, closeDialog } from "../../store/dialog";
import { ZStorageUsage } from "../internal-component/z-storage-usage";
export class QuickMessageImageComponent {
    handleClose;
    value;
    isMaster = false;
    searchImage = '';
    images = [];
    imageDisplayMode = 'grid';
    isLoading = false;
    isLoadingMore = false;
    isUploading = false;
    isDeleting = false;
    totalImages = 0;
    totalPages = 0;
    renameTargetId = null;
    renameName = '';
    renameExtension = '';
    isRenaming = false;
    openMenuId = null;
    loadedUrls = new Set();
    errorUrls = new Set();
    pageSize = 15;
    localUploadPrefix = 'uploaded-image-';
    page = 1;
    currentSearch = '';
    fileInput;
    imagesChange;
    sendImages;
    pendingDeleteImageIds = [];
    // Memoization cache for filtered images
    cachedFilteredImages = null;
    cachedSearchTerm = '';
    cachedImagesLength = 0;
    handleDocumentClick(event) {
        const target = event.target;
        if (target && target.closest('[data-quick-message-image-menu-root]')) {
            return;
        }
        this.openMenuId = null;
    }
    componentWillLoad() {
        this.syncImagesFromProp(this.value);
    }
    async componentDidLoad() {
        await this.fetchImages({ reset: true });
    }
    handleValueChange(newValue) {
        this.syncImagesFromProp(newValue);
    }
    syncImagesFromProp(value) {
        if (value === undefined || value === null) {
            this.setImages([], false);
            return;
        }
        const parsed = this.parseImagesValue(value);
        this.setImages(parsed, false);
    }
    parseImagesValue(value) {
        if (typeof value === 'string') {
            try {
                const deserialized = JSON.parse(value);
                return this.cloneImages(deserialized);
            }
            catch (error) {
                console.warn('[quick-message-image] Failed to parse images value', error);
                return [];
            }
        }
        return this.cloneImages(value);
    }
    cloneImages(images) {
        return (images || []).map(image => ({
            ...image,
            isSelected: image.isSelected || false,
        }));
    }
    setImages(next, shouldEmit = true) {
        this.images = next;
        if (shouldEmit) {
            const payload = this.cloneImages(next);
            this.imagesChange.emit(payload);
        }
    }
    isLocalUpload(image) {
        return image.id.startsWith(this.localUploadPrefix);
    }
    getRemoteImageCount() {
        return this.images.filter(image => !this.isLocalUpload(image)).length;
    }
    mergeFetchedImages(fetched, reset) {
        const localUploads = this.images.filter(image => this.isLocalUpload(image));
        const selectionMap = new Map(this.images.map(image => [image.id, image.isSelected || false]));
        const normalizedFetched = fetched.map(image => ({
            ...image,
            isSelected: selectionMap.get(image.id) || image.isSelected || false,
        }));
        if (reset) {
            return [...localUploads, ...normalizedFetched];
        }
        const existingRemote = this.images.filter(image => !this.isLocalUpload(image));
        const remoteIndexMap = new Map();
        existingRemote.forEach((image, index) => {
            remoteIndexMap.set(image.id, index);
        });
        const nextRemote = [...existingRemote];
        normalizedFetched.forEach(image => {
            const existingIndex = remoteIndexMap.get(image.id);
            if (existingIndex !== undefined) {
                nextRemote[existingIndex] = image;
            }
            else {
                remoteIndexMap.set(image.id, nextRemote.length);
                nextRemote.push(image);
            }
        });
        return [...localUploads, ...nextRemote];
    }
    /**
     * Memoized image filtering - only recalculates when search term or images change
     * Performance: Reduces operations from 60fps to only when user types
     */
    filterImages() {
        const search = this.searchImage.trim().toLowerCase();
        // Quick return for no search
        if (!search)
            return this.images;
        // Check if we can use cached results
        if (this.cachedFilteredImages && search === this.cachedSearchTerm && this.images.length === this.cachedImagesLength) {
            return this.cachedFilteredImages;
        }
        // Recalculate filtered results
        const filtered = this.images.filter(image => image.name.toLowerCase().includes(search));
        // Update cache
        this.cachedFilteredImages = filtered;
        this.cachedSearchTerm = search;
        this.cachedImagesLength = this.images.length;
        return filtered;
    }
    splitFileName(name) {
        const lastDotIndex = name.lastIndexOf('.');
        if (lastDotIndex <= 0 || lastDotIndex === name.length - 1) {
            return { base: name, extension: '' };
        }
        return {
            base: name.slice(0, lastDotIndex),
            extension: name.slice(lastDotIndex),
        };
    }
    getRenameTarget() {
        if (!this.renameTargetId) {
            return undefined;
        }
        return this.images.find(image => image.id === this.renameTargetId);
    }
    openRenameModal(image, event) {
        if (event) {
            event.preventDefault();
            event.stopPropagation();
        }
        const { base, extension } = this.splitFileName(image.name);
        this.renameTargetId = image.id;
        this.renameName = base;
        this.renameExtension = extension;
    }
    closeRenameModal(force = false) {
        if (this.isRenaming && !force) {
            return;
        }
        this.renameTargetId = null;
        this.renameName = '';
        this.renameExtension = '';
    }
    toggleMenu(imageId, event) {
        event.preventDefault();
        event.stopPropagation();
        this.openMenuId = this.openMenuId === imageId ? null : imageId;
    }
    closeMenu() {
        this.openMenuId = null;
    }
    handleImageLoad = (url) => {
        this.loadedUrls = new Set([...this.loadedUrls, url]);
    };
    handleImageError = (url) => {
        this.errorUrls = new Set([...this.errorUrls, url]);
    };
    handleMenuRename(image, event) {
        event.preventDefault();
        event.stopPropagation();
        this.closeMenu();
        this.openRenameModal(image, event);
    }
    requestDeleteImage(image, event) {
        event.preventDefault();
        event.stopPropagation();
        if (this.isDeleting) {
            return;
        }
        this.pendingDeleteImageIds = [image.id];
        this.closeMenu();
        const t = useTranslation();
        openDialog({
            open: true,
            type: "WARNING" /* DIALOG_TYPE.WARNING */,
            title: t('quick_message.delete_item_confirmation'),
            buttonName: t('confirm'),
            cancelButtonName: t('cancel'),
            onSubmitDialog: () => {
                void this.confirmDeleteSelectedImages();
            },
            onCloseDialog: () => {
                this.pendingDeleteImageIds = [];
            },
        });
    }
    handleRenameInput(event) {
        const value = event.target.value;
        if (this.renameExtension && value.toLowerCase().endsWith(this.renameExtension.toLowerCase())) {
            this.renameName = value.slice(0, -this.renameExtension.length);
            return;
        }
        this.renameName = value;
    }
    async handleRenameSubmit(event) {
        const t = useTranslation();
        event.preventDefault();
        const target = this.getRenameTarget();
        if (!target) {
            return;
        }
        const trimmedBase = this.renameName.trim();
        if (!trimmedBase) {
            return;
        }
        const nextName = this.renameExtension ? `${trimmedBase}${this.renameExtension}` : trimmedBase;
        if (nextName === target.name) {
            this.closeRenameModal(true);
            return;
        }
        if (this.isLocalUpload(target)) {
            this.setImages(this.images.map(image => image.id === target.id
                ? {
                    ...image,
                    name: nextName,
                }
                : image));
            this.closeRenameModal(true);
            return;
        }
        this.isRenaming = true;
        try {
            const updated = await updateQuickMessageLibraryFileName({ id: target.id, name: nextName });
            this.setImages(this.images.map(image => image.id === target.id
                ? {
                    ...image,
                    name: updated.name,
                    last_updated_at: updated.last_updated_at,
                    last_updated_by: updated.last_updated_by,
                }
                : image));
            this.closeRenameModal(true);
            openDialog({
                open: true,
                type: "SUCCESS" /* DIALOG_TYPE.SUCCESS */,
                title: t('success'),
                onCloseDialog: closeDialog,
            });
        }
        catch (error) {
            showErrorDialog(error, '[quick-message-image] Failed to rename image');
        }
        finally {
            this.isRenaming = false;
        }
    }
    toggleImageSelection(id) {
        this.setImages(this.images.map(image => (image.id === id ? { ...image, isSelected: !image.isSelected } : image)));
    }
    toggleSelectAllImages() {
        const isAllSelected = this.images.length > 0 && this.images.every(image => image.isSelected);
        this.setImages(this.images.map(image => ({ ...image, isSelected: !isAllSelected })));
    }
    triggerImageUpload() {
        if (this.fileInput)
            this.fileInput.click();
    }
    handleImageSelection(event) {
        const input = event.target;
        if (!input.files || input.files.length === 0)
            return;
        const files = Array.from(input.files);
        input.value = '';
        void this.uploadAndCreateImages(files);
    }
    async uploadAndCreateImages(files) {
        const t = useTranslation();
        if (files.length === 0) {
            return;
        }
        this.isUploading = true;
        try {
            const payload = [];
            for (const file of files) {
                const response = await uploadFileService({
                    file,
                    filename: file.name.replaceAll(' ', '-'),
                    usageType: 'quick_message_template',
                });
                if (!response) {
                    continue;
                }
                payload.push({
                    file_type: 'image',
                    name: file.name,
                    url: response.url,
                    size: file.size,
                    file_id: response.id,
                });
            }
            if (payload.length > 0) {
                await createQuickMessageLibraryFiles({ files: payload });
                openDialog({
                    open: true,
                    type: "SUCCESS" /* DIALOG_TYPE.SUCCESS */,
                    title: t('success'),
                    onCloseDialog: closeDialog,
                });
                await this.fetchImages({ reset: true });
            }
        }
        catch (error) {
            showErrorDialog(error, '[quick-message-image] Failed to upload image');
        }
        finally {
            this.isUploading = false;
        }
    }
    renderFileMeta(size, createdAt, t) {
        const sizeKb = Math.round(size / 1024);
        return `${sizeKb} KB · ${t('quick_message.created_at').replace('{date}', dayjs(createdAt).tz().format('DD/MM/YYYY HH:mm'))}`;
    }
    handleSendImages() {
        const selected = this.images.filter(image => image.isSelected);
        if (selected.length === 0)
            return;
        const payload = this.cloneImages(selected);
        this.sendImages.emit(payload);
        if (this.handleClose)
            this.handleClose();
    }
    requestDeleteSelectedImages() {
        if (this.isDeleting) {
            return;
        }
        const selectedIds = this.images.filter(image => image.isSelected).map(image => image.id);
        if (selectedIds.length === 0) {
            return;
        }
        this.pendingDeleteImageIds = selectedIds;
        const t = useTranslation();
        openDialog({
            open: true,
            type: "WARNING" /* DIALOG_TYPE.WARNING */,
            title: t('quick_message.delete_selected_items_confirmation'),
            buttonName: t('confirm'),
            cancelButtonName: t('cancel'),
            onSubmitDialog: () => {
                void this.confirmDeleteSelectedImages();
            },
            onCloseDialog: () => {
                this.pendingDeleteImageIds = [];
            },
        });
    }
    async confirmDeleteSelectedImages() {
        const t = useTranslation();
        if (this.isDeleting) {
            return;
        }
        const pendingIds = [...this.pendingDeleteImageIds];
        this.pendingDeleteImageIds = [];
        if (pendingIds.length === 0) {
            return;
        }
        const pendingSet = new Set(pendingIds);
        const remoteIds = this.images.filter(image => pendingSet.has(image.id) && !this.isLocalUpload(image)).map(image => image.id);
        this.isDeleting = true;
        try {
            if (remoteIds.length > 0) {
                await deleteQuickMessageLibraryFile({ ids: remoteIds });
            }
            const remaining = this.images.filter(image => !pendingSet.has(image.id));
            this.setImages(remaining);
            if (remoteIds.length > 0) {
                this.totalImages = Math.max(0, this.totalImages - remoteIds.length);
                openDialog({
                    open: true,
                    type: "SUCCESS" /* DIALOG_TYPE.SUCCESS */,
                    title: t('success'),
                    onCloseDialog: closeDialog,
                });
                await this.fetchImages({ reset: true });
            }
        }
        catch (error) {
            showErrorDialog(error, '[quick-message-image] Failed to delete images');
        }
        finally {
            this.isDeleting = false;
        }
    }
    async fetchImages({ search, reset = true } = {}) {
        const businessId = configStore.get('businessId');
        const shopId = configStore.get('shopId');
        if (!businessId || !shopId) {
            return;
        }
        if (reset ? this.isLoading : this.isLoadingMore) {
            return;
        }
        const searchSource = search !== undefined ? search : reset ? this.searchImage : this.currentSearch;
        const trimmedSearch = searchSource ? searchSource.trim() : '';
        const nextPage = reset ? 1 : this.page + 1;
        if (search !== undefined) {
            this.searchImage = searchSource || '';
        }
        if (reset) {
            this.isLoading = true;
        }
        else {
            this.isLoadingMore = true;
        }
        try {
            const response = await getQuickMessageLibraryFiles({
                fileType: 'image',
                search: trimmedSearch ? trimmedSearch : undefined,
                page: nextPage,
                limit: this.pageSize,
            });
            const fetched = this.cloneImages(response.files || []);
            const merged = this.mergeFetchedImages(fetched, reset);
            this.page = response.page > 0 ? response.page : nextPage;
            const resolvedTotalPages = response.total_pages > 0 ? response.total_pages : fetched.length > 0 ? 1 : 0;
            this.totalPages = resolvedTotalPages;
            this.totalImages = typeof response.total === 'number' ? response.total : fetched.length;
            this.currentSearch = trimmedSearch;
            this.setImages(merged);
        }
        catch (error) {
            console.error('[quick-message-image] Failed to fetch images', error);
        }
        finally {
            if (reset) {
                this.isLoading = false;
            }
            else {
                this.isLoadingMore = false;
            }
        }
    }
    async loadMoreImages() {
        if (this.isLoading || this.isLoadingMore) {
            return;
        }
        if (this.totalPages === 0 || this.page >= this.totalPages) {
            return;
        }
        if (this.totalImages > 0) {
            const remoteCount = this.getRemoteImageCount();
            if (remoteCount >= this.totalImages) {
                return;
            }
        }
        await this.fetchImages({ reset: false });
    }
    handleScroll(event) {
        const target = event.target;
        if (!target) {
            return;
        }
        const remaining = target.scrollHeight - target.scrollTop - target.clientHeight;
        if (remaining < 160) {
            void this.loadMoreImages();
        }
    }
    handleSearchInput(event) {
        const value = event.target.value;
        this.searchImage = value;
        if (!value.trim() && this.currentSearch && !this.isLoading && !this.isLoadingMore) {
            void this.fetchImages({ search: '', reset: true });
        }
    }
    async handleSearchSubmit(event) {
        if (event)
            event.preventDefault();
        await this.fetchImages({ search: this.searchImage, reset: true });
    }
    clearSearch() {
        if (!this.searchImage) {
            return;
        }
        this.searchImage = '';
        if (this.currentSearch) {
            void this.fetchImages({ search: '', reset: true });
        }
    }
    renderRenameModal(labels) {
        const target = this.getRenameTarget();
        if (!this.renameTargetId || !target) {
            return null;
        }
        const trimmedBase = this.renameName.trim();
        const nextName = this.renameExtension ? `${trimmedBase}${this.renameExtension}` : trimmedBase;
        const isSaveDisabled = this.isRenaming || trimmedBase.length === 0 || nextName === target.name;
        const inputId = `quick-message-image-rename-${target.id}`;
        return (h("div", { class: "quick-message-image__rename-overlay", role: "dialog", "aria-modal": "true", "aria-labelledby": "quick-message-image-rename-title", onClick: () => this.closeRenameModal() }, h("div", { class: `quick-message-image__rename-modal bg-background text-surface`, onClick: event => event.stopPropagation() }, h("div", { class: "quick-message-image__rename-header" }, h("h3", { id: "quick-message-image-rename-title", class: "text-base font-semibold" }, labels.renameLabel), h("button", { type: "button", class: "quick-message-image__rename-close", onClick: () => this.closeRenameModal(), "aria-label": labels.closeLabel, disabled: this.isRenaming }, h(Icon, { name: "X" }))), h("form", { class: "flex flex-col gap-4", onSubmit: event => this.handleRenameSubmit(event) }, h("label", { class: "flex flex-col gap-2 text-sm", htmlFor: inputId }, h("span", { class: "font-medium" }, labels.nameLabel), h("div", { class: `quick-message-image__rename-input-row border border-divider bg-background` }, h("input", { id: inputId, type: "text", class: "quick-message-image__rename-input text-surface", value: this.renameName, onInput: event => this.handleRenameInput(event) }), this.renameExtension && h("span", { class: "quick-message-image__rename-extension" }, this.renameExtension))), h("div", { class: "flex justify-end gap-2 text-sm" }, h("button", { type: "button", class: "quick-message-image__rename-cancel", onClick: () => this.closeRenameModal(), disabled: this.isRenaming }, labels.cancelLabel), h("button", { type: "submit", class: "quick-message-image__rename-save", disabled: isSaveDisabled }, this.isRenaming ? h(Icon, { name: "Loader2", addClass: "size-4 animate-spin" }) : labels.saveLabel))))));
    }
    handleChangeDisplayMode = () => {
        this.imageDisplayMode = this.imageDisplayMode === 'grid' ? 'list' : 'grid';
        this.loadedUrls.clear();
        this.errorUrls.clear();
    };
    render() {
        const theme = configStore.get('theme');
        const t = useTranslation();
        const filteredImages = this.filterImages();
        const hasSelection = this.images.some(image => image.isSelected);
        const isInitialLoading = this.isLoading && this.images.length === 0;
        const renameLabel = t('quick_message.rename_item');
        const deleteLabel = t('remove');
        const nameLabel = t('quick_message.name');
        const saveLabel = t('save');
        const cancelLabel = t('cancel');
        const closeLabel = t('close');
        const isStorageFull = storageUsageStore.get('usage') >= configStore.get('package').maxStorage;
        return (h(Host, { key: 'f2ee534edec7fe079e57653d6f88172f795cdf03', class: "flex min-h-0 flex-1 flex-col gap-4", "data-theme": theme }, h("form", { key: '31736bf38d19c3f89f8fa4cd5459a9e308125c43', class: "w-full", onSubmit: event => this.handleSearchSubmit(event) }, h("div", { key: '95494cfa718ddb61c1ab95c584488acf0081c82c', class: "relative" }, h("input", { key: '8d588c295ded010e6d1d25e6e74aa3fe3e75256c', type: "text", class: `w-full border border-divider text-sm px-4 py-2 pr-9 rounded-lg ring-primary focus:outline-none focus:border-primary bg-background text-surface`, placeholder: t('quick_message.search_image'), value: this.searchImage, onInput: event => this.handleSearchInput(event) }), this.searchImage && (h("button", { key: 'a92344e2fbba94224bf41c195f57d294f18d877a', type: "button", class: "absolute right-2 top-1/2 -translate-y-1/2 text-xs text-gray-400 hover:text-gray-600", onClick: () => this.clearSearch(), "aria-label": t('clear') || 'Clear' }, h(Icon, { key: 'f83bab69ff054c23ff3ea87a3ada39d4f692005e', name: "X" }))))), h("div", { key: '97f18fe032dc5a80db9fc38edf0a29eff8efebbd', class: "flex items-center justify-between" }, this.images.length > 0 ? (h("label", { class: "inline-flex items-center gap-2 text-sm" }, h("input", { type: "checkbox", checked: this.images.length > 0 && this.images.every(image => image.isSelected), onChange: () => this.toggleSelectAllImages() }), h("span", null, t('select_all')))) : (h("span", null)), h("div", { key: '00f2f26ff86fbb7dd8e789ef42ce8238a3576d61', class: "flex items-center gap-2" }, h("input", { key: 'ec10cbf4e05013b75a21aec92b3638c4efc04df6', class: "hidden", type: "file", accept: "image/*", multiple: true, ref: el => (this.fileInput = el), onChange: event => this.handleImageSelection(event) }), h("button", { key: '3dae01e5948de80c0781b2b7f9ab7e190ff70512', type: "button", class: "quick-message-image__action-button inline-flex h-9 w-9 items-center justify-center rounded-lg cursor-pointer", onClick: () => !this.isUploading && this.triggerImageUpload(), "aria-label": t('quick_message.add_image'), disabled: this.isUploading || isStorageFull }, this.isUploading ? h(Icon, { name: "Loader2", addClass: "size-4 animate-spin" }) : h(Icon, { name: "Plus" })), this.images.length > 0 && (h("button", { key: '3949d973a40b252ae6be493bdf416923c6e0372d', class: "quick-message-image__action-button quick-message-image__display-switch inline-flex h-9 w-9 items-center justify-center rounded-lg cursor-pointer", type: "button", onClick: this.handleChangeDisplayMode, "aria-label": this.imageDisplayMode === 'grid' ? t('quick_message.display_list') : t('quick_message.display_grid') }, h(Icon, { key: 'f0d9b22ac6b1140509ac7872cbfa973522f5e9f4', name: this.imageDisplayMode === 'grid' ? 'List' : 'Grid' }))))), h(ZStorageUsage, { key: '395d2705f89b94c0e6fe06fb73b11802e908c41f' }), this.isUploading && (h("div", { key: 'b99ae7fc8e402624782a6215193d938393cce90c', class: `flex items-center gap-2 text-xs text-primary` }, h(Icon, { key: '248dd7faf57084568ba36534ed0c1ec2c1fb2e22', name: "Loader2", addClass: "size-4 animate-spin" }), h("span", { key: '0af10045ee747a972df450c8ecf41bd02b612777' }, t('quick_message.uploading') || 'Uploading...'))), isInitialLoading ? (h("div", { class: `flex flex-1 items-center justify-center text-sm text-theme-gray` }, "Loading...")) : filteredImages.length === 0 ? (h("div", { class: `flex flex-1 items-center justify-center text-sm text-theme-gray` }, t('quick_message.image_empty'))) : this.imageDisplayMode === 'grid' ? (h("div", { class: "grid flex-1 grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 auto-rows-auto items-start content-start gap-3 overflow-y-auto", onScroll: event => this.handleScroll(event) }, filteredImages.map(image => (h("div", { class: "quick-message-image__grid-item", key: image.id }, h("button", { type: "button", class: `flex w-full flex-col items-center gap-2 rounded-xl border border-transparent bg-background p-1.5 cursor-pointer ${image.isSelected ? 'border-primary' : ''}`, onClick: () => this.toggleImageSelection(image.id) }, h("div", { class: "quick-message-image__thumbnail" }, image.isSelected && (h("span", { class: `quick-message-image__selection-indicator bg-primary`, "aria-hidden": "true" }, h(Icon, { name: "Check", addClass: "size-3 text-white" }))), !this.loadedUrls.has(image.file?.url || image.url || '') && (h(MediaSkeleton, { addClass: "rounded-lg" })), h("img", { src: image.file?.url || image.url || '', alt: image.name, class: "quick-message-image__thumbnail-image", style: { animation: 'z-fadeIn 0.3s ease-in-out' }, onLoad: () => this.handleImageLoad(image.file?.url || image.url || ''), onError: () => this.handleImageError(image.file?.url || image.url || ''), loading: "lazy" })), h("div", { class: `text-center text-xs line-clamp-2 text-theme-gray` }, image.name)), h("div", { class: "quick-message-image__menu-wrapper quick-message-image__menu-wrapper--grid", "data-quick-message-image-menu-root": "" }, h("button", { type: "button", class: "quick-message-image__more-button", onClick: event => this.toggleMenu(image.id, event), "aria-haspopup": "menu", "aria-expanded": this.openMenuId === image.id ? 'true' : 'false', "aria-label": renameLabel, "data-quick-message-image-menu-root": "" }, h(Icon, { name: "MoreVertical", addClass: "size-4" })), this.openMenuId === image.id && (h("div", { class: `quick-message-image__menu bg-background text-surface`, role: "menu", "data-quick-message-image-menu-root": "" }, h("button", { type: "button", class: "quick-message-image__menu-item", role: "menuitem", onClick: event => this.handleMenuRename(image, event) }, renameLabel), h("button", { type: "button", class: "quick-message-image__menu-item quick-message-image__menu-item--danger", role: "menuitem", onClick: event => this.requestDeleteImage(image, event) }, deleteLabel))))))), this.isLoadingMore && h("div", { class: `col-span-full py-3 text-center text-xs text-theme-gray` }, "Loading..."))) : (h("div", { class: "flex flex-1 flex-col gap-2.5 overflow-y-auto", onScroll: event => this.handleScroll(event) }, filteredImages.map(image => (h("label", { class: `flex items-center gap-3 rounded-xl bg-background px-3 py-2.5`, key: image.id }, h("input", { type: "checkbox", checked: !!image.isSelected, onChange: () => this.toggleImageSelection(image.id) }), h("div", { class: "relative h-16 w-16 rounded-xl overflow-hidden" }, !this.loadedUrls.has(image.file?.url || image.url || '') && (h(MediaSkeleton, null)), h("img", { src: image.file?.url || image.url || '', alt: image.name, class: "h-16 w-16 rounded-xl object-cover", style: { animation: 'z-fadeIn 0.3s ease-in-out' }, onLoad: () => this.handleImageLoad(image.file?.url || image.url || ''), onError: () => this.handleImageError(image.file?.url || image.url || ''), loading: "lazy" })), h("div", { class: "flex flex-1 items-center gap-3 min-w-0" }, h("div", { class: `flex min-w-0 flex-col gap-1 text-theme-gray` }, h("div", { class: "text-sm font-medium line-clamp-2 wrap-break-words" }, image.name), h("div", { class: `text-xs text-theme-gray` }, this.renderFileMeta(image.size, image.created_at, t))), h("div", { class: "quick-message-image__menu-wrapper", "data-quick-message-image-menu-root": "" }, h("button", { type: "button", class: "quick-message-image__list-more-button", onClick: event => this.toggleMenu(image.id, event), "aria-haspopup": "menu", "aria-expanded": this.openMenuId === image.id ? 'true' : 'false', "aria-label": renameLabel, "data-quick-message-image-menu-root": "" }, h(Icon, { name: "MoreVertical", addClass: "size-4" })), this.openMenuId === image.id && (h("div", { class: `quick-message-image__menu quick-message-image__menu--list bg-background text-surface`, role: "menu", "data-quick-message-image-menu-root": "" }, h("button", { type: "button", class: "quick-message-image__menu-item", role: "menuitem", onClick: event => this.handleMenuRename(image, event) }, renameLabel), h("button", { type: "button", class: "quick-message-image__menu-item quick-message-image__menu-item--danger", role: "menuitem", onClick: event => this.requestDeleteImage(image, event) }, deleteLabel)))))))), this.isLoadingMore && h("div", { class: `py-3 text-center text-xs text-theme-gray` }, "Loading..."))), h("div", { key: '4865a10d1e0f8a704dd3ae8d9121cbaa4124ac34', class: `mt-auto flex items-center gap-2 pt-2 text-theme-gray` }, hasSelection && (h("button", { key: '65c1b6e93b11aa137f320b00098de891cf9f0f68', type: "button", class: `quick-message-image__action-button inline-flex h-9 w-9 items-center justify-center rounded-lg cursor-pointer disabled:cursor-not-allowed disabled:opacity-40`, onClick: () => this.requestDeleteSelectedImages(), "aria-label": t('remove'), disabled: this.isDeleting }, this.isDeleting ? h(Icon, { name: "Loader2", addClass: "size-4 animate-spin" }) : h(Icon, { name: "Trash2" }))), !this.isMaster && (h("button", { key: '17a315df3c600d3daefe2366c8f387d3e6bfb693', type: "button", disabled: !hasSelection, class: `quick-message-image__send ml-auto inline-flex items-center justify-center rounded-full px-4 py-2 text-xs font-semibold bg-primary text-white disabled:cursor-not-allowed disabled:opacity-40 cursor-pointer`, onClick: () => this.handleSendImages() }, t('quick_message.send_images')))), this.renderRenameModal({ renameLabel, nameLabel, saveLabel, cancelLabel, closeLabel })));
    }
    static get is() { return "quick-message-image"; }
    static get originalStyleUrls() {
        return {
            "$": ["quick-message-image.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["quick-message-image.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 | QuickMessageLibraryFile[]",
                    "resolved": "QuickMessageLibraryFile[] | string",
                    "references": {
                        "QuickMessageLibraryFile": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::QuickMessageLibraryFile",
                            "referenceLocation": "QuickMessageLibraryFile"
                        }
                    }
                },
                "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"
            }
        };
    }
    static get states() {
        return {
            "searchImage": {},
            "images": {},
            "imageDisplayMode": {},
            "isLoading": {},
            "isLoadingMore": {},
            "isUploading": {},
            "isDeleting": {},
            "totalImages": {},
            "totalPages": {},
            "renameTargetId": {},
            "renameName": {},
            "renameExtension": {},
            "isRenaming": {},
            "openMenuId": {},
            "loadedUrls": {},
            "errorUrls": {}
        };
    }
    static get events() {
        return [{
                "method": "imagesChange",
                "name": "imagesChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "QuickMessageLibraryFile[]",
                    "resolved": "QuickMessageLibraryFile[]",
                    "references": {
                        "QuickMessageLibraryFile": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::QuickMessageLibraryFile",
                            "referenceLocation": "QuickMessageLibraryFile"
                        }
                    }
                }
            }, {
                "method": "sendImages",
                "name": "sendImages",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "QuickMessageLibraryFile[]",
                    "resolved": "QuickMessageLibraryFile[]",
                    "references": {
                        "QuickMessageLibraryFile": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::QuickMessageLibraryFile",
                            "referenceLocation": "QuickMessageLibraryFile"
                        }
                    }
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "value",
                "methodName": "handleValueChange"
            }];
    }
    static get listeners() {
        return [{
                "name": "click",
                "method": "handleDocumentClick",
                "target": "document",
                "capture": false,
                "passive": false
            }];
    }
}
