ChatGPT Widescreen Mode 🖥️

Adds Widescreen + Fullscreen modes to ChatGPT for enhanced viewing + reduced scrolling

Install this script?
Author's suggested script

You may also like Autoclear ChatGPT History.

Install this script
// ==UserScript==
// @name                ChatGPT Widescreen Mode 🖥️
// @name:af             ChatGPT Widescreen Modus 🖥️
// @name:ar             ChatGPT وضع شاشة عريضة 🖥️
// @name:az             ChatGPT Geniş Ekran Rejimi 🖥️
// @name:be             ChatGPT Рэжым шырокага экрана 🖥️
// @name:bg             ChatGPT Широкоекранен режим 🖥️
// @name:bn             ChatGPT উইডস্ক্রিন মোড 🖥️
// @name:bo             ChatGPT རྒྱུ་ཆེན་གཞི་བསྒྲུབ་ རྒྱལ་བཤད། 🖥️
// @name:bs             ChatGPT Režim širokog ekrana 🖥️
// @name:ca             ChatGPT Mode de pantalla ampla 🖥️
// @name:ckb            ChatGPT دەستکاری چوارچێوەی ڕووکاری 🖥️
// @name:cs             ChatGPT Režim širokoúhlé obrazovky 🖥️
// @name:cy             ChatGPT Mod Sgrin Lled 🖥️
// @name:da             ChatGPT Bredformat-tilstand 🖥️
// @name:de             ChatGPT Breitbildmodus 🖥️
// @name:dv             ChatGPT ވިސްނުވެއް މޯޑި 🖥️
// @name:dz             ChatGPT འབྲེལ་བ་གཞུང་ལས་སྤྱི་ཚོགས་གླེང་། 🖥️
// @name:el             ChatGPT Λειτουργία ευρείας οθόνης 🖥️
// @name:eo             ChatGPT Larĝekrana reĝimo 🖥️
// @name:es             ChatGPT Modo de pantalla panorámica 🖥️
// @name:et             ChatGPT Laiarakenduse režiim 🖥️
// @name:eu             ChatGPT Pantaila Zabalaren Modua 🖥️
// @name:fa             ChatGPT حالت تلویزیونی 🖥️
// @name:fi             ChatGPT Laajakuva-tila 🖥️
// @name:fo             ChatGPT Búðarformaður háttur 🖥️
// @name:fr             ChatGPT Mode Écran Large 🖥️
// @name:fr-CA          ChatGPT Mode Écran Large 🖥️
// @name:gd             ChatGPT Dreach-sgrìn Leud 🖥️
// @name:gl             ChatGPT Modo de pantalla ancha 🖥️
// @name:gu             ChatGPT પ્રશાંત સ્ક્રીન મોડ 🖥️
// @name:he             ChatGPT מצב מסך רחב 🖥️
// @name:hi             ChatGPT चहचटजीपटी वाइडस्क्रीन मोड 🖥️
// @name:hr             ChatGPT Način širokog zaslona 🖥️
// @name:ht             ChatGPT Mod Fomat Gwo 🖥️
// @name:hu             ChatGPT Szélesvásznú mód 🖥️
// @name:hy             ChatGPT լայնէկրանանշանի ռեժիմ 🖥️
// @name:id             ChatGPT Mode Layar Lebar 🖥️
// @name:is             ChatGPT Breiðskjásstilling 🖥️
// @name:it             ChatGPT Modalità schermo panoramica 🖥️
// @name:ja             ChatGPT ワイドスクリーンモード 🖥️
// @name:jv             ChatGPT Mode Layar Lebar 🖥️
// @name:ka             ChatGPT ფანტსარიშის რეჟიმი 🖥️
// @name:kab            ChatGPT Amezwaru n Tikliwin Isellalen 🖥️
// @name:kk             ChatGPT Көлеңкескен түрі 🖥️
// @name:km             ChatGPT របៀបបង្អស្សមួយធ្វើដំបូង 🖥️
// @name:kn             ChatGPT ChatGPT ವೈಡ್ಸ್ಕ್ರೀನ್ ಮೋಡ್ 🖥️
// @name:ko             ChatGPT 와이드 스크린 모드 🖥️
// @name:ku             ChatGPT Moda Pêlên Dirêj 🖥️
// @name:ky             ChatGPT Жогорку Экрандык Режим 🖥️
// @name:la             ChatGPT Modus Latus Plenus 🖥️
// @name:lb             ChatGPT Breitbild-Modus 🖥️
// @name:lo             ChatGPT ຮູບແບບໂປຣຟອນໃຫຍ່ 🖥️
// @name:lt             ChatGPT Išplėstojo ekrano režimas 🖥️
// @name:lv             ChatGPT Plašā ekrāna režīms 🖥️
// @name:mg             ChatGPT Tarehimarika tamin'ny Widescreen 🖥️
// @name:mi             ChatGPT Āhua Whātika ā-Raupapa 🖥️
// @name:mk             ChatGPT Режим на широк екран 🖥️
// @name:ml             ChatGPT വൈഡ്സ്ക്രീൻ മോഡ് 🖥️
// @name:mn             ChatGPT Жинхэнэ Экранны Арга 🖥️
// @name:ms             ChatGPT Mod Skrin Lebar 🖥️
// @name:mt             ChatGPT Modalità Widescreen 🖥️
// @name:my             ChatGPT အများနှုန်းကျော်ဘုံ 🖥️
// @name:ne             ChatGPT विस्तृत प्राण्डविक पद्धति 🖥️
// @name:nl             ChatGPT Breedbeeldmodus 🖥️
// @name:no             ChatGPT Bredskjermmodus 🖥️
// @name:ny             ChatGPT Mawonekedwe Wathandiza 🖥️
// @name:pa             ChatGPT ਵਾਇਡਸਕ੍ਰੀਨ ਮੋਡ 🖥️
// @name:pl             ChatGPT Tryb szerokoekranowy 🖥️
// @name:ps             ChatGPT د ډیسپلې موډ 🖥️
// @name:pt             ChatGPT Modo Tela Larga 🖥️
// @name:pt-BR          ChatGPT Modo Tela Larga 🖥️
// @name:ro             ChatGPT Mod ecran lat 🖥️
// @name:ru             ChatGPT Режим широкоформатного экрана 🖥️
// @name:rw             ChatGPT Ibindi by'umuhondo bw'ishusho 🖥️
// @name:sg             ChatGPT Mode Écran Large 🖥️
// @name:si             ChatGPT විශේෂාංග පෙළක්ෂාව 🖥️
// @name:sk             ChatGPT Režim širokouhlého displeja 🖥️
// @name:sl             ChatGPT Način širokega zaslona 🖥️
// @name:sm             ChatGPT Laititi Fuamatala 🖥️
// @name:sn             ChatGPT Zvimwe Zvitsva Mode 🖥️
// @name:so             ChatGPT hab Widescreen Mode 🖥️
// @name:sr             ChatGPT Режим широког екрана 🖥️
// @name:sv             ChatGPT Bredbildsläge 🖥️
// @name:sw             ChatGPT Njia ya Skrini Panoramio 🖥️
// @name:ta             ChatGPT விரிவான திரை முறை 🖥️
// @name:te             ChatGPT ChatGPT వైడ్ స్క్రీన్ మోడ్ 🖥️
// @name:tg             ChatGPT Возачи Режаи Дисплеи Барнома 🖥️
// @name:th             ChatGPT โหมดหน้าจอแบบเต็มจอ 🖥️
// @name:ti             ቻትጂፒቲ ዋይድስክሪን ሞድ 🖥️
// @name:tk             ChatGPT Giň Ekran Tertibi 🖥️
// @name:tn             ChatGPT Nyemba Yemba Mzizo 🖥️
// @name:to             ChatGPT Moli ʻo e Ngaahi Fatongi ʻo Haʻaneesi 🖥️
// @name:tr             ChatGPT Geniş Ekran Modu 🖥️
// @name:uk             ChatGPT Режим широкого екрана 🖥️
// @name:ur             ChatGPT وائڈ اسکرین موڈ 🖥️
// @name:uz             ChatGPT Keng ekranga rejim 🖥️
// @name:vi             ChatGPT Chế độ Màn hình Rộng 🖥️
// @name:xh             ChatGPT Indlela ye-Widescreen Mode 🖥️
// @name:yi             ChatGPT ווידעסקרעען מאָדע 🖥️
// @name:zh             ChatGPT 宽屏模式 🖥️
// @name:zh-CN          ChatGPT 宽屏模式 🖥️
// @name:zh-HK          ChatGPT 寬螢幕模 🖥️
// @name:zh-SG          ChatGPT 宽屏模式 🖥️
// @name:zh-TW          ChatGPT 寬螢幕模 🖥️
// @name:zu             ChatGPT Isimo sokudlalwa emkhumbini 🖥️
// @description         Adds Widescreen + Fullscreen modes to ChatGPT for enhanced viewing + reduced scrolling
// @description:af      Voeg Widescreen + Volledige skermmodusse by ChatGPT vir verbeterde kyk + verminderde skrol
// @description:am      የራስ መጠን በ ChatGPT ውስጥ የተከፈተውን ወደ ትንቢት ማድረግ + ድምፅ እንዲታትና
// @description:ar      إضافة وضعي الشاشة العريضة + الشاشة الكاملة إلى ChatGPT لتحسين العرض + تقليل التمرير
// @description:az      ChatGPT üçün Geniş Ekran + Tam Ekran rejimləri əlavə etmək, görüntünü yaxşılaşdırmaq + səlahətən keçirməni azaltmaq
// @description:be      Дадае рэжымы шырокага экрана + поўнага экрана да ChatGPT для паляпшэнага прагляду + змяншэння скролінгу
// @description:bem     Ena Mode ya Widescreen + ya Fullscreen ku ChatGPT pa kuongeza kulandila + ukukonda scrolling
// @description:bg      Добавя режими на Широк екран + Пълен екран към ChatGPT за подобрено гледане + намалено плъзгане
// @description:bn      এক্স এগ্রিসিভ দেখার জন্য ChatGPT-এ ওয়াইডস্ক্রিন + ফুলস্ক্রিন মোড যুক্ত করে + স্ক্রলিং হ্রাস করে
// @description:bo      བཅའ་དྲུག་རྒྱུས་པ་+ བདེ་ཆེན་རྒྱུས་པ་འདི་ChatGPT་ནང་ལས་བསྒྲགས་བཞག་བའི་ལྷག་པ་ཞིག་ཁམས་པའི་བརྟག་ཞིབ་བཅོ་སྒྲིག་འདུག
// @description:bs      Dodaje Widescreen + Fullscreen režime ChatGPT-u za poboljšani prikaz + smanjenje klizanja
// @description:ca      Afegeix els modes de pantalla ampla + pantalla completa a ChatGPT per a una visualització millorada + reducció de desplaçament
// @description:ceb     Gidugang ang Mga Modo sa Widescreen + Fullscreen sa ChatGPT alang sa labaw nga pagtan-aw + paggamot sa pag-scroll
// @description:ckb     Mode Widescreen + Mode Fullscreen bo ChatGPT zêde bike ji bo nêzîkbûna başkirinê + kam kirina birevandinê
// @description:cs      Přidává režimy Widescreen + Fullscreen do ChatGPT pro zlepšené zobrazení + snížení posouvání
// @description:cy      Ychwanega dulliau Sgrin Llydan + Sgrin Lawn i ChatGPT ar gyfer gwylio well + lleihau sgrolio
// @description:da      Tilføjer Widescreen + Fuldscreen-tilstande til ChatGPT for forbedret visning + reduceret rulning
// @description:de      Fügt Widescreen + Vollbildmodus zu ChatGPT für verbesserte Ansicht + reduziertes Scrollen hinzu
// @description:dv      ChatGPT ބޮޓޮބޭސީ + ފަންވައިދާ މޯޑިއުލްއަޤް ހެދުމަށް ކަނޑުގެންނަވަން + ރުސަބް ބެންކުރުމަށްވެއްޖެ
// @description:dz      ChatGPT སྒྲུབ་ཐབས་ + མིང་དཔྱད་ཆེས་དང་པ་ཡོངས་ཀྱི་ལྷག་པ་ཁྱབ་ལ་ཉོ་གར་བཞག་པ་དང་བདེན་པས་ཆེད་པ་དང་ཚིག་རྐྱང་ལ་མགོ་ནི་
// @description:el      Προσθέτει λειτουργίες Widescreen + Fullscreen στο ChatGPT για βελτιωμένη προβολή + μείωση της κύλισης
// @description:eo      Aldonas larĝekranajn + plenekranajn reĝimojn al ChatGPT por plibonigita vidado + malpliigo de ŝovado
// @description:es      Agrega modos de pantalla panorámica + pantalla completa a ChatGPT para una visualización mejorada + desplazamiento reducido
// @description:et      Lisab ChatGPT-le Widescreen + Täisekraani režiimid parema vaatamise ja vähenenud kerimisega
// @description:eu      Gehitu Widescreen + Pantaila oso moduak ChatGPT-ra ikusmen hobetu + mugimendua gutxituz
// @description:fa      اضافه کردن حالت های واید اسکرین + تمام صفحه به ChatGPT برای مشاهده بهتر + کاهش اسکرول
// @description:fi      Lisää Widescreen + Koko näytön tilat ChatGPT:hen paremman katselun + vähentyneen vierityksen ansiosta
// @description:fo      Leggur til Widescreen + Fullscreen hamrar á ChatGPT fyri bætta sýning + minnka skúvsetan
// @description:fr      Ajoute les modes écran large + plein écran à ChatGPT pour une meilleure visualisation + un défilement réduit
// @description:fr-CA   Ajoute les modes écran large + plein écran à ChatGPT pour une meilleure visualisation + un défilement réduit
// @description:gd      Cuir gnèithean Leudachaidh + Faidhlichean sàbhaladh sgrùdair gu ChatGPT airson sealladh air àrdachadh + sgroladh lag
// @description:gl      Engade os modos de pantalla panorámica + pantalla completa a ChatGPT para unha visualización mellorada + desprazamento reducido
// @description:gu      એન્હાનો જોડાણ કરો વાઈડસ્ક્રીન + ફુલસ્ક્રીન મોડ તેમજ ChatGPT માટે સુધારેલ જોઈન્ટ પ્રદર્શન + કમેલી સ્ક્રોલિંગ માટે
// @description:haw     Kālele i nā Ao Waiwai + Ao Piha i loko o ChatGPT no ka ho'ohana'ana ikaika + ka'u hā'ule 'ana
// @description:he      מוסיף מצבי מסך מורחב + מסך מלא ל־ChatGPT לשיפור תצוגה + הפחתת גלילה
// @description:hi      बढ़िया दृश्य + कम स्क्रोलिंग के लिए ChatGPT में वाइडस्क्रीन + फुलस्क्रीन मोड जोड़ता है
// @description:hr      Dodaje Widescreen + Fullscreen načine na ChatGPT za poboljšani prikaz + smanjenje klizanja
// @description:ht      Ajoute modes Widescreen + Fullscreen nan ChatGPT pou amelyore gade + redui defileman
// @description:hu      Hozzáadja a Widescreen + Teljes képernyő módokat a ChatGPT-hoz jobb megtekintés + görgetés csökkentése érdekében
// @description:hy      Ավելացնում է Widescreen + Fullscreen ռեժիմները ChatGPT-ում բարելավված դիտումի համար + սահմանափակումը
// @description:id      Menambahkan mode Widescreen + Layar Penuh ke ChatGPT untuk penampilan yang lebih baik + pengurangan pengguliran
// @description:is      Bætir við Widescreen + Fullskjárshamra í ChatGPT til að bæta sýn + draga úr skruni
// @description:it      Aggiunge le modalità Widescreen + Schermo intero a ChatGPT per una visualizzazione migliorata + riduzione dello scorrimento
// @description:ja      ChatGPTの表示を向上するために、ワイドスクリーン+フルスクリーンモードを追加します
// @description:jv      Nambahi Modus Widescreen + Fullscreen menyang ChatGPT kanggo tampilan sing ditingkatake + ngecilake scrolling
// @description:ka      დაამატებს Widescreen + Fullscreen რეჟიმებს ChatGPT-ში გაუმჯობესებული ნახვა + გამოკლებული გადადების მიზნით
// @description:kk      ChatGPT-ге Widescreen + Fullscreen режимдерін қосу арқылы көрініс үздіктемелеу + скроллауды кеміту
// @description:km      បន្ថែមរបៀប Widescreen + Fullscreen ទៅក្នុង ChatGPT សម្រាប់ការមើលឡើងប្រហែលជាក្រុមហ៊ុន + ការរងចាំខ្លួនឯងប៉ុណ្ណោះ
// @description:kn      ಅಭ್ಯಾಸಕ್ರಮದ ದೃಷ್ಟಿಗೆ ಅನುಗುಣವಾಗಿ Widescreen + Fullscreen ಮೋಡ್ಗಳನ್ನು ChatGPTಗೆ ಸೇರಿಸುತ್ತದೆ
// @description:ko      ChatGPT에 와이드스크린 + 전체화면 모드를 추가하여 개선된 화면 표시 + 스크롤 감소
// @description:ku      Dihênîne modên Widescreen + Fullscreenê bo ChatGPTê ji bo pêşînkirina nîşandina + kêmkirina kayanînê
// @description:ky      ChatGPT-го Widescreen + Fullscreen режимдору кошо аркылуу жакшы көрүнүштү + скроллоо жоготуу
// @description:la      TV + Fullscreen modos addit ChatGPT ad augendam viewing + reducta scrolling
// @description:lb      Füügt Widescreen + Fullscreen Modi dem ChatGPT bäi fir verbessert Visioun + reduzéiert Scrollen
// @description:lo      ເພີ່ມຮູບແບບ Widescreen + Fullscreen ໃຫ້ໄດ້ຮຽນ ChatGPT ສຳເລັດຂອງການສະແດງອ້າງວ່າງ + ການປະເມີດໃຫ້ນ້ໍາຂາຍຫນ້າ
// @description:lt      Prideda Widescreen + Fullscreen režimus į ChatGPT, siekiant pagerinti peržiūrą ir sumažinti slinkimą
// @description:lv      Pievieno Widescreen + Fullscreen režīmus ChatGPT, lai uzlabotu skatīšanos + samazinātu ritināšanu
// @description:mg      Mametraka ny fomba Widescreen + Fullscreen amin'ny ChatGPT mba handresy ny fandefasana + famindrampoana ny firotsahana
// @description:mi      Ka whakarite ana i ngā āhuatanga Widescreen + Fullscreen ki te ChatGPT mō te whakaatu whakapai ake + te whakaiti i te whakararuraru
// @description:mk      Додава режими на Widescreen + Fullscreen во ChatGPT за подобрување на приказот + намалување на скролирањето
// @description:ml      വായ്ഡ്സ്ക്രീൻ + പൂർണ്ണസ്ക്രീൻ മോഡുകൾ ചേർക്കുന്നു ChatGPT-യിൽ മിക്കവാറും കാഴ്ചപ്പാട് + കുറവ് തിരിക്കൽ ചെയ്യുന്നതിന്
// @description:mn      Widescreen + Fullscreen горимуудыг ChatGPT рүү нэмэх нь дэлгэцэнд хувцаслан + гүйлгээний эвдрэлдээ хянахыг оруулна
// @description:mr      व्हाइडस्क्रीन + फुलस्क्रीन मोड्स चे ChatGPTमध्ये जोडले जातात व पाहणी वाढविण्यासाठी स्क्रोलिंग कमी करतात
// @description:ms      Menambah mod Widescreen + Layar Penuh ke ChatGPT untuk tampilan yang lebih baik + pengurangan penatalan
// @description:mt      Jiddoqq modes Widescreen + Fullscreen għal ChatGPT għall-viżwalizzazzjoni miġġielda + qasam it-telf
// @description:my      ပိုမိုကောင်းမွန်သောကြည့်ရှုရန်အတွက် ChatGPT တွင် Widescreen + မျက်နှာပြင်အပြည့်မုဒ်များကို ထည့်သွင်းထားသည်။
// @description:ne      सुधारिएको दृश्य + कम स्क्रोलिंगका लागि वाइडस्क्रिन + फुलस्क्रिन मोडहरूलाई ChatGPTमा थप्दछ
// @description:nl      Voegt Widescreen + Fullscreen modi toe aan ChatGPT voor verbeterde weergave + verminderd scrollen
// @description:no      Legger til Widescreen + Fullskjerm-moduser i ChatGPT for forbedret visning + redusert rulling
// @description:ny      Ndiwonetsa zolengedwa + Zomwe zosowa ndi ChatGPT kwa kudzaza kuona + kuchotsa kupinda
// @description:pa      ਚਾਟਜੀਪੀਟੀ ਵਿੱਚ Widescreen + Fullscreen ਮੋਡਾਂ ਸ਼ਾਮਿਲ ਕਰਦਾ ਹੈ ਜਿਹਨਾਂ ਨਾਲ ਵੇਖਾਉਣ ਵਧੀਆ ਹੋ ਜਾਂਦਾ ਹੈ + ਘੂਮਣ ਦੀ ਘਟ-ਪੁਟ ਹੋ ਜਾਂਦੀ ਹੈ
// @description:pl      Dodaje tryby Widescreen + Fullscreen do ChatGPT dla lepszej widoczności + zmniejszonego przewijania
// @description:ps      ځانګړې + ټولې پرده په ChatGPT کې اضافه کړي لپاره لاسرسی ترلاسه کړي + کوښښول په کمته
// @description:pt      Adiciona modos Widescreen + Tela cheia ao ChatGPT para visualização aprimorada + rolagem reduzida
// @description:pt-BR   Adiciona modos Widescreen + Tela cheia ao ChatGPT para visualização aprimorada + rolagem reduzida
// @description:ro      Adaugă modurile Widescreen + Ecran complet la ChatGPT pentru vizualizare îmbunătățită + defilare redusă
// @description:ru      Добавляет режимы Widescreen + Fullscreen в ChatGPT для улучшенного просмотра + сокращенной прокрутки
// @description:rw      Ongeraho Mugari Mugari + Byuzuye Mugaragaza kuri ChatGPT kugirango ubone kureba neza + kugabanya umuzingo
// @description:sg      Ajoute les modes écran large + plein écran à ChatGPT pour une meilleure visualisation + un défilement réduit
// @description:si      ChatGPT සඳහා Widescreen + Fullscreen ප්‍රදර්ශනයක් එක් කරයි තවත් පෙන්වන්නේ දැන් සිතූවාසිකාරක්ෂක විසින් සහ කෙසේදැයි ඇති අගයන් හුස්ම ක්‍රියාවලියකි
// @description:sk      Pridáva Widescreen + Fullscreen režimy do ChatGPT pre vylepšené zobrazenie + zníženie posúvania
// @description:sl      Dodaja Widescreen + Fullscreen načine v ChatGPT za izboljšan prikaz + zmanjšano premikanje
// @description:sm      Faamauina Widescreen + Fullscreen faavae i le ChatGPT mo le faailoga faapea le mafaufau + le auina faavaivai
// @description:sn      Ongorora Mutaundi wa Widescreen + Fullscreen muChatGPT kutora dzokubvumidzwa + kusha kusweropfuura
// @description:so      Wax ka beddelaa Hababka Widescreen + Fullscreen ee ChatGPT si aad u fiirsato + si aad u yaraato garaabinta
// @description:sq      Shton modalitete Widescreen + Fullscreen në ChatGPT për pamje të përmirësuar + ulje të skrollimit
// @description:sr      Додаје Widescreen + Fullscreen режиме у ЧатГПТ за унапређен приказ + смањено листање
// @description:st      E ngolisitsoe mokhabo Widescreen + Fullscreen ho ChatGPT bakeng sa mofuta ona le ho fokotsa liphalantere
// @description:sv      Lägger till Widescreen + Fullscreen-lägen i ChatGPT för förbättrad visning + minskad scrollning
// @description:sw      Inaongeza modes Widescreen + Fullscreen kwenye ChatGPT kwa kuimarisha kuonyesha + kupunguza kusokota
// @description:ta      மேலதிரும் பார்வை + சுழற்சியை மோதித்து சாட்ஜிபிடியில் Widescreen + Fullscreen முறைகளைச் சேர்க்கிறது
// @description:te      Widescreen + Fullscreen మోడ్లను ChatGPTకి చేర్చుకోవడంతో చంపుకునే వీక్షణ కనిపించడానికి స్క్రోల్ తక్కువగా మార్చండి
// @description:tg      Маводиҳои Widescreen + Fullscreen-ро ба ChatGPT илова мекунад, барои кӯҳнашудаи намоиш + кам кардани скроллаш
// @description:th      เพิ่มโหมดจอแบบ Widescreen + Fullscreen ใน ChatGPT สำหรับการดูที่ดีขึ้น + การเลื่อนลดลง
// @description:ti      ንዝለዓለ ምርኣይ + ምጉዳል ምዝዋር ኣብ ChatGPT Widescreen + Fullscreen modes ይውስኽ
// @description:tk      Giňeldilen görmek + peseltmek üçin ChatGPT-ä giň ekran + Doly ekran reesimlerini goşýar
// @description:tl      Nagdaragdag ng mga mode ng Widescreen + Fullscreen sa ChatGPT para sa pinabuting pagtingin + pinaikling pag-scroll
// @description:tn      Inowedzera Widescreen + Fullscreen modes kuChatGPT yekuwedzera kutarisa + kuderedzwa kupuruzira
// @description:to      Hoʻohui i ka Widescreen + Fullscreen modes i ChatGPT no ka hoʻonui ʻia ʻana o ka nānā ʻana + hoʻemi i ka ʻōwili ʻana
// @description:tr      Geliştirilmiş görüntüleme + azaltılmış kaydırma için ChatGPT'ye Widescreen + Fullscreen modları ekler
// @description:tt      ChatGPT-га Widescreen + Fullscreen рәжимләрен өстәәдегезгә, күрүләштеңләри үткәргә + скроллауны буянтартарга
// @description:ug      ChatGPTغا Widescreen + Fullscreen كۆرۈنمە پەسەند قىلىش+يىتىپ ئاجرا قىلىش مۆچىيى
// @description:uk      Додає режими Widescreen + Fullscreen до ChatGPT для поліпшеного перегляду + зменшення прокрутки
// @description:ur      ترقی یافتہ دیکھائی کے لئے ChatGPT میں وائڈ اسکرین + پوری اسکرین موڈز شامل کرتا ہے
// @description:uz      ChatGPT-ga Widescreen + Fullscreen rejimlarini qo'shadi, ko'rishni yaxshilash + aylantirishni kamaytirish uchun
// @description:vi      Thêm chế độ Widescreen + Fullscreen vào ChatGPT để cải thiện hiển thị + giảm cuộn trang
// @description:wo      Bëgg na ñiis-ñiis Widescreen + Fullscreen ci ChatGPT buñ leen waxtu dib lu jàmm + ñaari jëm
// @description:xh      Enza izimvo Widescreen + Fullscreen kwakuhlanganiselelwa kwiChatGPT ukuze kube khona okukhulu + kokucima kwesithombe
// @description:yi      מוסיף Widescreen + Fullscreen מאָדעס צו ChatGPT פֿאַר ימפּרוווד וויוינג + רידוסט סקראָללינג
// @description:yo      Fi àwọn ohun ọrọ Widescreen + Fullscreen si ChatGPT fun iwọle aiyewo + iwọle ififunwọle
// @description:zh      向 ChatGPT 添加宽屏 + 全屏模式以增强查看效果 + 减少滚动
// @description:zh-CN   向 ChatGPT 添加宽屏 + 全屏模式以增强查看效果 + 减少滚动
// @description:zh-HK   向 ChatGPT 添加寬屏 + 全屏模式以增強查看效果 + 減少滾動
// @description:zh-SG   向 ChatGPT 添加宽屏 + 全屏模式以增强查看效果 + 减少滚动
// @description:zh-TW   向 ChatGPT 添加寬屏 + 全屏模式以增強查看效果 + 減少滾動
// @description:zu      Engeza izinhlobo zezimodi ze-Widescreen + Fullscreen ku-ChatGPT ukuze kube nokubonakala + ukuncitsha ukusukela
// @author              Adam Lui
// @namespace           https://github.com/adamlui
// @version             2024.11.14.2
// @license             MIT
// @compatible          chrome
// @compatible          firefox
// @compatible          edge
// @compatible          opera
// @compatible          brave
// @compatible          vivaldi
// @compatible          librewolf
// @compatible          ghost
// @compatible          qq
// @match               *://chatgpt.com/*
// @match               *://chat.openai.com/*
// @match               *://*.perplexity.ai/*
// @match               *://poe.com/*
// @icon                https://media.chatgptwidescreen.com/images/icons/widescreen-robot-emoji/icon48.png?9a393be
// @icon64              https://media.chatgptwidescreen.com/images/icons/widescreen-robot-emoji/icon64.png?9a393be
// @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-widescreen@47779d6fbebaf40fd58e58f99df44ce2c8dd5956/chrome/extension/lib/dom.js#sha256-0bhycl7Nr7KvGksQRDWBMgooDl4os2GXpjKlHT2t+TY=
// @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.chatgptwidescreen.com
// @supportURL          https://support.chatgptwidescreen.com
// @contributionURL     https://github.com/sponsors/adamlui
// ==/UserScript==

