(function(){const r=document.createElement("link").relList;if(r&&r.supports&&r.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const t of o.addedNodes)t.tagName==="LINK"&&t.rel==="modulepreload"&&i(t)}).observe(document,{childList:!0,subtree:!0});function a(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(s){if(s.ep)return;s.ep=!0;const o=a(s);fetch(s.href,o)}})();const J={brandAccent:"#0ea5e9",brandAccentHover:"#0b73b9",bgDark:"#1b1b1b",bgDarker:"#2a2a2a",borderDark:"#333",inputBorder:"#555",textPrimary:"#ffffff",textMuted:"#999999",textSubtle:"#cccccc",success:"#4caf50",error:"#f44336",info:"#2196f3",lightBg:"#ffffff",lightBorder:"#e9ecef",lightMutedText:"#6c757d",lightPanelBg:"#f8f9fa",lightMutedText2:"#95a5a6",darkTextStrong:"#2c3e50"};function re(r=typeof document<"u"?document:null,a=J,i="site-theme-vars"){if(r)try{if(r.getElementById(i))return;const s=r.createElement("style");s.id=i;const o={...J,...a||{}};s.textContent=`:root{
      --brand-accent:${o.brandAccent};
      --brand-accent-hover:${o.brandAccentHover};
      --bg-dark:${o.bgDark};
      --bg-darker:${o.bgDarker};
      --border-dark:${o.borderDark};
      --input-border:${o.inputBorder};
      --text-primary:${o.textPrimary};
      --text-muted:${o.textMuted};
      --text-subtle:${o.textSubtle};
      --success:${o.success};
      --error:${o.error};
      --info:${o.info};
      --light-bg:${o.lightBg};
      --light-border:${o.lightBorder};
      --light-muted-text:${o.lightMutedText};
      --light-panel-bg:${o.lightPanelBg};
      --light-muted-text2:${o.lightMutedText2};
      --dark-text-strong:${o.darkTextStrong};
    }`,(r.head||r.documentElement).appendChild(s)}catch{}}const ie={baseUrl:"https://auth.serp.co",storagePrefix:"auth",requiresCode:!0};function ae(r={}){const a=r.AUTH||{},i=r.COLORS||r.colors||{};return{SITE_NAME:r.SITE_NAME||r.siteName||"Downloader",AUTH:{...ie,...a,entitlement:a.entitlement||r.authEntitlement||r.ENTITLEMENT},PRODUCT_URL:r.PRODUCT_URL||r.productUrl||null,WORKER_URL:r.WORKER_URL||r.workerUrl||"",GUMROAD_PRODUCT_ID:r.GUMROAD_PRODUCT_ID||"",GH_LICENSE_ID:r.GH_LICENSE_ID||"",LOG_LEVEL:r.LOG_LEVEL||"error",LOG_MIRROR_TO_BG:r.LOG_MIRROR_TO_BG!==!1,COLORS:{...J,...i}}}const j=ae({SITE_NAME:"ThisVid",AUTH:{entitlement:"thisvid-downloader",storagePrefix:"thisvid-downloader",requiresCode:!0},PRODUCT_URL:"https://serp.ly/thisvid-downloader",LOG_LEVEL:"error",LOG_MIRROR_TO_BG:!0});j.AUTH_BASE_URL=j.AUTH.baseUrl,j.AUTH_ENTITLEMENT=j.AUTH.entitlement,j.AUTH_STORAGE_PREFIX=j.AUTH.storagePrefix;try{globalThis.SiteConfig=j,typeof document<"u"&&re(document,j.COLORS,"serp-auth-theme-vars")}catch{}function se(r){const{requireCode:a,otpStateKey:i,otpStateTtlMs:s,emailInput:o,revealCodeEntry:t,setStatus:m}=r;function f(p){if(!a)return;const g={email:p||null,sentAt:Date.now()};try{chrome.storage.local.set({[i]:g})}catch{}}function S(){try{chrome.storage.local.remove([i])}catch{}}function u(p){if(!a||!p)return;const{sentAt:g,email:h}=p||{};h&&!o.value&&(o.value=h),typeof g=="number"&&Date.now()-g<s?(t(),m("Enter the code we emailed you.","info")):S()}return{persistOtpState:f,clearOtpState:S,restoreOtpState:u}}function le(r){const{codeInput:a,verifyButton:i,statusElement:s,activationSection:o,mainContent:t,onAuthenticated:m}=r;function f(p,g="info"){s.textContent=p,s.className=`activation-status ${g}`,s.classList.remove("hidden")}function S(){var p,g,h;const C=(p=a?.closest)==null?void 0:p.call(a,".hidden");C&&C.classList.remove("hidden"),(h=(g=i?.classList)==null?void 0:g.remove)==null||h.call(g,"hidden")}function u(){o&&(o.style.display="none",o.classList.add("hidden")),t&&(t.style.removeProperty("display"),t.classList.remove("hidden")),m?.()}return{setStatus:f,revealCodeEntry:S,showMain:u}}function ce(r){var a,i,s;const{entitlement:o,siteConfig:t,emailInput:m,codeInput:f,sendButton:S,verifyButton:u,statusElement:p,activationSection:g,mainContent:h,lastEmailKey:C="authEmail",onAuthenticated:e,requireCode:n,logger:d}=r||{};if(!m||!f||!S||!u||!p)throw new Error("initOtpPopup: missing required DOM elements");const c={info:(...b)=>{var T;return(T=d?.info)==null?void 0:T.call(d,...b)},warn:(...b)=>{var T;return(T=d?.warn)==null?void 0:T.call(d,...b)},error:(...b)=>{var T;return(T=d?.error)==null?void 0:T.call(d,...b)}},w=o||((a=t?.AUTH)==null?void 0:a.entitlement)||t?.authEntitlement||t?.ENTITLEMENT||t?.SITE_NAME||"default-entitlement",v=String(w).replace(/[^a-z0-9_-]+/gi,"-"),B=r?.otpStateKey||`otpState:${v}`,P=typeof r?.otpStateTtlMs=="number"?r.otpStateTtlMs:600*1e3,O=typeof n=="boolean"?n:((i=t?.AUTH)==null?void 0:i.requiresCode)!==!1&&((s=t?.AUTH)==null?void 0:s.otp)!==!1,{setStatus:l,revealCodeEntry:_,showMain:L}=le({codeInput:f,verifyButton:u,statusElement:p,activationSection:g,mainContent:h,onAuthenticated:e}),{persistOtpState:k,clearOtpState:E,restoreOtpState:$}=se({requireCode:O,otpStateKey:B,otpStateTtlMs:P,emailInput:m,revealCodeEntry:_,setStatus:l}),y=b=>{try{if(!b)return;b.style.display="none",b.classList.add("hidden")}catch{}},U=b=>{try{if(!b)return;b.style.removeProperty("display"),b.classList.remove("hidden")}catch{}};y(g||null),y(h||null);const D=(()=>{try{const b=g?.parentElement||h?.parentElement||document.body;if(!b)return null;const T=document.createElement("div");return T.setAttribute("data-serp-auth-loading","true"),T.textContent="Loading…",T.style.padding="16px",T.style.color="var(--text-subtle, #9aa0a6)",T.style.fontSize="14px",T.style.textAlign="center",g&&g.parentElement===b?b.insertBefore(T,g):b.appendChild(T),T}catch{return null}})(),x=()=>{var b;try{(b=D?.remove)==null||b.call(D)}catch{}};function A(){E(),x(),L()}const R=b=>{const T=String(b||"");return T.includes("Receiving end does not exist")||T.includes("Could not establish connection")||T.includes("message port closed")||T.includes("The message port closed before a response was received")};async function I(){var b;let T=!1;try{const V=await chrome.storage.local.get(["isActivated"]);T=!!(V!=null&&V.isActivated),T&&A()}catch{}const N=T?3:2;for(let V=1;V<=N;V+=1)try{const F=await chrome.runtime.sendMessage({type:"auth/check",name:w});return F!=null&&F.ok?(A(),!0):(x(),U(g||null),y(h||null),!1)}catch(F){const G=F instanceof Error?F.message:String(F);if(R(G)&&V<N){await new Promise(Z=>setTimeout(Z,120*V));continue}if((b=c.warn)==null||b.call(c,"auth/check failed",G),T)return x(),!0;break}return x(),U(g||null),y(h||null),!1}async function H(){const b=m.value.trim();if(!b){l("Enter your email to receive a code.","error");return}S.disabled=!0,l(O?"Sending code...":"Signing in...","loading");try{const T=await chrome.runtime.sendMessage({type:"auth/login",email:b});T!=null&&T.ok?O?(l("Code sent. Check your email.","success"),_(),k(b)):(l("Access granted!","success"),setTimeout(()=>A(),200)):l(T?.error||"Unable to send code.","error")}catch(T){const N=T instanceof Error?T.message:String(T);l(N||"Unable to send code.","error")}finally{S.disabled=!1}}async function q(){const b=m.value.trim();if(!O)return H();const T=f.value.trim();if(!b||!T){l("Enter your email and code.","error");return}u.disabled=!0,l("Verifying...","loading");try{const N=await chrome.runtime.sendMessage({type:"auth/verify",email:b,code:T});if(N!=null&&N.ok){if(l("Checking access...","loading"),!await I()){const V=t!=null&&t.SITE_NAME?String(t.SITE_NAME):String(w);l(`This email does not have access to ${V}.`,"error")}}else l(N?.error||"Invalid code.","error")}catch(N){const V=N instanceof Error?N.message:String(N);l(V||"Verification failed.","error")}finally{u.disabled=!1}}return chrome.storage.local.get([C,B],b=>{b&&b[C]&&(m.value=b[C]),$(b?.[B])}),m.addEventListener("change",()=>{const b=m.value.trim();b&&chrome.storage.local.set({[C]:b})}),S.addEventListener("click",H),u.addEventListener("click",q),I(),{sendCode:H,verifyCode:q,checkAccess:I}}function K(r,a,i){var s;return((s=r?.AUTH)==null?void 0:s[a])||r?.[a]||i}function de(r){var a,i,s;const{root:o,siteConfig:t,ids:m={}}=r||{};if(!o)throw new Error("renderAuthSection: root is required");const f=(L,k)=>m[L]||k,S=o;S.innerHTML="",S.classList.add("activation-section"),S.classList.add("hidden"),S.style.display="none";const u=((a=t?.AUTH)==null?void 0:a.requiresCode)!==!1&&((i=t?.AUTH)==null?void 0:i.otp)!==!1,p=document.createElement("div");p.className="activation-header";const g=document.createElement("h2");g.textContent=K(t,"activationTitle",`Activate ${t?.SITE_NAME||"Downloader"}`),p.appendChild(g);const h=document.createElement("p");h.className="activation-subtitle",h.textContent=K(t,"activationSubtitle","Sign in with your email to unlock the extension"),p.appendChild(h);const C=document.createElement("div");C.className="activation-form";const e=document.createElement("div");e.className="input-group";const n=document.createElement("label");n.setAttribute("for",f("email","activationEmail")),n.textContent="Email";const d=document.createElement("input");d.type="email",d.id=f("email","activationEmail"),d.placeholder="you@example.com",d.autocomplete="email",e.append(n,d);const c=document.createElement("div");c.className="input-group hidden",c.id=f("codeGroup","otpGroup");const w=document.createElement("label");w.setAttribute("for",f("code","activationCode")),w.textContent="Verification Code";const v=document.createElement("input");v.type="text",v.id=f("code","activationCode"),v.placeholder="123456",v.inputMode="numeric",v.autocomplete="one-time-code",c.append(w,v);const B=document.createElement("div");B.className="activation-actions";const P=document.createElement("button");P.id=f("sendButton","sendCodeBtn"),P.className="activate-btn secondary",P.textContent=K(t,"sendCodeLabel","Send Code");const O=document.createElement("button");O.id=f("verifyButton","verifyOtpBtn"),O.className="activate-btn hidden",O.textContent=K(t,"verifyCodeLabel","Verify & Continue"),B.append(P,O);const l=document.createElement("div");l.id=f("status","activationStatus"),l.className="activation-status hidden";const _=((s=t?.AUTH)==null?void 0:s.productUrl)||t?.PRODUCT_URL||null;if(_){const L=document.createElement("a");L.href=_,L.target="_blank",L.rel="noreferrer",L.textContent=K(t,"buyLinkLabel","Buy Product Key"),L.className="buy-key-link",C.append(L)}return C.append(e,c,B,l),S.append(p,C),u||(c.classList.add("hidden"),O.classList.add("hidden"),P.textContent=K(t,"sendCodeLabel","Activate")),{activationSection:S,emailInput:d,codeInput:v,codeGroup:c,sendButton:P,verifyButton:O,statusElement:l}}function ue(r={}){r.getSiteConfig;const a=r.logger||{log:()=>{},warn:()=>{},error:()=>{}};let i=!1;const s=(e,n,d,c,w)=>{if(!e)return!1;const v=`serpBound${d}`;try{if(e.dataset&&e.dataset[v]==="1")return!1;e.dataset&&(e.dataset[v]="1")}catch{}return e.addEventListener(n,c,w),!0},o=(e,n={})=>{var d,c;try{(c=(d=chrome==null?void 0:chrome.runtime)==null?void 0:d.sendMessage)==null||c.call(d,{type:"TELEMETRY_LOG",evt:e,source:"popup",data:n})}catch{}},t=(e={},{timeoutMs:n=5e3}={})=>new Promise(d=>{const c=e.action||e.type||"unknown";let w=null;try{n&&(w=setTimeout(()=>{o("popup.runtime.timeout",{action:c,timeoutMs:n}),d({success:!1,error:"Timed out waiting for response"})},n)),chrome.runtime.sendMessage(e,v=>{w&&clearTimeout(w);const B=chrome.runtime.lastError;if(B){o("popup.runtime.error",{action:c,error:B.message}),d({success:!1,error:B.message});return}if(!v){o("popup.runtime.noResponse",{action:c}),d({success:!1,error:"No response from background"});return}d(v)})}catch(v){w&&clearTimeout(w),o("popup.runtime.exception",{action:c,error:v?.message||String(v)}),d({success:!1,error:v?.message||String(v)})}}),m=()=>{try{const e=getComputedStyle(document.documentElement);o("popup.theme.snapshot",{bg:e.getPropertyValue("--bg-dark"),text:e.getPropertyValue("--text-primary"),accent:e.getPropertyValue("--brand-accent")})}catch{}},f=e=>e?`https://thumbs.externulls.com/videos/${String(e).replace(/^0+/,"")||String(e)}/1523.webp?size=480x270`:null,S=e=>{if(!e)return!1;const n=String(e).trim();return!(!n||n.startsWith("data:"))},u=(e={},n)=>{const d=B=>{if(!S(B))return null;const P=String(B).startsWith("//")?`https:${B}`:String(B);try{return new URL(P,"https://beeg.com/").toString()}catch{return P}},c=String(e?.source||"").toLowerCase().includes("beeg")?f(e.id||e.apiVideoId):null,w=[d(n),d(e.thumbnail),d(c)],v=w.find(B=>B&&String(B).trim());return v?(e.thumbnail=v,o("popup.thumb.chosen",{src:v,apiThumb:!!n,constructed:!!c,order:w.map((B,P)=>B?P:null).filter(B=>B!==null)})):o("popup.thumb.chosen.none",{constructed:c,apiThumb:n,hasInfoThumb:!!e.thumbnail}),v||null};function p(e){if(!e)return"";const n=Math.floor(e/3600),d=Math.floor(e%3600/60),c=Math.floor(e%60);return n>0?`${n}:${d.toString().padStart(2,"0")}:${c.toString().padStart(2,"0")}`:`${d}:${c.toString().padStart(2,"0")}`}function g(e){if(e===0)return"0 Bytes";const n=1024,d=["Bytes","KB","MB","GB"],c=Math.floor(Math.log(e)/Math.log(n));return parseFloat((e/Math.pow(n,c)).toFixed(2))+" "+d[c]}function h(e=[]){if(!Array.isArray(e)||e.length===0)return null;const n=c=>c!=null&&c.height?Number(c.height):(()=>{const w=String(c?.format_id||"").match(/(\d{3,4})/);return w?Number(w[1]):0})()||(c?.format_type==="hls"?1:0);let d={idx:0,score:-1/0};return e.forEach((c,w)=>{const v=n(c);v>d.score&&(d={idx:w,score:v})}),d.idx}async function C(){if(i){o("popup.mainContent.alreadyInitialized",{});return}i=!0;const e={loading:document.getElementById("loading"),error:document.getElementById("error"),errorMessage:document.querySelector(".error-message"),videoInfo:document.getElementById("video-info"),thumbnail:document.getElementById("thumbnail"),title:document.getElementById("video-title"),uploader:document.getElementById("video-uploader"),duration:document.getElementById("video-duration"),views:document.getElementById("video-views"),likes:document.getElementById("video-likes"),dislikes:document.getElementById("video-dislikes"),durationBadge:document.getElementById("duration-badge"),thumbnailPlaceholder:document.getElementById("thumbnail-placeholder"),qualitySelect:document.getElementById("quality-select"),downloadBtn:document.getElementById("download-btn"),downloadProgress:document.getElementById("download-progress"),progressFill:document.querySelector(".progress-fill"),progressText:document.querySelector(".progress-text"),openOptions:document.getElementById("open-options"),viewHistory:document.getElementById("view-history")};let n=null,d=[],c=null,w=0;m(),e.thumbnail&&(s(e.thumbnail,"error","ThumbError",()=>{var l,_;console.warn("popup.thumb.error",{src:(l=e.thumbnail)==null?void 0:l.src}),o("popup.thumb.error",{src:(_=e.thumbnail)==null?void 0:_.src}),e.thumbnailPlaceholder&&e.thumbnailPlaceholder.classList.remove("hidden")}),s(e.thumbnail,"load","ThumbLoad",()=>{var l;o("popup.thumb.loaded",{src:(l=e.thumbnail)==null?void 0:l.src}),e.thumbnailPlaceholder&&e.thumbnailPlaceholder.classList.add("hidden")}));try{const[l]=await chrome.tabs.query({active:!0,currentWindow:!0});c=l?.id??null;const _=String(l?.url||"");if(r.shouldAllowTab&&!r.shouldAllowTab(l)){P("This extension only works on supported pages."),o("popup.page.notAllowed",{url:l?.url});return}if(r.isVideoUrl&&!r.isVideoUrl(l?.url||"")){P("No video found on this page."),o("popup.page.notVideo",{url:l?.url});return}const L=()=>new Promise(E=>{chrome.tabs.sendMessage(l.id,{action:"getVideoInfo"},$=>{const y=chrome.runtime.lastError;if(y){E({success:!1,error:y.message});return}E($||{success:!1,error:"No response"})})}),k=async({maxMs:E=12e3,intervalMs:$=600}={})=>{const y=Date.now();for(;Date.now()-y<E;){const U=await L();if(U!=null&&U.success&&U.data)return U;await new Promise(D=>setTimeout(D,$))}return null};chrome.tabs.sendMessage(l.id,{action:"getVideoInfo"},async E=>{var $,y,U,D,x,A;if(chrome.runtime.lastError){P("Could not connect to the page. Please refresh and try again."),o("popup.videoInfo.connectFail",{error:($=chrome.runtime.lastError)==null?void 0:$.message});return}if(!E||!E.success)if(_.toLowerCase().includes("mindvalley.com/")){P("Press play on the video, then wait a moment…"),o("popup.videoInfo.mindvalley.waiting",{error:E?.error});const H=await k();if(!(H!=null&&H.success)||!H.data){P("No video found on this page."),o("popup.videoInfo.fail",{error:E?.error,lastError:(y=chrome.runtime.lastError)==null?void 0:y.message});return}E=H}else{P("No video found on this page."),o("popup.videoInfo.fail",{error:E?.error,lastError:(U=chrome.runtime.lastError)==null?void 0:U.message});return}n=E.data,a.log("🎬 Received video info in popup:",n),console.log("popup.videoInfo",{hasTitle:!!(n!=null&&n.title),hasThumb:!!(n!=null&&n.thumbnail),id:n?.id,url:n?.url}),o("popup.videoInfo",{hasTitle:!!(n!=null&&n.title),hasThumb:!!(n!=null&&n.thumbnail),id:n?.id,url:n?.url});const R=u(n);R&&e.thumbnail?e.thumbnail.src=R:e.thumbnailPlaceholder&&e.thumbnailPlaceholder.classList.remove("hidden"),v(n);let I=null;try{I=await t({action:"getVideoFormats",videoInfo:n,tabId:c??void 0})}catch(H){a.error("❌ getVideoFormats threw",H?.message||H)}if(a.log("📊 Received formats response:",I),o("popup.formats",{success:!!(I!=null&&I.success),count:((D=I?.formats)==null?void 0:D.length)||0,error:I?.error}),!I){P("Could not retrieve video formats: no response from background."),o("popup.formats.missingResponse",{});return}if(I!=null&&I.success){d=I.formats||[],a.log("📋 Available formats:",d),w=B(d),e.qualitySelect&&typeof w=="number"&&w>=0&&(e.qualitySelect.value=String(w));try{!n.duration&&I.apiDuration&&(n.duration=Number(I.apiDuration),e.duration&&n.duration&&(e.duration.textContent=p(n.duration))),!n.title&&I.apiTitle&&(n.title=String(I.apiTitle),e.title&&(e.title.textContent=n.title));const H=I.apiThumbnail||((x=I.apiMeta)==null?void 0:x.thumbnail),q=u(n,H);q&&e.thumbnail?(e.thumbnail.src=q,(A=e.thumbnailPlaceholder)==null||A.classList.add("hidden")):e.thumbnailPlaceholder&&e.thumbnailPlaceholder.classList.remove("hidden"),console.log("popup.videoInfo.afterFormats",{hasTitle:!!(n!=null&&n.title),hasThumb:!!(n!=null&&n.thumbnail),apiThumb:I.apiThumbnail,used:q}),o("popup.videoInfo.afterFormats",{hasTitle:!!(n!=null&&n.title),hasThumb:!!(n!=null&&n.thumbnail),apiThumb:I.apiThumbnail,used:q})}catch{}}else a.error("❌ Failed to get formats:",I?.error),P("Could not retrieve video formats: "+(I?.error||"Unknown error")),o("popup.formats.fail",{error:I?.error})})}catch(l){a.error("Error:",l),P("An error occurred. Please try again."),o("popup.error",{message:l?.message||String(l)})}function v(l){var _,L,k,E;(_=e.loading)==null||_.classList.add("hidden"),(L=e.videoInfo)==null||L.classList.remove("hidden"),e.title&&(e.title.textContent=l.title||"Untitled Video"),e.thumbnail&&S(l.thumbnail)?(e.thumbnail.src=l.thumbnail,(k=e.thumbnailPlaceholder)==null||k.classList.add("hidden"),o("popup.thumb.set",{src:l.thumbnail})):((E=e.thumbnailPlaceholder)==null||E.classList.remove("hidden"),o("popup.thumb.missing",{reason:"invalid-or-data-uri"})),e.uploader&&l.uploader&&(e.uploader.textContent=`By ${l.uploader}`),e.duration&&l.duration&&(e.duration.textContent=p(l.duration)),e.durationBadge&&l.duration&&(e.durationBadge.textContent=p(l.duration),e.durationBadge.classList.remove("hidden")),e.views&&l.views&&(e.views.textContent=`${l.views} views`),e.likes&&l.likes&&(e.likes.textContent=`👍 ${l.likes}`),e.dislikes&&l.dislikes&&(e.dislikes.textContent=`👎 ${l.dislikes}`)}function B(l){if(!e.qualitySelect||!e.downloadBtn)return;if(e.qualitySelect.innerHTML="",l.length===0){e.qualitySelect.innerHTML='<option value="">No formats available</option>',e.downloadBtn.disabled=!0,o("popup.formats.empty",{});return}o("popup.formats.list",{count:l.length});const _=h(l);return l.forEach((L,k)=>{const E=document.createElement("option");E.value=String(k);let $="Unknown";L.height?$=`${L.height}p`:L.format_id&&(L.format_id.includes("low")?$="240p (Low)":L.format_id.includes("high")?$="480p (High)":L.format_id.includes("hls")?$="720p+ (HLS)":L.format_id.includes("flv")&&($="240p (FLV)"));let y=L.format_type||L.ext||"Unknown";(y==="m3u8"||y==="hls")&&(y="HLS"),E.textContent=`${$} - ${String(y).toUpperCase()}`,k===_&&(E.selected=!0),e.qualitySelect.appendChild(E)}),e.downloadBtn.disabled=!1,o("popup.formats.defaultSelected",{index:_,format:l[_]}),typeof _=="number"?_:0}function P(l){var _,L;(_=e.loading)==null||_.classList.add("hidden"),(L=e.error)==null||L.classList.remove("hidden"),e.errorMessage&&(e.errorMessage.textContent=String(l||"Unknown error")),o("popup.error.display",{message:String(l||"Unknown error")})}s(e.downloadBtn,"click","DownloadClick",async()=>{var l,_,L;if(!e.qualitySelect)return;let k=e.qualitySelect.value;if(!k&&k!=="0"&&d.length>0&&(k=String(typeof w=="number"?w:0),e.qualitySelect.value=k,o("popup.download.autoSelect",{index:Number(k)})),!k&&k!=="0"){P("Please select a quality."),o("popup.download.noSelection",{});return}const E=d[Number(k)];if(!E){P("Selected format unavailable. Please refresh and try again."),o("popup.download.missingFormat",{selectedIndex:Number(k),formatCount:d.length}),e.downloadBtn.disabled=!1,(l=e.downloadProgress)==null||l.classList.add("hidden");return}o("popup.download.click",{selectedIndex:Number(k),format:E}),e.downloadBtn.disabled=!0;const $=E.ext==="m3u8"||E.format_type==="hls"||(E.url||"").includes(".m3u8");e.downloadProgress&&!$&&e.downloadProgress.classList.remove("hidden");try{const y=await t({action:"downloadVideo",videoInfo:{...n,selectedFormat:E},tabId:c??void 0});if(!y){P("Download failed: No response from background"),o("popup.download.noResponse",{}),e.downloadBtn.disabled=!1,(_=e.downloadProgress)==null||_.classList.add("hidden");return}if(y.success){const U=y.result||{},D=U.downloadId??y.downloadId??null,x=typeof U.isHLS=="boolean"?U.isHLS:typeof y.isHLS=="boolean"?y.isHLS:$;if(o("popup.download.start",{isHLS:!!x}),!D){P("Download failed: Missing download id"),o("popup.download.missingDownloadId",{}),e.downloadBtn.disabled=!1,(L=e.downloadProgress)==null||L.classList.add("hidden");return}x?(e.downloadBtn.disabled=!0,e.downloadBtn.textContent="Download Started",e.downloadBtn.style.background="var(--success)",e.downloadProgress&&e.downloadProgress.classList.remove("hidden"),e.progressFill&&(e.progressFill.style.width="0%"),e.progressText&&(e.progressText.textContent="Preparing HLS download (background)…"),O(D,!0)):O(D,!1)}else P("Download failed: "+y.error),o("popup.download.fail",{error:y.error}),e.downloadBtn.disabled=!1,e.downloadProgress&&e.downloadProgress.classList.add("hidden")}catch(y){a.error("Download error:",y),P("Download failed: "+y?.message),o("popup.download.exception",{message:y?.message}),e.downloadBtn.disabled=!1,e.downloadProgress&&e.downloadProgress.classList.add("hidden")}});function O(l,_=!1){let L=-1,k="";const E=setInterval(async()=>{var $,y,U;let D=null;try{D=await t({action:"getDownloadProgress",downloadId:l})}catch(x){o("popup.download.progress.error",{downloadId:l,error:x?.message||String(x)}),clearInterval(E),e.downloadBtn.disabled=!1,($=e.downloadProgress)==null||$.classList.add("hidden");return}if(!D){o("popup.download.progress.noResponse",{downloadId:l}),clearInterval(E),e.downloadBtn.disabled=!1,(y=e.downloadProgress)==null||y.classList.add("hidden");return}if(D&&D.success===!1&&D.error?o("popup.download.progress.responseError",{downloadId:l,error:D.error}):o("popup.download.progress.raw",{downloadId:l,hasProgress:!!(D!=null&&D.progress),status:(U=D?.progress)==null?void 0:U.status}),D&&D.progress)if(e.downloadProgress&&e.downloadProgress.classList.remove("hidden"),typeof l=="number")chrome.downloads.search({id:l},x=>{if(!x||x.length===0)return;const A=x[0];if(A.state==="in_progress"){const R=A.bytesReceived/A.totalBytes*100;e.progressFill&&(e.progressFill.style.width=`${R}%`),e.progressText&&(e.progressText.textContent=`${Math.round(R)}% - ${g(A.bytesReceived)} / ${g(A.totalBytes)}`)}else A.state==="complete"?(e.progressFill&&(e.progressFill.style.width="100%"),e.progressText&&(e.progressText.textContent="Download complete!"),clearInterval(E),setTimeout(()=>{var R;e.downloadBtn.disabled=!1,(R=e.downloadProgress)==null||R.classList.add("hidden"),e.progressFill&&(e.progressFill.style.width="0%"),e.downloadBtn.textContent="Download Video",e.downloadBtn.style.background=""},2e3)):A.state==="interrupted"&&(e.progressText&&(e.progressText.textContent="Download failed!"),clearInterval(E),e.downloadBtn.disabled=!1,setTimeout(()=>{var R;(R=e.downloadProgress)==null||R.classList.add("hidden"),e.progressFill&&(e.progressFill.style.width="0%"),e.downloadBtn.textContent="Download Video",e.downloadBtn.style.background=""},2e3))});else{const x=D.progress,A=typeof x.progress=="number"?Math.max(0,Math.min(100,Math.round(x.progress))):null;if(e.progressFill&&A!==null&&(e.progressFill.style.width=`${A}%`),e.progressText)if(x.status==="error")e.progressText.textContent=`Download failed: ${x.error||""}`;else if(x.status==="complete")e.progressText.textContent="Download complete!";else if(_&&typeof x.segmentIndex=="number"&&typeof x.totalSegments=="number"){const I=A!==null?`${A}%`:"";e.progressText.textContent=`${I} (${x.segmentIndex}/${x.totalSegments} segments)`}else A!==null?e.progressText.textContent=`${A}%`:e.progressText.textContent="Downloading...";(x.status==="complete"||x.status==="error")&&(clearInterval(E),e.downloadBtn.disabled=!1,setTimeout(()=>{var I;(I=e.downloadProgress)==null||I.classList.add("hidden"),e.progressFill&&(e.progressFill.style.width="0%"),e.downloadBtn.textContent="Download Video",e.downloadBtn.style.background=""},1200));const R=`${x.status||""}:${A??-1}`;(A!==L||R!==k)&&(o("popup.download.progress.tick",{downloadId:l,pct:A,status:x.status,seg:x.segmentIndex,total:x.totalSegments}),L=A??L,k=R)}else _&&e.progressText&&(e.progressText.textContent="Preparing HLS download (background)…",e.downloadProgress&&e.downloadProgress.classList.remove("hidden"))},500)}e.openOptions&&s(e.openOptions,"click","OpenOptionsClick",l=>{l.preventDefault(),chrome.runtime.openOptionsPage()}),e.viewHistory&&s(e.viewHistory,"click","ViewHistoryClick",l=>{l.preventDefault(),chrome.tabs.create({url:chrome.runtime.getURL("history.html")})})}return{initializeMainContent:C}}function me(r={}){var a,i,s;const{entitlement:o,siteConfig:t,logger:m=console,shouldAllowTab:f,isVideoUrl:S,renderAuthSection:u,initOtpPopup:p,installConsoleRelay:g,installNetworkRelay:h,logBuildBanner:C,quickHelpHtml:e,uiStrings:n={},telemetrySource:d="popup",bannerLabel:c="POPUP_LOAD",onReady:w}=r,v={pageTitle:n.pageTitle||"Video Downloader",headerTitle:n.headerTitle||"Video Downloader",helpHeading:n.helpHeading||"How to download:",helpHtml:e||n.helpHtml||""};typeof g=="function"&&g({source:d}),typeof h=="function"&&h({source:d});try{(i=(a=chrome==null?void 0:chrome.runtime)==null?void 0:a.sendMessage)==null||i.call(a,{type:"TELEMETRY_LOG",evt:"build.banner",data:{message:`#################################
POPUP LOAD
#################################`,ts:Date.now()}}),typeof C=="function"&&C({log:(O,l)=>{var _,L;return(L=(_=chrome==null?void 0:chrome.runtime)==null?void 0:_.sendMessage)==null?void 0:L.call(_,{type:"TELEMETRY_LOG",evt:O,data:l})}},c)}catch(O){(s=m?.warn)==null||s.call(m,"popup.telemetry.init.error",O)}const B=ue({logger:m,shouldAllowTab:f,isVideoUrl:S});function P(){var O,l;(O=document.getElementById("activationSection"))==null||O.classList.add("hidden"),(l=document.getElementById("mainContent"))==null||l.classList.remove("hidden"),B.initializeMainContent()}return document.addEventListener("DOMContentLoaded",()=>{var O,l,_,L;const k=document.getElementById("activationSection"),E=document.getElementById("mainContent"),$=document.getElementById("quickHelpBtn"),y=document.getElementById("quickHelpBanner"),U=(O=y?.querySelector)==null?void 0:O.call(y,".quick-help-text"),D=(l=y?.querySelector)==null?void 0:l.call(y,".quick-help-heading"),x=(_=document.querySelector)==null?void 0:_.call(document,".header h1");try{document.title=v.pageTitle,x&&(x.textContent=v.headerTitle),D&&(D.textContent=v.helpHeading)}catch{}U&&v.helpHtml&&(U.innerHTML=v.helpHtml);let A=null;if($&&y&&$.addEventListener("click",()=>{A&&(clearTimeout(A),A=null),y.classList.remove("hidden"),A=setTimeout(()=>{y.classList.add("hidden"),A=null},6e3)}),!k||!E||typeof u!="function"||typeof p!="function"){(L=m?.warn)==null||L.call(m,"popup.bootstrap.missingElements");return}const{emailInput:R,codeInput:I,codeGroup:H,sendButton:q,verifyButton:b,statusElement:T}=u({root:k,siteConfig:t});p({entitlement:o,siteConfig:t,emailInput:R,codeInput:I,sendButton:q,verifyButton:b,statusElement:T,activationSection:k,mainContent:E,onAuthenticated:()=>{var N,V;(V=(N=H?.classList)==null?void 0:N.remove)==null||V.call(N,"hidden"),P()},logger:m}),typeof w=="function"&&w({activationSection:k,mainContent:E,downloadPopup:B})}),{downloadPopup:B}}const he=r=>{var a;try{typeof chrome<"u"&&(a=chrome==null?void 0:chrome.runtime)!=null&&a.sendMessage&&chrome.runtime.sendMessage({type:"TELEMETRY_LOG",...r})}catch{}};function ee(r="unknown",a){const i=typeof a=="function"?a:he;return(s,o={})=>i({evt:s,source:r,data:o})}function fe(){return typeof window<"u"?window:typeof self<"u"?self:typeof globalThis<"u"?globalThis:void 0}function pe(r={}){const a=r.source||"page",i=r.globalThisOverride||fe();if(!i||!i.console)return;const s=`__telemetryConsoleRelayInstalled__${a}`;if(i[s])return;i[s]=!0;const o=ee(a,r.send);["log","info","warn","error","debug"].forEach(t=>{try{const m=i.console[t];i.console[t]=(...f)=>{try{o(`console.${t}`,{args:f})}catch{}return m?.apply(i.console,f)}}catch{}});try{i.addEventListener&&(i.addEventListener("error",t=>{var m;o("error",{message:t?.message,filename:t?.filename,lineno:t?.lineno,colno:t?.colno,stack:(m=t?.error)==null?void 0:m.stack})}),i.addEventListener("unhandledrejection",t=>{var m,f;o("unhandledrejection",{reason:((m=t?.reason)==null?void 0:m.message)||String(t?.reason||""),stack:(f=t?.reason)==null?void 0:f.stack})}))}catch{}}function ge(){return typeof window<"u"?window:typeof self<"u"?self:typeof globalThis<"u"?globalThis:void 0}function ye(r={}){const a=r.source||"page",i=r.globalThisOverride||ge();if(!i||typeof i.fetch!="function")return;const s=`__telemetryFetchRelayInstalled__${a}`;if(i[s])return;i[s]=!0;const o=ee(a,r.send),t=!!r.logSuccess,m=i.fetch.bind(i);i.fetch=async(...f)=>{const S=Date.now();try{const u=await m(...f);if(t||!(u!=null&&u.ok))try{o("fetch.response",{url:u?.url,status:u?.status,statusText:u?.statusText,durationMs:Date.now()-S})}catch{}return u}catch(u){try{o("fetch.exception",{url:String(f?.[0]||""),message:u?.message||String(u),durationMs:Date.now()-S})}catch{}throw u}}}function be(r={}){pe({source:r.source||"popup",send:r.send})}function we(r={}){ye({source:r.source||"popup",send:r.send,logSuccess:r.logSuccess})}const Q={debug:10,log:20,warn:30,error:40,none:100};function te(){try{return globalThis.SiteConfig&&globalThis.SiteConfig.LOG_LEVEL||"none"}catch{return"none"}}function Te(){try{return!!(globalThis.SiteConfig&&globalThis.SiteConfig.LOG_MIRROR_TO_BG)}catch{return!1}}const ve=typeof window>"u"||!globalThis.document;function z(r){return(Q[r]||100)>=(Q[te()]||100)}function Se(r){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};try{const a=new WeakSet,i=JSON.stringify(r,(s,o)=>{if(typeof o=="function")return`[Function ${o.name||"anonymous"}]`;if(typeof o=="symbol")return o.toString();if(typeof o=="object"&&o!==null){if(a.has(o))return"[Circular]";a.add(o)}return o});return JSON.parse(i)}catch{try{return String(r)}catch{return"[unserializable]"}}}function W(r,a,i){if(!(!Te()||ve))try{if(!(globalThis.chrome&&chrome.runtime&&chrome.runtime.sendMessage))return;const s=(i||[]).map(Se),o=typeof location<"u"&&location&&location.href?location.href:"";chrome.runtime.sendMessage({type:"LOG_MIRROR",level:r,prefix:a||"",args:s,pageUrl:o,ts:Date.now()})}catch{}}function Y(r=""){const a=r?String(r):"";return{debug:(...i)=>{if(z("debug")){try{console.debug(a,...i)}catch{}W("debug",a,i)}},log:(...i)=>{if(z("log")){try{console.log(a,...i)}catch{}W("log",a,i)}},warn:(...i)=>{if(z("warn")){try{console.warn(a,...i)}catch{}W("warn",a,i)}},error:(...i)=>{if(z("error")){try{console.error(a,...i)}catch{}W("error",a,i)}},level:()=>te()}}function Ee(r,a="BUILD"){var i;try{const s=new Date().toISOString(),o=["#################################",`${a} - ${s}`,"#################################"].join(`
`);(i=r?.log)==null||i.call(r,"build.banner",{message:o,ts:s})}catch{}}try{installGlobalLogger()}catch{}function Le(r={},a={}){const{extractVideoInfo:i,fetchApi:s,findM3u8:o,logger:t=Y(a.logPrefix||`🟡 [${(a.siteKey||"content").toUpperCase()}]`),siteKey:m=a.siteKey||"default-content",logMessages:f=a.logMessages===!0,messageMap:S={getVideoInfo:"getVideoInfo",fetchApi:"fetchApi",findM3U8:"findM3U8"}}=r,u=`__contentHarness_${m}_installed`;globalThis[u]||(globalThis[u]=!0,chrome.runtime.onMessage.addListener((p,g,h)=>{var C;const e=p?.action||p?.type;if(f&&e!=="TELEMETRY_LOG")try{t.log("Message received",{type:e,fromTabId:(C=g?.tab)==null?void 0:C.id,keys:Object.keys(p||{})})}catch{}switch(e){case S.getVideoInfo:{if(typeof i!="function")return!1;try{const n=i();h({success:!0,data:n})}catch(n){h({success:!1,error:n?.message||String(n)})}return!0}case S.fetchApi:return typeof s!="function"?!1:(s(p.videoId,p.refererUrl).then(n=>h({success:!0,data:n})).catch(n=>h({success:!1,error:n?.message||String(n)})),!0);case S.findM3U8:{if(typeof o!="function")return!1;try{const n=o(p)||[];h({success:n.length>0,urls:n})}catch(n){h({success:!1,error:n?.message||String(n)})}return!0}default:return!1}}))}function xe(r=typeof document<"u"?document:null){var a,i;const s=(c=[])=>{if(!r)return null;for(const w of c){const v=r.querySelector(`meta[property="${w}"]`)||r.querySelector(`meta[name="${w}"]`),B=v?.getAttribute("content");if(B&&B.trim())return B.trim()}return null},o=c=>{if(!c)return null;const w=parseInt(String(c).replace(/[^\d]/g,""),10);return Number.isFinite(w)?w:null};let t=null;if(r)try{const c=Array.from(r.querySelectorAll('script[type="application/ld+json"]'));for(const w of c)try{const v=JSON.parse(w.textContent||"{}"),B=(Array.isArray(v)?v:[v]).find(P=>P&&(P["@type"]==="VideoObject"||P.type==="VideoObject"));if(B){t=B;break}}catch{}}catch{}const m=t?.name||s(["og:title","twitter:title"])||(r!=null&&r.title?r.title.trim():null)||"Video",f=(Array.isArray(t?.thumbnailUrl)?t.thumbnailUrl[0]:t?.thumbnailUrl)||s(["og:image","twitter:image","og:image:secure_url"]),S=typeof f=="string"&&f.startsWith("data:")?null:f,u=t?.description||s(["og:description","description","twitter:description"]),p=o(t?.duration||s(["video:duration","duration","og:video:duration"])),g=t?.width||s(["og:video:width","video:width"]),h=t?.height||s(["og:video:height","video:height"]),C=g&&parseInt(g,10)||null,e=h&&parseInt(h,10)||null,n=((a=t?.author)==null?void 0:a.name)||((i=t?.publisher)==null?void 0:i.name)||s(["author","video:actor","video:director"])||null,d=[];return d.push("title"),S&&d.push("thumbnail"),u&&d.push("description"),p&&d.push("duration"),(C||e)&&d.push("dimensions"),n&&d.push("owner"),{title:m,thumbnail:S,description:u,duration:p,width:C,height:e,owner:n,foundKeys:d}}function ne(r,{stripLeadingZeros:a=!0}={}){const i=[],s=String(r||"");if(s&&i.push(s),a&&s){const o=s.replace(/^0+/,"")||s;o&&o!==s&&i.push(o)}return Array.from(new Set(i.filter(Boolean)))}async function Ie(r,a=120){var i,s;const o=await r.text();try{return JSON.parse(o)}catch{const t=((s=(i=r.headers)==null?void 0:i.get)==null?void 0:s.call(i,"content-type"))||"unknown",m=o.slice(0,a);throw new Error(`Unexpected response (content-type: ${t}): ${m}${o.length>a?"…":""}`)}}async function Pe(r=[],a={}){const{headers:i={},requestInit:s={},parse:o=Ie,log:t=()=>{}}=a;let m=null;for(const f of r){const{url:S,attemptEvent:u,successEvent:p,failEvent:g}=f||{};if(S){t(u||"fetch.attempt",{url:S,endpoint:f});try{const h=await fetch(S,{credentials:"omit",mode:"cors",...s,headers:{...s.headers||{},...i}});if(!h.ok)throw new Error(`HTTP ${h.status}`);const C=await o(h);return p&&t(p,{url:S,endpoint:f}),C}catch(h){m=h,t(g||"fetch.fail",{url:S,endpoint:f,error:h?.message||String(h)})}}}throw m||new Error("All endpoints failed")}async function Ae(r,a,i={}){const s=Array.isArray(r)?Array.from(new Set(r.filter(Boolean))):ne(r,i.variantOptions);let o=null;for(const t of s)try{const m=typeof a=="function"?a(t):[];return await Pe(m,i)}catch(m){o=m}throw o||new Error("All ID variants failed")}function Be(r){const a=String(r);return[{url:`https://beeg.com/api/v6/video/${a}`,attemptEvent:"beeg.bg.fetch",failEvent:"beeg.bg.fetch.fail"},{url:`https://video.beeg.com/api/v6/video/${a}`,attemptEvent:"beeg.bg.fetch",failEvent:"beeg.bg.fetch.fallback.fail"},{url:`https://store.externulls.com/facts/file/${a}`,attemptEvent:"beeg.bg.fetch",failEvent:"beeg.bg.fetch.externulls.fail",successEvent:"beeg.bg.fetch.externulls.success"}]}const M=Y("🟡 [Beeg Detect]");function _e(){var r,a,i,s,o;const t={source:"beeg",url:window.location.href,title:"",id:"",apiVideoId:"",thumbnail:"",duration:0,meta:{}};M.log("extractVideoInfo: start",{href:t.url});const m=e=>{try{const n=parseInt(e,10);return Number.isFinite(n)?n:0}catch{return 0}},f=e=>{try{const n=String(e||"").match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/i);if(!n)return 0;const d=m(n[1]||0),c=m(n[2]||0),w=m(n[3]||0);return d*3600+c*60+w}catch{return 0}},S=e=>{try{const n=String(e||"").trim().split(":").map(m);return n.length===2?n[0]*60+n[1]:n.length===3?n[0]*3600+n[1]*60+n[2]:0}catch{return 0}},u=new URL(window.location.href),p=u.pathname||"";let g=p.match(/(?:^|\/)video\/(\d+)(?:\/?|$)/)||p.match(/(?:^|\/)watch\/(\d+)(?:\/?|$)/)||p.match(/(?:^|\/)\D*(\d{5,})(?:\/?|$)/)||u.href.match(/(?:-|\/)\s*(\d{5,})(?:\/?|$)/);if(g&&g[1]&&(t.id=g[1],t.apiVideoId=t.id,M.log("ID detected from URL",{path:p,match:g[0],id:t.id})),!t.id){const e=document.querySelector('meta[property="og:url"]'),n=(r=e?.content)==null?void 0:r.match(/(\d{5,})/);n&&(t.id=n[1],t.apiVideoId=t.id,M.log("ID from og:url",{ogUrl:e?.content,id:t.id}))}if(!t.id)try{const e=Array.from(document.scripts).slice(0,30);for(const n of e){const d=n.textContent||"";let c=d.match(/"video_id"\s*[:=]\s*(\d{5,})/);if(c||(c=d.match(/"videoId"\s*[:=]\s*"?(\d{5,})"?/)),c||(c=d.match(/[^a-zA-Z]id"?\s*[:=]\s*"?(\d{5,})"?/)),c){t.id=c[1],t.apiVideoId=t.id,M.log("ID from inline script",{id:t.id});break}}}catch(e){M.warn("Script scan for ID failed",e?.message||e)}if(!t.id){const e=document.querySelector("[data-video-id], [data-id], [data-videoid]"),n=e?.getAttribute("data-video-id")||e?.getAttribute("data-id")||e?.getAttribute("data-videoid"),d=n?.match(/\d{5,}/);d&&(t.id=d[0],t.apiVideoId=t.id,M.log("ID from data-* attribute",{id:t.id}))}try{const e=[];t.id&&e.push(t.id);const n=t.id?t.id.replace(/^0+/,""):null;n&&n!==t.id&&e.push(n),e.length&&(window.__beegPageData=window.__beegPageData||{},window.__beegPageData.videoIdVariants=e)}catch{}const h=document.querySelector('meta[property="og:title"]');h!=null&&h.content&&(t.title=h.content.trim(),M.log("Title from og:title",t.title));const C=document.querySelector('meta[property="og:image"]');if(C!=null&&C.content&&(t.thumbnail=C.content.trim(),M.log("Thumbnail from og:image",t.thumbnail)),!t.title){const e=document.querySelector('meta[name="twitter:title"], meta[property="twitter:title"]');e!=null&&e.content&&(t.title=e.content.trim(),M.log("Title from twitter:title",t.title))}if(!t.title){const e=(document.title||"").trim();if(e){const n=e.replace(/\s*[|-]\s*beeg.*$/i,"").trim();t.title=n||e,M.log("Title from document.title",t.title)}}if(!t.thumbnail){const e=document.querySelector('meta[property="og:image:secure_url"]'),n=document.querySelector('meta[name="twitter:image"], meta[property="twitter:image"]'),d=e&&e.content||n&&n.content;d&&(t.thumbnail=d.trim(),M.log("Thumbnail from twitter/og secure",t.thumbnail))}if(!t.duration){const e=document.querySelector('meta[property="video:duration"], meta[itemprop="duration"]');if(e!=null&&e.content){const n=f(e.content)||S(e.content);n&&(t.duration=n,M.log("Duration from meta",n))}}if(!t.thumbnail)try{const e=Array.from(document.querySelectorAll("img")).map(n=>({img:n,area:(n.width||0)*(n.height||0)})).sort((n,d)=>d.area-n.area)[0];(a=e?.img)!=null&&a.src&&(t.thumbnail=new URL(e.img.src,document.baseURI).href,M.log("Thumbnail from best img",t.thumbnail))}catch(e){M.warn("Thumbnail selection failed",e?.message||e)}try{(s=(i=chrome==null?void 0:chrome.runtime)==null?void 0:i.sendMessage)==null||s.call(i,{type:"TELEMETRY_LOG",evt:"content.thumb.selected",data:{thumbnail:t.thumbnail,id:t.id,hasThumb:!!t.thumbnail}})}catch{}if(!t.thumbnail&&(o=window.__beegPageData)!=null&&o.apiThumbnail)try{t.thumbnail=new URL(window.__beegPageData.apiThumbnail,document.baseURI).href,M.log("Thumbnail from cached API thumb",t.thumbnail)}catch{}try{const e=xe(document);!t.title&&e.title&&(t.title=e.title,M.log("Title from generic metadata",t.title));const n=typeof e.thumbnail=="string"&&e.thumbnail.startsWith("data:")?null:e.thumbnail;!t.thumbnail&&n&&(t.thumbnail=n,M.log("Thumbnail from generic metadata",t.thumbnail)),!t.duration&&e.duration&&(t.duration=e.duration,M.log("Duration from generic metadata",t.duration))}catch{}return M.log("extractVideoInfo: complete",{id:t.id,title:t.title,hasThumb:!!t.thumbnail,duration:t.duration}),t}async function Ce(r,a){var i;const s=[];try{if((i=window.__beegPageData)!=null&&i.videoIdVariants)for(const u of Object.values(window.__beegPageData.videoIdVariants))typeof u=="string"&&u.trim()&&s.push(u.trim())}catch{}const o=Array.from(new Set([...ne(r),...s]));M.log("fetchBeegAPI: id variants",o);const t={Accept:"application/json, text/plain, */*",Referer:a||window.location.href,Origin:"https://beeg.com","User-Agent":navigator.userAgent},m=(u,p)=>M.log(u,p),f=u=>{var p;try{let g=null;if((p=u?.file)!=null&&p.thumb&&(g=u.file.thumb),!g&&Array.isArray(u?.fc_facts)){const h=u.fc_facts.find(C=>C?.thumb);h&&(g=h.thumb)}g&&(window.__beegPageData=window.__beegPageData||{},window.__beegPageData.apiThumbnail=g)}catch{}return u},S=async u=>{var p,g;const h=await u.text();try{const C=JSON.parse(h);return f(C)}catch{const C=((g=(p=u.headers)==null?void 0:p.get)==null?void 0:g.call(p,"content-type"))||"unknown",e=h.substring(0,120);throw new Error(`Unexpected response (content-type: ${C}): ${e}${h.length>120?"…":""}`)}};try{return await Ae(o,u=>Be(u),{headers:t,log:m,parse:S})}catch(u){throw M.log("fetchBeegAPI: all variants failed",{error:u?.message||String(u)}),u}}function ke(){Le({extractVideoInfo:_e,fetchApi:Ce,logger:M,siteKey:"beeg",messageMap:{getVideoInfo:"getVideoInfo",fetchApi:"fetchBeegAPI"}},{logPrefix:"🟡 [Beeg Detect]"})}function Oe(){ke()}try{typeof chrome<"u"&&Oe()}catch{}const De=Y("🟣 [ThisVid Popup]"),Me="thisvid-downloader",X="ThisVid Downloader";me({entitlement:Me,siteConfig:SiteConfig,logger:De,renderAuthSection:de,initOtpPopup:ce,installConsoleRelay:be,installNetworkRelay:we,logBuildBanner:Ee,uiStrings:{pageTitle:X,headerTitle:X}});
