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 { uploadFileService } from "../../utils/upload";
import { handleError as showErrorDialog, openDialog, closeDialog } from "../../store/dialog";
import { ZStorageUsage } from "../internal-component/z-storage-usage";
export class QuickMessageFileComponent {
    handleClose;
    value;
    isMaster = false;
    selectedUrl;
    searchFile = '';
    files = [];
    isLoading = false;
    isLoadingMore = false;
    isUploading = false;
    isDeleting = false;
    totalFiles = 0;
    totalPages = 0;
    renameTargetId = null;
    renameName = '';
    renameExtension = '';
    isRenaming = false;
    openMenuId = null;
    allowedFileExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'csv', 'zip', 'rar', '7z'];
    pageSize = 15;
    localUploadPrefix = 'uploaded-file-';
    page = 1;
    currentSearch = '';
    fileInput;
    filesChange;
    sendFiles;
    selectedFiles;
    pendingDeleteFileIds = [];
    // Memoization cache for filtered files
    cachedFilteredFiles = null;
    cachedSearchTerm = '';
    cachedFilesLength = 0;
    handleDocumentClick(event) {
        const target = event.target;
        if (target && target.closest('[data-quick-message-file-menu-root]')) {
            return;
        }
        this.openMenuId = null;
    }
    async componentWillLoad() {
        this.syncFilesFromProp(this.value);
        await this.fetchFiles({ reset: true });
        this.syncSelectedFilesFromProp(this.selectedUrl);
    }
    handleValueChange(newValue) {
        this.syncFilesFromProp(newValue);
    }
    handleSelectedUrlChange(newSelectedUrl) {
        this.syncSelectedFilesFromProp(newSelectedUrl);
    }
    syncSelectedFilesFromProp(selectedUrl) {
        if (!selectedUrl || selectedUrl.length === 0) {
            return;
        }
        const fileUrls = selectedUrl.filter(url => typeof url === 'string');
        if (fileUrls.length === 0) {
            return;
        }
        const selectedFiles = this.files.map(file => {
            const isSelected = fileUrls.includes(file.file?.url || file.url || '');
            return {
                ...file,
                isSelected,
            };
        });
        this.setFiles(selectedFiles, false);
    }
    syncFilesFromProp(value) {
        if (value === undefined || value === null) {
            this.setFiles([], false);
            return;
        }
        const parsed = this.parseFilesValue(value);
        this.setFiles(parsed, false);
    }
    parseFilesValue(value) {
        if (typeof value === 'string') {
            try {
                const deserialized = JSON.parse(value);
                return this.cloneFiles(deserialized);
            }
            catch (error) {
                console.warn('[quick-message-file] Failed to parse files value', error);
                return [];
            }
        }
        return this.cloneFiles(value);
    }
    cloneFiles(files) {
        return (files || []).map(file => ({
            ...file,
            isSelected: file.isSelected || false,
        }));
    }
    setFiles(next, shouldEmit = true) {
        this.files = next;
        if (shouldEmit) {
            const payload = this.cloneFiles(next);
            this.filesChange.emit(payload);
        }
    }
    isLocalUpload(file) {
        return file.id.startsWith(this.localUploadPrefix);
    }
    getRemoteFileCount() {
        return this.files.filter(file => !this.isLocalUpload(file)).length;
    }
    mergeFetchedFiles(fetched, reset) {
        const localUploads = this.files.filter(file => this.isLocalUpload(file));
        const selectionMap = new Map(this.files.map(file => [file.id, file.isSelected || false]));
        const normalizedFetched = fetched.map(file => ({
            ...file,
            isSelected: selectionMap.get(file.id) || file.isSelected || false,
        }));
        if (reset) {
            return [...localUploads, ...normalizedFetched];
        }
        const existingRemote = this.files.filter(file => !this.isLocalUpload(file));
        const remoteIndexMap = new Map();
        existingRemote.forEach((file, index) => {
            remoteIndexMap.set(file.id, index);
        });
        const nextRemote = [...existingRemote];
        normalizedFetched.forEach(file => {
            const existingIndex = remoteIndexMap.get(file.id);
            if (existingIndex !== undefined) {
                nextRemote[existingIndex] = file;
            }
            else {
                remoteIndexMap.set(file.id, nextRemote.length);
                nextRemote.push(file);
            }
        });
        return [...localUploads, ...nextRemote];
    }
    /**
     * Memoized file filtering - only recalculates when search term or files change
     * Performance: Reduces operations from 60fps to only when user types
     */
    filterFiles() {
        const search = this.searchFile.trim().toLowerCase();
        // Quick return for no search
        if (!search)
            return this.files;
        // Check if we can use cached results
        if (this.cachedFilteredFiles && search === this.cachedSearchTerm && this.files.length === this.cachedFilesLength) {
            return this.cachedFilteredFiles;
        }
        // Recalculate filtered results
        const filtered = this.files.filter(file => file.name.toLowerCase().includes(search));
        // Update cache
        this.cachedFilteredFiles = filtered;
        this.cachedSearchTerm = search;
        this.cachedFilesLength = this.files.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.files.find(file => file.id === this.renameTargetId);
    }
    openRenameModal(file, event) {
        if (event) {
            event.preventDefault();
            event.stopPropagation();
        }
        const { base, extension } = this.splitFileName(file.name);
        this.renameTargetId = file.id;
        this.renameName = base;
        this.renameExtension = extension;
    }
    closeRenameModal(force = false) {
        if (this.isRenaming && !force) {
            return;
        }
        this.renameTargetId = null;
        this.renameName = '';
        this.renameExtension = '';
    }
    toggleMenu(fileId, event) {
        event.preventDefault();
        event.stopPropagation();
        this.openMenuId = this.openMenuId === fileId ? null : fileId;
    }
    closeMenu() {
        this.openMenuId = null;
    }
    handleMenuRename(file, event) {
        event.preventDefault();
        event.stopPropagation();
        this.closeMenu();
        this.openRenameModal(file, event);
    }
    requestDeleteFile(file, event) {
        event.preventDefault();
        event.stopPropagation();
        if (this.isDeleting) {
            return;
        }
        this.pendingDeleteFileIds = [file.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.confirmDeleteSelectedFiles();
            },
            onCloseDialog: () => {
                this.pendingDeleteFileIds = [];
            },
        });
    }
    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.setFiles(this.files.map(file => file.id === target.id
                ? {
                    ...file,
                    name: nextName,
                }
                : file));
            this.closeRenameModal(true);
            return;
        }
        this.isRenaming = true;
        try {
            const updated = await updateQuickMessageLibraryFileName({ id: target.id, name: nextName });
            this.setFiles(this.files.map(file => file.id === target.id
                ? {
                    ...file,
                    name: updated.name,
                    last_updated_at: updated.last_updated_at,
                    last_updated_by: updated.last_updated_by,
                }
                : file));
            this.closeRenameModal(true);
            openDialog({
                open: true,
                type: "SUCCESS" /* DIALOG_TYPE.SUCCESS */,
                title: t('success'),
                onCloseDialog: closeDialog,
            });
        }
        catch (error) {
            showErrorDialog(error, '[quick-message-file] Failed to rename file');
        }
        finally {
            this.isRenaming = false;
        }
    }
    toggleFileSelection(id) {
        this.setFiles(this.files.map(file => (file.id === id ? { ...file, isSelected: !file.isSelected } : file)));
        this.selectedFiles.emit(this.files.filter(file => file.isSelected));
    }
    toggleSelectAllFiles() {
        const isAllSelected = this.files.length > 0 && this.files.every(file => file.isSelected);
        this.setFiles(this.files.map(file => ({ ...file, isSelected: !isAllSelected })));
        this.selectedFiles.emit(this.files.filter(file => file.isSelected));
    }
    triggerFileUpload() {
        if (this.fileInput)
            this.fileInput.click();
    }
    handleFileSelection(event) {
        const input = event.target;
        if (!input.files || input.files.length === 0)
            return;
        const validFiles = Array.from(input.files).filter(file => {
            const fileNamePopped = file.name.split('.').pop();
            const extension = fileNamePopped ? fileNamePopped.toLowerCase() : null;
            return extension && this.allowedFileExtensions.includes(extension);
        });
        input.value = '';
        if (validFiles.length === 0) {
            return;
        }
        void this.uploadAndCreateFiles(validFiles);
    }
    async uploadAndCreateFiles(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: 'file',
                    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.fetchFiles({ reset: true });
            }
        }
        catch (error) {
            showErrorDialog(error, '[quick-message-file] Failed to upload files');
        }
        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'))}`;
    }
    handleSendFiles() {
        const selected = this.files.filter(file => file.isSelected);
        if (selected.length === 0)
            return;
        const payload = this.cloneFiles(selected);
        this.sendFiles.emit(payload);
        if (this.handleClose)
            this.handleClose();
    }
    requestDeleteSelectedFiles() {
        if (this.isDeleting) {
            return;
        }
        const selectedIds = this.files.filter(file => file.isSelected).map(file => file.id);
        if (selectedIds.length === 0) {
            return;
        }
        this.pendingDeleteFileIds = 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.confirmDeleteSelectedFiles();
            },
            onCloseDialog: () => {
                this.pendingDeleteFileIds = [];
            },
        });
    }
    async confirmDeleteSelectedFiles() {
        const t = useTranslation();
        if (this.isDeleting) {
            return;
        }
        const pendingIds = [...this.pendingDeleteFileIds];
        this.pendingDeleteFileIds = [];
        if (pendingIds.length === 0) {
            return;
        }
        const pendingSet = new Set(pendingIds);
        const remoteIds = this.files.filter(file => pendingSet.has(file.id) && !this.isLocalUpload(file)).map(file => file.id);
        this.isDeleting = true;
        try {
            if (remoteIds.length > 0) {
                await deleteQuickMessageLibraryFile({ ids: remoteIds });
            }
            const remaining = this.files.filter(file => !pendingSet.has(file.id));
            this.setFiles(remaining);
            if (remoteIds.length > 0) {
                this.totalFiles = Math.max(0, this.totalFiles - remoteIds.length);
                openDialog({
                    open: true,
                    type: "SUCCESS" /* DIALOG_TYPE.SUCCESS */,
                    title: t('success'),
                    onCloseDialog: closeDialog,
                });
                await this.fetchFiles({ reset: true });
            }
        }
        catch (error) {
            showErrorDialog(error, '[quick-message-file] Failed to delete files');
        }
        finally {
            this.isDeleting = false;
        }
    }
    async fetchFiles({ 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.searchFile : this.currentSearch;
        const trimmedSearch = searchSource ? searchSource.trim() : '';
        const nextPage = reset ? 1 : this.page + 1;
        if (search !== undefined) {
            this.searchFile = searchSource || '';
        }
        if (reset) {
            this.isLoading = true;
        }
        else {
            this.isLoadingMore = true;
        }
        try {
            const response = await getQuickMessageLibraryFiles({
                fileType: 'file',
                search: trimmedSearch ? trimmedSearch : undefined,
                page: nextPage,
                limit: this.pageSize,
            });
            const fetched = this.cloneFiles(response.files || []);
            const merged = this.mergeFetchedFiles(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.totalFiles = typeof response.total === 'number' ? response.total : fetched.length;
            this.currentSearch = trimmedSearch;
            this.setFiles(merged);
        }
        catch (error) {
            console.error('[quick-message-file] Failed to fetch files', error);
        }
        finally {
            if (reset) {
                this.isLoading = false;
            }
            else {
                this.isLoadingMore = false;
            }
        }
    }
    async loadMoreFiles() {
        if (this.isLoading || this.isLoadingMore) {
            return;
        }
        if (this.totalPages === 0 || this.page >= this.totalPages) {
            return;
        }
        if (this.totalFiles > 0) {
            const remoteCount = this.getRemoteFileCount();
            if (remoteCount >= this.totalFiles) {
                return;
            }
        }
        await this.fetchFiles({ reset: false });
    }
    handleScroll(event) {
        const target = event.target;
        if (!target) {
            return;
        }
        const remaining = target.scrollHeight - target.scrollTop - target.clientHeight;
        if (remaining < 160) {
            void this.loadMoreFiles();
        }
    }
    handleSearchInput(event) {
        const value = event.target.value;
        this.searchFile = value;
        if (!value.trim() && this.currentSearch && !this.isLoading && !this.isLoadingMore) {
            void this.fetchFiles({ search: '', reset: true });
        }
    }
    async handleSearchSubmit(event) {
        if (event)
            event.preventDefault();
        await this.fetchFiles({ search: this.searchFile, reset: true });
    }
    clearSearch() {
        if (!this.searchFile) {
            return;
        }
        this.searchFile = '';
        if (this.currentSearch) {
            void this.fetchFiles({ 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-file-rename-${target.id}`;
        return (h("div", { class: "quick-message-file__rename-overlay", role: "dialog", "aria-modal": "true", "aria-labelledby": "quick-message-file-rename-title", onClick: () => this.closeRenameModal() }, h("div", { class: "quick-message-file__rename-modal bg-background text-surface", onClick: event => event.stopPropagation() }, h("div", { class: "quick-message-file__rename-header" }, h("h3", { id: "quick-message-file-rename-title", class: "text-base font-semibold" }, labels.renameLabel), h("button", { type: "button", class: "quick-message-file__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-file__rename-input-row border border-divider bg-background` }, h("input", { id: inputId, type: "text", class: "quick-message-file__rename-input text-surface", value: this.renameName, onInput: event => this.handleRenameInput(event) }), this.renameExtension && h("span", { class: "quick-message-file__rename-extension" }, this.renameExtension))), h("div", { class: "flex justify-end gap-2 text-sm" }, h("button", { type: "button", class: "quick-message-file__rename-cancel", onClick: () => this.closeRenameModal(), disabled: this.isRenaming }, labels.cancelLabel), h("button", { type: "submit", class: "quick-message-file__rename-save", disabled: isSaveDisabled }, this.isRenaming ? h(Icon, { name: "Loader2", addClass: "size-4 animate-spin" }) : labels.saveLabel))))));
    }
    disconnectedCallback() {
        // this.objectUrls.forEach((url) => URL.revokeObjectURL(url));
        // this.objectUrls = [];
    }
    render() {
        const theme = configStore.get('theme');
        const t = useTranslation();
        const filteredFiles = this.filterFiles();
        const isInitialLoading = this.isLoading && this.files.length === 0;
        const hasSelection = this.files.some(file => file.isSelected);
        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: 'd3181a6cb184cb6e8f354fa8d50e64c6bd3d4112', class: "flex min-h-0 flex-1 flex-col gap-4", "data-theme": theme }, h("form", { key: '808569cabc8f7796eb5ff1d8fdbdac5c1c8c4b90', class: "w-full", onSubmit: event => this.handleSearchSubmit(event) }, h("div", { key: '4a75e9f08e6101debb4f25539cdd8d8ec4afd246', class: "relative" }, h("input", { key: '35ccaa703f78b421742ef3824bc1aa836ea91589', 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_file'), value: this.searchFile, onInput: event => this.handleSearchInput(event) }), this.searchFile && (h("button", { key: '032d6f05fc2ae1b53c4f9ec89f36657ad3aa0577', 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: '95b900b585d6ab66661f9c626491223346e83e30', name: "X" }))))), h("div", { key: '39089c335a254d2eb602a7b3053cdd97b388af5c', class: "flex items-center justify-between" }, this.files.length > 0 ? (h("label", { class: "inline-flex items-center gap-2 text-sm" }, h("input", { type: "checkbox", checked: this.files.length > 0 && this.files.every(file => file.isSelected), onChange: () => this.toggleSelectAllFiles() }), h("span", { class: "text-surface" }, t('select_all')))) : (h("span", null)), h("div", { key: '11bd166154351fb72cb86aacd442a88446325947', class: "flex items-center gap-2" }, h("input", { key: '39aa8f15631d5122ba29a0fccbf9520943bce16e', class: "hidden", type: "file", multiple: true, accept: this.allowedFileExtensions.map(extension => `.${extension}`).join(','), ref: el => (this.fileInput = el), onChange: event => this.handleFileSelection(event) }), h("button", { key: '9e567bc51a2fa8fc9de5b7df05d5eb8dacd53149', type: "button", class: "quick-message-file__action-button inline-flex h-9 w-9 items-center justify-center rounded-lg cursor-pointer text-surface", onClick: () => !this.isUploading && this.triggerFileUpload(), "aria-label": t('quick_message.add_file'), disabled: this.isUploading || isStorageFull }, this.isUploading ? h(Icon, { name: "Loader2", addClass: "size-4 animate-spin" }) : h(Icon, { name: "Plus" })))), h(ZStorageUsage, { key: 'a2ab0e6130246a43e0d44b4b4f438724fc8184b2' }), this.isUploading && (h("div", { key: 'bd44371a0eea4d0ce1e2f3ea392de5a0a9af8378', class: "flex items-center gap-2 text-xs text-primary" }, h(Icon, { key: '8ccc3c2caeaabe72a26b0c7cf1877c06c5eded5a', name: "Loader2", addClass: "size-4 animate-spin" }), h("span", { key: '1d788ba21a7de7290ff766d53e475ee0b4024cc5' }, t('quick_message.uploading') || 'Uploading...'))), isInitialLoading ? (h("div", { class: `flex flex-1 items-center justify-center text-sm text-theme-gray` }, "Loading...")) : filteredFiles.length === 0 ? (h("div", { class: `flex flex-1 items-center justify-center text-sm text-theme-gray` }, t('quick_message.file_empty'))) : (h("div", { class: "flex flex-1 flex-col gap-2.5 overflow-y-auto", onScroll: event => this.handleScroll(event) }, filteredFiles.map(file => (h("label", { class: "flex items-center gap-3 rounded-xl px-3 py-2.5", key: file.id }, h("input", { type: "checkbox", checked: !!file.isSelected, onChange: () => this.toggleFileSelection(file.id) }), h("div", { class: "quick-message-file__icon flex size-10 items-center justify-center rounded-xl" }, h(Icon, { name: "File" })), h("div", { class: "flex flex-1 items-center gap-3 min-w-0" }, h("div", { class: "flex min-w-0 flex-col gap-1" }, h("div", { class: "text-sm font-semibold line-clamp-2 wrap-break-word text-surface" }, file.name), h("div", { class: `text-xs text-theme-gray` }, this.renderFileMeta(file.size, file.created_at, t))), h("div", { class: "quick-message-file__menu-wrapper", "data-quick-message-file-menu-root": "" }, h("button", { type: "button", class: "quick-message-file__list-more-button", onClick: event => this.toggleMenu(file.id, event), "aria-haspopup": "menu", "aria-expanded": this.openMenuId === file.id ? 'true' : 'false', "aria-label": renameLabel, "data-quick-message-file-menu-root": "" }, h(Icon, { name: "MoreVertical", addClass: "size-4 text-surface" })), this.openMenuId === file.id && (h("div", { class: "quick-message-file__menu bg-background text-surface", role: "menu", "data-quick-message-file-menu-root": "" }, h("button", { type: "button", class: "quick-message-file__menu-item", role: "menuitem", onClick: event => this.handleMenuRename(file, event) }, renameLabel), h("button", { type: "button", class: "quick-message-file__menu-item quick-message-file__menu-item--danger", role: "menuitem", onClick: event => this.requestDeleteFile(file, event) }, deleteLabel)))))))), this.isLoadingMore && h("div", { class: `py-3 text-center text-xs text-theme-gray` }, "Loading..."))), h("div", { key: 'fa4438254eb08b3a4c517a20ef40d70130d8115e', class: `mt-auto flex items-center gap-2 pt-2` }, hasSelection && (h("button", { key: '5c519594ca96bb38444cab66260b789564c10f6c', type: "button", class: `quick-message-file__action-button inline-flex size-9 items-center justify-center rounded-lg cursor-pointer text-surface disabled:cursor-not-allowed disabled:opacity-40`, onClick: () => this.requestDeleteSelectedFiles(), "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: '3987b7dd0e802fd985c46b2246881172b6a0d471', type: "button", disabled: !hasSelection, class: `quick-message-file__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.handleSendFiles() }, t('quick_message.send_files')))), this.renderRenameModal({ renameLabel, nameLabel, saveLabel, cancelLabel, closeLabel })));
    }
    static get is() { return "quick-message-file"; }
    static get originalStyleUrls() {
        return {
            "$": ["quick-message-file.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["quick-message-file.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"
            },
            "selectedUrl": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "string[]",
                    "resolved": "string[]",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            }
        };
    }
    static get states() {
        return {
            "searchFile": {},
            "files": {},
            "isLoading": {},
            "isLoadingMore": {},
            "isUploading": {},
            "isDeleting": {},
            "totalFiles": {},
            "totalPages": {},
            "renameTargetId": {},
            "renameName": {},
            "renameExtension": {},
            "isRenaming": {},
            "openMenuId": {}
        };
    }
    static get events() {
        return [{
                "method": "filesChange",
                "name": "filesChange",
                "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": "sendFiles",
                "name": "sendFiles",
                "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": "selectedFiles",
                "name": "selectedFiles",
                "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"
            }, {
                "propName": "selectedUrl",
                "methodName": "handleSelectedUrlChange"
            }];
    }
    static get listeners() {
        return [{
                "name": "click",
                "method": "handleDocumentClick",
                "target": "document",
                "capture": false,
                "passive": false
            }];
    }
}
