import { r as registerInstance, d as createEvent, h, a as Host } from './index-DH4fm3JO.js';

const uploadFileComponentCss = ".file-upload-section{background:#f8f9fa;border:1px solid #e9ecef;border-radius:8px;padding:20px;margin-top:20px}.file-section-title{color:#495057;margin-bottom:8px;font-weight:600;font-size:1.25rem}.file-section-description{color:#6c757d;font-size:0.9em;margin-bottom:15px;line-height:1.4}.file-input-container{display:flex;gap:10px;margin-bottom:15px;flex-wrap:wrap}.file-input{position:absolute;opacity:0;width:100%;height:100%;cursor:pointer}.file-input-label{padding:12px 20px}.file-input-label,.btn-add-more{display:inline-flex;align-items:center;gap:8px;padding:12px 20px;background:#007bff;color:white;border:none;border-radius:6px;cursor:pointer;transition:background-color 0.2s;font-weight:600;text-decoration:none}.file-input-label:hover,.btn-add-more:hover{background:#0056b3}.btn-add-more{background:#28a745}.btn-add-more:hover{background:#218838}.file-preview-container{background:white;border:1px solid #dee2e6;border-radius:6px;padding:15px;margin-top:15px}.preview-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;padding-bottom:10px;border-bottom:1px solid #e9ecef}.preview-title{color:#495057;margin:0;font-weight:600}.file-counter{color:#6c757d;font-size:0.9em;font-weight:500}.file-preview-item{display:flex;justify-content:space-between;align-items:center;padding:12px;border:1px solid #e9ecef;border-radius:4px;margin-bottom:8px;background:#f8f9fa;transition:background-color 0.2s}.file-preview-item:hover{background:#e9ecef}.file-info{display:flex;align-items:center;gap:12px;flex:1;min-width:0}.file-details{display:flex;flex-direction:column;min-width:0;flex:1}.file-name{font-weight:500;color:#495057;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.file-size{font-size:0.85em;color:#6c757d}.btn-remove-file{background:#dc3545;color:white;border:none;border-radius:4px;padding:8px 10px;cursor:pointer;transition:background-color 0.2s;font-size:0.9em;flex-shrink:0}.btn-remove-file:hover{background:#c82333}.preview-actions{display:flex;gap:10px;justify-content:flex-start;margin-top:15px;padding-top:10px;border-top:1px solid #e9ecef}.btn-remove-all{background:#dc3545;color:white;border:none;border-radius:4px;padding:8px 16px;cursor:pointer;transition:background-color 0.2s;font-size:0.9em;display:inline-flex;align-items:center;gap:6px}.btn-remove-all:hover{background:#c82333}.file-info small{display:flex;align-items:center;gap:6px;margin-top:10px}.text-danger{color:#dc3545}.text-primary{color:#007bff}.text-success{color:#28a745}.text-warning{color:#ffc107}.text-secondary{color:#6c757d}@media (max-width: 768px){.file-input-container{flex-direction:column}.preview-header{flex-direction:column;align-items:flex-start;gap:5px}.preview-actions{flex-direction:column}.file-preview-item{flex-direction:column;align-items:flex-start;gap:10px}}.notification-container{position:fixed;top:20px;right:20px;z-index:9999;width:300px;display:flex;flex-direction:column;gap:10px;}.toast{padding:15px;border-radius:4px;color:#fff;font-family:-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Helvetica, Arial, sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\";font-size:14px;box-shadow:0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);animation:slideInFromRight 0.5s ease}.toast.success{background-color:#28a745;}.toast.error{background-color:#dc3545;}@keyframes slideInFromRight{0%{transform:translateX(110%);opacity:0}100%{transform:translateX(0);opacity:1}}";

