import * as i0 from '@angular/core';
import { inject, Injector, DestroyRef, viewChild, output, input, signal, computed, forwardRef, ViewEncapsulation, ChangeDetectionStrategy, Component } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NgControl, NgModel, PristineChangeEvent, TouchedChangeEvent, NG_VALUE_ACCESSOR } from '@angular/forms';
import { TranslatePipe } from '@ngx-translate/core';
import { ZIconComponent } from '@shival99/z-ui/components/z-icon';
import { ZLoadingComponent } from '@shival99/z-ui/components/z-loading';
import { ZTooltipDirective } from '@shival99/z-ui/components/z-tooltip';
import { ZTranslateService } from '@shival99/z-ui/services';
import { zTransform, zUuid, zMergeClasses, zCreateEvent } from '@shival99/z-ui/utils';
import { merge, filter } from 'rxjs';
import { cva } from 'class-variance-authority';

const formatFileSize = (bytes) => {
    if (bytes === 0) {
        return '0 B';
    }
    const units = ['B', 'KB', 'MB', 'GB'];
    const k = 1024;
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    const size = bytes / Math.pow(k, i);
    return `${size.toFixed(i > 0 ? 1 : 0)} ${units[i]}`;
};

const zUploadDropzoneVariants = cva([
    'relative flex flex-col items-center justify-center rounded-sm border-2 border-dashed',
    'transition-[border-color,background-color] duration-200 cursor-pointer',
    'hover:border-primary/50 hover:bg-primary/5',
], {
    variants: {
        zSize: {
            sm: 'min-h-24 gap-1 p-3',
            default: 'min-h-32 gap-2 p-4',
            lg: 'min-h-40 gap-3 p-6',
        },
        zStatus: {
            default: 'border-input bg-background',
            active: 'border-primary bg-primary/10',
            disabled: 'opacity-50 cursor-not-allowed bg-muted border-muted',
            readonly: 'opacity-70 cursor-default bg-muted/50 border-muted',
            error: 'border-destructive! bg-destructive/5 hover:border-destructive!',
        },
    },
    defaultVariants: {
        zSize: 'default',
        zStatus: 'default',
    },
});
const zUploadFileItemVariants = cva(['relative flex items-center gap-3 rounded-sm border border-input bg-background p-3', 'transition-all duration-200'], {
    variants: {
        zStatus: {
            pending: '',
            uploading: '',
            success: '',
            error: '',
        },
    },
    defaultVariants: {
        zStatus: 'pending',
    },
});

