Infinity Craft (in English)

Adds a language selector to the interface of the game Infinity Craft at https://neal.fun/infinite-craft/ — the infinite game.

// ==UserScript==
// @name            Infinity Craft (no seu idioma)
// @namespace       linkme.bio/jhonpergon/?userscript=infinite_craft
// @match           https://neal.fun/infinite-craft/*
// @version         1.0
// @author          Jhon Pérgon

// @name:pt       Infinity Craft (no seu idioma)
// @name:pt-BR    Infinity Craft (em português)
// @name:pt-PT    Infinity Craft (em português)
// @name:es       Infinity Craft (en español)
// @name:en       Infinity Craft (in English)
// @name:en-US    Infinity Craft (in American English)
// @name:fr       Infinity Craft (en français)
// @name:ru       Infinity Craft (на русском)
// @name:ja       Infinity Craft (日本語)
// @name:ko       Infinity Craft (한국어)
// @name:zh-TW    Infinity Craft (繁體中文)
// @name:zh-CN    Infinity Craft (简体中文)
// @name:id       Infinity Craft (dalam bahasa Indonesia)
// @name:ug       Infinity Craft (بىلىمىي ۇيغۇرچە)
// @name:ar       Infinity Craft (باللغة العربية)
// @name:he       Infinity Craft (בעברית)
// @name:hi       Infinity Craft (हिन्दी में)
// @name:th       Infinity Craft (เป็นภาษาไทย)
// @name:bg       Infinity Craft (на български)
// @name:ro       Infinity Craft (în limba română)
// @name:fi       Infinity Craft (suomeksi)
// @name:it       Infinity Craft (in italiano)
// @name:el       Infinity Craft (στα ελληνικά)
// @name:eo       Infinity Craft (en Esperanto)
// @name:hu       Infinity Craft (magyarul)
// @name:nb       Infinity Craft (på norsk bokmål)
// @name:sk       Infinity Craft (v slovenčine)
// @name:sv       Infinity Craft (på svenska)
// @name:sr       Infinity Craft (на српском)
// @name:pl       Infinity Craft (po polsku)
// @name:nl       Infinity Craft (in het Nederlands)
// @name:de       Infinity Craft (auf Deutsch)
// @name:da       Infinity Craft (på dansk)
// @name:cs       Infinity Craft (v češtině)
// @name:uk       Infinity Craft (українською мовою)
// @name:tr       Infinity Craft (Türkçe)
// @name:vi       Infinity Craft (bằng tiếng Việt)
// @name:fr-CA    Infinity Craft (en français canadien)

