-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
1 lines (1 loc) · 47.4 KB
/
Copy pathpopup.js
File metadata and controls
1 lines (1 loc) · 47.4 KB
1
document.addEventListener("DOMContentLoaded",()=>{chrome.storage.sync.get(["isBanned"],e=>{e.isBanned&&(document.body.innerHTML='\n <div class="ev-si-overlay ev-si-theme-red" style="display: block;">\n <div class="ev-si-card ev-si-visible">\n <div class="ev-si-particles">\n <span class="ev-si-p ev-si-p1"></span>\n <span class="ev-si-p ev-si-p2"></span>\n <span class="ev-si-p ev-si-p3"></span>\n <span class="ev-si-p ev-si-p4"></span>\n </div>\n <div class="ev-si-icon-wrap">\n <div class="ev-si-ring"></div>\n <div class="ev-si-icon-inner">\n <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="url(#redGrad)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <defs>\n <linearGradient id="redGrad" x1="0%" y1="0%" x2="100%" y2="100%">\n <stop offset="0%" stop-color="#ef4444" />\n <stop offset="100%" stop-color="#b91c1c" />\n </linearGradient>\n </defs>\n <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"></path>\n <line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line>\n </svg>\n </div>\n </div>\n <div class="ev-si-eyebrow"><span class="ev-si-dot"></span> Action Required</div>\n <h2 class="ev-si-title">Account<br><span class="ev-si-gradient-text">Suspended</span></h2>\n <p class="ev-si-sub">Your EasyView access has been restricted due to a violation of our terms of service.</p>\n <a href="mailto:support@easyview.in" class="ev-si-btn-primary" style="text-decoration: none; display: flex; align-items: center; justify-content: center; margin-top: 10px;">\n <span class="ev-si-btn-shimmer"></span>\n Contact Support\n </a>\n </div>\n </div>\n ')});const e=document.getElementById("privacyShieldToggle"),t=document.getElementById("privacyOptions"),n=document.getElementById("subClassicBlur"),o=document.getElementById("subFlashlight"),s=document.getElementById("flashlightCustomization"),a="wa_styler_enabled",i="privacy_config";function c(e,t){return document.querySelector(`#${e} .swatch.active`)?.getAttribute(t)}function r(e){chrome.storage.sync.get(["isPremium"],t=>{const a=!0===t?.isPremium;let r=c("beamShapeRow","data-shape")||"circle";"line"!==r||a||(r="circle",document.querySelectorAll("#beamShapeRow .swatch").forEach(e=>{e.classList.toggle("active","circle"===e.getAttribute("data-shape"))}));const d={blur:!1!==n?.checked,flashlight:o?.checked||!1,beamTint:c("beamTintRow","data-tint")||"transparent",beamShape:r,beamSize:parseInt(document.getElementById("flashlightSizeRange")?.value||"35",10),bgColor:c("ambientBgRow","data-bg")||"rgba(0, 0, 0, 0.45)"};s&&(s.style.display=d.flashlight?"flex":"none"),chrome.tabs.query({},t=>{t.forEach(t=>{t.id&&chrome.tabs.sendMessage(t.id,{type:"TOGGLE_STYLE",enabled:e,config:d})})}),chrome.storage.local.set({[i]:d})})}if(e){chrome.storage.local.get([a,i],c=>{const r=!!c[a];e.checked=r,t&&(t.style.display=r?"block":"none");const d=c[i]||{};n&&(n.checked=!1!==d.blur),o&&(o.checked=!!d.flashlight,s&&(s.style.display=o.checked?"flex":"none")),d.beamTint&&document.querySelectorAll("#beamTintRow .swatch").forEach(e=>{e.classList.toggle("active",e.getAttribute("data-tint")===d.beamTint)}),d.beamShape&&document.querySelectorAll("#beamShapeRow .swatch").forEach(e=>{e.classList.toggle("active",e.getAttribute("data-shape")===d.beamShape)}),d.bgColor&&document.querySelectorAll("#ambientBgRow .swatch").forEach(e=>{e.classList.toggle("active",e.getAttribute("data-bg")===d.bgColor)});const l=document.getElementById("flashlightSizeRange"),m=document.getElementById("beamSizeValue");l&&d.beamSize&&(l.value=d.beamSize,m&&(m.textContent=`${d.beamSize}px`)),Qe()}),e.addEventListener("change",()=>{const n=e.checked;chrome.storage.local.set({[a]:n}),t&&(n?(t.style.display="block",t.animate([{opacity:0,height:0},{opacity:1,height:"auto"}],{duration:200})):t.style.display="none"),r(n),Qe()}),[n,o].forEach(t=>{t?.addEventListener("change",()=>r(e.checked))});const tt=document.getElementById("flashlightSizeRange"),nt=document.getElementById("beamSizeValue");tt&&tt.addEventListener("input",()=>{nt&&(nt.textContent=`${tt.value}px`),r(e.checked)}),document.querySelectorAll(".color-swatch-row .swatch").forEach(t=>{t.addEventListener("click",n=>{if("line"===t.getAttribute("data-shape"))return void chrome.storage.sync.get("isPremium",n=>{if(n&&!0===n.isPremium){t.parentElement.querySelectorAll(".swatch").forEach(e=>e.classList.remove("active")),t.classList.add("active"),r(e.checked)}else"function"==typeof window.showPremiumModal?window.showPremiumModal("Reading Ruler Mode"):alert("Reading Ruler Mode is exclusive to Pro subscriptions.")});t.parentElement.querySelectorAll(".swatch").forEach(e=>e.classList.remove("active")),t.classList.add("active"),r(e.checked)})})}const d=document.getElementsByClassName("system-fonts-group");d.length>0&&chrome.fontSettings&&"function"==typeof chrome.fontSettings.getFontList&&chrome.fontSettings.getFontList(e=>{if(!e||0===e.length)return;Array.from(d).forEach(e=>e.innerHTML=""),e.sort((e,t)=>e.displayName.localeCompare(t.displayName));const t=document.createDocumentFragment();e.forEach(e=>{const n=document.createElement("option");n.value=e.fontId,n.textContent=e.displayName,n.style.fontFamily=`"${e.fontId}", sans-serif`,t.appendChild(n)}),Array.from(d).forEach(e=>{e.appendChild(t.cloneNode(!0))}),chrome.storage.sync.get("lastVisualSettings",e=>{const t=document.getElementById("fontSelect");t&&e?.lastVisualSettings?.font&&(t.value=e.lastVisualSettings.font)})});const l=document.getElementById("enableVisualsCheckbox"),m=[document.getElementById("darkModeBtn"),document.getElementById("lightModeBtn"),document.getElementById("brightnessRange"),document.getElementById("contrastRange"),document.getElementById("sepiaRange"),document.getElementById("grayscaleRange"),document.getElementById("fontSelect"),document.getElementById("textStrokeRange"),document.getElementById("fontSizeRange")];function u(e){m.forEach(t=>{t&&(t.disabled=!e)})}function g(){return{mode:document.getElementById("darkModeBtn")?.classList.contains("active")?"dark":"light",brightness:parseInt(document.getElementById("brightnessRange")?.value||"100",10),contrast:parseInt(document.getElementById("contrastRange")?.value||"100",10),sepia:parseInt(document.getElementById("sepiaRange")?.value||"0",10),grayscale:parseInt(document.getElementById("grayscaleRange")?.value||"0",10),font:document.getElementById("fontSelect")?.value||"default",textStroke:parseFloat(document.getElementById("textStrokeRange")?.value||"0"),fontSize:parseInt(document.getElementById("fontSizeRange")?.value||"100",10)}}let y=null;function p(){const e=document.getElementById("saveStatus");e&&(e.textContent="Saved",e.classList.add("visible"),y&&clearTimeout(y),y=setTimeout(()=>{e.classList.remove("visible")},1500))}function h(e=!0){const t=g();v()&&(chrome?.runtime?.sendMessage&&chrome.runtime.sendMessage({type:"APPLY_VISUALS",settings:t}),chrome?.tabs?.query&&chrome.tabs.query({active:!0,currentWindow:!0},e=>{e?.[0]?.id&&chrome.tabs.sendMessage(e[0].id,{type:"APPLY_VISUALS",settings:t})})),e&&chrome?.storage?.sync&&chrome.storage.sync.set({lastVisualSettings:t},()=>{p()})}function v(){return l&&l.checked}chrome.storage.sync.get(["lastVisualSettings","enableVisuals"],e=>{const t=!(!e||"boolean"!=typeof e.enableVisuals)&&e.enableVisuals;l&&(l.checked=t,u(t));const n=e?.lastVisualSettings||{};document.getElementById("brightnessRange").value=n.brightness??100,document.getElementById("contrastRange").value=n.contrast??100,document.getElementById("sepiaRange").value=n.sepia??0,document.getElementById("grayscaleRange").value=n.grayscale??0,document.getElementById("fontSelect").value=n.font||"default",document.getElementById("textStrokeRange").value=n.textStroke??0,document.getElementById("fontSizeRange").value=n.fontSize??100,document.getElementById("brightnessValue").textContent=(n.brightness??100)+"%",document.getElementById("contrastValue").textContent=(n.contrast??100)+"%",document.getElementById("sepiaValue").textContent=(n.sepia??0)+"%",document.getElementById("grayscaleValue").textContent=(n.grayscale??0)+"%",document.getElementById("textStrokeValue").textContent=n.textStroke??0,document.getElementById("fontSizeValue").textContent=(n.fontSize??100)+"%";const o=n.mode??"light";document.getElementById("darkModeBtn").classList.toggle("active","dark"===o),document.getElementById("lightModeBtn").classList.toggle("active","dark"!==o);const s=document.getElementById("modeSelectedText");s&&(s.textContent=o.charAt(0).toUpperCase()+o.slice(1))}),l.addEventListener("change",function(){u(l.checked),chrome.storage.sync.set({enableVisuals:l.checked}),l.checked?h():chrome.tabs.query({active:!0,currentWindow:!0},function(e){chrome.tabs.sendMessage(e[0].id,{type:"APPLY_VISUALS",settings:{}})}),Qe()});[{id:"brightnessRange",valueId:"brightnessValue",suffix:"%"},{id:"contrastRange",valueId:"contrastValue",suffix:"%"},{id:"sepiaRange",valueId:"sepiaValue",suffix:"%"},{id:"grayscaleRange",valueId:"grayscaleValue",suffix:"%"},{id:"textStrokeRange",valueId:"textStrokeValue",suffix:""},{id:"fontSizeRange",valueId:"fontSizeValue",suffix:"%"}].forEach(({id:e,valueId:t,suffix:n})=>{const o=document.getElementById(e),s=document.getElementById(t);o&&s&&(o.addEventListener("input",()=>{if(s.textContent=o.value+n,"fontSizeRange"===e){const e=document.getElementById("dyslexiaFontSize"),t=document.getElementById("dyslexiaFontSizeValue");e&&(e.value=o.value,t&&(t.textContent=o.value+"%"))}v()&&h(!1)}),o.addEventListener("change",()=>{if("fontSizeRange"===e){const e=parseInt(o.value);chrome.storage.sync.set({dyslexiaFontSize:e})}h(!0)}),s.textContent=o.value+n)});const f=document.getElementById("fontSelect");if(f){function E(){v()&&h(),chrome&&chrome.storage&&chrome.storage.sync&&chrome.storage.sync.set({lastVisualSettings:g()})}f.addEventListener("change",()=>{const e=f.options[f.selectedIndex];"true"===e?.dataset?.premium?chrome.storage.sync.get("isPremium",e=>{!0!==e.isPremium?(chrome.storage.sync.get("lastVisualSettings",e=>{f.value=e.lastVisualSettings?.font||"default"}),Ke("This Visuals font")):E()}):E()})}["darkModeBtn","lightModeBtn"].forEach(e=>{const t=document.getElementById(e);t&&t.addEventListener("click",()=>{document.getElementById("darkModeBtn").classList.toggle("active","darkModeBtn"===e),document.getElementById("lightModeBtn").classList.toggle("active","lightModeBtn"===e);const t=document.getElementById("modeSelectedText");t&&(t.textContent="darkModeBtn"===e?"Dark":"Light"),v()&&h(),chrome&&chrome.storage&&chrome.storage.sync&&chrome.storage.sync.set({lastVisualSettings:g()})})});const w=document.getElementById("settingsBtnIcon"),b=document.getElementById("panel-settings"),I=document.getElementById("tab-vocab"),B=document.getElementById("panel-vocab");w&&b&&w.addEventListener("click",()=>{const e="block"===b.style.display;b.style.display=e?"none":"block",e||([P,T,R,B,C].forEach(e=>e&&(e.style.display="none")),[x,k,S,I,M].forEach(e=>e&&e.classList.remove("active")))});const x=document.getElementById("tab-features"),k=document.getElementById("tab-visuals"),S=document.getElementById("tab-converter"),L=document.getElementById("tab-settings"),M=document.getElementById("tab-morph"),P=document.getElementById("panel-features"),T=document.getElementById("panel-visuals"),R=document.getElementById("panel-converter"),C=document.getElementById("panel-morph");function A(e,t){[x,k,S,I,L,M].forEach(e=>e&&e.classList.remove("active")),[P,T,R,B,C,b].forEach(e=>e&&(e.style.display="none")),e&&e.classList.add("active"),t&&(t.style.display="block"),e===I&&"function"==typeof window.loadAndRenderVocab&&window.loadAndRenderVocab()}x&&P&&x.addEventListener("click",()=>A(x,P)),k&&T&&k.addEventListener("click",()=>A(k,T)),I&&B&&I.addEventListener("click",()=>A(I,B)),M&&C&&M.addEventListener("click",()=>A(M,C)),S&&R&&S.addEventListener("click",()=>A(S,R));const V=[document.getElementById("tab-features"),document.getElementById("tab-visuals"),document.getElementById("tab-converter"),document.getElementById("tab-vocab"),document.getElementById("tab-morph"),document.getElementById("tab-settings")],z=[document.getElementById("panel-features"),document.getElementById("panel-visuals"),document.getElementById("panel-converter"),document.getElementById("panel-vocab"),document.getElementById("panel-morph"),document.getElementById("panel-settings")];V.forEach((e,t)=>{e&&e.addEventListener("click",()=>{V.forEach((e,n)=>{e&&(e.classList.toggle("active",n===t),e.setAttribute("aria-selected",n===t?"true":"false"))}),z.forEach((e,n)=>{e&&(e.style.display=n===t?"block":"none")}),"tab-vocab"===e.id&&"function"==typeof window.loadAndRenderVocab&&window.loadAndRenderVocab()})});const N=document.getElementById("morphPromptInput"),F=document.getElementById("morphCharCount");N&&F&&N.addEventListener("input",()=>{const e=N.value.length;F.textContent=`${e} / 500`,N.style.height="auto",N.style.height=Math.min(N.scrollHeight,120)+"px"});const H=document.getElementById("btnApplyMorph"),U=document.getElementById("btnResetMorph"),_=document.querySelectorAll(".preset-card"),q=document.getElementById("recent-prompts-section"),O=document.getElementById("recent-prompts-list"),$=document.getElementById("active-morph-hint");$&&chrome.tabs.query({active:!0,currentWindow:!0},e=>{const t=e[0];if(t&&t.url)try{const e=new URL(t.url),n="ev_morph_"+e.hostname;chrome.storage.local.get([n],e=>{e[n]&&($.style.display="flex")})}catch(e){}});const j=e=>{const t=e.slice(0,3);t.length>0&&q&&O&&(q.style.display="block",O.innerHTML="",t.forEach(e=>{const t=document.createElement("div");t.style.cssText="padding: 8px 10px; background: var(--bg-tertiary, #f8fafc); border: 1px solid var(--border-color, #e2e8f0); border-radius: 6px; font-size: 11px; color: var(--text-secondary, #475569); cursor: pointer; display: flex; align-items: center; gap: 8px; transition: all 0.2s;";const n=e.replace(/</g,"<").replace(/>/g,">");t.innerHTML=`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg><span style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 1;">${n}</span>`,t.addEventListener("mouseover",()=>t.style.opacity="0.8"),t.addEventListener("mouseout",()=>t.style.opacity="1"),t.addEventListener("click",()=>{N.value=e,N.focus(),N.dispatchEvent(new Event("input"))}),O.appendChild(t)}))};chrome.storage.local.get(["recentPrompts"],e=>{const t=e.recentPrompts||[];j(t)}),H&&N&&H.addEventListener("click",()=>{if(!window.evIsUserSignedIn)return void("function"==typeof window.showSignInNudgeModal&&window.showSignInNudgeModal({desc:"Create a free EasyView account to track your usage quota and unlock the AI Morph Engine."}));const e=N.value.trim();if(!e){if("function"==typeof showNotification)showNotification("Please describe your morph transformation first.","error");else{const e=document.createElement("div");e.innerHTML='<div style="display: flex; align-items: center; gap: 8px;">\n <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#f59e0b" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>\n <span>Please describe your morph first.</span>\n </div>',e.style.cssText="position:fixed;bottom:28px;left:50%;transform:translate(-50%, 15px) scale(0.95);opacity:0;background:var(--bg-secondary, #1e293b);border:1px solid rgba(245, 158, 11, 0.4);color:var(--text-primary, #f8fafc);padding:10px 18px;border-radius:12px;font-size:13px;font-weight:600;z-index:99999;box-shadow:0 14px 28px rgba(0,0,0,0.6);transition:all 0.4s cubic-bezier(0.16, 1, 0.3, 1);backdrop-filter:blur(8px);width:max-content;pointer-events:none;",document.body.appendChild(e),e.offsetWidth,e.style.opacity="1",e.style.transform="translate(-50%, 0) scale(1)",setTimeout(()=>{e.style.opacity="0",e.style.transform="translate(-50%, 10px) scale(0.95)",setTimeout(()=>e.remove(),400)},2800)}return}const t=H.innerHTML;H.disabled=!0,H.innerHTML='\n <svg class="animate-spin" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="animation: spin 1s linear infinite;">\n <path d="M21 12a9 9 0 1 1-6.219-8.56"/>\n </svg>\n <span>Morphing...</span>\n ',chrome.tabs.query({active:!0,currentWindow:!0},n=>{const o=n[0];if(!o||!o.id)return H.disabled=!1,void(H.innerHTML=t);chrome.tabs.sendMessage(o.id,{type:"MORPH_PAGE",prompt:e},n=>{if(H.disabled=!1,H.innerHTML=t,chrome.runtime.lastError){const e=chrome.runtime.lastError.message||JSON.stringify(chrome.runtime.lastError);return void("function"==typeof showNotification&&showNotification(`Failed: ${e}. Please reload the tab.`,"error"))}n&&n.success?($&&($.style.display="flex"),"function"==typeof showNotification&&showNotification(`Applied: ${n.themeName||"Theme"}`,"success"),chrome.storage.local.get(["recentPrompts"],t=>{let n=t.recentPrompts||[];n=n.filter(t=>t!==e),n.unshift(e),n.length>3&&n.pop(),chrome.storage.local.set({recentPrompts:n},()=>{j(n)})}),Qe()):"function"==typeof showNotification&&showNotification(n?.error||"Transformation failed.","error")})})}),U&&U.addEventListener("click",()=>{chrome.tabs.query({active:!0,currentWindow:!0},e=>{const t=e[0];t&&t.id&&chrome.tabs.sendMessage(t.id,{type:"CLEAR_MORPH"},e=>{if(chrome.runtime.lastError){chrome.runtime.lastError.message||JSON.stringify(chrome.runtime.lastError);return}e&&e.success&&($&&($.style.display="none"),N&&(N.value=""),"function"==typeof showNotification&&showNotification("Cleared morphed layout.","success"),Qe())})})});const D=document.getElementById("btnExportMorph"),W=document.getElementById("btnGlobalExportMorph"),K=document.getElementById("btnLoadMorph"),Q=document.getElementById("morphFileInput"),G=document.getElementById("exportMorphModal"),Y=document.getElementById("closeExportMorphModal"),J=document.getElementById("btnExportCurrent"),Z=document.getElementById("btnExportAll"),X=()=>{G&&(G.style.display="flex",G.classList.remove("hidden"),J&&chrome.tabs.query({active:!0,currentWindow:!0},e=>{const t=e[0];if(t&&t.url)try{const e="ev_morph_"+new URL(t.url).hostname;chrome.storage.local.get([e],t=>{t[e]?(J.style.opacity="1",J.style.pointerEvents="auto",J.innerHTML='<span class="ev-si-btn-shimmer"></span>Export Current Page'):(J.style.opacity="0.4",J.style.pointerEvents="none",J.innerHTML="No Theme on Page")})}catch(e){J.style.opacity="0.4",J.style.pointerEvents="none",J.innerHTML="No Theme on Page"}}))};D&&D.addEventListener("click",X),W&&W.addEventListener("click",X),G&&(Y&&Y.addEventListener("click",()=>{G.style.display="none"}),J&&J.addEventListener("click",()=>{chrome.storage.sync.get(["isPremium","userId","accessToken"],e=>{if(!0!==e.isPremium)return G.style.display="none",void("function"==typeof window.showPremiumModal&&window.showPremiumModal("Theme Export"));chrome.tabs.query({active:!0,currentWindow:!0},t=>{const n=t[0];if(n&&n.url)try{const t=new URL(n.url).hostname,o="ev_morph_"+t;chrome.storage.local.get([o],async n=>{const s=n[o];if(s){const n=J.innerHTML;J.innerHTML='<svg class="animate-spin" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-right:8px"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg> Compiling...';try{const n=await fetch("https://easyview.in/api/export-morph",{method:"POST",headers:{"Content-Type":"application/json",Authorization:e.accessToken?`Bearer ${e.accessToken}`:""},body:JSON.stringify({userId:e.userId,libraryThemes:{[t]:s}})}),o=await n.json();if(!n.ok||!o.success)throw new Error(o.error);{const e=new Blob([o.payload],{type:"application/json"}),n=URL.createObjectURL(e);chrome.downloads.download({url:n,filename:`easyview-theme-${t}.json`,saveAs:!0}),"function"==typeof window.showNotification&&window.showNotification("Theme exported successfully!","success")}}catch(e){"function"==typeof window.showPremiumModal&&window.showPremiumModal("Theme Export")}J.innerHTML=n,G.style.display="none"}else"function"==typeof window.showNotification&&window.showNotification("No active theme found on this page.","error")})}catch(e){}})})}),Z&&Z.addEventListener("click",()=>{chrome.storage.sync.get(["isPremium","userId","accessToken"],e=>{if(!0!==e.isPremium)return G.style.display="none",void("function"==typeof window.showPremiumModal&&window.showPremiumModal("Theme Library Backup"));chrome.storage.local.get(null,async t=>{const n={};for(const e in t)e.startsWith("ev_morph_")&&(n[e.replace("ev_morph_","")]=t[e]);if(Object.keys(n).length>0){const t=Z.innerHTML;Z.innerHTML='<svg class="animate-spin" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-right:8px"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg> Compiling...';try{const t=await fetch("https://easyview.in/api/export-morph",{method:"POST",headers:{"Content-Type":"application/json",Authorization:e.accessToken?`Bearer ${e.accessToken}`:""},body:JSON.stringify({userId:e.userId,libraryThemes:n})}),o=await t.json();if(!t.ok||!o.success)throw new Error(o.error);{const e=new Blob([o.payload],{type:"application/json"}),t=URL.createObjectURL(e);chrome.downloads.download({url:t,filename:"easyview-all-themes.json",saveAs:!0}),"function"==typeof window.showNotification&&window.showNotification("Library exported successfully!","success")}}catch(e){"function"==typeof window.showPremiumModal&&window.showPremiumModal("Theme Library Backup")}Z.innerHTML=t,G.style.display="none"}else"function"==typeof window.showNotification&&window.showNotification("Your theme library is empty.","error")})})})),K&&Q&&(K.addEventListener("click",()=>{Q.click()}),Q.addEventListener("change",e=>{const t=e.target.files[0];if(!t)return;const n=new FileReader;n.onload=e=>{try{const t=JSON.parse(e.target.result);if("EasyViewLibrary"===t.type&&t.themes){const e={};let n=0;for(const o in t.themes)e[`ev_morph_${o}`]=t.themes[o],n++;const o=K.innerHTML;return K.innerHTML='<svg class="animate-spin" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',chrome.storage.local.set(e,()=>{K.innerHTML=o,"function"==typeof window.showNotification&&window.showNotification(`Restored ${n} themes from library!`,"success"),chrome.tabs.query({active:!0,currentWindow:!0},e=>{const n=e[0];if(n&&n.id&&n.url)try{const e=new URL(n.url).hostname,o=t.themes[e];o&&chrome.tabs.sendMessage(n.id,{type:"MORPH_PAGE_DIRECT",recipe:o},()=>{$&&($.style.display="flex"),Qe()})}catch(e){}})}),void(Q.value="")}const n=t.themes?Object.values(t.themes)[0]:t;if(!n||!n.jsMutations)throw new Error("Invalid Morph Recipe format.");chrome.tabs.query({active:!0,currentWindow:!0},e=>{const t=e[0];if(!t||!t.id)return;const o=K.innerHTML;K.innerHTML='<svg class="animate-spin" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',chrome.tabs.sendMessage(t.id,{type:"MORPH_PAGE_DIRECT",recipe:n},e=>{if(K.innerHTML=o,$&&($.style.display="flex"),"function"==typeof window.showNotification&&window.showNotification("Custom theme loaded successfully!","success"),Qe(),t.url)try{const e=new URL(t.url),o="ev_morph_"+e.hostname;chrome.storage.local.set({[o]:n})}catch(e){}})})}catch(e){"function"==typeof window.showNotification&&window.showNotification("Failed to read theme file.","error")}Q.value=""},n.readAsText(t)})),_.forEach(e=>{e.addEventListener("click",()=>{const t=e.getAttribute("data-prompt");N&&t&&(N.value=t,N.focus(),N.dispatchEvent(new Event("input")))})});const ee=document.getElementById("jargonToggle"),te=document.getElementById("sensoryToggle"),ne=document.getElementById("sensoryOptions"),oe=document.querySelectorAll('input[name="sensoryMode"]'),se=document.getElementById("dyslexiaToggle"),ae=document.getElementById("dyslexiaOptions"),ie=document.getElementById("dyslexiaFont"),ce=document.getElementById("letterSpacing"),re=document.getElementById("letterSpacingValue"),de=document.getElementById("lineHeight"),le=document.getElementById("lineHeightValue"),me=document.getElementById("wordSpacing"),ue=document.getElementById("wordSpacingValue"),ge=document.getElementById("overlayColor"),ye=document.getElementById("bionicReading"),pe=document.getElementById("ttsToggle"),he=document.getElementById("ttsOptions"),ve=document.getElementById("ttsPlay"),fe=document.getElementById("ttsPause"),Ee=document.getElementById("ttsStop"),we=document.getElementById("ttsSpeed"),be=document.getElementById("ttsPauseOnPunctuation"),Ie=document.getElementById("ttsWordHighlight"),Be=document.getElementById("ttsVolume"),xe=document.getElementById("ttsVolumeValue"),ke=document.getElementById("settingsBtn"),Se=document.getElementById("settingsPanel"),Le=document.getElementById("apiKey"),Me=document.getElementById("toggleKey"),Pe=document.getElementById("saveKey"),Te=document.getElementById("apiStatus"),Re=document.getElementById("statusText"),Ce=document.getElementById("apiProvider"),Ae=document.getElementById("geminiKey"),Ve=document.getElementById("toggleGeminiKey"),ze=document.getElementById("ttsVoice"),Ne=document.getElementById("apiProviderBadge"),Fe=document.getElementById("feedbackBtn"),He=document.getElementById("feedbackPanel"),Ue=document.getElementById("sendFeedbackBtn"),_e=document.getElementById("themeToggle"),qe=document.getElementById("themeLabel"),Oe=document.querySelectorAll(".size-btn");chrome.storage.sync.get(["jargonEnabled","sensoryEnabled","sensoryMode","dyslexiaEnabled","dyslexiaFont","letterSpacing","lineHeight","wordSpacing","overlayColor","enableVisuals","lastVisualSettings","bionicReading","ttsEnabled","ttsSpeed","ttsPauseOnPunctuation","ttsWordHighlight","ttsVolume","theme","popupSize","apiProvider","ttsVoice","isPremium","premiumExpiresAt","userEmail","userId","tourCompleted","lastTourSkipTime"],e=>{let t=e.isPremium||!1;if(t&&e.premiumExpiresAt&&new Date(e.premiumExpiresAt).getTime()<Date.now()&&(t=!1,e.isPremium=!1,chrome.runtime.sendMessage({type:"SYNC_PREMIUM_STATUS"})),window.evIsUserSignedIn=t||!!e.userId,!t){const t=(globalThis.EASYVIEW_TIERS||{PREMIUM:{fonts:[],beamShapes:[],sensoryModes:[]}}).PREMIUM;if(t.fonts&&t.fonts.includes(e.dyslexiaFont)&&(e.dyslexiaFont="opendyslexic",chrome.storage.sync.set({dyslexiaFont:"opendyslexic"})),e.lastVisualSettings){let n=!1;t.fonts&&t.fonts.includes(e.lastVisualSettings.font)&&(e.lastVisualSettings.font="default",n=!0),t.beamShapes&&t.beamShapes.includes(e.lastVisualSettings.beamShape)&&(e.lastVisualSettings.beamShape="circle",n=!0),n&&chrome.storage.sync.set({lastVisualSettings:e.lastVisualSettings})}t.sensoryModes&&t.sensoryModes.includes(e.sensoryMode)&&(e.sensoryMode="freeze",chrome.storage.sync.set({sensoryMode:"freeze"}))}ee.checked=e.jargonEnabled||!1,te.checked=e.sensoryEnabled||!1,ne.style.display=e.sensoryEnabled?"flex":"none";const n=e.sensoryMode||"freeze",o=document.querySelector(`input[name="sensoryMode"][value="${n}"]`);o&&!o.disabled&&(o.checked=!0),se.checked=e.dyslexiaEnabled||!1;const s=!(!e||"boolean"!=typeof e.enableVisuals)&&e.enableVisuals;l&&(l.checked=s,u(s));const a=e?.lastVisualSettings||{};document.getElementById("brightnessRange")&&(document.getElementById("brightnessRange").value=a.brightness??100,document.getElementById("brightnessValue").textContent=(a.brightness??100)+"%"),document.getElementById("contrastRange")&&(document.getElementById("contrastRange").value=a.contrast??100,document.getElementById("contrastValue").textContent=(a.contrast??100)+"%"),document.getElementById("sepiaRange")&&(document.getElementById("sepiaRange").value=a.sepia??0,document.getElementById("sepiaValue").textContent=(a.sepia??0)+"%"),document.getElementById("grayscaleRange")&&(document.getElementById("grayscaleRange").value=a.grayscale??0,document.getElementById("grayscaleValue").textContent=(a.grayscale??0)+"%"),document.getElementById("fontSelect")&&(document.getElementById("fontSelect").value=a.font||"default"),document.getElementById("textStrokeRange")&&(document.getElementById("textStrokeRange").value=a.textStroke??0,document.getElementById("textStrokeValue").textContent=a.textStroke??0),document.getElementById("fontSizeRange")&&(document.getElementById("fontSizeRange").value=a.fontSize??100,document.getElementById("fontSizeValue").textContent=(a.fontSize??100)+"%");const i=a.mode??"light";document.getElementById("darkModeBtn")&&document.getElementById("darkModeBtn").classList.toggle("active","dark"===i),document.getElementById("lightModeBtn")&&document.getElementById("lightModeBtn").classList.toggle("active","dark"!==i);const c=document.getElementById("modeSelectedText");c&&(c.textContent="dark"===i?"Dark Mode":"Light Mode"),ie.value=e.dyslexiaFont||"opendyslexic",ce.value=e.letterSpacing??0,de.value=e.lineHeight??1.5,me.value=e.wordSpacing??0,ge.value=e.overlayColor||"none",ye.checked=e.bionicReading||!1;const r=e.dyslexiaFontSize||e.lastVisualSettings?.fontSize||100;document.getElementById("dyslexiaFontSize")&&(document.getElementById("dyslexiaFontSize").value=r,document.getElementById("dyslexiaFontSizeValue").textContent=r+"%"),document.getElementById("fontSizeRange")&&(document.getElementById("fontSizeRange").value=r,document.getElementById("fontSizeValue").textContent=r+"%"),pe.checked=e.ttsEnabled||!1,we.value=e.ttsSpeed||1,be.checked=!1!==e.ttsPauseOnPunctuation,Ie.checked=!1!==e.ttsWordHighlight,Be.value=void 0!==e.ttsVolume?e.ttsVolume:70,xe.textContent=(void 0!==e.ttsVolume?e.ttsVolume:70)+"%";const d=e.apiProvider||"gemini";Ce.value=d,Ne&&(Ne.textContent="gemini"===d?"Gemini":"OpenRouter",Ne.className="api-provider-badge "+d);const m=document.getElementById("openrouterSection"),g=document.getElementById("geminiSection");if(g&&(g.style.display="gemini"===d?"block":"none"),m&&(m.style.display="openrouter"===d?"block":"none"),Je(),ae.style.display=se.checked?"grid":"none",he.style.display=pe.checked?"flex":"none","function"==typeof window.refreshPremiumState&&window.refreshPremiumState(t,e.userEmail,e.premiumExpiresAt),Ze(e.theme||"dark"),Xe(e.popupSize||"normal"),et(e.ttsVoice),!e.tourCompleted){const t=864e5,n=e.lastTourSkipTime||0;Date.now()-n>t&&setTimeout(()=>{"function"==typeof window.startTour&&window.startTour()},500)}Qe()}),chrome.storage.local.get(["apiKey","geminiKey"],e=>{e.apiKey&&(Le.value=e.apiKey),e.geminiKey&&(Ae.value=e.geminiKey),(e.apiKey||e.geminiKey)&&We("API key configured (local only)","success")}),ee.addEventListener("change",async e=>{if(!window.evIsUserSignedIn)return e.target.checked=!e.target.checked,void("function"==typeof window.showSignInNudgeModal&&window.showSignInNudgeModal({desc:"Create a free EasyView account to track your quota and unlock the Jargon Decoder."}));const t=e.target.checked;await chrome.storage.sync.set({jargonEnabled:t}),p(),await De({action:"toggleJargon",enabled:t}),Qe()}),te.addEventListener("change",async e=>{const t=e.target.checked,n=document.querySelector('input[name="sensoryMode"]:checked')?.value||"freeze";ne.style.display=t?"flex":"none",await chrome.storage.sync.set({sensoryEnabled:t}),p(),await De({action:"toggleSensory",enabled:t,mode:n}),Qe()}),chrome.storage.sync.get(["isPremium","sensoryMode"],e=>{if(!0===e.isPremium){oe.forEach(e=>{e.disabled=!1}),document.querySelectorAll("#sensoryModeFadeLbl, #sensoryModeStopLbl, #sensoryModeBothLbl").forEach(e=>{e.style.opacity="1"});const t=e.sensoryMode||"freeze",n=document.querySelector(`input[name="sensoryMode"][value="${t}"]`);n&&(n.checked=!0)}else["sensoryModeFade","sensoryModeStop","sensoryModeBoth"].forEach(e=>{const t=document.getElementById(e+"Lbl")||document.getElementById(e)?.closest("label");t&&t.addEventListener("click",()=>Ke("Sensory Shield advanced modes"))})}),oe.forEach(e=>{e.addEventListener("change",async()=>{const t=e.value;if(["fade","stop","both"].includes(t)){if(!0!==(await chrome.storage.sync.get("isPremium")).isPremium)return document.getElementById("sensoryModeFreeze").checked=!0,void Ke("Advanced Sensory Shield modes")}await chrome.storage.sync.set({sensoryMode:t}),te.checked&&await De({action:"toggleSensory",enabled:!0,mode:t})})}),se.addEventListener("change",async e=>{const t=e.target.checked;t||(ye.checked=!1,await chrome.storage.sync.set({bionicReading:!1})),await chrome.storage.sync.set({dyslexiaEnabled:t}),ae.style.display=t?"grid":"none",await De({action:"toggleDyslexia",enabled:t,settings:Ge()}),Qe()}),ie.addEventListener("change",async e=>{const t=ie.options[ie.selectedIndex];if("true"===t?.dataset?.premium){if(!0!==(await chrome.storage.sync.get("isPremium")).isPremium){const e=await chrome.storage.sync.get("dyslexiaFont");return ie.value=e.dyslexiaFont||"opendyslexic",void Ke("This Dyslexia Reading font")}}await chrome.storage.sync.set({dyslexiaFont:e.target.value}),p(),await De({action:"updateDyslexia",settings:Ge()})}),ce.addEventListener("input",e=>{Je(),De({action:"updateDyslexia",settings:Ge()})}),ce.addEventListener("change",async e=>{await chrome.storage.sync.set({letterSpacing:parseFloat(e.target.value)}),p()}),de.addEventListener("input",e=>{Je(),De({action:"updateDyslexia",settings:Ge()})}),de.addEventListener("change",async e=>{await chrome.storage.sync.set({lineHeight:parseFloat(e.target.value)}),p()}),me.addEventListener("input",e=>{Je(),De({action:"updateDyslexia",settings:Ge()})}),me.addEventListener("change",async e=>{await chrome.storage.sync.set({wordSpacing:parseInt(e.target.value)}),p()});const $e=document.getElementById("dyslexiaFontSize"),je=document.getElementById("dyslexiaFontSizeValue");async function De(e){try{const[t]=await chrome.tabs.query({active:!0,currentWindow:!0});if(!t?.id||t.url.startsWith("chrome://")||t.url.startsWith("edge://"))return void We("Cannot run on this page (system page)","error");try{await chrome.tabs.sendMessage(t.id,e)}catch(n){if(!n.message.includes("Receiving end does not exist"))throw n;try{await chrome.scripting.executeScript({target:{tabId:t.id},files:["content.js"]}),await chrome.scripting.insertCSS({target:{tabId:t.id},files:["content.css"]}),await new Promise(e=>setTimeout(e,500)),await chrome.tabs.sendMessage(t.id,e),We("Extension loaded successfully","success")}catch(e){We("Could not load extension on this page","error")}}}catch(e){We("Error communicating with page","error")}}function We(e,t){Te.style.display="block",Te.textContent=e,Te.className=`status-message ${t}`,"success"===t&&setTimeout(()=>{Te.style.display="none"},3e3)}function Ke(e){let t=document.querySelector(".premium-locked-modal");t||(t=document.createElement("div"),t.className="premium-locked-modal ev-si-overlay ev-si-theme-blue",t.setAttribute("style","z-index: 999999;"),document.body.appendChild(t));let n="Feature Locked",o="",s="",a="",i="PRO ACCESS ONLY";if("jargon"===e)n='Jargon Decoder<br><span class="ev-si-gradient-text">Quota Reached</span>',i="OUT OF QUOTA",o="You've used all <strong>5 free decodes</strong> this month. Unlock unlimited access in seconds.",s='\n <div class="ev-si-benefit"><span class="ev-si-tick">⭐</span> Go Pro — Unlimited decodes</div>\n <div class="ev-si-benefit"><span class="ev-si-tick">🔑</span> Use your own API key</div>\n ',a='<button class="ev-si-btn-later" id="apiKeyBtn" style="margin-bottom:8px; border: 1px solid rgba(255,255,255,0.2);">🔑 Add API Key in Settings</button>';else if("export"===e)n='Study Deck Exporter<br><span class="ev-si-gradient-text">Pro Automation</span>',o="Instantly export your entire custom Study Notebook directly to <strong>Anki</strong> and <strong>Quizlet</strong>.",s='\n <div class="ev-si-benefit"><span class="ev-si-tick">✓</span> Ditch manual typing</div>\n <div class="ev-si-benefit"><span class="ev-si-tick">✓</span> RFC-4180 flashcard compiler</div>\n ';else{n=`${e||"This feature"}<br><span class="ev-si-gradient-text">Pro Access</span>`,o="Upgrade to unlock all accessibility features and power tools.",s='\n <div class="ev-si-benefit"><span class="ev-si-tick">✓</span> Advanced Accessibility</div>\n <div class="ev-si-benefit"><span class="ev-si-tick">✓</span> All Future Updates</div>\n '}t.innerHTML=`\n <div class="ev-si-card" id="evPremiumCard">\n <div class="ev-si-particles">\n <span class="ev-si-p ev-si-p1"></span><span class="ev-si-p ev-si-p2"></span><span class="ev-si-p ev-si-p3"></span><span class="ev-si-p ev-si-p4"></span><span class="ev-si-p ev-si-p5"></span>\n </div>\n <div class="ev-si-icon-wrap" style="height: 56px; width: 56px; margin-bottom: 12px;">\n <div class="ev-si-ring"></div>\n <div class="ev-si-icon-inner">\n <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>\n </div>\n </div>\n <div class="ev-si-eyebrow"><span class="ev-si-dot"></span> ${i}</div>\n <h2 class="ev-si-title" style="font-size: 16px;">${n}</h2>\n <p class="ev-si-sub">${o}</p>\n <div class="ev-si-benefits">\n ${s}\n </div>\n <button class="ev-si-btn-primary" id="upgradeBtn">\n <span class="ev-si-btn-shimmer"></span>\n ⭐ Upgrade to Pro\n </button>\n ${a}\n <button class="ev-si-btn-later" id="closePremiumModal">\n Maybe Later\n </button>\n </div>\n `,setTimeout(()=>{const e=document.getElementById("evPremiumCard");e&&e.classList.add("ev-si-visible")},10),document.getElementById("upgradeBtn").onclick=()=>{chrome.storage.sync.get(["userId"],e=>{const n="https://easyview.in",o="/pricing";if(e&&e.userId)window.open(`${n}${o}?source = extension`,"_blank");else{const e=encodeURIComponent(o);window.open(`${n}/login?redirect=${e}&source=extension`,"_blank")}t.style.display="none"})};const c=document.getElementById("apiKeyBtn");c&&(c.onclick=()=>{t.style.display="none";const e=document.getElementById("settingsBtnIcon");e&&e.click()}),document.getElementById("closePremiumModal").onclick=()=>{t.style.display="none"},t.style.display="block"}function Qe(){chrome.tabs.query({active:!0,currentWindow:!0},t=>{const n=t[0];let o="";if(n&&n.url)try{o=new URL(n.url).hostname}catch(e){}const s="ev_morph_"+o;chrome.storage.local.get([s],t=>{const n=!(!o||!t[s]);if(ee&&ee.checked||e&&e.checked||te&&te.checked||se&&se.checked||ye&&ye.checked||pe&&pe.checked||l&&l.checked||n){const t=[];ee&&ee.checked&&t.push("Jargon"),e&&e.checked&&t.push("Privacy"),te&&te.checked&&t.push("Sensory"),se&&se.checked&&t.push("Dyslexia"),ye&&ye.checked&&t.push("Bionic"),pe&&pe.checked&&t.push("TTS"),l&&l.checked&&t.push("Visuals"),n&&t.push("Morph"),Re.textContent=`Active: ${t.join(", ")}`}else Re.textContent="Ready to simplify"})})}function Ge(){return{font:ie.value,letterSpacing:parseFloat(ce.value),lineHeight:parseFloat(de.value),wordSpacing:parseInt(me.value),overlayColor:ge.value,bionicReading:ye.checked,fontSize:parseInt(document.getElementById("dyslexiaFontSize")?.value||"100",10)}}function Ye(){return{speed:parseFloat(we.value),pauseOnPunctuation:be.checked,wordHighlight:Ie.checked,volume:parseInt(Be.value),voice:ze.value}}function Je(){const e=parseFloat(ce.value);re.textContent=0===e?"None":e<2?"Normal":e<4?"Wide":"Extra Wide",le.textContent=de.value;const t=parseInt(me.value);ue.textContent=0===t?"None":t<4?"Normal":t<7?"Wide":"Extra Wide"}function Ze(e){"light"===e?(document.body.classList.add("light-theme"),qe.textContent="Dark",document.querySelector(".theme-icon-dark").style.display="none",document.querySelector(".theme-icon-light").style.display="block"):(document.body.classList.remove("light-theme"),qe.textContent="Light",document.querySelector(".theme-icon-dark").style.display="block",document.querySelector(".theme-icon-light").style.display="none")}function Xe(e){document.body.classList.remove("size-compact","size-expanded"),"compact"===e?document.body.classList.add("size-compact"):"expanded"===e&&document.body.classList.add("size-expanded"),Oe.forEach(t=>{t.classList.toggle("active",t.dataset.size===e)})}function et(e){const t=window.speechSynthesis.getVoices();if(0===t.length)return void window.speechSynthesis.addEventListener("voiceschanged",()=>{et(e)},{once:!0});ze.innerHTML='<option value="auto">Auto (Best Quality)</option>';t.filter(e=>e.lang.startsWith("en")).sort((e,t)=>{const n=e=>{let t=0;const n=e.name.toLowerCase();return(n.includes("neural")||n.includes("natural"))&&(t+=100),(n.includes("premium")||n.includes("enhanced"))&&(t+=80),n.includes("google")&&(t+=60),n.includes("microsoft")&&(t+=50),"en-US"===e.lang&&(t+=30),e.localService&&(t-=10),t};return n(t)-n(e)}).forEach(t=>{const n=document.createElement("option");n.value=t.name,n.textContent=`${t.name} (${t.lang})`,t.name===e&&(n.selected=!0),ze.appendChild(n)})}$e&&($e.addEventListener("input",e=>{const t=e.target.value;je&&(je.textContent=t+"%");const n=document.getElementById("fontSizeRange"),o=document.getElementById("fontSizeValue");n&&(n.value=t,o&&(o.textContent=t+"%"),v()&&h(!1)),De({action:"updateDyslexia",settings:Ge()})}),$e.addEventListener("change",async e=>{const t=parseInt(e.target.value);await chrome.storage.sync.set({dyslexiaFontSize:t,lastVisualSettings:g()}),p()})),ge.addEventListener("change",async e=>{await chrome.storage.sync.set({overlayColor:e.target.value}),p(),await De({action:"updateDyslexia",settings:Ge()})}),ye.addEventListener("change",async e=>{const t=e.target.checked;await chrome.storage.sync.set({bionicReading:t}),p(),await De({action:"toggleBionic",enabled:t}),Qe()}),pe.addEventListener("change",async e=>{const t=e.target.checked;await chrome.storage.sync.set({ttsEnabled:t}),p(),he.style.display=t?"flex":"none",await De({action:"toggleTTS",enabled:t,settings:Ye()}),Qe()}),ve.addEventListener("click",async()=>{await De({action:"ttsPlay"})}),fe.addEventListener("click",async()=>{await De({action:"ttsPause"})}),Ee.addEventListener("click",async()=>{await De({action:"ttsStop"})}),we.addEventListener("change",async e=>{await chrome.storage.sync.set({ttsSpeed:parseFloat(e.target.value)}),await De({action:"updateTTS",settings:Ye()})}),be.addEventListener("change",async e=>{await chrome.storage.sync.set({ttsPauseOnPunctuation:e.target.checked}),await De({action:"updateTTS",settings:Ye()})}),Ie.addEventListener("change",async e=>{await chrome.storage.sync.set({ttsWordHighlight:e.target.checked}),await De({action:"updateTTS",settings:Ye()})}),Be.addEventListener("input",e=>{const t=parseInt(e.target.value);xe.textContent=t+"%"}),Be.addEventListener("change",async e=>{const t=parseInt(e.target.value);await chrome.storage.sync.set({ttsVolume:t})}),ke.addEventListener("click",()=>{const e="block"===Se.style.display;Se.style.display=e?"none":"block",ke.classList.toggle("active",!e)}),Fe&&He&&Fe.addEventListener("click",()=>{const e="flex"===He.style.display;He.style.display=e?"none":"flex",Fe.classList.toggle("active",!e)}),Ue&&Ue.addEventListener("click",()=>{window.open("https://easyview.in/contact","_blank")}),Me.addEventListener("click",()=>{const e="password"===Le.type;Le.type=e?"text":"password";const t=Me.querySelector("svg");t.innerHTML=e?'<path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" x2="22" y1="2" y2="22"/>':'<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/>'}),Pe.addEventListener("click",async()=>{const e=Ce.value,t="gemini"===e?Ae.value.trim():Le.value.trim();if(!t)return void We("Please enter an API key","error");if(t.length<10)return void We("API key looks too short","error");const n="gemini"===e?"geminiKey":"apiKey";await chrome.storage.local.set({[n]:t}),We(("gemini"===e?"Gemini":"OpenRouter")+" API key saved locally (device-only) ✓","success"),chrome.storage.sync.get(["isPremium"],e=>{chrome.storage.local.get(["jargonQuota","morphQuota"],t=>{"function"==typeof window.updateQuotaUI&&window.updateQuotaUI(t.jargonQuota,e.isPremium),"function"==typeof window.updateMorphQuotaUI&&window.updateMorphQuotaUI(t.morphQuota,e.isPremium)})}),"function"==typeof window.refreshAiKeyPrefUI&&window.refreshAiKeyPrefUI(),Qe();try{We("Validating API key...","info");const n=await chrome.runtime.sendMessage({action:"testApiKey",apiKey:t,provider:e});n.success?(We(("gemini"===e?"Gemini":"OpenRouter")+" API key validated successfully","success"),chrome.storage.sync.get(["isPremium"],e=>{chrome.storage.local.get(["jargonQuota","morphQuota"],t=>{"function"==typeof window.updateQuotaUI&&window.updateQuotaUI(t.jargonQuota,e.isPremium),"function"==typeof window.updateMorphQuotaUI&&window.updateMorphQuotaUI(t.morphQuota,e.isPremium)})}),"function"==typeof window.refreshAiKeyPrefUI&&window.refreshAiKeyPrefUI()):We(`API key error: ${n.error}`,"error")}catch(e){We("Could not validate API key","error")}}),window.showPremiumModal=Ke,_e.addEventListener("click",async()=>{const e=document.body.classList.contains("light-theme")?"dark":"light";Ze(e),await chrome.storage.sync.set({theme:e})}),Oe.forEach(e=>{e.addEventListener("click",async()=>{const t=e.dataset.size;Xe(t),await chrome.storage.sync.set({popupSize:t})})}),Ce.addEventListener("change",async e=>{const t=e.target.value;await chrome.storage.sync.set({apiProvider:t}),function(e){Ne&&(Ne.textContent="gemini"===e?"Gemini":"OpenRouter",Ne.className="api-provider-badge "+e);const t=document.getElementById("openrouterSection"),n=document.getElementById("geminiSection");t&&(t.style.display="openrouter"===e?"block":"none");n&&(n.style.display="gemini"===e?"block":"none")}(t)}),Ve.addEventListener("click",()=>{const e="password"===Ae.type;Ae.type=e?"text":"password";const t=Ve.querySelector("svg");t.innerHTML=e?'<path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" x2="22" y1="2" y2="22"/>':'<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/>'}),ze.addEventListener("change",async e=>{await chrome.storage.sync.set({ttsVoice:e.target.value}),await De({action:"updateTTS",settings:{...Ye(),voice:e.target.value}})}),function(){const e="ev_first_use_ts",t="ev_signin_snoozed_until",n=432e5,o=document.getElementById("signInNudgeModal"),s=document.getElementById("evSiCard"),a=document.getElementById("evSiSignInBtn"),i=document.getElementById("evSiLaterBtn");function c(e={}){if(e.desc){const t=document.getElementById("evSiDesc");t&&(t.textContent=e.desc)}o.style.display="flex",requestAnimationFrame(()=>{requestAnimationFrame(()=>s.classList.add("ev-si-visible"))})}function r(){s.classList.remove("ev-si-visible"),setTimeout(()=>{o.style.display="none"},420)}o&&s&&a&&i&&(window.showSignInNudgeModal=c,a.addEventListener("click",()=>{window.open("https://easyview.in/login?redirect=%2Fpricing&source=extension","_blank"),r()}),i.addEventListener("click",()=>{chrome.storage.local.set({[t]:Date.now()+n}),r()}),chrome.storage.sync.get(["userId","isPremium"],o=>{o.userId||!0===o.isPremium||chrome.storage.local.get([e,t],o=>{const s=Date.now();if(!o[e])return void chrome.storage.local.set({[e]:s});const a=s-o[e],i=o[t]||0;a>=n&&s>=i&&c()})}))}()});