class ZUploadComponent {
    _injector = inject(Injector);
    _destroyRef = inject(DestroyRef);
    _zTranslate = inject(ZTranslateService);
    fileInputRef = viewChild('fileInput', ...(ngDevMode ? [{ debugName: "fileInputRef" }] : []));
    zOnUpload = output();
    zOnRemove = output();
    zOnDownload = output();
    zOnError = output();
    zOnFileChange = output();
    zOnDragover = output();
    zOnDragleave = output();
    zOnDrop = output();
    zControl = output();
    zEvent = output();
    class = input('', ...(ngDevMode ? [{ debugName: "class" }] : []));
    zLabel = input('', ...(ngDevMode ? [{ debugName: "zLabel" }] : []));
    zLabelClass = input('', ...(ngDevMode ? [{ debugName: "zLabelClass" }] : []));
    zNote = input('', ...(ngDevMode ? [{ debugName: "zNote" }] : []));
    zSize = input('default', ...(ngDevMode ? [{ debugName: "zSize" }] : []));
    zAcceptFile = input('*', ...(ngDevMode ? [{ debugName: "zAcceptFile" }] : []));
    zMultipleFile = input(false, { ...(ngDevMode ? { debugName: "zMultipleFile" } : {}), transform: zTransform });
    zMaxSize = input(10, ...(ngDevMode ? [{ debugName: "zMaxSize" }] : []));
    zMaxFiles = input(5, ...(ngDevMode ? [{ debugName: "zMaxFiles" }] : []));
    zRequired = input(false, { ...(ngDevMode ? { debugName: "zRequired" } : {}), transform: zTransform });
    zDisabled = input(false, { ...(ngDevMode ? { debugName: "zDisabled" } : {}), transform: zTransform });
    zReadonly = input(false, { ...(ngDevMode ? { debugName: "zReadonly" } : {}), transform: zTransform });
    zLoading = input(false, { ...(ngDevMode ? { debugName: "zLoading" } : {}), transform: zTransform });
    zShowProgress = input(true, { ...(ngDevMode ? { debugName: "zShowProgress" } : {}), transform: zTransform });
    zValidators = input([], ...(ngDevMode ? [{ debugName: "zValidators" }] : []));
    files = signal([], ...(ngDevMode ? [{ debugName: "files" }] : []));
    inputId = zUuid('z-upload');
    labelId = zUuid('z-upload-label');
    isDragOver = signal(false, ...(ngDevMode ? [{ debugName: "isDragOver" }] : []));
    uiState = signal({
        touched: false,
        dirty: false,
    }, ...(ngDevMode ? [{ debugName: "uiState" }] : []));
    _fileError = signal('', ...(ngDevMode ? [{ debugName: "_fileError" }] : []));
    _disabled = signal(false, ...(ngDevMode ? [{ debugName: "_disabled" }] : []));
    _formControl = signal(null, ...(ngDevMode ? [{ debugName: "_formControl" }] : []));
    _formStateVersion = signal(0, ...(ngDevMode ? [{ debugName: "_formStateVersion" }] : []));
    _isNgModel = signal(false, ...(ngDevMode ? [{ debugName: "_isNgModel" }] : []));
    _onChange = () => void 0;
    _onTouched = () => void 0;
    _ngControl = null;
    isDisabled = computed(() => this._disabled() || this.zDisabled(), ...(ngDevMode ? [{ debugName: "isDisabled" }] : []));
    isBlocked = computed(() => this.isDisabled() || this.zLoading() || this.zReadonly(), ...(ngDevMode ? [{ debugName: "isBlocked" }] : []));
    _shouldShowValidation = computed(() => {
        const control = this._formControl();
        this._formStateVersion();
        if (this._isNgModel()) {
            return this.uiState().dirty || this.uiState().touched;
        }
        if (control) {
            return control.dirty;
        }
        return this.uiState().dirty || this.uiState().touched;
    }, ...(ngDevMode ? [{ debugName: "_shouldShowValidation" }] : []));
    hasError = computed(() => {
        if (this._fileError()) {
            return true;
        }
        const customErrors = this._getValidationErrors();
        if (customErrors.length > 0) {
            return true;
        }
        const control = this._formControl();
        this._formStateVersion();
        if (!control) {
            return false;
        }
        return control.invalid && this._shouldShowValidation();
    }, ...(ngDevMode ? [{ debugName: "hasError" }] : []));
    showError = computed(() => this.hasError() && (this._shouldShowValidation() || !!this._fileError()), ...(ngDevMode ? [{ debugName: "showError" }] : []));
    errorMessage = computed(() => {
        const fileError = this._fileError();
        if (fileError) {
            return fileError;
        }
        const customErrors = this._getValidationErrors();
        if (customErrors.length > 0) {
            return customErrors[0];
        }
        const control = this._formControl();
        const errors = control?.errors;
        if (!errors) {
            return '';
        }
        const validators = this.zValidators();
        for (const validator of validators) {
            if (errors[validator.error]) {
                return validator.message;
            }
        }
        return '';
    }, ...(ngDevMode ? [{ debugName: "errorMessage" }] : []));
    currentStatus = computed(() => {
        if (this.isDisabled()) {
            return 'disabled';
        }
        if (this.zReadonly()) {
            return 'readonly';
        }
        if (this._fileError()) {
            return 'error';
        }
        if (this.hasError() && this._shouldShowValidation()) {
            return 'error';
        }
        if (this.isDragOver()) {
            return 'active';
        }
        return 'default';
    }, ...(ngDevMode ? [{ debugName: "currentStatus" }] : []));
    dropzoneClasses = computed(() => zMergeClasses(zUploadDropzoneVariants({
        zSize: this.zSize(),
        zStatus: this.currentStatus(),
    }), this.class()), ...(ngDevMode ? [{ debugName: "dropzoneClasses" }] : []));
    acceptTypes = computed(() => {
        const accept = this.zAcceptFile();
        return accept === '*' ? '' : accept;
    }, ...(ngDevMode ? [{ debugName: "acceptTypes" }] : []));
    formatFileSize = formatFileSize;
    getFileItemClasses = (file) => zUploadFileItemVariants({ zStatus: file.status });
    ngOnInit() {
        queueMicrotask(() => {
            try {
                this._ngControl = this._injector.get(NgControl, null);
                this._isNgModel.set(this._ngControl instanceof NgModel);
                if (this._ngControl?.control) {
                    const { control } = this._ngControl;
                    this._formControl.set(control);
                    merge(control.statusChanges, control.valueChanges, control.events.pipe(filter(event => event instanceof PristineChangeEvent || event instanceof TouchedChangeEvent)))
                        .pipe(takeUntilDestroyed(this._destroyRef))
                        .subscribe(() => {
                        this._formStateVersion.update(v => v + 1);
                    });
                }
            }
            catch {
                this._ngControl = null;
            }
        });
        setTimeout(() => this._emitControl());
    }
    writeValue(value) {
        this.files.set(value ?? []);
    }
    registerOnChange(fn) {
        this._onChange = fn;
    }
    registerOnTouched(fn) {
        this._onTouched = fn;
    }
    setDisabledState(isDisabled) {
        this._disabled.set(isDisabled);
    }
    updateProgress(fileId, progress) {
        this.files.update(files => files.map(f => {
            if (f.id !== fileId) {
                return f;
            }
            return {
                ...f,
                progress: Math.min(100, Math.max(0, progress)),
                status: progress >= 100 ? 'success' : 'uploading',
            };
        }));
        this._notifyChange();
    }
    setFileStatus(fileId, status) {
        this.files.update(files => files.map(f => {
            if (f.id !== fileId) {
                return f;
            }
            return { ...f, status };
        }));
        this._notifyChange();
    }
    clearFiles() {
        this.files.set([]);
        this._notifyChange();
    }
    /** @deprecated Use `valid()` for boolean form-submit checks. */
    validate() {
        this.uiState.update(s => ({ ...s, touched: true, dirty: true }));
        this._onTouched();
        if (this._ngControl?.control) {
            this._ngControl.control.markAsDirty();
            this._ngControl.control.markAsTouched();
        }
        return this.hasError();
    }
    valid() {
        return !this.validate();
    }
    reset() {
        this.files.set([]);
        this.uiState.update(s => ({ ...s, touched: false, dirty: false }));
        this._fileError.set('');
        this._onChange([]);
        if (this._ngControl?.control) {
            this._ngControl.control.markAsPristine();
            this._ngControl.control.markAsUntouched();
        }
    }
    markAsTouched() {
        this.uiState.update(s => ({ ...s, touched: true }));
        this._onTouched();
    }
    markAsUntouched() {
        this.uiState.update(s => ({ ...s, touched: false }));
    }
    markAsDirty() {
        this.uiState.update(s => ({ ...s, dirty: true }));
    }
    markAsPristine() {
        this.uiState.update(s => ({ ...s, dirty: false }));
    }
    _emitControl() {
        this.zControl.emit({
            valid: () => this.valid(),
            validate: () => this.validate(),
            reset: () => this.reset(),
            clearFiles: () => this.clearFiles(),
            openFileDialog: () => this.openFileDialog(),
            markAsTouched: () => this.markAsTouched(),
            markAsUntouched: () => this.markAsUntouched(),
            markAsDirty: () => this.markAsDirty(),
            markAsPristine: () => this.markAsPristine(),
            hasError: this.hasError,
            files: this.files.asReadonly(),
            errorMessage: this.errorMessage,
        });
    }
    getFiles() {
        return this.files()
            .filter(f => f.file)
            .map(f => f.file);
    }
    openFileDialog() {
        if (this.isBlocked()) {
            return;
        }
        this.fileInputRef()?.nativeElement.click();
    }
    onFileSelected(event) {
        const input = event.target;
        if (!input.files?.length) {
            return;
        }
        this._processFiles(Array.from(input.files));
        input.value = '';
    }
    onDragOver(event) {
        event.preventDefault();
        event.stopPropagation();
        if (this.isBlocked()) {
            return;
        }
        this.isDragOver.set(true);
        this.zOnDragover.emit(event);
        this.zEvent.emit(zCreateEvent('dragover', event));
    }
    onDragLeave(event) {
        event.preventDefault();
        event.stopPropagation();
        this.isDragOver.set(false);
        this.zOnDragleave.emit(event);
        this.zEvent.emit(zCreateEvent('dragleave', event));
    }
    onDrop(event) {
        event.preventDefault();
        event.stopPropagation();
        this.isDragOver.set(false);
        this.zOnDrop.emit(event);
        this.zEvent.emit(zCreateEvent('drop', event));
        if (this.isBlocked()) {
            return;
        }
        const droppedFiles = event.dataTransfer?.files;
        if (!droppedFiles?.length) {
            return;
        }
        this._processFiles(Array.from(droppedFiles));
    }
    removeFile(file) {
        if (this.zLoading()) {
            return;
        }
        this.files.update(files => files.filter(f => f.id !== file.id));
        this._notifyChange();
        this._emitFileChange();
        this.zOnRemove.emit(file);
    }
    downloadFile(file) {
        if (this.zLoading()) {
            return;
        }
        this.zOnDownload.emit(file);
        if (file.url) {
            const link = document.createElement('a');
            link.href = file.url;
            link.download = file.name;
            link.target = '_blank';
            link.rel = 'noopener noreferrer';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            return;
        }
        if (file.file) {
            const url = URL.createObjectURL(file.file);
            const link = document.createElement('a');
            link.href = url;
            link.download = file.name;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
        }
    }
    _getValidationErrors() {
        const validators = this.zValidators();
        const currentFiles = this.files();
        const control = this._formControl();
        const errors = [];
        const isRequired = this.zRequired() || control?.errors?.['required'];
        if (isRequired && currentFiles.length === 0) {
            this._zTranslate.currentLang();
            errors.push(this._zTranslate.instant('i18n_z_ui_upload_required'));
        }
        for (const validator of validators) {
            if (validator.validate && !validator.validate(currentFiles)) {
                errors.push(validator.message);
            }
        }
        return errors;
    }
    _processFiles(newFiles) {
        const maxFiles = this.zMaxFiles();
        const maxSize = this.zMaxSize() * 1024 * 1024;
        const accept = this.zAcceptFile();
        const validFiles = [];
        if (!this.zMultipleFile()) {
            this.files.set([]);
        }
        for (const file of newFiles) {
            if (!this.zMultipleFile() && validFiles.length > 0) {
                break;
            }
            if (this.zMultipleFile()) {
                const currentCount = this.files().length + validFiles.length;
                if (currentCount >= maxFiles) {
                    const errorMsg = this._zTranslate.instant('i18n_z_ui_upload_max_files', { count: maxFiles });
                    this._fileError.set(errorMsg);
                    this.zOnError.emit({ file, error: errorMsg });
                    continue;
                }
            }
            if (file.size > maxSize) {
                const errorMsg = this._zTranslate.instant('i18n_z_ui_upload_max_size', { size: this.zMaxSize() + 'MB' });
                this._fileError.set(errorMsg);
                this.zOnError.emit({ file, error: errorMsg });
                continue;
            }
            if (accept !== '*' && !this._isValidFileType(file, accept)) {
                const errorMsg = this._zTranslate.instant('i18n_z_ui_upload_invalid_type');
                this._fileError.set(errorMsg);
                this.zOnError.emit({ file, error: errorMsg });
                continue;
            }
            validFiles.push({
                id: zUuid('file'),
                name: file.name,
                size: file.size,
                type: file.type,
                file,
                progress: 0,
                status: 'pending',
            });
        }
        if (validFiles.length === 0) {
            this._notifyChange();
            return;
        }
        this._fileError.set('');
        if (!this.zMultipleFile()) {
            this.files.set(validFiles.slice(0, 1));
            this.uiState.update(s => ({ ...s, touched: true, dirty: true }));
            this._onTouched();
            this._notifyChange();
            this._emitFileChange();
            this.zOnUpload.emit(validFiles);
            return;
        }
        this.files.update(files => [...files, ...validFiles]);
        this.uiState.update(s => ({ ...s, touched: true, dirty: true }));
        this._onTouched();
        this._notifyChange();
        this._emitFileChange();
        this.zOnUpload.emit(validFiles);
    }
    _emitFileChange() {
        const rawFiles = this.getFiles();
        this.zOnFileChange.emit(rawFiles);
    }
    _isValidFileType(file, accept) {
        const acceptTypes = accept.split(',').map(t => t.trim().toLowerCase());
        for (const type of acceptTypes) {
            if (type.startsWith('.')) {
                if (file.name.toLowerCase().endsWith(type)) {
                    return true;
                }
                continue;
            }
            if (type.endsWith('/*')) {
                const category = type.slice(0, -2);
                if (file.type.startsWith(category + '/')) {
                    return true;
                }
                continue;
            }
            if (file.type.toLowerCase() === type) {
                return true;
            }
        }
        return false;
    }
    _notifyChange() {
        this._onChange(this.files());
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.0.9", ngImport: i0, type: ZUploadComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.0.9", type: ZUploadComponent, isStandalone: true, selector: "z-upload", inputs: { class: { classPropertyName: "class", publicName: "class", isSignal: true, isRequired: false, transformFunction: null }, zLabel: { classPropertyName: "zLabel", publicName: "zLabel", isSignal: true, isRequired: false, transformFunction: null }, zLabelClass: { classPropertyName: "zLabelClass", publicName: "zLabelClass", isSignal: true, isRequired: false, transformFunction: null }, zNote: { classPropertyName: "zNote", publicName: "zNote", isSignal: true, isRequired: false, transformFunction: null }, zSize: { classPropertyName: "zSize", publicName: "zSize", isSignal: true, isRequired: false, transformFunction: null }, zAcceptFile: { classPropertyName: "zAcceptFile", publicName: "zAcceptFile", isSignal: true, isRequired: false, transformFunction: null }, zMultipleFile: { classPropertyName: "zMultipleFile", publicName: "zMultipleFile", isSignal: true, isRequired: false, transformFunction: null }, zMaxSize: { classPropertyName: "zMaxSize", publicName: "zMaxSize", isSignal: true, isRequired: false, transformFunction: null }, zMaxFiles: { classPropertyName: "zMaxFiles", publicName: "zMaxFiles", isSignal: true, isRequired: false, transformFunction: null }, zRequired: { classPropertyName: "zRequired", publicName: "zRequired", isSignal: true, isRequired: false, transformFunction: null }, zDisabled: { classPropertyName: "zDisabled", publicName: "zDisabled", isSignal: true, isRequired: false, transformFunction: null }, zReadonly: { classPropertyName: "zReadonly", publicName: "zReadonly", isSignal: true, isRequired: false, transformFunction: null }, zLoading: { classPropertyName: "zLoading", publicName: "zLoading", isSignal: true, isRequired: false, transformFunction: null }, zShowProgress: { classPropertyName: "zShowProgress", publicName: "zShowProgress", isSignal: true, isRequired: false, transformFunction: null }, zValidators: { classPropertyName: "zValidators", publicName: "zValidators", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { zOnUpload: "zOnUpload", zOnRemove: "zOnRemove", zOnDownload: "zOnDownload", zOnError: "zOnError", zOnFileChange: "zOnFileChange", zOnDragover: "zOnDragover", zOnDragleave: "zOnDragleave", zOnDrop: "zOnDrop", zControl: "zControl", zEvent: "zEvent" }, providers: [
            {
                provide: NG_VALUE_ACCESSOR,
                useExisting: forwardRef(() => ZUploadComponent),
                multi: true,
            },
            TranslatePipe,
        ], viewQueries: [{ propertyName: "fileInputRef", first: true, predicate: ["fileInput"], descendants: true, isSignal: true }], exportAs: ["zUpload"], ngImport: i0, template: "<div class=\"z-upload-wrapper flex w-full flex-col gap-2\">\n  @if (zLabel()) {\n    <label [id]=\"labelId\" class=\"text-xs leading-none font-medium\" [class]=\"zLabelClass()\">\n      {{ zLabel() }}\n      @if (zRequired()) {\n        <span class=\"text-destructive! ml-0.5\">*</span>\n      }\n    </label>\n  }\n\n  <div\n    class=\"z-upload-dropzone\"\n    [class]=\"dropzoneClasses()\"\n    (click)=\"openFileDialog()\"\n    (dragover)=\"onDragOver($event)\"\n    (dragleave)=\"onDragLeave($event)\"\n    (drop)=\"onDrop($event)\">\n    @if (zLoading()) {\n      <div class=\"bg-background/80 absolute inset-0 z-10 flex items-center justify-center rounded-sm\">\n        <svg\n          class=\"text-primary size-6 animate-spin\"\n          viewBox=\"0 0 24 24\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          stroke-width=\"2\">\n          <path d=\"M21 12a9 9 0 1 1-6.219-8.56\" />\n        </svg>\n      </div>\n    }\n\n    <svg\n      class=\"text-muted-foreground\"\n      [class.size-5]=\"zSize() === 'sm'\"\n      [class.size-6]=\"zSize() === 'default'\"\n      [class.size-8]=\"zSize() === 'lg'\"\n      viewBox=\"0 0 24 24\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      stroke-width=\"2\"\n      stroke-linecap=\"round\"\n      stroke-linejoin=\"round\">\n      @if (isDragOver()) {\n        <path d=\"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242\" />\n        <path d=\"M12 12v9\" />\n        <path d=\"m16 16-4-4-4 4\" />\n      } @else {\n        <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\" />\n        <polyline points=\"17 8 12 3 7 8\" />\n        <line x1=\"12\" x2=\"12\" y1=\"3\" y2=\"15\" />\n      }\n    </svg>\n\n    <div class=\"text-center\">\n      <p class=\"text-muted-foreground m-0 text-sm\">\n        @if (isDragOver()) {\n          {{ 'i18n_z_ui_upload_drop_here' | translate }}\n        } @else {\n          {{ 'i18n_z_ui_upload_drag_drop' | translate }}\n          {{ 'i18n_z_ui_upload_or' | translate }}\n          <span class=\"text-primary cursor-pointer font-medium\">{{ 'i18n_z_ui_upload_browse' | translate }}</span>\n        }\n      </p>\n\n      @if (zNote() || zAcceptFile() !== '*') {\n        <div class=\"text-muted-foreground/70 mt-2 flex flex-col gap-0.5 text-xs\">\n          @if (zNote()) {\n            <span>{{ zNote() }}</span>\n          }\n          @if (zAcceptFile() !== '*') {\n            <span>{{ 'i18n_z_ui_upload_accepted' | translate }}: {{ zAcceptFile() }}</span>\n          }\n        </div>\n      }\n    </div>\n\n    <input\n      #fileInput\n      type=\"file\"\n      class=\"hidden\"\n      [id]=\"inputId\"\n      [accept]=\"acceptTypes()\"\n      [multiple]=\"zMultipleFile()\"\n      [disabled]=\"isBlocked()\"\n      [attr.aria-labelledby]=\"zLabel() ? labelId : null\"\n      (change)=\"onFileSelected($event)\" />\n  </div>\n\n  @if (showError()) {\n    <p class=\"text-destructive animate-in fade-in slide-in-from-top-1 m-0 text-xs duration-200\">\n      {{ errorMessage() }}\n    </p>\n  }\n\n  @if (files().length > 0) {\n    <div class=\"z-upload-file-list flex flex-col gap-1.5\">\n      @for (file of files(); track file.id) {\n        <div [class]=\"getFileItemClasses(file)\" class=\"relative overflow-hidden p-2!\">\n          <!-- Progress border at bottom -->\n          @if (zShowProgress() && file.status === 'uploading') {\n            <div\n              class=\"bg-primary absolute bottom-0 left-0 h-0.5 transition-all duration-300\"\n              [style.width.%]=\"file.progress\"></div>\n          }\n\n          <div class=\"bg-muted relative flex size-8 shrink-0 items-center justify-center self-start rounded-sm\">\n            <z-icon zType=\"lucideFile\" zSize=\"16\" class=\"text-muted-foreground\" />\n          </div>\n\n          <div class=\"flex min-w-0 flex-1 flex-col\">\n            <div class=\"flex items-center gap-1.5\">\n              <span class=\"line-clamp-2 text-xs font-medium\" z-tooltip [zContent]=\"file.name\" [zAlwaysShow]=\"false\">\n                {{ file.name }}\n              </span>\n\n              @if (file.status === 'uploading') {\n                <z-loading zSize=\"2xs\" class=\"shrink-0\" [zLoading]=\"true\" />\n                @if (zShowProgress() && file.progress > 0) {\n                  <span class=\"text-primary shrink-0 text-[0.625rem] font-medium\">{{ file.progress }}%</span>\n                }\n              }\n              @if (file.status === 'success') {\n                <z-icon zType=\"lucideCheckCircle\" zSize=\"14\" class=\"shrink-0 text-green-500\" />\n              }\n              @if (file.status === 'error') {\n                <z-icon zType=\"lucideXCircle\" zSize=\"14\" class=\"text-destructive shrink-0\" />\n              }\n            </div>\n\n            <span class=\"text-muted-foreground mt-0.5 text-[0.625rem]\">\n              {{ formatFileSize(file.size) }}\n            </span>\n          </div>\n\n          <div class=\"flex shrink-0 items-center gap-0.5\">\n            @if (file.url || file.file) {\n              <button\n                type=\"button\"\n                class=\"group hover:bg-accent flex size-6 cursor-pointer items-center justify-center rounded-sm transition-colors\"\n                [class.pointer-events-none]=\"zLoading()\"\n                [class.opacity-50]=\"zLoading()\"\n                (click)=\"downloadFile(file); $event.stopPropagation()\">\n                <z-icon zType=\"lucideDownload\" zSize=\"14\" class=\"text-muted-foreground\" />\n              </button>\n            }\n\n            @if (!zReadonly()) {\n              <button\n                type=\"button\"\n                class=\"hover:bg-destructive/10 flex size-6 cursor-pointer items-center justify-center rounded-sm transition-colors\"\n                [class.pointer-events-none]=\"zLoading()\"\n                [class.opacity-50]=\"zLoading()\"\n                (click)=\"removeFile(file); $event.stopPropagation()\">\n                <z-icon zType=\"lucideX\" zSize=\"14\" class=\"text-destructive\" />\n              </button>\n            }\n          </div>\n        </div>\n      }\n    </div>\n  }\n</div>\n", styles: [".z-upload-wrapper .z-upload-dropzone:focus-visible{outline:2px solid var(--color-ring);outline-offset:2px}.z-upload-wrapper .z-upload-progress-bar .z-upload-progress-fill{transition:width .3s ease-out}.z-upload-wrapper .z-upload-file-list{animation:z-upload-slide-in .2s ease-out}@keyframes z-upload-slide-in{0%{opacity:0;transform:translateY(-.25rem)}to{opacity:1;transform:translateY(0)}}\n"], dependencies: [{ kind: "component", type: ZIconComponent, selector: "z-icon, [z-icon]", inputs: ["class", "zType", "zAnimatedType", "zAnimate", "zAnimationTrigger", "zSize", "zStrokeWidth", "zSvg"] }, { kind: "component", type: ZLoadingComponent, selector: "z-loading", inputs: ["class", "zSpinner", "zSize", "zColor", "zText", "zOverlay", "zOverlayType", "zFullscreen", "zLoading"] }, { kind: "directive", type: ZTooltipDirective, selector: "[z-tooltip], [zTooltip]", inputs: ["zContent", "zPosition", "zTooltipPosition", "zTrigger", "zTooltipTrigger", "zTooltipType", "zTooltipSize", "zClass", "zTooltipClass", "zShowDelay", "zTooltipShowDelay", "zHideDelay", "zTooltipHideDelay", "zArrow", "zTooltipArrow", "zDisabled", "zTooltipDisabled", "zOffset", "zTooltipOffset", "zAutoDetect", "zTriggerElement", "zAlwaysShow", "zMaxWidth"], outputs: ["zShow", "zHide"], exportAs: ["zTooltip"] }, { kind: "pipe", type: TranslatePipe, name: "translate" }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.0.9", ngImport: i0, type: ZUploadComponent, decorators: [{
            type: Component,
            args: [{ selector: 'z-upload', imports: [ZIconComponent, ZLoadingComponent, ZTooltipDirective, TranslatePipe], standalone: true, providers: [
                        {
                            provide: NG_VALUE_ACCESSOR,
                            useExisting: forwardRef(() => ZUploadComponent),
                            multi: true,
                        },
                        TranslatePipe,
                    ], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, exportAs: 'zUpload', template: "<div class=\"z-upload-wrapper flex w-full flex-col gap-2\">\n  @if (zLabel()) {\n    <label [id]=\"labelId\" class=\"text-xs leading-none font-medium\" [class]=\"zLabelClass()\">\n      {{ zLabel() }}\n      @if (zRequired()) {\n        <span class=\"text-destructive! ml-0.5\">*</span>\n      }\n    </label>\n  }\n\n  <div\n    class=\"z-upload-dropzone\"\n    [class]=\"dropzoneClasses()\"\n    (click)=\"openFileDialog()\"\n    (dragover)=\"onDragOver($event)\"\n    (dragleave)=\"onDragLeave($event)\"\n    (drop)=\"onDrop($event)\">\n    @if (zLoading()) {\n      <div class=\"bg-background/80 absolute inset-0 z-10 flex items-center justify-center rounded-sm\">\n        <svg\n          class=\"text-primary size-6 animate-spin\"\n          viewBox=\"0 0 24 24\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          stroke-width=\"2\">\n          <path d=\"M21 12a9 9 0 1 1-6.219-8.56\" />\n        </svg>\n      </div>\n    }\n\n    <svg\n      class=\"text-muted-foreground\"\n      [class.size-5]=\"zSize() === 'sm'\"\n      [class.size-6]=\"zSize() === 'default'\"\n      [class.size-8]=\"zSize() === 'lg'\"\n      viewBox=\"0 0 24 24\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      stroke-width=\"2\"\n      stroke-linecap=\"round\"\n      stroke-linejoin=\"round\">\n      @if (isDragOver()) {\n        <path d=\"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242\" />\n        <path d=\"M12 12v9\" />\n        <path d=\"m16 16-4-4-4 4\" />\n      } @else {\n        <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\" />\n        <polyline points=\"17 8 12 3 7 8\" />\n        <line x1=\"12\" x2=\"12\" y1=\"3\" y2=\"15\" />\n      }\n    </svg>\n\n    <div class=\"text-center\">\n      <p class=\"text-muted-foreground m-0 text-sm\">\n        @if (isDragOver()) {\n          {{ 'i18n_z_ui_upload_drop_here' | translate }}\n        } @else {\n          {{ 'i18n_z_ui_upload_drag_drop' | translate }}\n          {{ 'i18n_z_ui_upload_or' | translate }}\n          <span class=\"text-primary cursor-pointer font-medium\">{{ 'i18n_z_ui_upload_browse' | translate }}</span>\n        }\n      </p>\n\n      @if (zNote() || zAcceptFile() !== '*') {\n        <div class=\"text-muted-foreground/70 mt-2 flex flex-col gap-0.5 text-xs\">\n          @if (zNote()) {\n            <span>{{ zNote() }}</span>\n          }\n          @if (zAcceptFile() !== '*') {\n            <span>{{ 'i18n_z_ui_upload_accepted' | translate }}: {{ zAcceptFile() }}</span>\n          }\n        </div>\n      }\n    </div>\n\n    <input\n      #fileInput\n      type=\"file\"\n      class=\"hidden\"\n      [id]=\"inputId\"\n      [accept]=\"acceptTypes()\"\n      [multiple]=\"zMultipleFile()\"\n      [disabled]=\"isBlocked()\"\n      [attr.aria-labelledby]=\"zLabel() ? labelId : null\"\n      (change)=\"onFileSelected($event)\" />\n  </div>\n\n  @if (showError()) {\n    <p class=\"text-destructive animate-in fade-in slide-in-from-top-1 m-0 text-xs duration-200\">\n      {{ errorMessage() }}\n    </p>\n  }\n\n  @if (files().length > 0) {\n    <div class=\"z-upload-file-list flex flex-col gap-1.5\">\n      @for (file of files(); track file.id) {\n        <div [class]=\"getFileItemClasses(file)\" class=\"relative overflow-hidden p-2!\">\n          <!-- Progress border at bottom -->\n          @if (zShowProgress() && file.status === 'uploading') {\n            <div\n              class=\"bg-primary absolute bottom-0 left-0 h-0.5 transition-all duration-300\"\n              [style.width.%]=\"file.progress\"></div>\n          }\n\n          <div class=\"bg-muted relative flex size-8 shrink-0 items-center justify-center self-start rounded-sm\">\n            <z-icon zType=\"lucideFile\" zSize=\"16\" class=\"text-muted-foreground\" />\n          </div>\n\n          <div class=\"flex min-w-0 flex-1 flex-col\">\n            <div class=\"flex items-center gap-1.5\">\n              <span class=\"line-clamp-2 text-xs font-medium\" z-tooltip [zContent]=\"file.name\" [zAlwaysShow]=\"false\">\n                {{ file.name }}\n              </span>\n\n              @if (file.status === 'uploading') {\n                <z-loading zSize=\"2xs\" class=\"shrink-0\" [zLoading]=\"true\" />\n                @if (zShowProgress() && file.progress > 0) {\n                  <span class=\"text-primary shrink-0 text-[0.625rem] font-medium\">{{ file.progress }}%</span>\n                }\n              }\n              @if (file.status === 'success') {\n                <z-icon zType=\"lucideCheckCircle\" zSize=\"14\" class=\"shrink-0 text-green-500\" />\n              }\n              @if (file.status === 'error') {\n                <z-icon zType=\"lucideXCircle\" zSize=\"14\" class=\"text-destructive shrink-0\" />\n              }\n            </div>\n\n            <span class=\"text-muted-foreground mt-0.5 text-[0.625rem]\">\n              {{ formatFileSize(file.size) }}\n            </span>\n          </div>\n\n          <div class=\"flex shrink-0 items-center gap-0.5\">\n            @if (file.url || file.file) {\n              <button\n                type=\"button\"\n                class=\"group hover:bg-accent flex size-6 cursor-pointer items-center justify-center rounded-sm transition-colors\"\n                [class.pointer-events-none]=\"zLoading()\"\n                [class.opacity-50]=\"zLoading()\"\n                (click)=\"downloadFile(file); $event.stopPropagation()\">\n                <z-icon zType=\"lucideDownload\" zSize=\"14\" class=\"text-muted-foreground\" />\n              </button>\n            }\n\n            @if (!zReadonly()) {\n              <button\n                type=\"button\"\n                class=\"hover:bg-destructive/10 flex size-6 cursor-pointer items-center justify-center rounded-sm transition-colors\"\n                [class.pointer-events-none]=\"zLoading()\"\n                [class.opacity-50]=\"zLoading()\"\n                (click)=\"removeFile(file); $event.stopPropagation()\">\n                <z-icon zType=\"lucideX\" zSize=\"14\" class=\"text-destructive\" />\n              </button>\n            }\n          </div>\n        </div>\n      }\n    </div>\n  }\n</div>\n", styles: [".z-upload-wrapper .z-upload-dropzone:focus-visible{outline:2px solid var(--color-ring);outline-offset:2px}.z-upload-wrapper .z-upload-progress-bar .z-upload-progress-fill{transition:width .3s ease-out}.z-upload-wrapper .z-upload-file-list{animation:z-upload-slide-in .2s ease-out}@keyframes z-upload-slide-in{0%{opacity:0;transform:translateY(-.25rem)}to{opacity:1;transform:translateY(0)}}\n"] }]
        }], propDecorators: { fileInputRef: [{ type: i0.ViewChild, args: ['fileInput', { isSignal: true }] }], zOnUpload: [{ type: i0.Output, args: ["zOnUpload"] }], zOnRemove: [{ type: i0.Output, args: ["zOnRemove"] }], zOnDownload: [{ type: i0.Output, args: ["zOnDownload"] }], zOnError: [{ type: i0.Output, args: ["zOnError"] }], zOnFileChange: [{ type: i0.Output, args: ["zOnFileChange"] }], zOnDragover: [{ type: i0.Output, args: ["zOnDragover"] }], zOnDragleave: [{ type: i0.Output, args: ["zOnDragleave"] }], zOnDrop: [{ type: i0.Output, args: ["zOnDrop"] }], zControl: [{ type: i0.Output, args: ["zControl"] }], zEvent: [{ type: i0.Output, args: ["zEvent"] }], class: [{ type: i0.Input, args: [{ isSignal: true, alias: "class", required: false }] }], zLabel: [{ type: i0.Input, args: [{ isSignal: true, alias: "zLabel", required: false }] }], zLabelClass: [{ type: i0.Input, args: [{ isSignal: true, alias: "zLabelClass", required: false }] }], zNote: [{ type: i0.Input, args: [{ isSignal: true, alias: "zNote", required: false }] }], zSize: [{ type: i0.Input, args: [{ isSignal: true, alias: "zSize", required: false }] }], zAcceptFile: [{ type: i0.Input, args: [{ isSignal: true, alias: "zAcceptFile", required: false }] }], zMultipleFile: [{ type: i0.Input, args: [{ isSignal: true, alias: "zMultipleFile", required: false }] }], zMaxSize: [{ type: i0.Input, args: [{ isSignal: true, alias: "zMaxSize", required: false }] }], zMaxFiles: [{ type: i0.Input, args: [{ isSignal: true, alias: "zMaxFiles", required: false }] }], zRequired: [{ type: i0.Input, args: [{ isSignal: true, alias: "zRequired", required: false }] }], zDisabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "zDisabled", required: false }] }], zReadonly: [{ type: i0.Input, args: [{ isSignal: true, alias: "zReadonly", required: false }] }], zLoading: [{ type: i0.Input, args: [{ isSignal: true, alias: "zLoading", required: false }] }], zShowProgress: [{ type: i0.Input, args: [{ isSignal: true, alias: "zShowProgress", required: false }] }], zValidators: [{ type: i0.Input, args: [{ isSignal: true, alias: "zValidators", required: false }] }] } });

/**
 * Generated bundle index. Do not edit.
 */

export { ZUploadComponent, formatFileSize, zUploadDropzoneVariants, zUploadFileItemVariants };
//# sourceMappingURL=shival99-z-ui-components-z-upload.mjs.map
