(function () {
    if (window.__amMobileKeyboardInitialized) {
        return;
    }

    window.__amMobileKeyboardInitialized = true;

    const isTouchDevice = () =>
        window.matchMedia('(pointer: coarse)').matches ||
        navigator.maxTouchPoints > 0 ||
        'ontouchstart' in window;

    const isSmallViewport = () => window.matchMedia('(max-width: 1024px)').matches;

    const keyboardInputTypes = new Set([
        '',
        'text',
        'search',
        'email',
        'number',
        'password',
        'tel',
        'url'
    ]);

    const isEligibleTarget = (element) => {
        if (!element) {
            return false;
        }

        if (element.matches('textarea')) {
            return !element.readOnly && !element.disabled;
        }

        if (element.matches('input')) {
            const type = (element.getAttribute('type') || '').toLowerCase();
            return !element.readOnly && !element.disabled && keyboardInputTypes.has(type);
        }

        return element.isContentEditable;
    };

    const getScrollTarget = (element) =>
        element?.closest('.sky-atlas-popup, .sky-atlas-settings-panel, #settings-modal-container, .e-input-group, .e-control-wrapper, .e-ddl, .e-multiselect, .form-field, .x-form-row, .x-form-section, .e-dialog, .e-card, .row, .col-md-6')
        || element;

    const scrollFieldIntoView = (element) => {
        if (!isTouchDevice() || !isSmallViewport() || !isEligibleTarget(element)) {
            return;
        }

        const target = getScrollTarget(element);
        if (!target || typeof target.scrollIntoView !== 'function') {
            return;
        }

        window.clearTimeout(window.__amKeyboardScrollTimer);
        window.__amKeyboardScrollTimer = window.setTimeout(() => {
            try {
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'center',
                    inline: 'nearest'
                });
            } catch {
                target.scrollIntoView(true);
            }
        }, 220);
    };

    document.addEventListener('focusin', (event) => {
        scrollFieldIntoView(event.target);
    }, true);

    if (window.visualViewport) {
        let viewportResizeTimer = 0;
        window.visualViewport.addEventListener('resize', () => {
            const active = document.activeElement;
            if (!isEligibleTarget(active)) {
                return;
            }

            window.clearTimeout(viewportResizeTimer);
            viewportResizeTimer = window.setTimeout(() => {
                scrollFieldIntoView(active);
            }, 140);
        });
    }
})();
