var VanillaUploader = function(options) {
    this.opts = options;
    this.btn = options.button;
    this._progressBar = null;
    this._progressContainer = null;
    this.init();
};

// These two methods keep your existing onSubmit logic working
VanillaUploader.prototype.setProgressBar = function(elem) {
    this._progressBar = elem;
};

VanillaUploader.prototype.setProgressContainer = function(elem) {
    this._progressContainer = elem;
};

VanillaUploader.prototype.init = function() {
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.style.display = 'none';
    if (this.opts.multiple) fileInput.multiple = true;
    document.body.appendChild(fileInput);

    this.btn.addEventListener('click', (e) => {
        e.preventDefault();
        fileInput.click();
    });

    fileInput.addEventListener('change', () => {
        const files = fileInput.files;
        for (let i = 0; i < files.length; i++) {
            this.uploadFile(files[i]);
        }
        fileInput.value = ''; 
    });
};

VanillaUploader.prototype.uploadFile = function(file) {
    const ext = file.name.split('.').pop().toLowerCase();
    
    // Check onSubmit - if it returns false, we stop
    if (this.opts.onSubmit && this.opts.onSubmit.call(this, file.name, ext) === false) {
        return;
    }

    const xhr = new XMLHttpRequest();
    const formData = new FormData();
    formData.append(this.opts.name || 'uploadfile', file);

    xhr.upload.onprogress = (e) => {
        if (e.lengthComputable) {
            const pct = Math.round((e.loaded / e.total) * 100);
            
            // 1. Update the bar width automatically if setProgressBar was called
            if (this._progressBar) {
                this._progressBar.style.width = pct + '%';
            }
            
            // 2. Trigger your existing onProgress callback (for the text percentage)
            if (this.opts.onProgress) {
                this.opts.onProgress.call(this, pct);
            }
        }
    };

    xhr.onload = () => {
        let response = xhr.responseText;
        if (this.opts.responseType === 'json') {
            try { response = JSON.parse(xhr.responseText); } catch (err) { response = {status: 'fail'}; }
        }
        if (this.opts.onComplete) this.opts.onComplete.call(this, file.name, response);
    };

    xhr.open('POST', this.opts.url);
    xhr.send(formData);
};
export default VanillaUploader;