jQuery(document).ready(function($) {
    var fileFrame;

    $('#add-repeatable-file').on('click', function(event) {
        event.preventDefault();

        // If the media frame already exists, reopen it.
        if (fileFrame) {
            fileFrame.open();
            return;
        }

        // Create the media frame.
        fileFrame = wp.media({
            title: 'Select a File',
            button: {
                text: 'Use this file'
            },
            multiple: true // Set to true to allow multiple file selection.
        });

        // When a file is selected, run a callback.
        fileFrame.on('select', function() {
            var selection = fileFrame.state().get('selection');
            selection.each(function(attachment) {
                var fileId = attachment.id;
                var fileUrl = attachment.url;
                var fileName = attachment.attributes.title;

                // Append the new file field to the list.
                $('#repeatable-files-list').append(
                    '<li>' +
                    '<span class="file-title">' + fileName + '</span>' +
                    '<input type="hidden" name="_repeatable_files[]" value="' + fileId + '">' +
                    '<a href="#" class="remove-file-button button">Remove File</a>' +
                    '</li>'
                );
            });
        });

        // Open the media frame.
        fileFrame.open();
    });

    // Handle removing a file field.
    $(document).on('click', '.remove-file-button', function(event) {
        event.preventDefault();
        $(this).closest('li').remove();
    });
});