// @description    Adiciona um seletor de idiomas à interface do jogo Infinity Craft em https://neal.fun/infinite-craft/ — o jogo infinito.
// @description    Adiciona um seletor de idiomas à interface do jogo Infinity Craft em https://neal.fun/infinite-craft/ — o jogo infinito.
// @description:pt-BR    Adiciona um seletor de idiomas à interface do jogo Infinity Craft em https://neal.fun/infinite-craft/ — o jogo infinito.
// @description:pt-PT    Adiciona um seletor de idiomas à interface do jogo Infinity Craft em https://neal.fun/infinite-craft/ — o jogo infinito.
// @description:es    Agrega un selector de idiomas a la interfaz del juego Infinity Craft en https://neal.fun/infinite-craft/ — el juego infinito.
// @description:en    Adds a language selector to the interface of the game Infinity Craft at https://neal.fun/infinite-craft/ — the infinite game.
// @description:en-US    Adds a language selector to the interface of the game Infinity Craft at https://neal.fun/infinite-craft/ — the infinite game.
// @description:fr    Ajoute un sélecteur de langue à l'interface du jeu Infinity Craft sur https://neal.fun/infinite-craft/ — le jeu infini.
// @description:ru    Добавляет селектор языка в интерфейс игры Infinity Craft на https://neal.fun/infinite-craft/ — бесконечная игра.
// @description:ja    Infinity Craft のゲームインターフェースに言語セレクタを追加します。https://neal.fun/infinite-craft/ — 無限のゲーム。
// @description:ko    https://neal.fun/infinite-craft/에 언어 선택기를 추가합니다. — 무한한 게임.
// @description:zh-TW    在 https://neal.fun/infinite-craft/ 的界面中添加語言選擇器 — 無限遊戲。
// @description:zh-CN    在 https://neal.fun/infinite-craft/ 的界面中添加语言选择器 — 无限游戏。
// @description:id    Menambahkan pemilih bahasa ke antarmuka permainan Infinity Craft di https://neal.fun/infinite-craft/ — permainan tak terbatas.
// @description:ug    https://neal.fun/infinite-craft/دىكى ئارايىشقۇچ تىل تاللاشنى قوشۇدۇ — ئەسسىز ياخشى سەۋمەلىك.
// @description:ar    يضيف محدد اللغة إلى واجهة لعبة Infinity Craft على https://neal.fun/infinite-craft/ — اللعبة اللانهائية.
// @description:he    מוסיף בורר שפה לממשק המשחק של Infinity Craft ב- https://neal.fun/infinite-craft/ — המשחק האין-סופי.
// @description:hi    https://neal.fun/infinite-craft/ पर खेल Infinity Craft के इंटरफ़ेस में भाषा चयनकर्ता जोड़ता है — अनंत खेल।
// @description:th    เพิ่มเครื่องเลือกภาษาในอินเตอร์เฟซของเกม Infinity Craft ที่ https://neal.fun/infinite-craft/ — เกมอนันต์
// @description:bg    Добавя селектор на език към интерфейса на играта Infinity Craft в https://neal.fun/infinite-craft/ — безкрайната игра.
// @description:ro    Adaugă un selector de limbă la interfața jocului Infinity Craft la https://neal.fun/infinite-craft/ — jocul infinit.
// @description:fi    Lisää kielen valitsin Infinity Craft -pelin käyttöliittymään osoitteessa https://neal.fun/infinite-craft/ — loputon peli.
// @description:it    Aggiunge un selettore di lingua all'interfaccia del gioco Infinity Craft su https://neal.fun/infinite-craft/ — il gioco infinito.
// @description:el    Προσθέτει έναν επιλογέα γλώσσας στο περιβάλλον του παιχνιδιού Infinity Craft στο https://neal.fun/infinite-craft/ — το άπειρο παιχνίδι.
// @description:eo    Aldonas lingvon elektilon al la interfaco de la ludo Infinity Craft ĉe https://neal.fun/infinite-craft/ — la senfina ludo.
// @description:hu    Nyelvválasztó hozzáadása a Infinity Craft játék felületéhez a https://neal.fun/infinite-craft/ oldalon — a végtelen játék.
// @description:nb    Legger til et språkvelger i grensesnittet til spillet Infinity Craft på https://neal.fun/infinite-craft/ — det uendelige spillet.
// @description:sk    Pridáva jazykový selektor do rozhrania hry Infinity Craft na https://neal.fun/infinite-craft/ — nekonečná hra.
// @description:sv    Lägger till en språkväljare i gränssnittet för spelet Infinity Craft på https://neal.fun/infinite-craft/ — det oändliga spelet.
// @description:sr    Додаје изборник језика на интерфејс игре Infinity Craft на https://neal.fun/infinite-craft/ — бесконачна игра.
// @description:pl    Dodaje selektor języka do interfejsu gry Infinity Craft na https://neal.fun/infinite-craft/ — nieskończona gra.
// @description:nl    Voegt een taalselector toe aan de interface van het spel Infinity Craft op https://neal.fun/infinite-craft/ — het oneindige spel.
// @description:de    Fügt dem Interface des Spiels Infinity Craft auf https://neal.fun/infinite-craft/ einen Sprachauswahl hinzu — das unendliche Spiel.
// @description:da    Tilføjer en sprogvælger til grænsefladen af spillet Infinity Craft på https://neal.fun/infinite-craft/ — det uendelige spil.
// @description:cs    Přidává jazykový selektor do rozhraní hry Infinity Craft na https://neal.fun/infinite-craft/ — nekonečná hra.
// @description:uk    Додає селектор мови до інтерфейсу гри Infinity Craft на https://neal.fun/infinite-craft/ — нескінченна гра.
// @description:tr    Infinity Craft oyununun https://neal.fun/infinite-craft/ arayüzüne dil seçici ekler — sonsuz oyun.
// @description:vi    Thêm một trình chọn ngôn ngữ vào giao diện của trò chơi Infinity Craft tại https://neal.fun/infinite-craft/ — trò chơi vô tận.
// @description:fr-CA    Ajoute un sélecteur de langue à l'interface du jeu Infinity Craft sur https://neal.fun/infinite-craft/ — le jeu infini.

// @icon    https://static.fanbyte.com/uploads/2024/02/Infinite%20Craft%20Inverted-360x360.jpg
// @license      MIT
// @grant           none

// @compatible      chrome
// @compatible      firefox
// @compatible      opera
// @compatible      edge
// @compatible      safari
// ==/UserScript==

