import { r as registerInstance, c as createEvent, h, H as Host } from './index-BIwHMk6j.js';

/**
 * Format a file size in bytes into a human readable string.
 *
 * Uses base 1024 units (binary prefixes without the "i" designation)
 * and applies adaptive precision: one decimal for values < 10 of the
 * chosen unit, otherwise no decimals.
 *
 * Examples:
 *  - 0 => "0 B"
 *  - 512 => "512 B"
 *  - 1536 => "1.5 KB"
 *  - 1048576 => "1 MB"
 *  - 5347737600 => "4.98 GB" (value < 10 so one decimal)
 *
 * @param bytes - the size in bytes
 * @param decimals - max number of decimals for small unit values (default: 1)
 * @returns formatted size string
 */
function formatBytes(bytes, decimals = 1) {
    if (bytes == null || Number.isNaN(bytes)) {
        return '';
    }
    if (bytes < 0) {
        return '';
    }
    if (bytes === 0) {
        return '0 B';
    }
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    const i = Math.min(sizes.length - 1, Math.floor(Math.log(bytes) / Math.log(k)));
    const value = bytes / Math.pow(k, i);
    const precision = value < 10 ? Math.max(0, decimals) : 0; // only keep decimals for small values
    const rounded = Number.parseFloat(value.toFixed(precision));
    return `${rounded} ${sizes[i]}`;
}

const documentItemCss = () => `*{box-sizing:border-box;min-width:0;min-height:0}:host(limebb-document-item){position:relative}limel-card:not([clickable]):not([clickable=true]){pointer-events:none;opacity:0.75}div[slot=component]{pointer-events:none;display:flex;flex-direction:column;margin-top:-0.25rem;padding:0 0.25rem}limel-checkbox,limel-radio-button{width:100%}.file-size{pointer-events:none;width:fit-content;padding:0 0.375rem;font-size:0.6875rem;color:rgb(var(--color-white));border-radius:1rem;opacity:0.75;background-color:rgb(var(--color-glaucous-darker), 0.8);box-shadow:var(--shadow-brighten-edges-outside);backdrop-filter:blur(0.75rem);margin-top:0.5rem}:host(.has-image) .file-size{margin-top:-1.5rem;margin-bottom:0.5rem}limel-help{position:absolute;top:0;right:0}:host(.has-error) limel-card{box-shadow:0 0 0 1px rgb(var(--color-red-light))}:host(.has-error) limel-help{--color-sky-default:var(       --color-red-default   );--color-sky-lighter:var(--color-red-lighter);--lime-elevated-surface-background-color:rgb(       var(--color-yellow-default)   )}`;

