(function ($) {
    const settings = window.flysystemOffloadSettings || {};
    const s3Label = settings.labels ? settings.labels.s3 : 'Amazon S3 / Compatible';

    function ensureS3Wrapper() {
        const $heading = $('h2').filter(function () {
            return $(this).text().trim() === s3Label;
        });

        if ($heading.length && !$heading.parent().hasClass('flysystem-offload-adapter-section')) {
            const $table = $heading.next('table');
            if ($table.length) {
                const $wrapper = $('<div>', {
                    class: 'flysystem-offload-adapter-section',
                    'data-adapter': 's3'
                });

                $heading.add($table).wrapAll($wrapper);
            }
        }
    }

    function toggleSections() {
        const adapter = $('#flysystem-offload-adapter').val();

        $('.flysystem-offload-adapter-section').hide();
        $('.flysystem-offload-field').closest('tr').hide();

        if (adapter === 's3') {
            $('.flysystem-offload-adapter-section[data-adapter="s3"]').show();
            $('.flysystem-offload-field--s3').closest('tr').show();
        }
    }

    $(document).ready(function () {
        ensureS3Wrapper();
        toggleSections();
        $('#flysystem-offload-adapter').on('change', function () {
            toggleSections();
        });
    });
})(jQuery);
