export function highlightCharacter(str, char, charClass) {
    if (!str.includes(char)) {
        return str;
    }

    const pattern = new RegExp(`\\${char}+`, 'g');
    const replacement = `<span class="${charClass}">$&</span>`;

    return str.replace(pattern, replacement);
}

export function createImageElements(images, alt) {
    return images.map((link) => {
        return $('<img>').attr('src', link).attr('alt', alt);
    });
}

export function countLetters(str) {
    const letterRegex = /[a-zA-Z]/g;
    const matchedLetters = str.match(letterRegex);
    return matchedLetters ? matchedLetters.length : 0;
}

export function scrollToTop($element) {
    $element.scrollTop(0);
}

export function isHasSymbol(str, symbol) {
    return str.includes(symbol);
}

export function isKeyboardOpen() {
    const screenHeight = window.innerHeight;
    const screenHeightWithoutKeyboard = window.visualViewport.height;
    return screenHeight !== screenHeightWithoutKeyboard;
}

export function isTouchDevice() {
    return 'ontouchstart' in window;
}

export function isApp() {
    return navigator.userAgent.match(
        /TradeProMobile_iOS|TradeProMobile_Android|DIYMobile_iOS|DIYMobile_Android|DIYApp_Guest_Mobile_iOS|DIYApp_Guest_Mobile_Android|AGENT_PLACEHOLDER/i
    );
}

export function trimFields() {
    const fields = Wick.AddressBook.getFieldsConfigurations();
    fields.forEach((field) => {
        const trimmedValue = field.input.val().trim();
        field.input.val(trimmedValue);
    });
}

export function scrollToElement(element, offset = 20) {
    const targetElement = $(element);

    if (targetElement.length > 0) {
        $('html, body').animate(
            {
                scrollTop: targetElement.offset().top - offset,
            },
            300
        );
    }
}