const DocumentItemComponent = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.interact = createEvent(this, "interact");
        /**
         * The semantic role of the list item.
         * - 'radio': renders a radio button for single selection.
         * - 'checkbox': renders a checkbox for multiple selection.
         */
        this.type = 'checkbox';
        /**
         * The preferred file URL types to use when displaying
         * the document's image preview.
         */
        this.fileTypes = ['view', 'contents', 'download'];
        this.handleDocumentItemClick = (event) => {
            if (this.isUnavailable()) {
                return;
            }
            if ((event === null || event === void 0 ? void 0 : event.target) instanceof HTMLElement) {
                const isSelectionControl = event.target.closest('limel-checkbox') ||
                    event.target.closest('limel-radio-button');
                if (isSelectionControl) {
                    return;
                }
            }
            this.toggleSelection();
        };
        this.handleSelectionControlClick = (event) => {
            var _a, _b;
            event.stopPropagation();
            if (this.isUnavailable()) {
                return;
            }
            if (this.type === 'radio' && ((_a = this.item) === null || _a === void 0 ? void 0 : _a.selected)) {
                event.preventDefault();
                this.forceInputUnchecked(event);
                this.emitSelectionChange(!((_b = this.item) === null || _b === void 0 ? void 0 : _b.selected));
            }
        };
        this.handleSelectionControlChange = (event) => {
            var _a;
            event.stopPropagation();
            if (this.isUnavailable()) {
                return;
            }
            let isChecked;
            if ('detail' in event &&
                typeof event.detail === 'boolean') {
                isChecked = event.detail;
            }
            else {
                const input = event.target;
                isChecked = !!(input === null || input === void 0 ? void 0 : input.checked);
            }
            if (this.type === 'radio' && ((_a = this.item) === null || _a === void 0 ? void 0 : _a.selected) && !isChecked) {
                this.emitSelectionChange(false);
                return;
            }
            this.emitSelectionChange(isChecked);
        };
        this.handleKeyDown = (event) => {
            if (event.key !== ' ' && event.key !== 'Enter') {
                return;
            }
            event.preventDefault();
            if (this.isUnavailable()) {
                return;
            }
            this.toggleSelection();
        };
    }
    render() {
        const isUnavailable = this.isUnavailable();
        const image = this.getImage();
        return (h(Host, { key: '4e7f632c97cd078ee44cc262b3531b87409344fb', id: String(this.item.file.id), class: {
                'has-image': !!image,
                'has-error': !!this.item.hasError,
            }, role: this.type === 'radio' ? 'radio' : 'checkbox', "aria-checked": this.item.selected ? 'true' : 'false', "aria-disabled": isUnavailable ? 'true' : 'false', tabIndex: isUnavailable ? -1 : 0 }, h("limel-card", { key: 'b560d107ba3bfee84158b2867fb594eb698072c3', image: image, clickable: isUnavailable ? false : true, onClick: this.handleDocumentItemClick, onKeyDown: this.handleKeyDown }, h("div", { key: '798a25ef8ef4ca1470a91afaaf2fc3e975473368', slot: "component" }, this.renderFileSize(), this.renderBooleanInput())), this.renderHelp()));
    }
    renderBooleanInput() {
        const id = this.getControlId();
        if (this.type === 'radio') {
            return (h("limel-radio-button", { id: id, label: this.item.file.filename, disabled: this.isUnavailable(), checked: this.item.selected, onClick: this.handleSelectionControlClick, onChange: this.handleSelectionControlChange }));
        }
        return (h("limel-checkbox", { id: id, label: this.item.file.filename, disabled: this.isUnavailable(), checked: this.item.selected, onClick: this.handleSelectionControlClick, onChange: this.handleSelectionControlChange }));
    }
    renderFileSize() {
        var _a, _b;
        const formattedFileSize = formatBytes((_b = (_a = this.item) === null || _a === void 0 ? void 0 : _a.file) === null || _b === void 0 ? void 0 : _b.size);
        if (!formattedFileSize) {
            return;
        }
        return h("span", { class: "file-size" }, formattedFileSize);
    }
    renderHelp() {
        if (!this.item.help) {
            return;
        }
        return h("limel-help", { value: this.item.help, openDirection: "bottom-end" });
    }
    toggleSelection() {
        var _a, _b;
        if (this.type === 'radio') {
            const nextSelectedState = !((_a = this.item) === null || _a === void 0 ? void 0 : _a.selected);
            this.emitSelectionChange(nextSelectedState);
            return;
        }
        const nextSelectedState = !((_b = this.item) === null || _b === void 0 ? void 0 : _b.selected);
        this.emitSelectionChange(nextSelectedState);
    }
    emitSelectionChange(selected) {
        this.interact.emit(Object.assign(Object.assign({}, this.item), { selected }));
    }
    getControlId() {
        return `boolean-input-${String(this.item.file.id)}`;
    }
    isUnavailable() {
        var _a, _b;
        return ((_a = this.item) === null || _a === void 0 ? void 0 : _a.disabled) || ((_b = this.item) === null || _b === void 0 ? void 0 : _b.hasError);
    }
    forceInputUnchecked(event) {
        const target = event.target;
        const host = target === null || target === void 0 ? void 0 : target.closest('limel-radio-button');
        const input = host === null || host === void 0 ? void 0 : host.querySelector('input[type="radio"]');
        if (input) {
            input.checked = false;
        }
    }
    getImage() {
        const href = this.hrefForFile();
        if (!href) {
            return;
        }
        return {
            src: href,
            alt: this.item.file.filename,
        };
    }
    hrefForFile() {
        return ['preview', ...this.fileTypes]
            .map((type) => this.item.file.getUrl(type))
            .find(Boolean);
    }
    static get delegatesFocus() { return true; }
};
DocumentItemComponent.style = documentItemCss();

export { DocumentItemComponent as limebb_document_item };
