ChatGPT Infinitate ∞

Generează răspunsuri infinite de la ChatGPT omniscient (în orice limbă!)

// ==UserScript==
// @name                ChatGPT Infinity ∞
// @name:af             ChatGPT Oneindig ∞
// @name:ar             دردشةGPT إنفينيتي ∞
// @name:az             ChatGPT Sonsuzluq ∞
// @name:be             ChatGPT Бясконцасць ∞
// @name:bg             ChatGPT Безкрайност ∞
// @name:bn             ChatGPT ইনফিনিটি ∞
// @name:bo             ChatGPT དག་སྐྱེས་ཡོད་པ་ ∞
// @name:bs             ChatGPT Beskrajnost ∞
// @name:ca             ChatGPT Infinit ∞
// @name:ckb            ChatGPT نەپێندییە ∞
// @name:cs             ChatGPT Nekonečno ∞
// @name:cy             ChatGPT Anfeidredd ∞
// @name:da             ChatGPT Uendelighed ∞
// @name:de             ChatGPT Unendlichkeit ∞
// @name:dv             ChatGPT ނުވަތަ ބާވައްޖޭގެން ∞
// @name:dz             ChatGPT རྩེད་སྒྲིབ་གཉིས་ ∞
// @name:el             ChatGPT Άπειρο ∞
// @name:eo             ChatGPT Infinito ∞
// @name:es             ChatGPT Infinito ∞
// @name:et             ChatGPT Lõpmatus ∞
// @name:eu             ChatGPT Infinitua ∞
// @name:fa             ChatGPT بینهایت ∞
// @name:fi             ChatGPT Ääretön ∞
// @name:fo             ChatGPT Óendanlighed ∞
// @name:fr             ChatGPT Infini ∞
// @name:fr-CA          ChatGPT Infini ∞
// @name:gl             ChatGPT Infinito ∞
// @name:gu             ChatGPT અનંત ∞
// @name:haw            ChatGPT Māhina ʻole ∞
// @name:he             ChatGPT אינסוף ∞
// @name:hi             ChatGPT अनंत ∞
// @name:hr             ChatGPT Beskrajnost ∞
// @name:hu             ChatGPT Végtelenség ∞
// @name:hy             ChatGPT Անվերջ ∞
// @name:id             ChatGPT Infinity ∞
// @name:is             ChatGPT Óendanleiki ∞
// @name:it             ChatGPT Infinito ∞
// @name:ja             ChatGPT 無限 ∞
// @name:ka             ChatGPT უსასრულობა ∞
// @name:km             ChatGPT អនឡាញ ∞
// @name:kn             ChatGPT ಅನಂತ ∞
// @name:ko             ChatGPT 무한 ∞
// @name:ku             ChatGPT Pêşangeh ∞
// @name:ky             ChatGPT Ички ∞
// @name:la             ChatGPT Infinitas ∞
// @name:lb             ChatGPT Unendlechkeet ∞
// @name:lo             ChatGPT ບໍ່ໄປສູ່ຈັກຂອງສາມຫວ່າງ ∞
// @name:lt             ChatGPT Begalybė ∞
// @name:lv             ChatGPT Bezgalība ∞
// @name:mk             ChatGPT Бесконечност ∞
// @name:ml             ChatGPT അനന്തത ∞
// @name:mn             ChatGPT Тэгш бус ∞
// @name:mt             ChatGPT Infinità ∞
// @name:my             ChatGPT မြင်ကွင်း ∞
// @name:ne             ChatGPT अनंत ∞
// @name:nl             ChatGPT Oneindigheid ∞
// @name:no             ChatGPT Uendelighet ∞
// @name:pa             ChatGPT ਇਨਫਿਨਿਟੀ ∞
// @name:pl             ChatGPT Nieskończoność ∞
// @name:ps             ChatGPT لامکان ∞
// @name:pt             ChatGPT Infinito ∞
// @name:pt-BR          ChatGPT Infinito ∞
// @name:ro             ChatGPT Infinitate ∞
// @name:ru             ChatGPT Бесконечность ∞
// @name:si             ChatGPT අනන්තය ∞
// @name:sk             ChatGPT Nekonečno ∞
// @name:sl             ChatGPT Neskončnost ∞
// @name:so             ChatGPT Qaybtiisa ∞
// @name:sr             ChatGPT Бескрајност ∞
// @name:sv             ChatGPT Oändlighet ∞
// @name:ta             ChatGPT முடிவிலிருந்து ∞
// @name:te             ChatGPT అనంతత ∞
// @name:tg             ChatGPT Беоҳӣ ∞
// @name:th             ChatGPT อนันต์ ∞
// @name:ti             ChatGPT መደመር ∞
// @name:tk             ChatGPT Sonsuzluk ∞
// @name:tr             ChatGPT Sonsuzluk ∞
// @name:uk             ChatGPT Нескінченність ∞
// @name:ur             ChatGPT بے انتہا ∞
// @name:vi             ChatGPT Vô cùng ∞
// @name:yi             ChatGPT אינפיניטי ∞
// @name:zh             ChatGPT 无限 ∞
// @name:zh-CN          ChatGPT 无限 ∞
// @name:zh-HK          ChatGPT 無限 ∞
// @name:zh-SG          ChatGPT 无限 ∞
// @name:zh-TW          ChatGPT 無限 ∞
// @description         Generate endless answers from all-knowing ChatGPT (in any language!)
// @description:af      Genereer eindelose antwoorde van die alwetende ChatGPT (in enige taal!)
// @description:am      ሓበሬታይ ኣይነበርና መልእኽቲ ኣለኹም ኣሎኻዊ ያልኣይት ChatGPT (በቋንቋ!)
// @description:ar      قم بتوليد إجابات لا نهائية من ChatGPT المعرف بكل شيء (بأي لغة!)
// @description:az      Hər şeyi bilən ChatGPT-dən sonsuz cavablar yaradın (hər hansı bir dil ilə!)
// @description:be      Стварыце бясконцы адказы ад ўсеведучага ChatGPT (на любой мове!)
// @description:bem     Pamene mwaposa mafolosho a mʌnoze ChatGPT (mu lupiya lwa ndalama!)
// @description:bg      Генерирайте безкрайни отговори от всезнайния ChatGPT (на всяк език!)
// @description:bn      সর্বজ্ঞ চ্যাটজিপিটি থেকে অসীম উত্তর তৈরি করুন (যে কোন ভাষায়!)
// @description:bo      བཟོས་པ་བརྗོད་པའི་ChatGPTགི་གྲོས་པར་འགྲུབ་འདེམས་བསྐྱེད་མི་འོངས་པ། (ལས་སྐབས་ཀྱི་སྐད་ཡིག་གི་སྐད་!)
// @description:bs      Generišite beskonačne odgovore od sveznajućeg ChatGPT (na bilo kom jeziku!)
// @description:ca      Genereu respostes infinites des de l'omniscient ChatGPT (en qualsevol idioma!)
// @description:ceb     Sukdagon ang walay katapusan nga mga tubag gikan sa tanan-mahibaw-anong ChatGPT (sa bisan unsang pinulongan!)
// @description:ckb     پێشبینی چاتگپتەکە دیارییەکانی پێکراوەکان بنووسە (بە هەر زمانێکی دیکە!)
// @description:cs      Generujte nekonečné odpovědi od vševědoucího ChatGPT (v jakémkoli jazyce!)
// @description:cy      Cynhyrchwch atebion diddiwedd o ChatGPT y gŵr sy'n gwybod popeth (mewn unrhyw iaith!)
// @description:da      Generer endeløse svar fra den altvidende ChatGPT (på hvilket som helst sprog!)
// @description:de      Generieren Sie endlose Antworten von dem allwissenden ChatGPT (in beliebiger Sprache!)
// @description:dv      އެހެނދުކަޗެއްވެސީ ޗެއްސިސްޓޯނަށް ނިޔަލައިފައިވަނީ ސުރުކޮށް ފީހުން (ކަންއެވެސް ހަމަވެސް!)
// @description:dz      ཆགས་ཀྱིས་ལ་བརྟེན་གང་རུང་གི་ChatGPTགི་ཚོགས་པའི་སྐད་ཡིག་གྱི་སྐད་ཡིག་བྱེད་པ། (བླ་མའི་སྐད་ཡིག་!)
// @description:el      Δημιουργήστε ατελείωτες απαντήσεις από το γνώστη ChatGPT (σε οποιαδήποτε γλώσσα!)
// @description:eo      Kreu nesfinaĵajn respondojn el la ĉio-scianta ChatGPT (en ajn lingvo!)
// @description:es      Genera respuestas infinitas desde el ChatGPT omnisciente (¡en cualquier idioma!)
// @description:et      Loo lõputuid vastuseid kõike-teadvast ChatGPT-st (mis tahes keeles!)
// @description:eu      Sortu erantzun infinituak guztiz-arduratsuaren ChatGPT-tik (edozein hizkuntzan!)
// @description:fa      پاسخهای بیپایانی را از ChatGPT همهدانا تولید کنید (به هر زبانی!)
// @description:fi      Luo loputtomia vastauksia kaikkitietävästä ChatGPT:stä (millä tahansa kielellä!)
// @description:fo      Skapa endalaus svør frá altvitandi ChatGPT (á hvørjum málrøð!)
// @description:fr      Générez des réponses infinies à partir de ChatGPT qui sait tout (dans n'importe quelle langue!)
// @description:fr-CA   Générez des réponses infinies à partir de ChatGPT qui sait tout (dans n'importe quelle langue!)
// @description:gd      Cruthaich freagairtean gun crìoch à ChatGPT a tha a' faighneachd gach càil (ann an sam bith cànan!)
// @description:gl      Xere as respostas infinitas do ChatGPT que todo o sabe (en calquera lingua!)
// @description:gu      જ્ઞાનવાન ChatGPT થી અનંત જવાબો ઉત્પન કરો (કોઈ પણ ભાષામાં!)
// @description:haw     Haleleʻa i nā ʻōlelo pālulelo mai ke kupa ʻike loa o ChatGPT (i loko o kēlā ʻōlelo aku aʻe!)
// @description:he      יצרו תשובות אינסופיות מה-ChatGPT המבין הכל (בכל שפה!)
// @description:hi      सभी-जाननेवाले चैटजीपीटी से अनंत उत्तरों का उत्पादन करें (किसी भी भाषा में!)
// @description:hr      Generirajte beskrajne odgovore iz sveznajućeg ChatGPT-a (na bilo kojem jeziku!)
// @description:ht      Jenere repons san fen soti nan ChatGPT k-ap konnen tout bagay yo (nan nenpòt lang!)
// @description:hu      Végtelen válaszokat generáljon a mindentudó ChatGPT-ből (bármely nyelven!)
// @description:hy      Ստեղծեք անսահմանափակ պատասխաններ ամենագիտական ChatGPT-ից (ցանկացած լեզուն մեջ!)
// @description:id      Hasilkan jawaban tak terbatas dari ChatGPT yang tahu segalanya (dalam bahasa apa pun!)
// @description:is      Búið til endalaus svör frá allvissu ChatGPT (á hvaða tungumáli sem er!)
// @description:it      Genera risposte infinite dall'onnisciente ChatGPT (in qualsiasi lingua!)
// @description:ja      あらゆる言語で全知のChatGPTから無限の回答を生成します!
// @description:jv      Mbukak panggung jawaban saka ChatGPT kang suwénéh kabèh (kénging basa apapun!)
// @description:ka      შექმენით უსასრულო პასუხები ყველგანაწილებული ChatGPT-დან (ნელა ენაზე!)
// @description:kab     Kkes-as yidir seg yisem-asen n tafriqt ara ddunnit ChatGPT (di tifrat ara ddunit!)
// @description:kk      Барлық тілде бар білген ChatGPT-ден шексіз жауаптар жасау (қандай да тілде!)
// @description:km      បង្កើតចម្លើយមិនឃើញចប់ពី ChatGPT ដែលចែកសង្ស័យទាំងអស់ (ជាន់គ្រប់ភាសា!)
// @description:kn      ಎಲ್ಲರು ತಿಳಿದಿರುವ ಚಾಟ್ಜಿಪಿಟಿಯಿಂದ ಅನಂತ ಉತ್ತರಗಳನ್ನು ರಚಿಸಿ (ಯಾವುದೇ ಭಾಷೆಯಲ್ಲಿ!)
// @description:ko      어떤 언어로든지 무궁무진한 답변을 만들어내는 ChatGPT입니다!
// @description:ku      Ji ChatGPT-ê, ku hemî tiştan dizane, bersiva li serbazên li dor qewî yên hilbijartin (bi hertiştî zimanek!)
// @description:ky      Түз билимдүү ChatGPT боюнча чыгармаларды жаса
// @description:la      Genera infinitas responsiones de ChatGPT omniscio (in qualibet lingua!)
// @description:lb      Generéiert endlos Äntwerten vum allwëssende ChatGPT (op jiddere Sprooch!)
// @description:lo      ສ້າງຜົນສົດທີ່ສາມາດເລືອກຈາກພາສາທີ່ຮູ້ບຸກກຳລັງ ChatGPT (ໃນພາສາໃດໜຶ່ງ!)
// @description:lt      Sugeneruokite begalinį atsakymų kiekį iš visai žinoančio ChatGPT (bet kuria kalba!)
// @description:lv      Ģenerē nebeidzamus atbilžu variantus no vissapratīgā ChatGPT (jebkurā valodā!)
// @description:mg      Mandoza ny valiny miaraka amin'ny ChatGPT mahalala ny zavatra rehetra (amin'ny fiteny iray kokoa!)
// @description:mi      Whakapūmau i ngā whakautu kore mutunga mai i te ChatGPT matau i ngā reo katoa!
// @description:mk      Генерирајте безброј одговори од сèзнаената ChatGPT (на било кој јазик!)
// @description:ml      എന്നെഴുതാൻ അനന്യനായ ChatGPT (ഏതെങ്കിലും ഭാഷയിൽ) ഇന്നേക്കും വേണ്ടി അവസാനിപ്പിക്കുക!
// @description:mn      Сүүлд үлдсэнээсээ хайрцаг болох ChatGPT (ямар ч хэл дээр) дээрхээр ярих
// @description:ms      Cipta pelbagai jawapan daripada ChatGPT yang tahu segala-galanya (dalam apa-apa bahasa!)
// @description:mt      Iġġenera risposti infiniti mill-ChatGPT li kollha jaf (f'xi lingwa!)
// @description:my      အားလုံးကိုသင်ရိုးရိုးဆွဲနိုင်သည့် ChatGPT (တစ်ခုမှာယူသုံးရန်!)
// @description:ne      सबै-ज्ञानी ChatGPT बाट अनंत उत्तरहरू उत्पन्न गर्नुहोस् (कुनै पनि भाषामा!)
// @description:nl      Genereer eindeloze antwoorden van alwetende ChatGPT (in elke taal!)
// @description:no      Generer endeløse svar fra allvitende ChatGPT (på hvilket som helst språk!)
// @description:ny      Galimoto mabwino a mtendere zosiyanasiyana kuchokera ku ChatGPT woyankhula zonse! (muyankhulitsa chilichonse!)
// @description:pa      ਸਭ ਜਾਣ ਵਾਲੇ ChatGPT ਤੋਂ ਲੰਬੇ ਉੱਤਰਾਂ ਨੂੰ ਬਣਾਓ (ਕਿਸੇ ਵੀ ਭਾਸ਼ਾ ਵਿੱਚ!)
// @description:pap     Hasi respuesta sinfin di ChatGPT ku tur sabi (na kua idioma!)
// @description:pl      Generuj nieskończone odpowiedzi od wszechwiedzącego ChatGPT (w dowolnym języku!)
// @description:ps      د هغوی چټکال ChatGPT لخوا نهایت جوابونه جوړه کړئ (د هر یوه ژبه کی!)
// @description:pt      Gere respostas infinitas do ChatGPT onisciente (em qualquer idioma!)
// @description:pt-BR   Gere respostas infinitas do ChatGPT onisciente (em qualquer idioma!)
// @description:rn      Basha inzira nk'itandukanye z'uko ChatGPT uzi (mu rurimi rwose!)
// @description:ro      Generează răspunsuri infinite de la ChatGPT omniscient (în orice limbă!)
// @description:ru      Генерируйте бесконечные ответы от всезнающего ChatGPT (на любом языке!)
// @description:rw      Banda inama z'imirimo isigaye zose z'umuco wa ChatGPT (mu rurimi rwose!)
// @description:sg      Tia ngamana nga mbetela ti ChatGPT tozuwa mitayi mingi (po wundi ndimi yo ngambo!)
// @description:si      සියළු දැනටමත් සහතිකපත්කරන තවත් සිතියම් සැකසුම් ලබා දෙන්නාවූ ChatGPT සෑදීම (ඕනෑම භාෂාවෙන්ම!)
// @description:sk      Generujte nekonečné odpovede od vševietajúceho ChatGPT (v akomkoľvek jazyku!)
// @description:sl      Generirajte neskončne odgovore iz vsevednega ChatGPT (v katerem koli jeziku!)
// @description:sm      Faia se faiga tele i le ChatGPT eseese (i nisi gagana!)
// @description:sn      Simudza mhinduro dzakawanda kubva kune ChatGPT ichiwanikwa chisarudzo! (mune rimwe nguva!)
// @description:so      Kor u qaado jawaabo kala duwan oo ka soo saar ChatGPT (luuqad ka mid ah!)
// @description:sr      Генеришите безброј одговора од свемоћног ChatGPT (на било ком језику!)
// @description:sv      Generera oändliga svar från allvetande ChatGPT (på valfritt språk!)
// @description:sw      Toa majibu yasiyokuwa na mwisho kutoka kwa ChatGPT mwenye maarifa yote (katika lugha yoyote!)
// @description:ta      அனைத்து தகவலையும் அறியப்பட்ட சொந்தமான ChatGPT இலிருந்து முடிவுகளை உருவாக்கவும் (எந்த மொழியிலும்!)
// @description:te      అన్నింటినీకింట మాటలు రాయండి ChatGPT గురించి అనేక జవాబాలను సృష్టించండి (ఏదైనా భాషలో!)
// @description:tg      Ҷавобҳои бесуданни ChatGPTи ҳамаифақат (дар як забони муайяни!)
// @description:th      สร้างคำตอบไม่สิ้นสุดจาก ChatGPT ที่รู้ทุกสิ่ง (ในภาษาใดก็ได้!)
// @description:ti      ክርስትን ለማውጣት ከገጽታውን ChatGPT የተከሳሽ አስተካክል አስተካክሎት (በእውነት ቋንቋ!)
// @description:tk      Şeýle anlaşylýan ChatGPT (her hili üçin) arasyndan bäşmüňhat jawaplar döret
// @description:tn      Hlela zitsha zwine zwiṱhiselela kha ChatGPT vhufudziṱe (muvhili wo vha u ite!)
// @description:to      Fakatonutonu ʻihe ngāuekesi mei he ChatGPT fakaongoongo toenga (i he lea faka-Tonga ia!)
// @description:tpi     Sanapim hamamasples long save olsem ChatGPT i masples (long wanpela tok ples!)
// @description:tr      Bilge ChatGPT'den sonsuz cevaplar üret (herhangi bir dilde!)
// @description:uk      Генеруйте безкінечні відповіді від усезнаючого ChatGPT (на будь-якій мові!)
// @description:ur      سب جاننے والے ChatGPT سے لامتناہی جوابات پیدا کریں (کسی بھی زبان میں!)
// @description:uz      Barcha biladigan ChatGPT dan cheklovli javoblar oling (hech qanday tilda ham)!
// @description:vi      Tạo ra vô số câu trả lời từ ChatGPT thông minh (bằng bất kỳ ngôn ngữ nào!)
// @description:xh      Bhala izinto ezingekwaziyo eziyimfihlo kusuka ku ChatGPT (ngolwimi lwanyanetha!)
// @description:yi      דזשענערייט סאָף ענטפֿערס פֿון אַלע-געוויסן ChatGPT (אין קיין שפּראַך!)
// @description:zh      从无所不知的 ChatGPT 生成无穷无尽的答案 (用任何语言!)
// @description:zh-CN   从无所不知的 ChatGPT 生成无穷无尽的答案 (用任何语言!)
// @description:zh-HK   從無所不知的 ChatGPT 生成無窮無盡的答案 (用任何語言!)
// @description:zh-SG   从无所不知的 ChatGPT 生成无穷无尽的答案 (用任何语言!)
// @description:zh-TW   從無所不知的 ChatGPT 生成無窮無盡的答案 (用任何語言!)
// @author              Adam Lui
// @namespace           https://github.com/adamlui
// @version             2024.11.23
// @license             MIT
// @match               *://chatgpt.com/*
// @match               *://chat.openai.com/*
// @icon                https://media.chatgptinfinity.com/images/icons/infinity-symbol/circled/with-robot/icon48.png?f196818
// @icon64              https://media.chatgptinfinity.com/images/icons/infinity-symbol/circled/with-robot/icon64.png?f196818
// @compatible          chrome
// @compatible          firefox
// @compatible          edge
// @compatible          opera
// @compatible          brave
// @compatible          vivaldi
// @compatible          waterfox
// @compatible          librewolf
// @compatible          ghost
// @compatible          qq
// @compatible          whale
// @compatible          kiwi
// @require             https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.3.5/dist/chatgpt.min.js#sha256-rfC4kk8q0byrafp7X0Qf9vaa3JNvkHRwNnUt6uL2hUE=
// @require             https://cdn.jsdelivr.net/gh/adamlui/chatgpt-infinity@a0d6630c225f26ae7cd5ccd1fda39bc45177bebc/chrome/extension/lib/dom.js#sha256-pbJ15rhD5UtxxSCn+L0ybKnlrT3SNm3t8Dc99qtN4KQ=
// @connect             cdn.jsdelivr.net
// @connect             update.greasyfork.org
// @grant               GM_setValue
// @grant               GM_getValue
// @grant               GM_registerMenuCommand
// @grant               GM_unregisterMenuCommand
// @grant               GM_xmlhttpRequest
// @grant               GM.xmlHttpRequest
// @noframes
// @homepageURL         https://www.chatgptinfinity.com
// @supportURL          https://support.chatgptinfinity.com
// @contributionURL     https://github.com/sponsors/adamlui
// ==/UserScript==