(function() {

    let getLangs = "en|pt"; // de inglês para português (padrão)

    // Adiciona o seletor de idiomas ao canto superior esquerdo
    var languageSelector = document.createElement('select');
    languageSelector.style.position = 'fixed';
    languageSelector.style.top = '10px';
    languageSelector.style.left = '140px';
    languageSelector.style.padding = '5px 2px';
    languageSelector.style.fontSize = '1rem';
    languageSelector.style.background = 'transparent';
    languageSelector.style.border = 'solid 2px #6a8491';
    languageSelector.style.zIndex = '22';
    languageSelector.style.borderRadius = '4px';
    languageSelector.style.color = '#57788c';


    // Adiciona as opções de idioma
    var languages = [
        { name: 'Português', code: 'pt' },
        { name: 'Español', code: 'es' },
        { name: 'Русский', code: 'ru' },
        { name: 'Français', code: 'fr' },
        { name: '日本語', code: 'ja' },
        { name: '한국어', code: 'ko' },
        { name: '中文 (台灣)', code: 'zh-TW' },
        { name: '中文 (简体)', code: 'zh-CN' },
        { name: 'Bahasa Indonesia', code: 'id' },
        { name: 'ئۇيغۇرچە', code: 'ug' },
        { name: 'العربية', code: 'ar' },
        { name: 'עברית', code: 'he' },
        { name: 'हिन्दी', code: 'hi' },
        { name: 'ไทย', code: 'th' },
        { name: 'български', code: 'bg' },
        { name: 'Română', code: 'ro' },
        { name: 'Suomi', code: 'fi' },
        { name: 'Italiano', code: 'it' },
        { name: 'Ελληνικά', code: 'el' },
        { name: 'Esperanto', code: 'eo' },
        { name: 'Magyar', code: 'hu' },
        { name: 'Norsk bokmål', code: 'nb' },
        { name: 'Slovenčina', code: 'sk' },
        { name: 'Svenska', code: 'sv' },
        { name: 'Српски', code: 'sr' },
        { name: 'Polski', code: 'pl' },
        { name: 'Nederlands', code: 'nl' },
        { name: 'Deutsch', code: 'de' },
        { name: 'Dansk', code: 'da' },
        { name: 'Čeština', code: 'cs' },
        { name: 'Українська', code: 'uk' },
        { name: 'Türkçe', code: 'tr' },
        { name: 'Tiếng Việt', code: 'vi' }
    ];

    for (var i = 0; i < languages.length; i++) {
        var option = document.createElement('option');
        option.textContent = languages[i].name;
        option.value = languages[i].code;
        languageSelector.appendChild(option);
    }

    document.body.appendChild(languageSelector);

    // Função para atualizar a variável de idioma quando uma nova opção é selecionada
    languageSelector.addEventListener('change', function() {
        var selectedLanguage = languageSelector.value;
        localStorage.setItem('lang', selectedLanguage); // Armazena o idioma selecionado localmente
        location.reload(); // Recarrega a página
    });

    // Define o idioma inicialmente selecionado
    var initialLang = localStorage.getItem('lang');
    if (initialLang) {
        languageSelector.value = initialLang;
        getLangs = `en|${initialLang}`
    }



    function addTranslate() {
        document.querySelectorAll('.item').forEach(async (item, index, array) => {
            const texto = getTextContent(item); // Use a função getTextContent para obter apenas o texto
            if (getLangs !== "" && !item.dataset.translated) { // Verifica se o texto ainda não foi traduzido
                let textoEnviado = texto;
                let apiURL = "https://api.mymemory.translated.net/get";
                let params = {
                    q: textoEnviado,
                    langpair: getLangs
                };

                let queryString = Object.keys(params)
                    .map(key => key + '=' + encodeURIComponent(params[key]))
                    .join('&');

                let requestUrl = apiURL + '?' + queryString;

                try {
                    const response = await fetch(requestUrl);
                    const data = await response.json();
                    if (data && data.responseData && data.responseData.translatedText) {
                        setTextContent(item, data.responseData.translatedText); // Use a função setTextContent para definir apenas o texto
                        item.dataset.translated = true; // Define o atributo de dados para indicar que o texto foi traduzido
                    } else {
                        setTextContent(item, "Não foi possível traduzir o texto.");
                    }
                } catch (error) {
                    if (error) {
                        setTextContent(item, error);
                    } else {
                        setTextContent(item, "[ERRO: Sem conexão com a internet].");
                    }
                }
            }
            // Aguarda um pequeno intervalo antes de passar para o próximo item, exceto para o último item
            if (index !== array.length - 1) {
                await new Promise(resolve => setTimeout(resolve, 2000)); // Aguarda 2 segundos antes de passar para o próximo item
            }
        });
    }

    setTimeout(function() {
        setInterval(addTranslate, 1500);
    }, 1500);


    // Função para obter apenas o texto, excluindo elementos filhos
    function getTextContent(element) {
        return Array.from(element.childNodes)
            .filter(node => node.nodeType === Node.TEXT_NODE)
            .map(node => node.textContent)
            .join('');
    }

    // Função para definir apenas o texto, preservando elementos filhos
    function setTextContent(element, text) {
        Array.from(element.childNodes)
            .filter(node => node.nodeType === Node.TEXT_NODE)
            .forEach(node => {
                node.textContent = text;
            });
    }

})();