// Documentation: https://docs.chatgptwidescreen.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 vars 
    const env = {
        browser: { isFF: chatgpt.browser.isFirefox() },
        scriptManager: (() => { try { return GM_info.scriptHandler } catch (err) { return 'unknown' }})(),
        site: /([^.]+)\.[^.]+$/.exec(location.hostname)[1]
    }
    const xhr = env.scriptManager == 'OrangeMonkey' ? GM_xmlhttpRequest : GM.xmlHttpRequest

    // Init APP info
    const app = { configKeyPrefix: `${env.site} Widescreen`, latestAssetCommitHash: '70a00a8' },
          assetHostURL = `https://cdn.jsdelivr.net/gh/adamlui/chatgpt-widescreen@${app.latestAssetCommitHash}`
    Object.assign(app, await new Promise(resolve => xhr({
        method: 'GET', url: `${assetHostURL}/data/app.json`,
        onload: resp => resolve(JSON.parse(resp.responseText))
    })))
    app.urls.update = app.urls.greasyFork.replace('https://', 'https://update.')
        .replace(/(\d+)-?([a-z-]*)$/i, (_, id, name) => `${id}/${ name || 'script' }.meta.js`)
    
    // Init SITE props
    const sites = Object.assign(Object.create(null), await new Promise(resolve => xhr({
        method: 'GET', url: `${assetHostURL}/data/sites.json`,
        onload: resp => resolve(JSON.parse(resp.responseText))
    })))
    sites.openai = { ...sites.chatgpt } // shallow copy to cover old domain

    // Init CONFIG
    const config = { userLanguage: chatgpt.getUserLanguage() }
    const settings = {
        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(sites[env.site].availFeatures)

    // Init app MESSAGES
    app.msgs = {
        appName: app.name,
        appAuthor: app.author.name,
        appDesc: 'Adds Widescreen + Fullscreen modes to ChatGPT for enhanced viewing + reduced scrolling',
        menuLabel_fullerWins: 'Fuller Windows',
        menuLabel_tallerChatbox: 'Taller Chatbox',
        menuLabel_widerChatbox: 'Wider Chatbox',
        menuLabel_newChatBtn: 'New Chat Button',
        menuLabel_hiddenHeader: 'Hidden Header',
        menuLabel_hiddenFooter: 'Hidden Footer',
        menuLabel_modeNotifs: 'Mode Notifications',
        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',
        mode_wideScreen: 'Wide screen',
        mode_fullWindow: 'Full-window',
        mode_fullScreen: 'Full screen',
        tooltip_wideScreenON: 'Wide screen',
        tooltip_wideScreenOFF: 'Exit wide screen',
        tooltip_fullWindowON: 'Full-window mode',
        tooltip_fullWindowOFF: 'Exit full window',
        tooltip_fullScreenON: 'Full screen',
        tooltip_fullScreenOFF: 'Exit full screen',
        tooltip_newChat: 'New chat',
        helptip_fullerWins: 'Also activate Wide Screen when activating Full-Window',
        helptip_tallerChatbox: 'Expand the chatbox vertically',
        helptip_widerChatbox: 'Expand the chatbox horizontally in Wide Screen mode',
        helptip_newChatBtn: 'Show New Chat button in chatbox',
        helptip_hiddenFooter: 'Hide site footer',
        helptip_hiddenHeader: 'Hide site header',
        helptip_modeNotifs: 'Show notifications when toggling modes/settings',
        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',
        alert_pressF11: 'Press F11 to exit full screen',
        alert_f11reason: 'F11 was used to enter full screen, and due to browser security reasons, the same key must be used to exit it',
        btnLabel_moreApps: 'More ChatGPT Apps',
        btnLabel_rateUs: 'Rate Us',
        btnLabel_getSupport: 'Get Support',
        btnLabel_updateCheck: 'Check for Updates',
        btnLabel_update: 'Update',
        btnLabel_dismiss: 'Dismiss',
        link_viewChanges: 'View changes',
        state_on: 'on',
        state_off: 'off'
    }
    if (!config.userLanguage.startsWith('en')) { // localize msgs for non-English users
        const localizedMsgs = await new Promise(resolve => {
            const msgHostDir = assetHostURL + '/chrome/extension/_locales/',
                  msgLocaleDir = ( config.userLanguage ? config.userLanguage.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 up to 3X (original/region-stripped/EN) only
                    msgHref = config.userLanguage.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 props
    Object.assign(app, { settings: {
        fullerWindows: { type: 'toggle', label: app.msgs.menuLabel_fullerWins},
        tcbDisabled: { type: 'toggle', label: app.msgs.menuLabel_tallerChatbox, symbol: '↕️' },
        widerChatbox: { type: 'toggle', label: app.msgs.menuLabel_widerChatbox, symbol: '↔️' },
        ncbDisabled: { type: 'toggle', label: app.msgs.menuLabel_newChatBtn },
        hiddenHeader: { type: 'toggle', label: app.msgs.menuLabel_hiddenHeader },
        hiddenFooter: { type: 'toggle', label: app.msgs.menuLabel_hiddenFooter },
        notifDisabled: { type: 'toggle', label: app.msgs.menuLabel_modeNotifs }
    }})

    // Define MENU functions

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

        register() {

            // Add toggles
            Object.keys(app.settings).forEach(key => {
                if (sites[env.site].availFeatures.includes(key)) {
                    const settingIsEnabled = config[key] ^ key.includes('Disabled'),
                          menuLabel = `${ app.settings[key].symbol || menu.state.symbols[+settingIsEnabled] } `
                                    + app.settings[key].label + menu.state.separator + menu.state.words[+settingIsEnabled]
                    menu.ids.push(GM_registerMenuCommand(menuLabel, () => {
                        settings.save(key, !config[key]) ; sync.configToUI()
                        notify(`${app.settings[key].label}: ${menu.state.words[+(key.includes('Disabled') ^ config[key])]}`)
                    }))
                }
            })

            // 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: response => { const updateAlertWidth = 377

                // Compare versions
                const latestVer = /@version +(.*)/.exec(response.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 (!config.userLanguage.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 found, nav back
                siteAlert(`${app.msgs.alert_upToDate}!`, // title
                    `${app.msgs.appName} (v${currentVer}) ${app.msgs.alert_isUpToDate}!`, // msg
                    '', '', updateAlertWidth
                )
                modals.about.show()
    }})}

    // Define FEEDBACK functions

    function notify(msg, pos = '', notifDuration = '', shadow = '') {
        if (config.notifDisabled && !msg.includes(app.msgs.menuLabel_modeNotifs)) return

        // 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 btn of document.getElementById(aboutModalID).querySelectorAll('button')) {
                    btn.style.cssText = 'cursor: pointer !important' // since tweaks won't load on auto-disable
                    if (/updates/i.test(btn.textContent)) btn.textContent = (
                        '🚀 ' + ( app.msgs.btnLabel_updateCheck ))
                    else if (/support/i.test(btn.textContent)) btn.textContent = (
                        '🧠 ' + ( app.msgs.btnLabel_getSupport ))
                    else if (/rate/i.test(btn.textContent)) btn.textContent = (
                        '⭐ ' + ( app.msgs.btnLabel_rateUs ))
                    else if (/apps/i.test(btn.textContent)) btn.textContent = (
                        '🤖 ' + ( app.msgs.btnLabel_moreApps ))
                    else btn.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.feedback.show() }
                    ], '', 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) }
                    ]
                )
                const reviewModal = document.getElementById(reviewModalID)
                reviewModal.querySelector('button').style.display = 'none' // hide Dismiss button
                reviewModal.addEventListener('DOMNodeRemoved', () => modals[modals.stack[0]]?.show() ) // nav back on btn/bg clicks
            }
        },

        safeWinOpen(url) { open(url, '_blank', 'noopener') } // to prevent backdoor vulnerabilities
    }
    
    // Define CHATBAR functions
    
    const chatbar = {

        get() {
            let chatbar = document.querySelector(sites[env.site].selectors.input)
            const parentLvls = /chatgpt|openai/.test(env.site) ? 3 : 2
            for (let i = 0 ; i < parentLvls ; i++) chatbar = chatbar?.parentNode
            return chatbar
        },

        tweak() {
            const chatbarDiv = chatbar.get() ; if (!chatbarDiv) return
            if (/chatgpt|openai/.test(env.site)) {
                const inputArea = chatbarDiv.querySelector(sites[env.site].selectors.input)
                if (inputArea) {
                    if (chatgpt.canvasIsOpen()) inputArea.parentNode.style.width = '100%'
                    else if (!env.tallChatbar) { // narrow it to not clash w/ buttons
                        const widths = { chatbar: chatbarDiv.getBoundingClientRect().width }
                        const visibleBtnTypes = [...btns.types, 'send'].filter(type =>
                            !(type == 'fullWindow' && !sites[env.site].hasSidebar)
                            && !(type == 'newChat' && config.ncbDisabled))
                        visibleBtnTypes.forEach(btnType =>
                            widths[btnType] = btns[btnType]?.getBoundingClientRect().width
                                        || document.querySelector(`${sites[env.site].selectors.btns.send}, ${
                                                                        sites[env.site].selectors.btns.stop}`)?.getBoundingClientRect().width || 0 )
                        const totalBtnWidths = visibleBtnTypes.reduce((sum, btnType) => sum + widths[btnType], 0)
                        inputArea.parentNode.style.width = `${ // expand to close gap w/ buttons
                            widths.chatbar - totalBtnWidths -( env.browser.isFF ? 60 : 43 )}px`
                        inputArea.style.width = '100%' // rid h-scrollbar
                    }
                }
            } else if (env.site == 'poe') {
                const attachFileBtn = chatbarDiv.querySelector(sites.poe.selectors.btns.attachFile),
                      clearBtn = document.querySelector(sites.poe.selectors.btns.clear)
                if (attachFileBtn && !attachFileBtn.style.cssText) { // left-align attach file button
                    attachFileBtn.style.cssText = 'position: absolute ; left: 1rem ; bottom: 0.35rem'
                    document.querySelector(sites.poe.selectors.input).style.padding = '0 13px 0 40px' // accommodate new btn pos
                }
                btns.newChat.style.top = clearBtn ? '-1px' : 0
                btns.newChat.style.marginRight = clearBtn ? '2px' : '1px'
            }
        }
    }

    // Define BUTTON props/functions

    const btns = {
        types: [ 'fullScreen', 'fullWindow', 'wideScreen', 'newChat' ], // right-to-left

        svgElems: {
            fullScreen: {
                off: [
                    dom.create.svgElem('path', { stroke: 'none', d: 'm10,16 2,0 0,-4 4,0 0,-2 L 10,10 l 0,6 0,0 z' }),
                    dom.create.svgElem('path', { stroke: 'none', d: 'm20,10 0,2 4,0 0,4 2,0 L 26,10 l -6,0 0,0 z' }),
                    dom.create.svgElem('path', { stroke: 'none', d: 'm24,24 -4,0 0,2 L 26,26 l 0,-6 -2,0 0,4 0,0 z' }),
                    dom.create.svgElem('path', { stroke: 'none', d: 'M 12,20 10,20 10,26 l 6,0 0,-2 -4,0 0,-4 0,0 z' }) ],
                on: [
                    dom.create.svgElem('path', { stroke: 'none', d: 'm14,14-4,0 0,2 6,0 0,-6 -2,0 0,4 0,0 z' }),
                    dom.create.svgElem('path', { stroke: 'none', d: 'm22,14 0,-4 -2,0 0,6 6,0 0,-2 -4,0 0,0 z' }),
                    dom.create.svgElem('path', { stroke: 'none', d: 'm20,26 2,0 0,-4 4,0 0,-2 -6,0 0,6 0,0 z' }),
                    dom.create.svgElem('path', { stroke: 'none', d: 'm10,22 4,0 0,4 2,0 0,-6 -6,0 0,2 0,0 z' }) ]
            },

            fullWin: [
                dom.create.svgElem('rect', { fill: 'none', x: '3', y: '3', width: '17', height: '17', rx: '2', ry: '2' }),
                dom.create.svgElem('line', { x1: '9', y1: '3', x2: '9', y2: '21' })
            ],

            newChat: [ dom.create.svgElem('path', { stroke: 'none', d: 'M22,13h-4v4h-2v-4h-4v-2h4V7h2v4h4V13z' }) ],

            wideScreen: {
                off: [
                    dom.create.svgElem('path', { stroke: 'none', 'fill-rule': 'evenodd',
                        d: 'm28,11 0,14 -20,0 0,-14 z m-18,2 16,0 0,10 -16,0 0,-10 z' }) ],
                on: [
                    dom.create.svgElem('path', { stroke: 'none', 'fill-rule': 'evenodd',
                        d: 'm26,13 0,10 -16,0 0,-10 z m-14,2 12,0 0,6 -12,0 0,-6 z' }) ]
            }
        },

        create() {
            if (/chatgpt|openai/.test(env.site) && chatbar.get().nextElementSibling && !env.tallChatbar)
                env.tallChatbar = true
            const validBtnTypes = btns.types.filter(type => !(type == 'fullWindow' && !sites[env.site].hasSidebar))
            const bOffset = env.site == 'poe' ? -1.5 : env.site == 'perplexity' ? -13 : env.tallChatbar ? 31 : -8.85,
                  rOffset = env.site == 'poe' ? -6   : env.site == 'perplexity' ? -4  : env.tallChatbar ? 47 : -0.25
            validBtnTypes.forEach(async (btnType, idx) => {
                btns[btnType] = document.createElement('div')
                btns[btnType].id = btnType + '-btn' // for toggle.tooltip()
                btns[btnType].style.position = env.tallChatbar ? 'absolute' : 'relative'
                if (env.tallChatbar) btns[btnType].style.bottom = '8.85px'
                else btns[btnType].style.top = /chatgpt|openai/.test(env.site) ? '-3.25px' : 0
                btns[btnType].style.right = `${ rOffset + idx * bOffset }px` // position left of prev button
                btns[btnType].style.cursor = 'pointer' // add finger cursor
                if (env.site == 'poe') btns[btnType].style.position = 'relative' // override static pos
                if (/chatgpt|perplexity/.test(env.site)) { // assign classes + tweak styles
                    const sendBtn = await new Promise(resolve => {
                        const sendBtn = document.querySelector(sites[env.site].selectors.btns.send)
                        if (sendBtn) resolve(sendBtn)
                        else new MutationObserver((_, obs) => {
                            const sendBtn = document.querySelector(sites[env.site].selectors.btns.send)
                            if (sendBtn) { obs.disconnect() ; resolve(sendBtn) }
                        }).observe(document.body, { childList: true, subtree: true })
                    })
                    btns[btnType].setAttribute('class', sendBtn.classList.toString() || '')
                    btns[btnType].style.backgroundColor = 'transparent' // remove dark mode overlay
                    btns[btnType].style.borderColor = 'transparent' // remove dark mode overlay
                } else if (env.site == 'poe') // lift buttons slightly
                    btns[btnType].style.marginBottom = ( btnType == 'newChat' ? '0.45' : '0.2' ) + 'rem'

                // Add hover/click listeners
                btns[btnType].onmouseover = btns[btnType].onmouseout = toggle.tooltip
                btns[btnType].onclick = () => {
                    if (btnType == 'newChat') {
                        document.querySelector(sites[env.site].selectors.btns.newChat)?.click()
                        tooltipDiv.style.opacity = 0
                    } else toggle.mode(btnType)
                }
            })
            btns.updateColor()
        },

        insert() {
            if (btns.status?.startsWith('insert') || document.getElementById('wideScreen-btn')) return
            btns.status = 'inserting' ; if (!btns.wideScreen) btns.create()
            
            // Init elems
            const chatbarDiv = chatbar.get() ; if (!chatbarDiv) return
            const btnTypesToInsert = btns.types.slice().reverse() // to left-to-right for insertion order
                .filter(type => !(type == 'fullWindow' && !sites[env.site].hasSidebar))
            const parentToInsertInto = /chatgpt|openai/.test(env.site) ? chatbarDiv.nextElementSibling || chatbarDiv
                                     : env.site == 'perplexity' ? chatbarDiv.lastChild // Pro spam toggle parent
                                     : chatbarDiv
            const elemToInsertBefore = /chatgpt|openai/.test(env.site) ? parentToInsertInto.lastChild
                                     : env.site == 'perplexity' ? parentToInsertInto.firstChild // Pro spam toggle
                                     : chatbarDiv.children[1]
            // Insert buttons
            btnTypesToInsert.forEach(btnType => {
                btns.updateSVG(btnType) // update icon
                parentToInsertInto.insertBefore(btns[btnType], elemToInsertBefore)
            })
            parentToInsertInto.insertBefore(tooltipDiv, elemToInsertBefore) // add tooltips
            setTimeout(() => chatbar.tweak(), 1)
            btns.status = 'inserted'
        },

        remove() {
            if (!chatbar.get() || !document.getElementById('wideScreen-btn')) return
            btns.types.forEach(type => btns[type]?.remove()) ; tooltipDiv?.remove()
        },

        updateColor() {
            btns.color = (
                /chatgpt|openai/.test(env.site) ? (
                    document.querySelector('.dark.bg-black') || chatgpt.isDarkMode() ? 'white' : '#202123' )
              : env.site == 'perplexity' ? (
                    document.documentElement.dataset.colorScheme == 'dark' ? 'oklch(var(--dark-text-color-100)/var(--tw-text-opacity))'
                                                                           : 'oklch(var(--text-color-100)/var(--tw-text-opacity))' )
              : 'currentColor' )

            if (btns.wideScreen?.style.fill != btns.color)
                btns.types.forEach(btnType => {
                    if (btns[btnType]) btns[btnType].style.fill = btns[btnType].style.stroke = btns.color })
        },

        updateSVG(mode, state = '') {
            if (!btns.wideScreen) btns.create()
    
            // Pick appropriate button/elements
            const [btn, ONelems, OFFelems] = (
                mode == 'fullScreen' ? [btns.fullScreen, btns.svgElems.fullScreen.on, btns.svgElems.fullScreen.off]
              : mode == 'fullWindow' ? [btns.fullWindow, btns.svgElems.fullWin, btns.svgElems.fullWin]
              : mode == 'wideScreen' ? [btns.wideScreen, btns.svgElems.wideScreen.on, btns.svgElems.wideScreen.off]
                                     : [btns.newChat, btns.svgElems.newChat, btns.svgElems.newChat])
            if (!btn) return

            // Set SVG attributes
            const btnSVG = btn?.querySelector('svg') || dom.create.svgElem('svg', { height: 18 })
            if (mode == 'fullWindow') { // stylize full-window button
                btnSVG.setAttribute('stroke-width', '2')
                const btnSize = env.site == 'perplexity' ? 18 : 'poe' ? '2em' : 17
                btnSVG.setAttribute('height', btnSize) ; btnSVG.setAttribute('width', btnSize)
            }
            btnSVG.setAttribute('viewBox', (
                mode == 'newChat' ? '11 6 ' : mode == 'fullWindow' ? '-2 -0.5 ' : '8 8 ' ) // move to XY coords to crop whitespace
            + ( mode == 'newChat' ? '13 13' : mode == 'fullWindow' ? '24 24' : '20 20' ) // shrink to fit size) // set pre-tweaked viewbox
            )
            btnSVG.style.pointerEvents = 'none' // prevent triggering tooltips twice
            if (/chatgpt|openai/.test(env.site)) // override button resizing
                btnSVG.style.height = btnSVG.style.width = '1.3rem'
    
            // Update SVG elements
            btnSVG.textContent = ''
            const svgElems = config[mode] || state.toLowerCase() == 'on' ? ONelems : OFFelems
            svgElems.forEach(elem => btnSVG.append(elem))
    
            // Update SVG
            if (!btn.contains(btnSVG)) btn.append(btnSVG)
        }
    }

    // Define UPDATE functions

    const update = {

        style: {

            chatbar() {
                chatbarStyle.innerText = (
                    /chatgpt|openai/.test(env.site) ? ( config.widerChatbox ? ''
                        : `main form { max-width: ${chatbar.nativeWidth}px !important ; margin: auto }` )
                  : env.site == 'poe' ? ( !config.widerChatbox ? ''
                        : '[class*=footerInner] { width: 100% }' )
                  : '' )
            },

            tweaks() {
                tweaksStyle.innerText = (
                    '.chatgpt-notif, [class*="-modal"] { font-family: system-ui !important }'
                  + `[class*="-modal"] { color: ${ chatgpt.isDarkMode() ? 'white' : 'black' }}`
                  + '[class*="modal-close-btn"] svg { height: 10px }'
                  + '[class*="-modal"] h2 { font-size: 24px ; font-weight: 600 }'
                  + '[class*="-modal"] p { font-size: 16px }'
                  + '[class*="-modal"] button {'
                      + 'font-size: 0.77rem ; text-transform: uppercase ;' // shrink/uppercase labels
                      + `border: 2px dashed ${ chatgpt.isDarkMode() ? 'white' : 'black' } !important ; border-radius: 0 !important ;` // thiccen/square/dash 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
                  + '[class*="-modal"] button:hover {' // add zoom, re-scheme
                      + 'transform: scale(1.055) ;'
                      + ( chatgpt.isDarkMode() ? 'background-color: #2cff00 !important ; box-shadow: 2px 1px 54px #38ff00 !important ; color: black !important'
                                               : 'background-color: #c7ff006b !important ; box-shadow: 2px 1px 30px #97ff006b !important' ) + '}'
                  + ( /chatgpt|openai/.test(env.site) ? (
                          ( '[id$="-btn"]:hover { opacity: 80% !important }' ) // dim chatbar btns on hover
                          + 'main { overflow: clip !important }' // prevent h-scrollbar on sync.mode('fullWindow) => delayed chatbar.tweak()
                    ) : env.site == 'poe' ? 'button[class*="Voice"] { margin: 0 -3px 0 -8px }' : '' )) // h-pad mic btn for even spread
                  + ( config.tcbDisabled == false ? tcbStyle : '' ) // expand text input vertically
                  + ( config.hiddenHeader ? hhStyle : '' ) // hide header
                  + ( config.hiddenFooter ? hfStyle : '' ) // hide footer
                  + `#newChat-btn { display: ${ config.ncbDisabled == true ? 'none' : 'flex' }}`
            },

            wideScreen() {
                wideScreenStyle.innerText = (
                    /chatgpt|openai/.test(env.site) ? (
                        '.text-base { max-width: 100% !important }' // widen outer container
                      + '.text-base:nth-of-type(2) { max-width: 97% !important }' // widen inner container
                  ) : env.site == 'perplexity' ? (
                        `${sites.perplexity.selectors.header} ~ div,` // outer container
                      + `${sites.perplexity.selectors.header} ~ div > div` // inner container
                          + '{ max-width: 100% }' // ...widen them
                      + '.col-span-8 { width: 154% }' // widen inner-left container
                      + '.col-span-4 { width: 13.5% ; position: absolute ; right: 0 }' // narrow right-bar
                  ) : env.site == 'poe' ? (
                        '[class*="ChatMessagesView"] { width: 100% !important }' // widen outer container
                      + '[class^="Message"] { max-width: 100% !important }' ) // widen speech bubbles
                  : '' )
            }
        },

        tooltip(btnType) { // text & position
            const visibleBtnTypes = btns.types.filter(type => !(type == 'fullWindow' && !sites[env.site].hasSidebar))
            const ctrAddend = ( env.site == 'perplexity' ? ( location.pathname == '/' ? 100 : 106 )
                              : env.site == 'poe' ? 45 : 13 ) +25,
                  spreadFactor = env.site == 'perplexity' ? 26.85 : env.site == 'poe' ? 34 : 30.55,
                  iniRoffset = spreadFactor * ( visibleBtnTypes.indexOf(btnType) +1 ) + ctrAddend
                             + ( env.tallChatbar ? -3 : 0 ) // nudge right
            tooltipDiv.innerText = app.msgs['tooltip_' + btnType + (
                !/full|wide/i.test(btnType) ? '' : (config[btnType] ? 'OFF' : 'ON'))]
            tooltipDiv.style.right = `${ // x-pos
                iniRoffset - tooltipDiv.getBoundingClientRect().width /2 }px`
            tooltipDiv.style.bottom = ( // y-pos
                env.site == 'perplexity' ? ( location.pathname != '/' ? '58px' :
                    ( !document.querySelector(sites.perplexity.selectors.btns.login) ? 'revert-layer' : '52.5vh' ))
                                         : '50px' )
        }
    }

    // Define TOGGLE functions

    const toggle = {

        mode(mode, state = '') {
            switch (state.toUpperCase()) {
                case 'ON' : activateMode(mode) ; break
                case 'OFF' : deactivateMode(mode) ; break
                default : ( mode == 'wideScreen' ? document.head.contains(wideScreenStyle)
                          : mode == 'fullWindow' ? isFullWin() : chatgpt.isFullScreen() ) ? deactivateMode(mode)
                                                                                          : activateMode(mode)
            }

            function activateMode(mode) {
                if (mode == 'wideScreen') { document.head.append(wideScreenStyle) ; sync.mode('wideScreen') }
                else if (mode == 'fullWindow') {
                    const sidebarToggle = document.querySelector(sites[env.site].selectors.btns.sidebarToggle)
                    if (sidebarToggle) sidebarToggle.click()
                    else { document.head.append(fullWinStyle) ; sync.mode('fullWindow') }
                } else if (mode == 'fullScreen') document.documentElement.requestFullscreen()
            }
        
            function deactivateMode(mode) {
                if (mode == 'wideScreen') {
                    wideScreenStyle.remove() ; sync.mode('wideScreen')
                } else if (mode == 'fullWindow') {
                    const sidebarToggle = document.querySelector(sites[env.site].selectors.btns.sidebarToggle)
                    if (sidebarToggle) sidebarToggle.click()
                    else { fullWinStyle.remove() ; sync.mode('fullWindow') }
                } else if (mode == 'fullScreen') {
                    if (config.f11) siteAlert(app.msgs.alert_pressF11, `${app.msgs.alert_f11reason}.`)
                    else document.exitFullscreen().catch(err => console.error(app.symbol + ' » Failed to exit fullscreen', err))
                }
            }
        },

        tooltip(event) {
            update.tooltip(event.currentTarget.id.replace(/-btn$/, ''))
            tooltipDiv.style.opacity = event.type == 'mouseover' ? 1 : 0
        }   
    }

    // Define SYNC functions

    const sync = {

        configToUI() { // from toolbar menu toggles
            sync.fullerWin() // sync FW
            update.style.tweaks() // sync TCB/NCB/HH/HF
            update.style.chatbar() // sync WCB
            chatbar.tweak() // update chatgpt.com chatbar inner width + apply poe.com btn alignment (once)
            menu.refresh() // to update state symbol/suffix
        },

        fullerWin() {
            if (config.fullWindow && config.fullerWindows && !config.wideScreen) { // activate fuller windows
                document.head.append(wideScreenStyle) ; btns.updateSVG('wideScreen', 'on')
            } else if (!config.fullWindow) { // de-activate fuller windows
                fullWinStyle.remove() // to remove style too so sidebar shows
                if (!config.wideScreen) { // disable widescreen if result of fuller window
                    wideScreenStyle.remove() ; btns.updateSVG('wideScreen', 'off')
            }}
        },

        mode(mode) { // setting + icon + tooltip + chatbar
            const state = ( mode == 'wideScreen' ? !!document.getElementById('wideScreen-mode')
                          : mode == 'fullWindow' ? isFullWin()
                                                 : chatgpt.isFullScreen() )
            settings.save(mode, state) ; btns.updateSVG(mode) ; update.tooltip(mode)
            if (mode == 'fullWindow') sync.fullerWin()
            if (/chatgpt|openai/.test(env.site)) setTimeout(() => chatbar.tweak(), // update inner width
                mode == 'fullWindow' && ( config.wideScreen || config.fullerWindows )
                                     && config.widerChatbox ? 111 : 0) // delay if toggled to/from active WCB to avoid inaccurate width
            notify(`${app.msgs[`mode_${mode}`]} ${app.msgs[`state_${ state ? 'on' : 'off' }`].toUpperCase()}`)
            config.modeSynced = true ; setTimeout(() => config.modeSynced = false, 100) // prevent repetition
        }
    }

    // Define UI functions

    function isFullWin() {
        return env.site == 'poe' ? !!document.getElementById('fullWindow-mode')
            : !sites[env.site].hasSidebar // false if sidebar non-existent
           || /\d+/.exec(getComputedStyle(document.querySelector(sites[env.site].selectors.sidebar))?.width || '')[0] < 100
    }

    chatgpt.canvasIsOpen = function() { return document.querySelector('section.popover')?.getBoundingClientRect().top == 0 }

    // 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.querySelector('[cwm-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 UI props
    if (/chatgpt|openai/.test(env.site)) {
        sites[env.site].hasSidebar = await Promise.race([
            dom.elemIsLoaded(sites[env.site].selectors.btns.sidebarToggle), // true if sidebar toggle loads
            dom.elemIsLoaded(sites[env.site].selectors.btns.login).then(() => false), // false if login button loads
            new Promise(resolve => setTimeout(() => resolve(null), 3000)) // null if 3s passed
        ])
        sites[env.site].selectors.footer = await Promise.race([
            new Promise(resolve => { // class of footer container
                const footerDiv = chatgpt.getFooterDiv()
                if (footerDiv) resolve(dom.cssSelectorize(footerDiv.classList))
                else new MutationObserver((_, obs) => {
                    const footerDiv = chatgpt.getFooterDiv()
                    if (footerDiv) { obs.disconnect() ; resolve(dom.cssSelectorize(footerDiv.classList)) }
                }).observe(document.body, { childList: true, subtree: true })
            }),
            new Promise(resolve => setTimeout(() => resolve(null), 500)) // null if 500ms passed
        ])
    }

    // Init FULL-MODE states
    config.fullScreen = chatgpt.isFullScreen()
    if (sites[env.site].selectors.btns.sidebarToggle) // site has native FW state
         config.fullWindow = isFullWin() // ...so match it
    else settings.load('fullWindow') // otherwise load CWM's saved state

    // Stylize ALERTS
    if (!document.getElementById('chatgpt-alert-override-style')) {
        const chatgptAlertStyle = dom.create.style()
        chatgptAlertStyle.id = 'chatgpt-alert-override-style'
        chatgptAlertStyle.innerText = (
            ( chatgpt.isDarkMode() ? '.chatgpt-modal > div { border: 1px solid white }' : '' )
          + '.modal-buttons { margin-left: -13px !important }'
        )
        document.head.append(chatgptAlertStyle)
    }

    // Create/stylize TOOLTIP div
    const tooltipDiv = dom.create.elem('div', { class: 'cwm-tooltip' })
    document.head.append(dom.create.style('.cwm-tooltip {'
        + 'background-color: rgba(0, 0, 0, 0.71) ; padding: 5px ; border-radius: 6px ; border: 1px solid #d9d9e3 ;' // bubble style
        + 'font-size: 0.85rem ; color: white ;' // font style
        + 'box-shadow: 4px 6px 16px 0 rgb(0 0 0 / 38%) ;' // drop shadow
        + 'position: absolute ; bottom: 58px ; opacity: 0 ; transition: opacity 0.1s ; z-index: 9999 ;' // visibility
        + '-webkit-user-select: none ; -moz-user-select: none ; -ms-user-select: none ; user-select: none }' // disable select
    ))

    // Create/apply general style TWEAKS
    const tweaksStyle = dom.create.style()
    const tcbStyle = ( // heighten chatbox
              /chatgpt|openai/.test(env.site) ? `div[class*="prose"]:has(${sites[env.site].selectors.input})`
                                              : sites[env.site].selectors.input )
                   + '{ max-height: 68vh }'
    const hhStyle = sites[env.site].selectors.header + '{ display: none !important }' // hide header
                  + ( /chatgpt|openai/.test(env.site) ? 'main { padding-top: 12px }' : '' ) // increase top-padding
    const hfStyle = sites[env.site].selectors.footer + '{ visibility: hidden ;' // hide footer text
                                                     + '  height: 3px ; overflow: clip }' // reduce height

    update.style.tweaks() ; document.head.append(tweaksStyle)

    // Create WIDESCREEN style
    const wideScreenStyle = dom.create.style()
    wideScreenStyle.id = 'wideScreen-mode' // for sync.mode()
    if (!chatbar.get()) await dom.elemIsLoaded(sites[env.site].selectors.input)
    if (/chatgpt|openai/.test(env.site)) // store native chatbar width for Wider Chatbox style
        chatbar.nativeWidth = /\d+/.exec(getComputedStyle(document.querySelector('main form')).width)[0]
    update.style.wideScreen()

    // Create FULL-WINDOW style
    const fullWinStyle = dom.create.style()
    fullWinStyle.id = 'fullWindow-mode' // for sync.mode()
    fullWinStyle.innerText = sites[env.site].selectors.sidebar + '{ display: none }'

    // Create/append CHATBAR style
    const chatbarStyle = dom.create.style()
    update.style.chatbar() ; document.head.append(chatbarStyle)

    // Insert BUTTONS
    btns.insert()

    // Restore PREV SESSION's state
    if (config.wideScreen) toggle.mode('wideScreen', 'ON')
    if (config.fullWindow && sites[env.site].hasSidebar) {
        if (sites[env.site].selectors.btns.sidebarToggle) // site has own FW config
             sync.mode('fullWindow') // ...so sync w/ it
        else toggle.mode('fullWindow', 'on') // otherwise self-toggle
    }

    // Monitor NODE CHANGES to maintain button visibility + update colors
    let isTempChat = false, canvasWasOpen = chatgpt.canvasIsOpen()
    const nodeObserver = new MutationObserver(([mutation]) => {
        if (/chatgpt|openai/.test(env.site)) {
            if (!canvasWasOpen && chatgpt.canvasIsOpen()) {
                btns.remove() ; chatbar.tweak() ; canvasWasOpen = true
            } else if (canvasWasOpen && !chatgpt.canvasIsOpen()) {
                btns.insert() ; chatbar.tweak() ; canvasWasOpen = false }
        }
        if (!document.getElementById('wideScreen-btn') && btns.status != 'inserting') {
            btns.status = 'missing' ; btns.insert() }
        if (/chatgpt|openai/.test(env.site)) { // Update button colors on ChatGPT scheme or temp chat toggle
            const chatbarIsBlack = !!document.querySelector('div[class*="bg-black"]:not([id$="-btn"])')
            if (chatbarIsBlack != isTempChat // temp chat toggled
                || mutation.target == document.documentElement && mutation.attributeName == 'class') { // scheme toggled
                    btns.updateColor() ; isTempChat = chatbarIsBlack }
        }
    })
    nodeObserver.observe(document.querySelector(env.site == 'poe' ? 'head' : 'body'), { attributes: true, subtree: true })

    // Monitor SIDEBAR to update full-window setting
    if (sites[env.site].selectors.btns.sidebarToggle && sites[env.site].hasSidebar) {
        const sidebarObserver = new MutationObserver(async () => {
            await new Promise(resolve => setTimeout(resolve, env.site == 'perplexity' ? 500 : 0))
            if ((config.fullWindow ^ isFullWin()) && !config.modeSynced) sync.mode('fullWindow')
        })
        setTimeout(() => { // delay half-sec before observing to avoid repeated toggles from nodeObserver
            let obsTarget = document.querySelector(sites[env.site].selectors.sidebar)
            if (env.site == 'perplexity') obsTarget = obsTarget.parentNode
            sidebarObserver.observe(obsTarget, { attributes: true })
        }, 500)
    }

    // Add RESIZE LISTENER to update full screen setting/button + disable F11 flag
    window.addEventListener('resize', () => {
        const fullScreenState = chatgpt.isFullScreen()
        if (config.fullScreen && !fullScreenState) { sync.mode('fullScreen') ; config.f11 = false } // exiting full screen
        else if (!config.fullScreen && fullScreenState) sync.mode('fullScreen') // entering full screen
        if (/chatgpt|openai/.test(env.site)) chatbar.tweak() // update ChatGPT chatbar inner width
    })

    // Add KEY LISTENER to enable flag on F11 + stop generating text on ESC
    document.addEventListener('keydown', event => {
        if ((event.key == 'F11' || event.keyCode == 122) && !config.fullScreen) config.f11 = true
        else if ((event.key == 'Escape' || event.keyCode == 27) && !chatgpt.isIdle()) chatgpt.stop()
    })

})()