function localizeHtmlPage() {
    const i18nRegex = /__MSG_(\w+)__/g;

    function replaceMsg(match, p1) {
        try {
            return p1 ? chrome.i18n.getMessage(p1) : match;
        } catch (e) {
            console.warn(`Could not find message for: ${p1}`);
            return match;
        }
    }

    const walker = document.createTreeWalker(
        document.documentElement,
        NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
        null,
        false
    );

    let node;
    while (node = walker.nextNode()) {
        if (node.nodeType === Node.ELEMENT_NODE) {
            for (const attr of node.attributes) {
                if (i18nRegex.test(attr.value)) {
                    attr.value = attr.value.replace(i18nRegex, replaceMsg);
                }
            }
        } else if (node.nodeType === Node.TEXT_NODE) {
            if (i18nRegex.test(node.nodeValue)) {
                node.nodeValue = node.nodeValue.replace(i18nRegex, replaceMsg);
            }
        }
    }

    document.documentElement.lang = chrome.i18n.getUILanguage().split('-')[0];
    document.title = document.title.replace(i18nRegex, replaceMsg);
    document.body.classList.remove('unlocalized');
}

document.addEventListener('DOMContentLoaded', localizeHtmlPage);