const UploadFileComponent = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.filesSelected = createEvent(this, "filesselected", 7);
        this.filesChanged = createEvent(this, "fileschanged", 7);
    }
    // === Props configurables (pueden llegar como string desde HTML) ===
    moduleName = 'FormAire';
    fileType = 'Aire';
    displayName = 'Aires';
    // Pueden venir como string; se normalizan en componentWillLoad
    maxFileSize = 8 * 1024 * 1024; // 8MB
    allowedExtensions = [
        '.pdf', '.doc', '.docx', '.jpg', '.jpeg', '.png', '.xlsx', '.xls',
    ];
    // === Estado interno ===
    selectedFiles = new Map();
    fileCounter = 0;
    fileInputRef;
    // === Internos normalizados ===
    _allowedExtArr = [];
    _maxFileSizeNum = 8 * 1024 * 1024;
    // === Normalización de props ===
    componentWillLoad() {
        // allowedExtensions → string[]
        if (Array.isArray(this.allowedExtensions)) {
            this._allowedExtArr = this.allowedExtensions.map((e) => String(e).toLowerCase());
        }
        else if (typeof this.allowedExtensions === 'string') {
            try {
                const parsed = JSON.parse(this.allowedExtensions);
                this._allowedExtArr = (Array.isArray(parsed) ? parsed : []).map((e) => String(e).toLowerCase());
            }
            catch {
                this._allowedExtArr = this.allowedExtensions
                    .split(',')
                    .map((s) => s.trim().toLowerCase())
                    .filter(Boolean);
            }
        }
        // maxFileSize → number
        const n = Number(this.maxFileSize);
        this._maxFileSizeNum = Number.isFinite(n) && n > 0 ? n : 8 * 1024 * 1024;
    }
    // === Eventos (kebab-case en el DOM) ===
    filesSelected;
    filesChanged;
    // === Métodos públicos ===
    async getSelectedFiles() {
        return Array.from(this.selectedFiles.values())
            .sort((a, b) => a.id - b.id)
            .map((x) => x.file);
    }
    async getSelectedFileObjects() {
        return Array.from(this.selectedFiles.values()).sort((a, b) => a.id - b.id);
    }
    // === Emisión unificada de eventos (SIEMPRE lista completa) ===
    emitSelection(reason) {
        const filesArr = Array.from(this.selectedFiles.values()).sort((a, b) => a.id - b.id); // orden estable
        const plain = filesArr.map((f) => f.file);
        const total = plain.reduce((s, f) => s + f.size, 0);
        // Enviar SIEMPRE TODOS
        this.filesSelected.emit({
            files: filesArr,
            plainFiles: plain,
            totalSize: total,
            count: filesArr.length,
            reason,
        });
        this.filesChanged.emit({
            files: filesArr,
            plainFiles: plain,
            totalSize: total,
            count: filesArr.length,
        });
    }
    // === Acciones ===
    openFileSelector = () => this.fileInputRef?.click();
    handleFileSelection = (event) => {
        const input = event.target;
        const files = Array.from(input.files || []);
        if (files.length === 0)
            return;
        const validFiles = [];
        const errors = [];
        files.forEach((file) => {
            const validation = this.validateFile(file);
            if (validation.valid) {
                // Detección de duplicados más robusta (nombre + size + lastModified)
                const isDuplicate = Array.from(this.selectedFiles.values()).some((f) => {
                    const sf = f.file;
                    return sf.name === file.name && sf.size === file.size && (sf.lastModified ?? 0) === (file.lastModified ?? 0);
                });
                if (!isDuplicate)
                    validFiles.push(file);
                else
                    errors.push(`${file.name}: Archivo duplicado`);
            }
            else {
                errors.push(`${file.name}: ${validation.error}`);
            }
        });
        if (errors.length)
            this.showFileErrors(errors);
        if (validFiles.length) {
            const newFiles = new Map(this.selectedFiles);
            validFiles.forEach((file) => {
                this.fileCounter++;
                newFiles.set(this.fileCounter, {
                    id: this.fileCounter,
                    file,
                    addedAt: new Date().toISOString(),
                });
            });
            this.selectedFiles = newFiles; // reasignar para reactividad
            this.showSuccessMessage(`${validFiles.length} archivo(s) agregado(s)`);
            this.emitSelection('add'); // ← emite TODOS los actuales
        }
        // permitir volver a seleccionar el mismo archivo desde el input
        input.value = '';
    };
    validateFile(file) {
        if (file.size > this._maxFileSizeNum) {
            return {
                valid: false,
                error: `Demasiado grande (${(file.size / 1024 / 1024).toFixed(1)}MB, máximo ${(this._maxFileSizeNum / 1024 / 1024).toFixed(1)}MB)`,
            };
        }
        const ext = '.' + (file.name.split('.').pop()?.toLowerCase() || '');
        if (this._allowedExtArr.length && !this._allowedExtArr.includes(ext)) {
            return { valid: false, error: `Extensión no permitida (${ext})` };
        }
        return { valid: true };
    }
    removeFile = (fileId) => {
        if (this.selectedFiles.has(fileId)) {
            const fileData = this.selectedFiles.get(fileId);
            const newFiles = new Map(this.selectedFiles);
            newFiles.delete(fileId);
            this.selectedFiles = newFiles; // reasignar para reactividad
            this.showSuccessMessage(`"${fileData?.file.name}" eliminado`);
            this.emitSelection('remove'); // ← emite TODOS los actuales (post-eliminación)
        }
    };
    clearAllFiles = () => {
        const count = this.selectedFiles.size;
        this.selectedFiles = new Map(); // en lugar de clear() para disparar render
        this.fileCounter = 0;
        this.showSuccessMessage(`${count} archivo(s) eliminado(s)`);
        this.emitSelection('clear'); // ← emite lista vacía
    };
    getFileIcon(filename) {
        const ext = filename.split('.').pop()?.toLowerCase() || '';
        const icons = {
            pdf: 'fas fa-file-pdf text-danger',
            doc: 'fas fa-file-word text-primary',
            docx: 'fas fa-file-word text-primary',
            xlsx: 'fas fa-file-excel text-success',
            xls: 'fas fa-file-excel text-success',
            jpg: 'fas fa-file-image text-warning',
            jpeg: 'fas fa-file-image text-warning',
            png: 'fas fa-file-image text-warning',
        };
        return icons[ext] || 'fas fa-file text-secondary';
    }
    getTotalSize() {
        return Array.from(this.selectedFiles.values()).reduce((sum, f) => sum + f.file.size, 0);
    }
    showSuccessMessage(msg) {
        const w = window;
        if (!w || !w.Swal) {
            console.log(msg);
            return;
        }
        w.Swal.fire({
            toast: true,
            position: 'top-end',
            icon: 'success',
            title: msg,
            showConfirmButton: false,
            timer: 2500,
            timerProgressBar: true,
        });
    }
    showFileErrors(errors) {
        const w = window;
        if (!w || !w.Swal) {
            console.warn(errors);
            return;
        }
        w.Swal.fire({
            toast: true,
            position: 'top-end',
            icon: 'warning',
            title: 'Error en algunos archivos',
            text: errors.join('\n'),
            showConfirmButton: false,
            timer: 4000,
            timerProgressBar: true,
        });
    }
    // === Render ===
    render() {
        const hasFiles = this.selectedFiles.size > 0;
        const totalSize = this.getTotalSize();
        const acceptAttr = this._allowedExtArr.length ? this._allowedExtArr.join(',') : undefined;
        return (h(Host, { key: '8fec4813fd2fc2bcfa4d2ef2c50a3613f3e9650c' }, h("link", { key: '27d5f71dd865b9a40e69a54c5239188591d92300', rel: "stylesheet", href: "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" }), h("div", { key: 'fd2aeb39d6802a3d946c87e0f613f00907279e80', class: "file-upload-section" }, h("h5", { key: 'e4f9cc8a6d17b181849cd585e16b3f96ad34f084', class: "file-section-title" }, "\uD83D\uDCCE Documentos T\u00E9cnicos"), h("p", { key: '38b15b235bf73a75f3680abd0837b298f617c700', class: "file-section-description" }, "Adjunte documentos t\u00E9cnicos, planos, im\u00E1genes, etc.", h("br", { key: '44f659fb2d799f6a8341a0c73635612604bae6e8' }), h("strong", { key: '7f272d8466a1f81c0a5bfe06c743bf0bedb9e72d' }, "Formatos:"), " ", this._allowedExtArr.join(', ') || 'cualquiera', " \u2014 M\u00E1x:", ' ', (this._maxFileSizeNum / 1024 / 1024).toFixed(1), " MB"), h("div", { key: '8ee8fed3737a2075298eb33f42889d31e5372d91', class: "file-input-container" }, h("input", { key: 'aabc321e63f8df8b140f2fcd00c474ec1f96609c', type: "file", ref: (el) => (this.fileInputRef = el), multiple: true, accept: acceptAttr, style: { display: 'none' }, onChange: this.handleFileSelection }), h("button", { key: 'dddc9626ae75d42487889735c8d186bfd67aa2ce', type: "button", class: "file-input-label", style: { display: hasFiles ? 'none' : 'inline-flex' }, onClick: this.openFileSelector }, h("i", { key: 'e6d0734f2ca98822db6771e5dc5412f92de22b72', class: "fas fa-cloud-upload-alt" }), " ", h("span", { key: '2d3f9d9a1462a04a28f65f6936609a8220529c6c' }, "Seleccionar Archivos"))), hasFiles && (h("div", { key: '5d7f81db7dd86329d03427219a8474f002c4f570', class: "file-preview-container" }, h("div", { key: '28480c091dcc9e34cc57a172e55e35b42f8fb049', class: "preview-header" }, h("h6", { key: '5d5c8e3c7a8041498ce789c4c45f6b7bdac8f233', class: "preview-title" }, "Archivos Seleccionados"), h("div", { key: 'b1d89b656fe3a7f9e8b34b6b023dc6ce9f4e7120', class: "file-counter" }, this.selectedFiles.size, " archivo(s) | ", (totalSize / 1024).toFixed(1), " KB")), h("div", { key: '1f042dac8effc830f8ba94f481de3c5ca077c004', class: "file-preview-list" }, Array.from(this.selectedFiles.values())
            .sort((a, b) => a.id - b.id)
            .map((f) => (h("div", { class: "file-preview-item", key: f.id }, h("div", { class: "file-info" }, h("i", { class: this.getFileIcon(f.file.name) }), h("div", { class: "file-details" }, h("span", { class: "file-name", title: f.file.name }, f.file.name), h("span", { class: "file-size" }, (f.file.size / 1024).toFixed(1), " KB"))), h("button", { type: "button", class: "btn-remove-file", onClick: () => this.removeFile(f.id), title: "Quitar archivo" }, h("i", { class: "fas fa-times" })))))), h("div", { key: '59cc73e175365a595b2541b34ad865b012e35737', class: "preview-actions" }, h("button", { key: '63495ada82c8d2ccdd0294d3dd7f2a580436e7b2', type: "button", class: "btn-add-more", onClick: this.openFileSelector }, h("i", { key: 'bf7e9eb0e8073a8bc712b3ff81d17d0a8e74ed30', class: "fas fa-plus" }), " Agregar M\u00E1s"), h("button", { key: '8af773087ccbdb24e702d11e01a939ffa9dd8f33', type: "button", class: "btn-remove-all", onClick: this.clearAllFiles }, h("i", { key: 'd6ad1932f2287dd20fa1a7d9ae8ed79e581edacf', class: "fas fa-trash" }), " Quitar Todos")))))));
    }
};
UploadFileComponent.style = uploadFileComponentCss;

export { UploadFileComponent as upload_file_component };
//# sourceMappingURL=upload-file-component.entry.esm.js.map