// Documentation: https://docs.chatgptinfinity.com
// NOTE: This script relies on the powerful chatgpt.js library @ https://chatgpt.js.org
//  © 2023–2024 KudoAI & contributors under the MIT license.

(async () => {

    // Init ENV context
    const env = {
        browser: {
            language: chatgpt.getUserLanguage(), isMobile: chatgpt.browser.isMobile(), isFF: chatgpt.browser.isFirefox()
        },
        scriptManager: (() => { try { return GM_info.scriptHandler } catch (err) { return 'unknown' }})()
    }
    const xhr = env.scriptManager == 'OrangeMonkey' ? GM_xmlhttpRequest : GM.xmlHttpRequest

    // Init APP data
    const app = { configKeyPrefix: 'chatGPTinfinity', latestAssetCommitHash: '0f2098f', urls: {} }
    app.urls.assetHost = `https://cdn.jsdelivr.net/gh/adamlui/chatgpt-infinity@${app.latestAssetCommitHash}`
    const appData = await new Promise(resolve => xhr({
        method: 'GET', url: `${app.urls.assetHost}/app.json`,
        onload: resp => resolve(JSON.parse(resp.responseText))
    }))
    Object.assign(app, { ...appData, urls: { ...app.urls, ...appData.urls }})
    app.urls.update = app.urls.greasyFork.replace('https://', 'https://update.')
        .replace(/(\d+)-?([a-z-]*)$/i, (_, id, name) => `${id}/${ name || 'script' }.meta.js`)
    app.msgs = {
        appName: app.name,
        appAuthor: app.author.name,
        appDesc: 'Generate endless answers from all-knowing ChatGPT (in any language!)',
        menuLabel_infinityMode: 'Infinity Mode',
        menuLabel_autoStart: 'Auto-Start',
        menuLabel_toggleVis: 'Toggle Visibility',
        menuLabel_autoScroll: 'Auto-Scroll',
        menuLabel_replyLang: 'Reply Language',
        menuLabel_replyTopic: 'Reply Topic',
        menuLabel_all: 'ALL',
        menuLabel_replyInt: 'Reply Interval',
        menuLabel_about: 'About',
        menuLabel_donate: 'Please send a donation',
        menuLabel_disabled: 'Disabled (extension installed)',
        about_version: 'Version',
        about_poweredBy: 'Powered by',
        about_sourceCode: 'Source code',
        prompt_updateReplyLang: 'Update reply language',
        prompt_updateReplyTopic: 'Update reply topic',
        prompt_orEnter: 'or enter',
        prompt_updateReplyInt: 'Update reply interval (minimum 5 secs)',
        alert_replyLangUpdated: 'Language updated',
        alert_willReplyIn: 'will reply in',
        alert_yourSysLang: 'your system language',
        alert_replyTopicUpdated: 'Topic updated',
        alert_willAnswer: 'will answer questions',
        alert_onTopicOf: 'on the topic of',
        alert_onAllTopics: 'on ALL topics',
        alert_replyIntUpdated: 'Interval updated',
        alert_willReplyEvery: 'will reply every',
        alert_choosePlatform: 'Choose a platform',
        alert_updateAvail: 'Update available',
        alert_newerVer: 'An update to',
        alert_isAvail: 'is available',
        alert_upToDate: 'Up-to-date',
        alert_isUpToDate: 'is up-to-date',
        alert_showYourSupport: 'Show your support',
        alert_isOSS: 'is open-source software built & maintained for free through 100% volunteer efforts',
        alert_despiteAffliction: 'Despite being severely afflicted by',
        alert_longCOVID: 'long COVID',
        alert_since2020: 'since 2020',
        alert_byDonatingResults: 'by donating, you help me to continue improving, fixing bugs, adding new features, and making the software even better',
        alert_yourContrib: 'Your contribution',
        alert_noMatterSize: 'no matter the size',
        alert_directlySupports: 'directly supports my unpaid efforts to ensure this project remains free and open for all to use',
        alert_tyForSupport: 'Thank you for your support',
        alert_author: 'author',
        btnLabel_moreAIextensions: 'More AI Extensions',
        btnLabel_rateUs: 'Rate Us',
        btnLabel_getSupport: 'Get Support',
        btnLabel_updateCheck: 'Check for Updates',
        btnLabel_update: 'Update',
        btnLabel_dismiss: 'Dismiss',
        link_viewChanges: 'View changes',
        unit_seconds: 'seconds',
        state_enabled: 'enabled',
        state_disabled: 'disabled',
        state_on: 'on',
        state_off: 'off'
    }

    // LOCALIZE app.msgs for non-English users
    if (!env.browser.language.startsWith('en')) {
        const localizedMsgs = await new Promise(resolve => {
            const msgHostDir = app.urls.assetHost + '/chrome/extension/_locales/',
                  msgLocaleDir = ( env.browser.language ? env.browser.language.replace('-', '_') : 'en' ) + '/'
            let msgHref = msgHostDir + msgLocaleDir + 'messages.json', msgXHRtries = 0
            function fetchMsgs() { xhr({ method: 'GET', url: msgHref, onload: handleMsgs })}
            function handleMsgs(resp) {
                try { // to return localized messages.json
                    const msgs = JSON.parse(resp.responseText), flatMsgs = {}
                    for (const key in msgs)  // remove need to ref nested keys
                        if (typeof msgs[key] == 'object' && 'message' in msgs[key])
                            flatMsgs[key] = msgs[key].message
                    resolve(flatMsgs)
                } catch (err) { // if bad response
                    msgXHRtries++ ; if (msgXHRtries == 3) return resolve({}) // try original/region-stripped/EN only
                    msgHref = env.browser.language.includes('-') && msgXHRtries == 1 ? // if regional lang on 1st try...
                        msgHref.replace(/([^_]+_[^_]+)_[^/]*(\/.*)/, '$1$2') // ...strip region before retrying
                            : ( msgHostDir + 'en/messages.json' ) // else use default English messages
                    fetchMsgs()
                }
            }
            fetchMsgs()
        })
        Object.assign(app.msgs, localizedMsgs)
    }

    // Init SETTINGS
    const config = {}
    const settings = {

        controls: {
            autoStart: { type: 'toggle', label: app.msgs.menuLabel_autoStart },
            toggleHidden: { type: 'toggle', label: app.msgs.menuLabel_toggleVis },
            autoScrollDisabled: { type: 'toggle', label: app.msgs.menuLabel_autoScroll },
            replyLanguage: { type: 'prompt', symbol: '🌐', label: app.msgs.menuLabel_replyLang },
            replyTopic: { type: 'prompt', symbol: '🧠', label: app.msgs.menuLabel_replyTopic },
            replyInterval: { type: 'prompt', symbol: '⌚', label: app.msgs.menuLabel_replyInt }
        },

        load(...keys) {
            if (Array.isArray(keys[0])) keys = keys[0] // use 1st array arg, else all comma-separated ones
            keys.forEach(key => config[key] = GM_getValue(app.configKeyPrefix + '_' + key, false))
        },

        save(key, value) { GM_setValue(app.configKeyPrefix + '_' + key, value) ; config[key] = value }
    }
    settings.load('autoScrollDisabled', 'autoStart', 'replyInterval', 'replyLanguage', 'replyTopic', 'toggleHidden')
    if (!config.replyLanguage) settings.save('replyLanguage', env.browser.language) // init reply language if unset
    if (!config.replyTopic) settings.save('replyTopic', 'ALL') // init reply topic if unset
    if (!config.replyInterval) settings.save('replyInterval', 7) // init refresh interval to 7 secs if unset

    // Define MENU functions

    const menu = {
        ids: [], state: {
            symbols: ['❌', '✔️'], separator: env.scriptManager == 'Tampermonkey' ? ' — ' : ': ',
            words: [app.msgs.state_off.toUpperCase(), app.msgs.state_on.toUpperCase()]
        },

        register() {

            // Init prompt setting status labels
            const re_all = new RegExp(`^(${app.msgs.menuLabel_all}|all|any|every)$`, 'i')
            settings.controls.replyLanguage.status = config.replyLanguage
            settings.controls.replyTopic.status = re_all.test(config.replyTopic) ? app.msgs.menuLabel_all
                                                                                 : toTitleCase(config.replyTopic)
            settings.controls.replyInterval.status = `${config.replyInterval}s`

            // Add Infinity Mode toggle
            const imLabel = `${menu.state.symbols[+!!config.infinityMode]} `
                          + `${app.msgs.menuLabel_infinityMode} ∞ `
                          + menu.state.separator + menu.state.words[+!!config.infinityMode]
            menu.ids.push(GM_registerMenuCommand(imLabel, () => {
                settings.save('infinityMode', !config.infinityMode) ; syncConfigToUI()
                infinity.toggle()
            }))

            // Add setting entries
            Object.keys(settings.controls).forEach(key => {
                const settingIsEnabled = config[key] ^ /disabled|hidden/i.test(key)
                const menuLabel = `${ settings.controls[key].symbol || menu.state.symbols[+settingIsEnabled] } `
                                + settings.controls[key].label
                                + ( settings.controls[key].type == 'toggle' ? menu.state.separator
                                                                            + menu.state.words[+settingIsEnabled]
                                                                            : `— ${settings.controls[key].status}` )
                menu.ids.push(GM_registerMenuCommand(menuLabel, () => {
                    if (settings.controls[key].type == 'toggle') {
                        settings.save(key, !config[key])
                        notify(`${settings.controls[key].label}: ${
                            menu.state.words[+(/disabled|hidden/i.test(key) ^ config[key])]}`)
                    } else if (key == 'replyLanguage') {
                        while (true) {
                            let replyLang = prompt(
                                `${app.msgs.prompt_updateReplyLang}:`, config.replyLanguage)
                            if (replyLang == null) break // user cancelled so do nothing
                            else if (!/\d/.test(replyLang)) {
                                replyLang = ( // auto-case for menu/alert aesthetics
                                    replyLang.length < 4 || replyLang.includes('-') ? replyLang.toUpperCase()
                                        : replyLang.charAt(0).toUpperCase() + replyLang.slice(1).toLowerCase() )
                                settings.save('replyLanguage', replyLang || env.browser.language)
                                siteAlert(( app.msgs.alert_replyLangUpdated ) + '!', // title
                                    ( app.msgs.appName ) + ' ' // msg
                                        + ( app.msgs.alert_willReplyIn ) + ' '
                                        + ( replyLang || app.msgs.alert_yourSysLang) + '.')
                                if (config.infinityMode) infinity.restart({ target: 'new' }) // using new reply language
                                break
                            }
                        }
                    } else if (key == 'replyTopic') {
                        const replyTopic = prompt(( app.msgs.prompt_updateReplyTopic )
                                        + ' (' + ( app.msgs.prompt_orEnter ) + ' \'ALL\'):', config.replyTopic)
                        if (replyTopic != null) { // user didn't cancel
                            const str_replyTopic = replyTopic.toString()
                            settings.save('replyTopic', !replyTopic || re_all.test(str_replyTopic) ? 'ALL'
                                                                                                   : str_replyTopic)
                            siteAlert(`${app.msgs.alert_replyTopicUpdated}!`,
                                `${app.msgs.appName} ${app.msgs.alert_willAnswer} `
                                    + ( !replyTopic || re_all.test(str_replyTopic) ? app.msgs.alert_onAllTopics
                                        : `${app.msgs.alert_onTopicOf} ${str_replyTopic}` )
                                    + '!'
                            )
                            if (config.infinityMode) infinity.restart({ target: 'new' })
                        }
                    } else if (key == 'replyInterval') {
                        while (true) {
                            const replyInterval = prompt(
                                `${app.msgs.prompt_updateReplyInt}:`, config.replyInterval)
                            if (replyInterval == null) break // user cancelled so do nothing
                            else if (!isNaN(parseInt(replyInterval, 10)) && parseInt(replyInterval, 10) > 4) {
                                settings.save('replyInterval', parseInt(replyInterval, 10))
                                siteAlert(( app.msgs.alert_replyIntUpdated ) + '!', // title
                                    ( app.msgs.appName ) + ' ' // msg
                                        + ( app.msgs.alert_willReplyEvery ) + ' '
                                        + replyInterval + ' ' + ( app.msgs.unit_seconds ) + '.')
                                if (config.infinityMode) infinity.restart({ target: 'self' })
                                break
                            }
                        }
                    }
                    syncConfigToUI()
                }))
            })

            // Add About entry
            const aboutLabel = `💡 ${app.msgs.menuLabel_about} ${app.msgs.appName}`
            menu.ids.push(GM_registerMenuCommand(aboutLabel, modals.about.show))

            // Add Donate entry
            const donateLabel = `💖 ${app.msgs.menuLabel_donate}`
            menu.ids.push(GM_registerMenuCommand(donateLabel, modals.donate.show))
        },

        refresh() {
            if (env.scriptManager == 'OrangeMonkey') return
            for (const id of menu.ids) { GM_unregisterMenuCommand(id) } menu.register()
        }
    }

    function updateCheck() {

        // Fetch latest meta
        const currentVer = GM_info.script.version
        xhr({
            method: 'GET', url: app.urls.update + '?t=' + Date.now(),
            headers: { 'Cache-Control': 'no-cache' },
            onload: resp => { const updateAlertWidth = 377

                // Compare versions
                const latestVer = /@version +(.*)/.exec(resp.responseText)[1]
                for (let i = 0 ; i < 4 ; i++) { // loop thru subver's
                    const currentSubVer = parseInt(currentVer.split('.')[i], 10) || 0,
                          latestSubVer = parseInt(latestVer.split('.')[i], 10) || 0
                    if (currentSubVer > latestSubVer) break // out of comparison since not outdated
                    else if (latestSubVer > currentSubVer) { // if outdated

                        // Alert to update
                        const updateModalID = siteAlert(`🚀 ${app.msgs.alert_updateAvail}!`, // title
                            `${app.msgs.alert_newerVer} ${app.msgs.appName} `
                                + `(v${latestVer}) ${app.msgs.alert_isAvail}!  `
                                + '<a target="_blank" rel="noopener" style="font-size: 0.7rem" '
                                    + 'href="' + app.urls.gitHub + '/commits/main/greasemonkey/'
                                    + app.urls.update.replace(/[^/]*\/([^/]*?)meta\.js/, '$1user.js') + '"'
                                    + `> ${app.msgs.link_viewChanges}</a>`,
                            function update() { // button
                                modals.safeWinOpen(app.urls.update.replace('meta.js', 'user.js') + '?t=' + Date.now())
                            }, '', updateAlertWidth
                        )

                        // Localize button labels if needed
                        if (!env.browser.language.startsWith('en')) {
                            const updateAlert = document.querySelector(`[id="${updateModalID}"]`),
                                  updateBtns = updateAlert.querySelectorAll('button')
                            updateBtns[1].textContent = app.msgs.btnLabel_update
                            updateBtns[0].textContent = app.msgs.btnLabel_dismiss
                        }

                        return
                }}

                // Alert to no update, return to About modal
                siteAlert(`${app.msgs.alert_upToDate}!`, // title
                    `${app.msgs.appName} (v${currentVer}) ${app.msgs.alert_isUpToDate}!`, // msg
                    '', '', updateAlertWidth
                )
                modals.about.show()
    }})}

    function toTitleCase(str) {
        const words = str.toLowerCase().split(' ')
        for (let i = 0 ; i < words.length ; i++) // for each word
            words[i] = words[i][0].toUpperCase() + words[i].slice(1) // title-case it
        return words.join(' ') // join'em back together
    }

    // Define FEEDBACK functions

    function notify(msg, pos = '', notifDuration = '', shadow = '') {

        // Strip state word to append colored one later
        const foundState = menu.state.words.find(word => msg.includes(word))
        if (foundState) msg = msg.replace(foundState, '')

        // Show notification
        chatgpt.notify(`${app.symbol} ${msg}`, pos, notifDuration, shadow || chatgpt.isDarkMode() ? '' : 'shadow')
        const notif = document.querySelector('.chatgpt-notif:last-child')

        // Append styled state word
        if (foundState) {
            const styledStateSpan = document.createElement('span')
            styledStateSpan.style.cssText = `color: ${
                foundState == menu.state.words[0] ? '#ef4848 ; text-shadow: rgba(255, 169, 225, 0.44) 2px 1px 5px'
                                                  : '#5cef48 ; text-shadow: rgba(255, 250, 169, 0.38) 2px 1px 5px' }`
            styledStateSpan.append(foundState) ; notif.append(styledStateSpan)
        }
    }

    function siteAlert(title = '', msg = '', btns = '', checkbox = '', width = '') {
        return chatgpt.alert(title, msg, btns, checkbox, width )}

    // Define MODAL functions

    const modals = {
        stack: [],

        about: {
            show() {
                modals.stack.unshift('about') ; modals.stack = [...new Set(modals.stack)] // track for nav

                // Show alert
                const chatgptJSver = (/chatgpt-([\d.]+)\.min/.exec(GM_info.script.header) || [null, ''])[1],
                      headingStyle = 'font-size: 1.15rem',
                      pStyle = 'position: relative ; left: 3px',
                      pBrStyle = 'position: relative ; left: 4px ',
                      aStyle = 'color: ' + ( chatgpt.isDarkMode() ? '#c67afb' : '#8325c4' ) // purple
                const aboutModalID = siteAlert(
                    app.msgs.appName, // title
                    `<span style="${headingStyle}"><b>🏷️ <i>${app.msgs.about_version}</i></b>: </span>`
                        + `<span style="${pStyle}">${GM_info.script.version}</span>\n`
                    + `<span style="${headingStyle}"><b>⚡ <i>${app.msgs.about_poweredBy}</i></b>: </span>`
                        + `<span style="${pStyle}">`
                            + `<a style="${aStyle}" href="${app.urls.chatgptJS}" target="_blank" rel="noopener">`
                                + 'chatgpt.js</a>' + ( chatgptJSver ? ( ' v' + chatgptJSver ) : '' ) + '</span>\n'
                    + `<span style="${headingStyle}"><b>📜 <i>${app.msgs.about_sourceCode}</i></b>:</span>\n`
                        + `<span style="${pBrStyle}"><a href="${app.urls.gitHub}" target="_blank" rel="nopener">`
                            + app.urls.gitHub + '</a></span>',
                    [ // buttons
                        function checkForUpdates() { updateCheck() },
                        function getSupport() { modals.safeWinOpen(app.urls.support) },
                        function rateUs() { modals.feedback.show() },
                        function moreChatGPTapps() { modals.safeWinOpen(app.urls.relatedApps) }
                    ], '', 478 // set width
                )

                // Re-format buttons to include emoji + localized label + hide Dismiss button
                for (const button of document.getElementById(aboutModalID).querySelectorAll('button')) {
                    button.style.cssText = 'cursor: pointer !important' // since tweaks won't load on auto-disable
                    if (/updates/i.test(button.textContent)) button.textContent = (
                        '🚀 ' + ( app.msgs.btnLabel_updateCheck ))
                    else if (/support/i.test(button.textContent)) button.textContent = (
                        '🧠 ' + ( app.msgs.btnLabel_getSupport ))
                    else if (/rate/i.test(button.textContent)) button.textContent = (
                        '⭐ ' + ( app.msgs.btnLabel_rateUs ))
                    else if (/apps/i.test(button.textContent)) button.textContent = (
                        '🤖 ' + ( app.msgs.btnLabel_moreAIextensions ))
                    else button.style.display = 'none' // hide Dismiss button
                }
            }
        },

        donate: {
            longCOVIDwikiLink: 'https://en.wikipedia.org/wiki/Long_COVID',

            show() {
                modals.stack.unshift('donate') ; modals.stack = [...new Set(modals.stack)] // track for nav

                // Show alert
                const donateModalID = siteAlert(
                    `💖 ${app.msgs.alert_showYourSupport}`, // title
                        `<p>${app.msgs.appName} ${app.msgs.alert_isOSS}.</p>`
                      + `<p>${app.msgs.alert_despiteAffliction} `
                          + `<a target="_blank" rel="noopener" href="${modals.donate.longCOVIDwikiLink}">`
                              + `${app.msgs.alert_longCOVID}</a> `
                          + `${app.msgs.alert_since2020}, ${app.msgs.alert_byDonatingResults}.</p>`
                      + `<p>${app.msgs.alert_yourContrib}, <b>${app.msgs.alert_noMatterSize}</b>, `
                          + `${app.msgs.alert_directlySupports}.</p>`
                      + `<p>${app.msgs.alert_tyForSupport}!</p>`
                      + '<img src="https://cdn.jsdelivr.net/gh/adamlui/adamlui/images/siggie/'
                          + `${ chatgpt.isDarkMode() ? 'white' : 'black' }.png" `
                          + 'style="height: 54px ; margin: 5px 0 -2px 5px"></img>'
                      + `<p>—<b><a target="_blank" rel="noopener" href="${app.author.url}">`
                          + `${app.msgs.appAuthor}</a></b>, ${app.msgs.alert_author}</p>`,
                    [ // buttons
                        function paypal() { modals.safeWinOpen(app.urls.donate.payPal) },
                        function githubSponsors() { modals.safeWinOpen(app.urls.donate.gitHub) },
                        function cashApp() { modals.safeWinOpen(app.urls.donate.cashApp) },
                        function rateUs() { modals.safeWinOpen(app.urls.review.greasyFork) }
                    ], '', 478 // set width
                )

                // Format text
                const donateModal = document.getElementById(donateModalID)
                donateModal.querySelectorAll('p').forEach(p => // v-pad text, shrink line height
                    p.style.cssText = 'padding: 8px 0 ; line-height: 20px')

                // Format buttons
                const btns = donateModal.querySelectorAll('button')
                btns.forEach((btn, idx) => {
                    if (idx == 0) btn.style.display = 'none' // hide Dismiss button
                    else {
                        btn.style.cssText = 'padding: 8px 6px !important ; margin-top: -14px ;'
                                          + ' width: 107px ; line-height: 14px'
                        if (idx == btns.length -1) // de-emphasize right-most button
                            btn.classList.remove('primary-modal-btn')
                        else if (/rate/i.test(btn.textContent)) // localize 'Rate Us' label
                            btn.textContent = app.msgs.btnLabel_rateUs
                    }
                })
            }
        },

        feedback: {
            show() {
                const reviewModalID = chatgpt.alert(
                    `${app.msgs.alert_choosePlatform}:`, '', // title
                    [ // buttons
                        function greasyFork() { modals.safeWinOpen(app.urls.review.greasyFork) },
                        function productHunt() { modals.safeWinOpen(app.urls.review.productHunt) },
                        function alternativeTo() { modals.safeWinOpen(app.urls.review.alternativeTo) }
                    ]
                )
                const reviewModal = document.getElementById(reviewModalID)
                reviewModal.querySelector('button').style.display = 'none' // hide Dismiss button
                reviewModal.addEventListener('DOMNodeRemoved', () => modals[modals.stack[0]]?.show() ) // nav back
            }
        },

        safeWinOpen(url) { open(url, '_blank', 'noopener') } // to prevent backdoor vulnerabilities
    }

    // Define UI functions

    function syncConfigToUI() {
        sidebarToggle.update() // based on config.toggleHidden + config.infinityMode
        menu.refresh() // prefixes/suffixes
    }

    const sidebarToggle = {

        create() {
            sidebarToggle.div = document.createElement('div')
            sidebarToggle.update() // create children

            // Stylize/classify
            sidebarToggle.div.style.cssText += 'height: 37px ; margin: 2px 0 ; user-select: none ; cursor: pointer'
            if (ui.firstLink) { // borrow/assign classes from sidebar elems
                const firstIcon = ui.firstLink.querySelector('div:first-child'),
                      firstLabel = ui.firstLink.querySelector('div:nth-child(2)')
                sidebarToggle.div.classList.add(...ui.firstLink.classList, ...(firstLabel?.classList || []))
                sidebarToggle.div.querySelector('img')?.classList.add(...(firstIcon?.classList || []))
            }

            // Add click listener
            sidebarToggle.div.onclick = () => {
                const toggleInput = sidebarToggle.div.querySelector('input')
                toggleInput.checked = !toggleInput.checked ; settings.save('infinityMode', toggleInput.checked)
                infinity.toggle()
            }
        },

        insert() {
            if (sidebarToggle.status?.startsWith('insert') || document.getElementById('infinity-toggle-navicon')) return
            sidebarToggle.status = 'inserting' ; if (!sidebarToggle.div) sidebarToggle.create()

            // Insert toggle
            const sidebar = document.querySelectorAll('nav')[env.browser.isMobile ? 1 : 0]
            if (!sidebar) return
            sidebar.insertBefore(sidebarToggle.div, sidebar.children[1])

            // Tweak styles
            const knobSpan = document.getElementById('infinity-toggle-knob-span'),
                  navicon = document.getElementById('infinity-toggle-navicon')
            sidebarToggle.div.style.flexGrow = 'unset' // overcome OpenAI .grow
            sidebarToggle.div.style.paddingLeft = '8px'
            if (knobSpan) knobSpan.style.boxShadow = (
                'rgba(0, 0, 0, .3) 0 1px 2px 0' + ( chatgpt.isDarkMode() ? ', rgba(0, 0, 0, .15) 0 3px 6px 2px' : '' ))
            if (navicon) navicon.src = `${ // update navicon color in case scheme changed
                app.urls.mediaHost}/images/icons/infinity-symbol/`
              + `${ chatgpt.isDarkMode() ? 'white' : 'black' }/icon32.png?${app.latestAssetCommitHash}`

            sidebarToggle.status = 'inserted'
        },

        update() {
            sidebarToggle.div.style.display = config.toggleHidden ? 'none' : 'flex'

            // Create/size/position navicon
            const navicon = document.getElementById('infinity-toggle-navicon')
                         || dom.create.elem('img', { id: 'infinity-toggle-navicon' })
            navicon.style.cssText = 'width: 1.25rem ; height: 1.25rem ; margin-left: 2px ; margin-right: 4px'

            // Create/ID/disable/hide/update checkbox
            const toggleInput = document.getElementById('infinity-toggle-input')
                             || dom.create.elem(
                                    'input', { id: 'infinity-toggle-input', type: 'checkbox', disabled: true })
            toggleInput.style.display = 'none' ; toggleInput.checked = config.infinityMode

            // Create/ID/stylize switch
            const switchSpan = document.getElementById('infinity-switch-span')
                            || dom.create.elem('span', { id: 'infinity-switch-span' })
            Object.assign(switchSpan.style, {
                position: 'relative', left: `${ env.browser.isMobile ? 169 : !ui.firstLink ? 160 : 154 }px`,
                backgroundColor: toggleInput.checked ? '#ccc' : '#AD68FF', // init opposite  final color
                bottom: `${ !ui.firstLink ? -0.15 : env.browser.isFF ? 0.05 : 0 }em`,
                width: '30px', height: '15px', '-webkit-transition': '.4s', transition: '0.4s',  borderRadius: '28px'
            })

            // Create/stylize knob, append to switch
            const knobSpan = document.getElementById('infinity-toggle-knob-span')
                          || dom.create.elem('span', { id: 'infinity-toggle-knob-span' })
            Object.assign(knobSpan.style, {
                position: 'absolute', left: '3px', bottom: '1.25px',
                width: '12px', height: '12px', content: '""', borderRadius: '28px',
                transform: toggleInput.checked ? // init opposite final pos
                    'translateX(0)' : 'translateX(13px) translateY(0)',
                backgroundColor: 'white',  '-webkit-transition': '0.4s', transition: '0.4s'
            }) ; switchSpan.append(knobSpan)

            // Create/stylize/fill label
            const toggleLabel = document.getElementById('infinity-toggle-label')
                             || dom.create.elem('label', { id: 'infinity-toggle-label' })
            if (!ui.firstLink) // add font size/weight since no ui.firstLink to borrow from
                toggleLabel.style.cssText = 'font-size: 0.875rem, font-weight: 600'
            Object.assign(toggleLabel.style, {
                marginLeft: `-${ !ui.firstLink ? 23 : 41 }px`, // left-shift to navicon
                cursor: 'pointer', // add finger cursor on hover
                width: `${ env.browser.isMobile ? 201 : 148 }px`, // to truncate overflown text
                overflow: 'hidden', textOverflow: 'ellipsis' // to truncate overflown text
            })
            toggleLabel.innerText = `${app.msgs.menuLabel_infinityMode} ${
                                       toggleInput.checked ? app.msgs.state_enabled : app.msgs.state_disabled }`
            // Append elements
            sidebarToggle.div.append(navicon, toggleInput, switchSpan, toggleLabel)

            // Update visual state
            setTimeout(() => {
                switchSpan.style.backgroundColor = toggleInput.checked ? '#ad68ff' : '#ccc'
                switchSpan.style.boxShadow = toggleInput.checked ? '2px 1px 9px #d8a9ff' : 'none'
                knobSpan.style.transform = toggleInput.checked ? 'translateX(13px) translateY(0)' : 'translateX(0)'
            }, 1) // min delay to trigger transition fx
        }
    }

    chatgpt.isIdle = function() { // replace waiting for chat to start in case of interrupts
        return new Promise(resolve => { // when stop btn missing
            new MutationObserver((_, obs) => {
                if (!chatgpt.getStopBtn()) { obs.disconnect(); resolve() }
            }).observe(document.body, { childList: true, subtree: true })
        })
    }

    // Define INFINITY MODE functions

    const infinity = {

        async activate() {
            settings.save('infinityMode', true) ; syncConfigToUI()
            const activatePrompt = 'Generate a single random question'
                + ( config.replyLanguage ? ( ' in ' + config.replyLanguage ) : '' )
                + ( ' on ' + ( config.replyTopic == 'ALL' ? 'ALL topics' : 'the topic of ' + config.replyTopic ))
                + ' then answer it. Don\'t type anything else.'
            notify(`${app.msgs.menuLabel_infinityMode}: ${app.msgs.state_on.toUpperCase()}`)
            if (env.browser.isMobile && chatgpt.sidebar.isOn()) chatgpt.sidebar.hide()
            if (!new URL(location).pathname.startsWith('/g/')) // not on GPT page
                try { chatgpt.startNewChat() } catch (err) { return } // start new chat
            await new Promise(resolve => setTimeout(resolve, 500)) // sleep 500ms
            chatgpt.send(activatePrompt)
            await new Promise(resolve => setTimeout(resolve, 3000)) // sleep 3s
            if (!document.querySelector('[data-message-author-role]') // new chat reset due to OpenAI bug
                && config.infinityMode) // ...and toggle still active
                    chatgpt.send(activatePrompt) // ...so prompt again
            await chatgpt.isIdle()
            if (config.infinityMode && !infinity.isActive) // double-check in case de-activated before scheduled
                infinity.isActive = setTimeout(infinity.continue, parseInt(config.replyInterval, 10) * 1000)
        },

        async continue() {
            if (!config.autoScrollDisabled) try { chatgpt.scrollToBottom() } catch(err) {}
            chatgpt.send('Do it again.')
            await chatgpt.isIdle() // before starting delay till next iteration
            if (infinity.isActive) // replace timer
                infinity.isActive = setTimeout(infinity.continue, parseInt(config.replyInterval, 10) * 1000)
        },

        deactivate() {
            settings.save('infinityMode', false) ; syncConfigToUI()
            if (chatgpt.getStopBtn()) chatgpt.stop()
            clearTimeout(infinity.isActive) ; infinity.isActive = null
            notify(`${app.msgs.menuLabel_infinityMode}: ${app.msgs.state_off.toUpperCase()}`)
        },

        async restart(options = { target: 'new' }) {
            if (options.target == 'new') {
                infinity.deactivate() ; setTimeout(() => infinity.activate(), 750)
            } else {
                clearTimeout(infinity.isActive) ; infinity.isActive = null ; await chatgpt.isIdle()
                if (config.infinityMode && !infinity.isActive) // double-check in case de-activated before scheduled
                    infinity.isActive = setTimeout(infinity.continue, parseInt(config.replyInterval, 10) * 1000)
            }
        },

        toggle() { infinity[config.infinityMode ? 'activate' : 'deactivate']() }
    }

    // Run MAIN routine

    // Create browser TOOLBAR MENU or DISABLE SCRIPT if extension installed
    const extensionInstalled = await Promise.race([
        new Promise(resolve => {
            (function checkExtensionInstalled() {
                if (document.documentElement.hasAttribute('cif-extension-installed')) resolve(true)
                else setTimeout(checkExtensionInstalled, 200)
            })()
        }), new Promise(resolve => setTimeout(() => resolve(false), 1500))])
    if (extensionInstalled) { // disable script/menu
        GM_registerMenuCommand(`${menu.state.symbols[0]} ${app.msgs.menuLabel_disabled}`, modals.about.show)
        return // exit script
    } else menu.register() // create functional menu

    // Init BROWSER/UI props
    await Promise.race([chatgpt.isLoaded(), new Promise(resolve => setTimeout(resolve, 5000))]) // initial UI loaded
    await chatgpt.sidebar.isLoaded()
    const ui = { firstLink: chatgpt.getNewChatLink() }

    // Add LISTENER to auto-disable Infinity Mode
    if (document.hidden != undefined) // ...if Page Visibility API supported
        document.onvisibilitychange = () => { if (config.infinityMode) infinity.deactivate() }

    // Add/update TWEAKS style
    const tweaksStyleUpdated = 20241002 // datestamp of last edit for this file's `tweaksStyle`
    let tweaksStyle = document.getElementById('tweaks-style') // try to select existing style
    if (!tweaksStyle || parseInt(tweaksStyle.getAttribute('last-updated'), 10) < tweaksStyleUpdated) {
        if (!tweaksStyle) { // outright missing, create/id/attr/append it first
            tweaksStyle = document.createElement('style') ; tweaksStyle.id = 'tweaks-style'
            tweaksStyle.setAttribute('last-updated', tweaksStyleUpdated.toString())
            document.head.append(tweaksStyle)
        }
        tweaksStyle.innerText = (
            ( chatgpt.isDarkMode() ? '.chatgpt-modal > div { border: 1px solid white }' : '' )
          + '.chatgpt-modal button {'
              + 'font-size: 0.77rem ; text-transform: uppercase ;' // shrink/uppercase labels
              + `border: 2px dashed ${ chatgpt.isDarkMode() ? 'white' : 'black' } !important ;` // dash borders
              + 'border-radius: 0 !important ;' // square borders
              + 'transition: transform 0.1s ease-in-out, box-shadow 0.1s ease-in-out ;' // smoothen hover fx
              + 'cursor: pointer !important ;' // add finger cursor
              + 'padding: 5px !important ; min-width: 102px }' // resize
          + '.chatgpt-modal button:hover {' // add zoom, re-scheme
              + 'transform: scale(1.055) ;'
              + ( chatgpt.isDarkMode() ? ( 'background-color: #2cff00 !important ; color: black !important ;'
                                             + 'box-shadow: 2px 1px 54px #38ff00 !important ;' )
                                       : ( 'background-color: #c7ff006b !important ;'
                                             + 'box-shadow: 2px 1px 30px #97ff006b !important' )) + '}'
          + '.modal-buttons { margin-left: -13px !important }'
          + '* { scrollbar-width: thin }' // make FF scrollbar skinny to not crop toggle
        )
    }

    sidebarToggle.insert()

    // Auto-start if enabled
    if (config.autoStart) infinity.activate()

    // Monitor NODE CHANGES to maintain sidebar toggle visibility
    new MutationObserver(() => {
        if (!config.toggleHidden && !document.getElementById('infinity-toggle-navicon')
            && sidebarToggle.status != 'inserting') {
                sidebarToggle.status = 'missing' ; sidebarToggle.insert() }
    }).observe(document.body, { attributes: true, subtree: true })

    // Disable distracting SIDEBAR CLICK-ZOOM effect
    if (!document.documentElement.hasAttribute('sidebar-click-zoom-observed')) {
        new MutationObserver(mutations => mutations.forEach(({ target }) => {
            if (target.closest('[class*="sidebar"]') // include sidebar divs
                && !target.id.endsWith('-knob-span') // exclude our sidebarToggle
                && target.style.transform != 'none' // click-zoom occurred
            ) target.style.transform = 'none'
        })).observe(document.body, { attributes: true, subtree: true, attributeFilter: [ 'style' ]})
        document.documentElement.setAttribute('sidebar-click-zoom-observed', true)
    }

})()