$(document).ready(function() {
    function initUploadFunctionality() {
        $('.ulz-upload-wrapper').each(function() {
            const dropZone = $(this);
            const id = dropZone.data('id');
            const fileInput = $('#ulz-upload-' + id);
            const customBtn = $('#ulz-custom-btn-' + id);

            if (!fileInput.length || !customBtn.length) {
                console.warn('Elements not found for ID:', id);
                return;
            }

            // Unbind any previous click event to prevent duplicate triggering
            customBtn.off('click').on('click', function(e) {
                e.preventDefault();
                fileInput.trigger('click');
            });

            // Handle drag and drop highlighting
            dropZone.off('dragenter dragover').on('dragenter dragover', function(e) {
                e.preventDefault();
                e.stopPropagation();
                dropZone.addClass('dragging');
            });

            dropZone.off('dragleave drop').on('dragleave drop', function(e) {
                e.preventDefault();
                e.stopPropagation();
                dropZone.removeClass('dragging');
            });

            // Handle file drop
            dropZone.off('drop').on('drop', function(e) {
                e.preventDefault();
                e.stopPropagation();
                fileInput.prop('files', e.originalEvent.dataTransfer.files);

                // Trigger a change event
                fileInput.trigger('change');
            });
        });
    }

    // Initialize upload functionality
    initUploadFunctionality(); 
});