/**
 * Helper for GA click event. When the user mouse clicks on a `base-input-button`, we
 * push the click event. When the user tabs through a list of radio buttons via a
 * keyboard, we only want to push the GA click event if the selection was deliberate
 * (space/enter key) or if there is a selection and the user tabs off of the radio group.
 */

let lastFocusedInputGroupName = '';
let onButtonQuestionLostFocusCallback = null;

const invokeButtonQuestionLostFocusCallback = () => {
    if (onButtonQuestionLostFocusCallback) {
        onButtonQuestionLostFocusCallback();
    }
};

const handleAnyComponentFocus = (e) => {
    const targetType = e.target.type;
    if (targetType !== 'radio' && targetType !== 'checkbox') {
        invokeButtonQuestionLostFocusCallback();
    }
};

const handleButtonComponentFocus = (e) => {
    if (e && lastFocusedInputGroupName !== e.groupName) {
        invokeButtonQuestionLostFocusCallback();
    }
};

const handleInputComponentBlur = (e) => {
    if (e) {
        lastFocusedInputGroupName = e.groupName;
        onButtonQuestionLostFocusCallback = e.onButtonQuestionLostFocusCallback;
    }
};

export { handleAnyComponentFocus, handleButtonComponentFocus, handleInputComponentBlur };
