(function () {
    'use strict';

    function setCredentialsDisabled(form, wrapper, disabled) {
        if (!form || !wrapper) {
            return;
        }

        var toggleField = form.querySelector('#' + form.name + '_' + wrapper.dataset.toggleFieldName);
        if (toggleField) {
            toggleField.value = disabled ? '0' : '1';
        }

        wrapper.querySelectorAll('input').forEach(function (input) {
            input.disabled = disabled;

            if (disabled) {
                input.style.pointerEvents = 'none';
            } else {
                input.style.removeProperty('pointer-events');
            }
        });
    }

    function activateMode(form, select) {
        var activeSandbox = select.value;
        var inactiveSandbox = activeSandbox === '1' ? '0' : '1';
        var activeWrapper = form.querySelector('.js-user-credentials-form[data-sandbox="' + activeSandbox + '"]');
        var inactiveWrapper = form.querySelector('.js-user-credentials-form[data-sandbox="' + inactiveSandbox + '"]');

        if (inactiveWrapper) {
            inactiveWrapper.style.display = 'none';
            setCredentialsDisabled(form, inactiveWrapper, true);
        }

        if (!activeWrapper) {
            return;
        }

        activeWrapper.style.removeProperty('display');
        setCredentialsDisabled(form, activeWrapper, true);

        activeWrapper.addEventListener('click', function unlockCredentials(event) {
            if (!event.target.closest('input, .js-user-credentials-form')) {
                return;
            }

            setCredentialsDisabled(form, activeWrapper, false);
            activeWrapper.removeEventListener('click', unlockCredentials);

            var firstInput = activeWrapper.querySelector('input');
            if (firstInput) {
                firstInput.focus();
            }
        });
    }

    document.addEventListener('DOMContentLoaded', function () {
        var form = document.querySelector('form[name="api_configuration"]');
        if (!form) {
            return;
        }

        var select = form.querySelector('.js-sandbox-enabled-choice');
        if (!select) {
            return;
        }

        activateMode(form, select);
        select.addEventListener('change', function () {
            activateMode(form, select);
        });
    });
})();
