itube-modern-player 0.8.1 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -890,6 +890,16 @@ npm publish # prepublishOnly прогонит typecheck + build
890
890
 
891
891
  Версионирование по [SemVer](https://semver.org/lang/ru/): `major.minor.patch`.
892
892
 
893
+ ### 0.8.3
894
+
895
+ - **Фикс: после прямого клика по плейсхолдеру поверх играющего видео оставался плейсхолдер/постер-оверлей.** Ролик стартовал (таймер тикал, звук шёл), но событие **`play` не эмитилось вовсе**: жест-`play()` без источника оставлял элемент в состоянии `paused === false`, и при реальном старте перехода paused→playing не происходило. Всё, что завязано на `play` — скрытие постера/заглушки (в т.ч. интеграционные `@play`-обработчики), `playedOnce`, стейт кнопок — не срабатывало. Теперь жест-разблокировка — канонический `play()`+`pause()` синхронно в жесте (активация на элементе сохраняется), а ядро дополнительно нормализует любой переданный `videoElement` с «фантомным» воспроизведением; `play` снова эмитится при каждом реальном старте. Со свайпа/фонового триггера работало и раньше (там жест-элемент не создаётся) — ломал именно прямой клик.
896
+
897
+ ### 0.8.2
898
+
899
+ - **Фикс: тап по плейсхолдеру на мобиле всё ещё мог «только инициализировать» плеер** (довершение фикса двойного тапа из 0.8.1) — закрыты две гонки:
900
+ 1. На быстром/закэшированном чанке `touchstart`-предзагрузка (`loadOn: 'placeholder'`) успевала **свопнуть плейсхолдер из-под пальца** посреди тапа — `click` умирал на отсоединённой ноде, намерение «играть» и жест-разблокировка терялись. Теперь при активном нажатии конструирование плеера откладывается до завершения тапа: клик успевает зарегистрировать намерение (в т.ч. блессинг видео), затем плеер конструируется и стартует; скролл-отмена (`pointercancel`) конструирует сразу, без автостарта. Исправлено и в `createLazyPlayer`, и во Vue-`lazy`.
901
+ 2. Безсорсовый `play()` жест-разблокировки (`gesture.ts`) в некоторых движках не реджектится, а висит до появления источника — и резолвится в момент **реального** старта видео; его success-обработчик (`video.pause()`) ставил только что запущенное видео на паузу. Теперь success-ветка — no-op.
902
+
893
903
  ### 0.8.1
894
904
 
895
905
  - **Новый мобильный лейаут по умолчанию** — `controls.mobileLayout: 'bar' | 'center'`. `'bar'` (default): поверх видео остаются только ±N-перемотка и большая play (как на десктопе), а кнопка play и «следующее видео» доступны в нижнем баре слева — по аналогии с десктопом. `'center'` — прежний вариант (prev · −N · play · +N · next кластером по центру, play/next в баре скрыты); вернуть старое поведение: `controls: { mobileLayout: 'center' }`.
package/dist/core.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";var pt=Object.create;var X=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var ft=Object.getOwnPropertyNames;var vt=Object.getPrototypeOf,gt=Object.prototype.hasOwnProperty;var yt=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ft(t))!gt.call(r,s)&&s!==e&&X(r,s,{get:()=>t[s],enumerable:!(i=mt(t,s))||i.enumerable});return r};var bt=(r,t,e)=>(e=r!=null?pt(vt(r)):{},yt(t||!r||!r.__esModule?X(e,"default",{value:r,enumerable:!0}):e,r));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const $=require("./placeholder.cjs"),V=require("./labels-BOrrLImF.cjs");function a(r,t,e){const i=document.createElement(r);if(t&&(i.className=t),e)for(const[s,n]of Object.entries(e))i.setAttribute(s,n);return i}function _(r,t){if(r.textContent="",typeof t=="object"){"url"in t?r.append(a("img","imp-icon-img",{src:t.url,alt:""})):r.innerHTML=t.svg;return}/^\s*</.test(t)?r.innerHTML=t:r.append(a("img","imp-icon-img",{src:t,alt:""}))}function T(r,t=""){const e=a("img","imp-cover-img",{alt:t,decoding:"async"});return e.src=r,e}function b(r,t,e){const i=a("button",`imp-btn ${r}`,{type:"button","aria-label":t,title:t});return _(i,e),i}function Y(r,t){const e=a("div",`${t}__meta`);return r.forEach((i,s)=>{s>0&&e.append(document.createTextNode(" "));const n=typeof i=="string"?i:i.text,o=typeof i=="string"?void 0:i.icon,l=a("span",`${t}__meta-chunk`);if(o){const h=a("span",`${t}__meta-icon`);_(h,o),l.append(h)}l.append(document.createTextNode(n)),e.append(l)}),e}function I(r,t,e){_(r,t),e!==void 0&&(r.setAttribute("aria-label",e),r.setAttribute("title",e))}function x(r,t,e){return Math.min(e,Math.max(t,r))}function L(r){if(!Number.isFinite(r)||r<0)return"0:00";const t=Math.floor(r%60),e=Math.floor(r/60%60),i=Math.floor(r/3600),s=i>0?String(e).padStart(2,"0"):String(e),n=String(t).padStart(2,"0");return i>0?`${i}:${s}:${n}`:`${s}:${n}`}function D(r){const t=r.trim().match(/^(?:(\d+):)?(\d{1,2}):(\d{2})(?:[.,](\d{1,3}))?$/);if(!t)return null;const e=t[1]?Number(t[1]):0,i=Number(t[2]),s=Number(t[3]),n=t[4]?Number(t[4].padEnd(3,"0")):0;return e*3600+i*60+s+n/1e3}function tt(r){const t=[],e=r.replace(/\r\n?/g,`
2
2
  `).split(/\n\n+/);for(const i of e){const s=i.split(`
3
3
  `).filter(f=>f.trim()!=="");if(s.length===0)continue;let n=s.findIndex(f=>f.includes("-->"));if(n===-1)continue;const[o,l]=s[n].split("-->"),h=D(o),c=D((l??"").split(" ")[1]??l??"")??D(l??"");if(h===null||c===null)continue;const u=s.slice(n+1).join(`
4
- `).trim();u&&t.push({start:h,end:c,text:u})}return t}function kt(r,t){try{return new URL(r,new URL(t,window.location.href)).toString()}catch{return r}}class et{constructor(){this.listeners=new Map}on(t,e){let i=this.listeners.get(t);return i||(i=new Set,this.listeners.set(t,i)),i.add(e),()=>this.off(t,e)}once(t,e){const i=this.on(t,s=>{i(),e(s)});return i}off(t,e){this.listeners.get(t)?.delete(e)}emit(t,e){const i=this.listeners.get(t);if(i)for(const s of[...i])try{s(e)}catch(n){console.error("[itube-player] listener error",n)}}removeAll(){this.listeners.clear()}}const g=(r,t="0 0 24 24")=>`<svg viewBox="${t}" fill="currentColor" aria-hidden="true" focusable="false">${r}</svg>`,it={play:g('<path d="M8 5.14v13.72c0 .8.87 1.3 1.56.88l10.54-6.86a1.05 1.05 0 0 0 0-1.76L9.56 4.26C8.87 3.84 8 4.34 8 5.14Z"/>'),pause:g('<rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/>'),replay:g('<path d="M12 5V2.5L7.5 6 12 9.5V7a5 5 0 1 1-5 5H5a7 7 0 1 0 7-7Z"/>'),bigPlay:g('<path d="M8 5.14v13.72c0 .8.87 1.3 1.56.88l10.54-6.86a1.05 1.05 0 0 0 0-1.76L9.56 4.26C8.87 3.84 8 4.34 8 5.14Z"/>'),volumeHigh:g('<path d="M4 9v6h3.5L12 19.5v-15L7.5 9H4Z"/><path d="M14.5 8.6a4.5 4.5 0 0 1 0 6.8v-1.9a2.5 2.5 0 0 0 0-3v-1.9Z"/><path d="M14.5 5.2a8 8 0 0 1 0 13.6v-2a6 6 0 0 0 0-9.6v-2Z"/>'),volumeLow:g('<path d="M4 9v6h3.5L12 19.5v-15L7.5 9H4Z"/><path d="M14.5 8.6a4.5 4.5 0 0 1 0 6.8v-1.9a2.5 2.5 0 0 0 0-3v-1.9Z"/>'),volumeMute:g('<path d="M4 9v6h3.5L12 19.5v-15L7.5 9H4Z"/><path d="m15.3 9.3 1.4 1.4 1.4-1.4 1.4 1.4-1.4 1.4 1.4 1.4-1.4 1.4-1.4-1.4-1.4 1.4-1.4-1.4 1.4-1.4-1.4-1.4 1.4-1.4Z"/>'),fullscreen:g('<path d="M5 5h5v2H7v3H5V5Zm9 0h5v5h-2V7h-3V5ZM5 14h2v3h3v2H5v-5Zm12 0h2v5h-5v-2h3v-3Z"/>'),fullscreenExit:g('<path d="M10 10H5V8h3V5h2v5Zm4 0V5h2v3h3v2h-5Zm-4 4v5H8v-3H5v-2h5Zm4 0h5v2h-3v3h-2v-5Z"/>'),pip:g('<path d="M3 5h18v14H3V5Zm2 2v10h14V7H5Z"/><rect x="12" y="11" width="6" height="4"/>'),settings:g('<path d="M12 8.5A3.5 3.5 0 1 0 12 15.5 3.5 3.5 0 0 0 12 8.5Zm0 2a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3Z"/><path d="M10.3 2.8 9.9 5.1a7 7 0 0 0-1.5.86l-2.2-.8-1.7 3 1.8 1.5a7 7 0 0 0 0 1.7l-1.8 1.5 1.7 3 2.2-.8c.46.36.97.65 1.5.86l.4 2.3h3.4l.4-2.3a7 7 0 0 0 1.5-.86l2.2.8 1.7-3-1.8-1.5a7 7 0 0 0 0-1.7l1.8-1.5-1.7-3-2.2.8a7 7 0 0 0-1.5-.86l-.4-2.3h-3.4Zm1.7 5.7a3.5 3.5 0 1 1 0 7 3.5 3.5 0 0 1 0-7Z"/>'),speed:g('<path d="M12 4a9 9 0 0 0-9 9 8.96 8.96 0 0 0 1.62 5.16l1.64-1.15A7 7 0 0 1 5 13a7 7 0 1 1 12.74 4.01l1.64 1.15A8.96 8.96 0 0 0 21 13a9 9 0 0 0-9-9Z"/><path d="m15.6 8.3-3.95 3.13a1.5 1.5 0 1 0 1.92 1.92L16.7 9.4a.78.78 0 0 0-1.1-1.1Z"/>'),scenes:g('<path d="M3 5h18v14H3V5Zm2 2v10h3V7H5Zm5 0v10h9V7h-9Zm-5 3h3v1H5v-1Zm0 3h3v1H5v-1Z"/>'),shuffle:g('<path d="M4 6h2.6c1.5 0 2.9.7 3.8 1.9l4.1 5.4a2.75 2.75 0 0 0 2.2 1.1H19l-1.8-1.8 1.4-1.4 4.2 4.2-4.2 4.2-1.4-1.4L19 16.4h-2.3a4.75 4.75 0 0 1-3.8-1.9L8.8 9.1A2.75 2.75 0 0 0 6.6 8H4V6Z"/><path d="M19 7.6h-2.3c-.86 0-1.67.41-2.18 1.1l-.93 1.23-1.25-1.65.58-.77A4.75 4.75 0 0 1 16.7 5.6H19L17.2 3.8l1.4-1.4 4.2 4.2-4.2 4.2-1.4-1.4L19 7.6Z" transform="translate(0 1.2)"/>'),repeat:g('<path d="M7 7h10v2.5L21 6l-4-3.5V5H5v6h2V7Zm10 10H7v-2.5L3 18l4 3.5V19h12v-6h-2v4Z"/>'),subtitles:g('<path d="M3 5h18v14H3V5Zm2 2v10h14V7H5Zm2 3h6v2H7v-2Zm8 0h2v2h-2v-2ZM7 14h2v2H7v-2Zm4 0h6v2h-6v-2Z"/>'),list:g('<path d="M4 6h2v2H4V6Zm4 0h12v2H8V6ZM4 11h2v2H4v-2Zm4 0h12v2H8v-2ZM4 16h2v2H4v-2Zm4 0h12v2H8v-2Z"/>'),next:g('<path d="M6 5.5v13c0 .77.84 1.25 1.5.85l9-6.5a1 1 0 0 0 0-1.7l-9-6.5c-.66-.4-1.5.08-1.5.85Z"/><rect x="17" y="5" width="2.5" height="14" rx="1"/>'),previous:g('<path d="M18 5.5v13c0 .77-.84 1.25-1.5.85l-9-6.5a1 1 0 0 1 0-1.7l9-6.5c.66-.4 1.5.08 1.5.85Z"/><rect x="4.5" y="5" width="2.5" height="14" rx="1"/>'),seekForward:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>',seekBack:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg>',like:g('<path d="M9 21H5a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h4v11Zm2 0h7.1a2 2 0 0 0 2-1.6l1.3-7a2 2 0 0 0-2-2.4H14V5.5A2.5 2.5 0 0 0 11.5 3l-.5.1V10h-.9L11 21Z"/>'),dislike:g('<path d="M15 3h4a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2h-4V3Zm-2 0H5.9a2 2 0 0 0-2 1.6l-1.3 7a2 2 0 0 0 2 2.4H10v4.5A2.5 2.5 0 0 0 12.5 21l.5-.1V14h.9L13 3Z"/>'),addTo:g('<path d="M4 6h12v2H4V6Zm0 4h12v2H4v-2Zm0 4h8v2H4v-2Zm14 0v-4h2v4h4v2h-4v4h-2v-4h-4v-2h4Z"/>'),share:g('<path d="M18 8a3 3 0 1 0-2.83-4H15a3 3 0 0 0 .14 1.06L8.4 8.94a3 3 0 1 0 0 6.12l6.74 3.88A3 3 0 1 0 16 16.6l-6.74-3.88a3.03 3.03 0 0 0 0-1.44L16 7.4c.55.38 1.24.6 2 .6Z"/>'),report:g('<path d="M5 3h2v18H5V3Zm4 1h10l-2.5 4L19 12H9V4Z"/>'),more:g('<circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/>'),close:g('<path d="m6.4 5 5.6 5.6L17.6 5 19 6.4 13.4 12l5.6 5.6-1.4 1.4-5.6-5.6L6.4 19 5 17.6 10.6 12 5 6.4 6.4 5Z"/>'),user:g('<path d="M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm0 2c-3.6 0-8 1.8-8 4.4V21h16v-2.6c0-2.6-4.4-4.4-8-4.4Z"/>'),channel:g('<path d="M3 5h18a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm7 3.5v7l6-3.5-6-3.5Z"/>')},O={en:V.defaultLabels};function wt(r,t){O[r]=t}function xt(r){for(const[t,e]of Object.entries(r))e&&(O[t]=e)}function st(r){return r&&O[r]||V.defaultLabels}function Lt(){return Object.keys(O)}function St(r){const t=[.06,.24,.4,.24,.06],e=r.length;return r.map((i,s)=>t.reduce((n,o,l)=>{const h=Math.min(e-1,Math.max(0,s+l-2));return n+o*r[h]},0))}function _t(r,t){if(r.length===0)return 0;const e=Math.min(r.length-1,Math.max(0,Math.round((r.length-1)*t)));return r[e]}function nt(r,t){if(r.length===0||r.every(n=>n<=0))return[];const e=St(r),i=t==="retention"?_t([...e].sort((n,o)=>n-o),.95):Math.max(...e);if(i<=0)return[];const s=.08;return e.map(n=>s+(1-s)*Math.min(1,Math.max(0,n/i)))}function rt(r,t,e=100){if(r.length===0||!Number.isFinite(t)||t<=0)return[];const i=new Array(e).fill(0);let s=!1;for(const n of r){if(!Number.isFinite(n.time)||n.time<0||n.time>t)continue;const o=Math.max(0,n.value);o!==0&&(i[Math.min(e-1,Math.floor(n.time/t*e))]+=o,s=!0)}return s?nt(i,"peaks"):[]}function Tt(r,t="peaks",e=200){let i=r.map(s=>Number.isFinite(s)?Math.max(0,s):0);if(i.length>e){const s=new Array(e).fill(0),n=new Array(e).fill(0);for(let o=0;o<i.length;o++){const l=Math.min(e-1,Math.floor(o/i.length*e));s[l]+=i[o],n[l]++}i=s.map((o,l)=>n[l]>0?o/n[l]:0)}return nt(i,t)}function ot(r,t=1,e=1e3,i=100){const s=r.length;if(s===0)return"";const n=e/(s-1||1),o=Math.max(0,t)/6,l=u=>{const f=Math.min(s-1,Math.max(0,u));return[f*n,i-r[f]*i]},[,h]=l(0);let c=`M 0 ${i} L 0 ${h.toFixed(1)}`;for(let u=0;u<s-1;u++){const[f,p]=l(u-1),[m,v]=l(u),[y,d]=l(u+1),[k,C]=l(u+2),A=m+(y-f)*o,Z=Math.min(i,Math.max(0,v+(d-p)*o)),P=y-(k-m)*o,R=Math.min(i,Math.max(0,d-(C-v)*o));c+=` C ${A.toFixed(1)} ${Z.toFixed(1)} ${P.toFixed(1)} ${R.toFixed(1)} ${y.toFixed(1)} ${d.toFixed(1)}`}return c+=` L ${e} ${i} Z`,c}async function at(r,t){if(r.src)return{roll:r.roll,mediaUrl:r.src,clickThrough:r.clickUrl,impressions:[],tracking:{}};if(!r.vastTag)throw new Error('Ad roll has neither "vastTag" nor "src"');return lt(r,r.vastTag,t,0,{impressions:[],tracking:{}})}async function lt(r,t,e,i,s){if(i>e.maxWrapperDepth)throw new Error("VAST wrapper depth limit exceeded");const n=new AbortController,o=setTimeout(()=>n.abort(),e.requestTimeout);let l;try{const v=await fetch(t,{signal:n.signal,credentials:"omit"});if(!v.ok)throw new Error(`VAST request failed (${v.status})`);l=await v.text()}finally{clearTimeout(o)}const h=new DOMParser().parseFromString(l,"text/xml");if(h.querySelector("parsererror"))throw new Error("VAST response is not valid XML");const c=h.querySelector("VAST > Ad");if(!c)throw new Error("VAST response contains no ads");Bt(c,s);const u=c.querySelector(":scope > Wrapper");if(u){const v=S(u.querySelector("VASTAdTagURI"));if(!v)throw new Error("VAST wrapper without VASTAdTagURI");return lt(r,v,e,i+1,s)}const f=c.querySelector(":scope > InLine");if(!f)throw new Error("VAST ad has neither InLine nor Wrapper");const p=f.querySelector("Creatives > Creative > Linear");if(!p)throw new Error("VAST ad has no Linear creative");const m=Et(p);if(!m)throw new Error("VAST ad has no playable MediaFile");return{roll:r.roll,mediaUrl:m.url,mediaType:m.type,clickThrough:S(p.querySelector("VideoClicks > ClickThrough"))??r.clickUrl,duration:W(S(p.querySelector(":scope > Duration"))),skipOffset:Mt(p.getAttribute("skipoffset"),W(S(p.querySelector(":scope > Duration")))),impressions:s.impressions,tracking:s.tracking,adTitle:S(f.querySelector(":scope > AdTitle"))??void 0}}function Bt(r,t){var e,i;for(const s of r.querySelectorAll("Impression")){const n=S(s);n&&t.impressions.push(n)}for(const s of r.querySelectorAll("Linear > TrackingEvents > Tracking")){const n=s.getAttribute("event"),o=S(s);!n||!o||["start","firstQuartile","midpoint","thirdQuartile","complete","skip","pause","resume"].includes(n)&&((e=t.tracking)[n]??(e[n]=[])).push(o)}for(const s of r.querySelectorAll("Linear > VideoClicks > ClickTracking")){const n=S(s);n&&((i=t.tracking).click??(i.click=[])).push(n)}}function Et(r){const e=[...r.querySelectorAll("MediaFiles > MediaFile")].map(o=>({url:S(o)??"",type:o.getAttribute("type")??void 0,delivery:o.getAttribute("delivery")??"",bitrate:Number(o.getAttribute("bitrate")??0),apiFramework:o.getAttribute("apiFramework")??""})).filter(o=>o.url&&o.apiFramework.toUpperCase()!=="VPAID").filter(o=>!o.type||/(video\/(mp4|webm|ogg)|application\/(x-mpegurl|vnd\.apple\.mpegurl))/i.test(o.type));if(e.length===0)return null;e.sort((o,l)=>o.bitrate-l.bitrate);const i=e.filter(o=>o.delivery!=="streaming"),s=i.length>0?i:e,n=s[Math.floor(s.length/2)];return{url:n.url,type:n.type}}function W(r){if(!r)return;const t=r.trim().match(/^(?:(\d+):)?(\d{1,2}):(\d{2})(?:\.(\d{1,3}))?$/);if(t)return(t[1]?Number(t[1])*3600:0)+Number(t[2])*60+Number(t[3])+(t[4]?Number(t[4].padEnd(3,"0"))/1e3:0)}function Mt(r,t){if(!r)return;const e=r.trim().match(/^(\d+(?:\.\d+)?)%$/);return e?t!==void 0?Number(e[1])/100*t:void 0:W(r)}function F(r){if(r)for(const t of r)try{new Image().src=t}catch{}}function S(r){return r?.textContent?.trim().replace(/^<!\[CDATA\[|\]\]>$/g,"").trim()||null}class Ct{constructor(t,e){this.host=t,this.playedRolls=new Set,this.sourcesSeen=0,this.activeBreak=null,this.layer=null,this.adVideo=null,this.destroyed=!1,this.opts={skipDelay:5,maxWrapperDepth:3,requestTimeout:8e3,mediaTimeout:1e4,playOn:"every",...e}}ensureAdVideo(){if(!this.adVideo){this.adVideo=a("video","imp-ad__video",{playsinline:""});try{this.adVideo.load()}catch{}}return this.adVideo}get adPlaying(){return this.activeBreak!==null}get hasPendingPreRoll(){return this.pending("preRoll").length>0}resetForNewSource(){if(this.sourcesSeen++,this.opts.playOn==="first"&&this.sourcesSeen>1){for(const t of this.opts.adList)this.playedRolls.add(t);return}this.playedRolls.clear()}async playPreRoll(){await this.playRolls(this.pending("preRoll"))}async playPostRoll(){await this.playRolls(this.pending("postRoll"))}checkMidRolls(t){if(this.adPlaying)return;const e=this.pending("midRoll").filter(i=>i.timer!==void 0&&t>=i.timer);e.length>0&&this.playRolls(e)}pending(t){return this.opts.adList.filter(e=>e.roll===t&&!this.playedRolls.has(e))}async playRolls(t){if(t.length===0||this.destroyed)return;if(this.activeBreak)return this.activeBreak;this.ensureAdVideo();const e=(async()=>{const i=this.host.contentVideo,s=!i.paused&&!i.ended;i.pause();for(const n of t){this.playedRolls.add(n);try{const o=await at(n,this.opts);await this.playAd(o)}catch(o){const l=o instanceof Error?o:new Error(String(o));this.host.emitter.emit("aderror",{roll:n,error:l})}if(this.destroyed)return}(s||t[0].roll==="preRoll")&&i.play().catch(()=>{})})();return this.activeBreak=e.finally(()=>{this.activeBreak=null}),this.activeBreak}playAd(t){return new Promise(e=>{const{labels:i}=this.host,s=a("div","imp-ad"),n=this.ensureAdVideo(),o=new AbortController,l=o.signal;n.src=t.mediaUrl,n.muted=this.host.contentVideo.muted,n.volume=this.host.contentVideo.volume;const h=a("div","imp-spinner imp-ad__spinner"),c=a("div","imp-ad__hud"),u=a("span","imp-ad__badge");u.textContent=t.adTitle?`${i.adLabel} · ${t.adTitle}`:i.adLabel;const f=a("span","imp-ad__countdown");c.append(u,f);const p=a("div","imp-ad__actions");let m=null;t.clickThrough&&(m=a("button","imp-ad__visit",{type:"button"}),m.textContent=i.visitAdvertiser,p.append(m));const v=a("button","imp-ad__skip",{type:"button"});v.hidden=!0,p.append(v),s.append(n,h,c,p),this.host.container.append(s),this.layer=s;const y=t.skipOffset??this.opts.skipDelay,d=new Set,k=w=>{d.has(w)||(d.add(w),F(t.tracking[w]))};let C=Date.now(),A=-1;const Z=setInterval(()=>{if(n.paused){C=Date.now();return}if(n.currentTime!==A){A=n.currentTime,C=Date.now();return}Date.now()-C>=this.opts.mediaTimeout&&(this.host.emitter.emit("aderror",{roll:{roll:t.roll},error:new Error(`Ad media stalled for ${this.opts.mediaTimeout} ms — skipping`)}),P())},500),P=()=>{clearInterval(Z),o.abort(),n.pause(),n.removeAttribute("src"),n.load(),s.remove(),this.layer=null,e()},R=w=>{w?(k("skip"),this.host.emitter.emit("adskip",{ad:t})):k("complete"),this.host.emitter.emit("adend",{ad:t}),P()};n.addEventListener("playing",()=>{F(t.impressions),k("start"),this.host.emitter.emit("adstart",{ad:t})},{once:!0,signal:l}),n.addEventListener("playing",()=>{h.hidden=!0},{signal:l}),n.addEventListener("waiting",()=>{h.hidden=!1},{signal:l}),n.addEventListener("timeupdate",()=>{const w=n.currentTime,B=n.duration;if(Number.isFinite(B)&&B>0&&(f.textContent=L(Math.max(0,B-w)),w/B>=.25&&k("firstQuartile"),w/B>=.5&&k("midpoint"),w/B>=.75&&k("thirdQuartile")),y>=0){const K=Math.ceil(y-w);K>0?(v.hidden=!1,v.disabled=!0,v.textContent=`${i.skipAdIn} ${K}`):(v.hidden=!1,v.disabled=!1,v.textContent=i.skipAd)}},{signal:l}),n.addEventListener("ended",()=>R(!1),{signal:l}),n.addEventListener("error",()=>{this.host.emitter.emit("aderror",{roll:{roll:t.roll},error:new Error("Ad media failed to play")}),P()},{signal:l}),v.addEventListener("click",()=>R(!0));const Q=()=>{t.clickThrough&&(k("click"),this.host.emitter.emit("adclick",{ad:t}),window.open(t.clickThrough,"_blank","noopener"),n.pause())};n.addEventListener("click",Q,{signal:l}),m?.addEventListener("click",Q);let U=!1,N=!1;n.addEventListener("playing",()=>{U=!0},{once:!0,signal:l}),n.addEventListener("pause",()=>{n.ended||!s.isConnected||(s.classList.add("imp-ad--paused"),U&&!N&&(N=!0,F(t.tracking.pause),this.host.emitter.emit("adpause",{ad:t})))},{signal:l}),n.addEventListener("play",()=>{s.classList.remove("imp-ad--paused"),N&&(N=!1,F(t.tracking.resume),this.host.emitter.emit("adresume",{ad:t}))},{signal:l}),s.addEventListener("click",w=>{(w.target===s||s.classList.contains("imp-ad--paused"))&&n.paused&&n.play().catch(()=>{})}),n.play().catch(()=>{s.classList.add("imp-ad--paused")})})}get closeIcon(){return this.host.closeIcon}destroy(){this.destroyed=!0,this.adVideo?.pause(),this.layer?.remove(),this.layer=null,this.adVideo=null}}function z(r,t){const e=[...r].sort((s,n)=>s.start-n.start),i=[];for(let s=0;s<e.length;s++){const n=Math.max(0,e[s].start);if(Number.isFinite(t)&&n>=t)continue;let o=e[s].end??e[s+1]?.start??t;Number.isFinite(t)&&(o=Math.min(o,t)),!(!Number.isFinite(o)||o<=n)&&i.push({start:n,end:o,title:e[s].title})}return i}async function ht(r){const t=await fetch(r);if(!t.ok)throw new Error(`Failed to load chapters VTT (${t.status})`);const e=await t.text();return tt(e).map(i=>({start:i.start,end:i.end,title:i.text}))}function j(r,t){for(const e of r)if(t>=e.start&&t<e.end)return e;return null}function ct(r,t){return t?/application\/(x-mpegurl|vnd\.apple\.mpegurl)/i.test(t):/\.m3u8(\?|#|$)/i.test(r)}let E;async function Pt(){if(E!==void 0)return E;const r=globalThis.Hls;if(r)return E=r,E;try{return E=(await import("hls.js/light")).default,E}catch{return null}}async function At(r,t,e,i){if(ct(t,e)){const s=r.canPlayType("application/vnd.apple.mpegurl"),n=s?null:await Pt();return n&&n.isSupported()?Rt(n,r,t,i):s?(r.src=t,G(r)):(i.onError("HLS is not supported in this browser and hls.js could not be loaded."),G(r))}return r.src=t,G(r)}function G(r){return{kind:"native",levels:[],selected:-1,setLevel(){},destroy(){r.removeAttribute("src"),r.load()}}}function Rt(r,t,e,i){const s=new r({enableWorker:!0}),n={kind:"hls",levels:[],selected:-1,setLevel(c){n.selected=c,s.currentLevel=c},destroy(){s.destroy(),t.removeAttribute("src"),t.load()}};s.on(r.Events.MANIFEST_PARSED,()=>{n.levels=s.levels.map((c,u)=>({index:u,label:c.height?`${c.height}p`:`${Math.round(c.bitrate/1e3)} kbps`})).reverse(),i.onLevels(n.levels)}),s.on(r.Events.LEVEL_SWITCHED,(c,u)=>{const f=s.levels[u.level];f&&i.onLevelSwitch(f.height?`${f.height}p`:`${Math.round(f.bitrate/1e3)} kbps`)});let o=0,l=0,h=!1;return s.on(r.Events.FRAG_BUFFERED,()=>{l=0}),s.on(r.Events.ERROR,(c,u)=>{if(u.fatal)switch(u.type){case r.ErrorTypes.NETWORK_ERROR:l<3?(l++,s.startLoad()):(i.onError(`HLS network error: ${u.details}`,u),s.destroy());break;case r.ErrorTypes.MEDIA_ERROR:o<3?(o++,s.recoverMediaError()):(i.onError(`HLS media error: ${u.details}`,u),s.destroy());break;default:if(h)i.onError(`HLS fatal error: ${u.details}`,u),s.destroy();else{h=!0;try{s.loadSource(e),s.startLoad()}catch{i.onError(`HLS fatal error: ${u.details}`,u),s.destroy()}}}}),s.loadSource(e),s.attachMedia(t),n}class H{constructor(t){this.cues=t}static async load(t){const e=await fetch(t);if(!e.ok)throw new Error(`Failed to load thumbnails VTT (${e.status})`);const i=await e.text(),s=[];for(const n of tt(i)){const[o,l]=n.text.trim().split("#");if(!o)continue;const h={start:n.start,end:n.end,src:kt(o,t)},c=l?.match(/xywh=(\d+),(\d+),(\d+),(\d+)/);c&&(h.xywh={x:Number(c[1]),y:Number(c[2]),w:Number(c[3]),h:Number(c[4])}),s.push(h)}return s.sort((n,o)=>n.start-o.start),new H(s)}cueAt(t){let e=0,i=this.cues.length-1;for(;e<=i;){const s=e+i>>1,n=this.cues[s];if(t<n.start)i=s-1;else if(t>=n.end)e=s+1;else return n}return null}}const Nt='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 6 6 6-6 6"/></svg>',It='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 6-6 6 6 6"/></svg>';class M{constructor(t){this.anchor=t,this.outsideListener=null,this.escListener=null,this.root=a("div","imp-menu"),this.root.hidden=!0,this.backdrop=a("div","imp-menu__backdrop"),this.backdrop.hidden=!0,this.backdrop.addEventListener("pointerdown",e=>{e.preventDefault(),this.close()})}get open(){return!this.root.hidden}toggle(t){this.open?this.close():this.show(t)}show(t){this.root.textContent="";for(const e of t)e.items.length!==0&&this.root.append(this.renderSection(e));this.reveal()}toggleSettings(t,e){this.open?this.close():this.showSettings(t,e)}showSettings(t,e){this.root.classList.add("imp-menu--wide"),this.renderSettingsRoot(e),this.reveal()}renderSettingsRoot(t){this.root.textContent="";const e=a("div","imp-menu__section");for(const i of t){if(i.toggle){e.append(this.buildToggleRow(i,i.toggle));continue}const s=a("button","imp-menu__item imp-menu__row",{type:"button"}),n=a("span","imp-menu__label");n.textContent=i.label;const o=a("span","imp-menu__value");o.textContent=i.value??"";const l=a("span","imp-menu__chevron");l.innerHTML=Nt,s.append(n,o,l),s.addEventListener("click",()=>this.renderSettingsDetail(t,i)),e.append(s)}this.root.append(e)}buildToggleRow(t,e){const i=a("button","imp-menu__item imp-menu__row imp-menu__toggle",{type:"button",role:"switch","aria-checked":String(e.value)}),s=a("span","imp-menu__label");s.textContent=t.label;const n=a("span","imp-switch");return n.append(a("span","imp-switch__knob")),i.classList.toggle("imp-menu__toggle--on",e.value),i.append(s,n),i.addEventListener("click",()=>{const o=i.getAttribute("aria-checked")!=="true";i.setAttribute("aria-checked",String(o)),i.classList.toggle("imp-menu__toggle--on",o),e.onChange(o)}),i}renderSettingsDetail(t,e){if(!e.section)return;this.root.textContent="";const i=a("button","imp-menu__item imp-menu__back",{type:"button"}),s=a("span","imp-menu__chevron");s.innerHTML=It;const n=a("span","imp-menu__label");n.textContent=e.label,i.append(s,n),i.addEventListener("click",()=>this.renderSettingsRoot(t)),this.root.append(i),this.root.append(this.renderSection(e.section())),this.root.scrollTop=0}renderSection(t){const e=a("div","imp-menu__section");if(t.title){const i=a("div","imp-menu__title");i.textContent=t.title,e.append(i)}for(const i of t.items){const s=a("button","imp-menu__item",{type:"button",role:"menuitemradio"});if(s.setAttribute("aria-checked",String(i.active)),i.active&&s.classList.add("imp-menu__item--active"),i.icon){const o=a("span","imp-menu__icon");_(o,i.icon),s.append(o)}const n=a("span","imp-menu__label");n.textContent=i.label,s.append(n),s.addEventListener("click",()=>{t.onSelect(i.value),this.close()}),e.append(s)}return e}reveal(){const t=this.root.parentElement;t&&this.backdrop.parentElement!==t&&t.insertBefore(this.backdrop,this.root),this.root.hidden=!1,this.backdrop.hidden=!1,this.outsideListener=e=>{const i=e.target;!this.root.contains(i)&&!this.anchor.contains(i)&&this.close()},this.escListener=e=>{e.key==="Escape"&&this.close()},document.addEventListener("keydown",this.escListener),setTimeout(()=>{this.outsideListener&&document.addEventListener("pointerdown",this.outsideListener)},0)}close(){this.root.hidden=!0,this.root.classList.remove("imp-menu--wide"),this.backdrop.hidden=!0,this.outsideListener&&(document.removeEventListener("pointerdown",this.outsideListener),this.outsideListener=null),this.escListener&&(document.removeEventListener("keydown",this.escListener),this.escListener=null)}destroy(){this.close(),this.backdrop.remove(),this.root.remove()}}class Ft{constructor(t,e="Seek"){this.cb=t,this.segments=[],this.duration=0,this.chapters=[],this.thumbnails=null,this.scrubbing=!1,this.root=a("div","imp-progress",{role:"slider","aria-label":e,tabindex:"-1"}),this.buffered=a("div","imp-progress__buffered"),this.track=a("div","imp-progress__track"),this.handle=a("div","imp-progress__handle"),this.tooltipThumb=a("div","imp-progress__thumb"),this.tooltipChapter=a("div","imp-progress__tooltip-chapter"),this.tooltipTime=a("div","imp-progress__tooltip-time"),this.tooltipCaption=a("div","imp-progress__caption"),this.tooltipCaption.append(this.tooltipChapter,this.tooltipTime),this.tooltip=a("div","imp-progress__tooltip"),this.tooltip.append(this.tooltipThumb,this.tooltipCaption),this.heatmap=a("div","imp-progress__heatmap"),this.heatmap.hidden=!0,this.root.append(this.heatmap,this.buffered,this.track,this.handle,this.tooltip),this.setChapters([]),this.bindPointer()}setHeatmap(t,e=1){if(t.length===0){this.heatmap.hidden=!0,this.heatmap.textContent="";return}this.heatmap.innerHTML=`<svg viewBox="0 0 1000 100" preserveAspectRatio="none" aria-hidden="true"><path d="${ot(t,e)}"/></svg>`,this.heatmap.hidden=!1}setDuration(t){this.duration=Number.isFinite(t)?t:0,this.root.classList.toggle("imp-progress--live",!Number.isFinite(t)),this.chapters.length===0&&this.setChapters([])}setChapters(t){this.chapters=t,this.track.textContent="",this.segments=[];const e=t.length>0?t:[{start:0,end:this.duration||1,title:""}],i=[];let s=0;for(const n of e)n.start>s&&i.push({start:s,end:n.start,title:""}),i.push(n),s=n.end;this.duration>0&&s<this.duration&&i.push({start:s,end:this.duration,title:""});for(const n of i){const o=a("div","imp-progress__segment");o.style.flexGrow=String(Math.max(n.end-n.start,.01));const l=a("div","imp-progress__fill");o.append(l),this.track.append(o),this.segments.push({chapter:n,root:o,fill:l})}}setThumbnails(t){this.thumbnails=t}update(t,e,i){if(e!==this.duration&&Number.isFinite(e)&&this.setDuration(e),this.scrubbing)return;this.render(t);const s=this.duration>0?x(i/this.duration,0,1):0;this.buffered.style.width=`${s*100}%`,this.root.setAttribute("aria-valuemin","0"),this.root.setAttribute("aria-valuemax",String(Math.round(this.duration))),this.root.setAttribute("aria-valuenow",String(Math.round(t))),this.root.setAttribute("aria-valuetext",`${L(t)} / ${L(this.duration)}`)}render(t){for(const{chapter:i,fill:s}of this.segments){const n=i.end-i.start,o=n>0?x((t-i.start)/n,0,1):0;s.style.transform=`scaleX(${o})`}const e=this.duration>0?x(t/this.duration,0,1):0;this.handle.style.left=`${e*100}%`}timeFromEvent(t){const e=this.root.getBoundingClientRect();return(e.width>0?x((t.clientX-e.left)/e.width,0,1):0)*this.duration}bindPointer(){this.root.addEventListener("pointerdown",t=>{this.duration<=0||(t.preventDefault(),this.scrubbing=!0,this.root.classList.add("imp-progress--scrubbing"),this.root.setPointerCapture(t.pointerId),this.cb.onScrubStart(),this.render(this.timeFromEvent(t)),this.showTooltip(t))}),this.root.addEventListener("pointermove",t=>{this.duration<=0||(this.showTooltip(t),this.scrubbing&&this.render(this.timeFromEvent(t)))}),this.root.addEventListener("pointerup",t=>{this.scrubbing&&(this.scrubbing=!1,this.root.classList.remove("imp-progress--scrubbing"),this.cb.onSeek(this.timeFromEvent(t)),this.cb.onScrubEnd())}),this.root.addEventListener("pointercancel",()=>{this.scrubbing=!1,this.root.classList.remove("imp-progress--scrubbing"),this.cb.onScrubEnd()}),this.root.addEventListener("pointerleave",()=>this.hideTooltip())}showTooltip(t){const e=this.timeFromEvent(t);this.tooltipTime.textContent=L(e);const i=j(this.chapters,e),s=!!i?.title;this.tooltipChapter.textContent=i?.title??"",this.tooltipChapter.hidden=!s,this.tooltipCaption.classList.toggle("imp-progress__caption--time-only",!s);const n=this.thumbnails?.cueAt(e)??null;this.tooltip.classList.toggle("imp-progress__tooltip--thumb",!!n),n?(this.tooltipThumb.hidden=!1,this.tooltipThumb.style.backgroundImage=`url("${n.src}")`,n.xywh?(this.tooltipThumb.style.width=`${n.xywh.w}px`,this.tooltipThumb.style.height=`${n.xywh.h}px`,this.tooltipThumb.style.backgroundPosition=`-${n.xywh.x}px -${n.xywh.y}px`,this.tooltipThumb.style.backgroundSize="auto"):(this.tooltipThumb.style.width="160px",this.tooltipThumb.style.height="90px",this.tooltipThumb.style.backgroundPosition="center",this.tooltipThumb.style.backgroundSize="cover")):this.tooltipThumb.hidden=!0,this.tooltip.classList.add("imp-progress__tooltip--visible");const o=this.root.getBoundingClientRect(),l=x(t.clientX-o.left,0,o.width),h=this.tooltip.offsetWidth/2;this.tooltip.style.left=`${x(l,h,Math.max(h,o.width-h))}px`}hideTooltip(){this.tooltip.classList.remove("imp-progress__tooltip--visible")}}class qt{constructor(t){this.player=t,this.rightItems=new Map,this.subtitlesBtn=null,this.settingsBtn=null,this.settingsMenu=null,this.subtitlesMenu=null,this.moreMenu=null,this.moreWrap=null,this.qualityBtn=null,this.qualityMenu=null,this.gearBtn=null,this.gearMenu=null,this.gear={speed:!1,quality:!1,subtitles:!1},this.nextPreviewEl=null,this.nextPreviewOpts=null,this.scenesBtn=null,this.sceneTypeBtn=null,this.sceneTypeMenu=null,this.likeBtn=null,this.dislikeBtn=null,this.likeCountEl=null,this.dislikeCountEl=null,this.prevBtn=null,this.nextBtn=null,this.seekBackBtn=null,this.seekFwdBtn=null,this.centerPlayBtn=null,this.centerPrevBtn=null,this.centerNextBtn=null,this.collapsibles=[],this.overflowed=new Set,this.resizeObserver=null,this.reflowScheduled=!1,this.actionItems=[],this.wasPlayingBeforeScrub=!1,this.disposers=[],this.onWindowResize=null;const{labels:e,icons:i}=t,s=t.controlsOptions;this.root=a("div","imp-controls"),this.progress=new Ft({onSeek:d=>t.seek(d),onScrubStart:()=>{t.scrubbing=!0,this.wasPlayingBeforeScrub=!t.paused,t.pause()},onScrubEnd:()=>{t.scrubbing=!1,this.wasPlayingBeforeScrub?t.play(!0):t.started||t.play()}},t.labels.seek),s.progress&&this.root.append(this.progress.root);const n=a("div","imp-controls__row");this.row=n,this.root.append(n);const o=a("div","imp-controls__group"),l=a("div","imp-controls__group");this.rightGroup=l;const h=a("div","imp-controls__spacer");this.chapterLabel=a("div","imp-controls__chapter"),n.append(o,h,l),h.append(this.chapterLabel);const c=typeof s.seekButtons=="object"?s.seekButtons:{},u=c.back??t.seekStep,f=c.forward??t.seekStep;if(this.seekLabelFn=c.label,s.playlist&&t.hasPlaylist&&!s.hidePrev&&(this.prevBtn=b("imp-btn--prev",e.previous,i.previous),this.prevBtn.addEventListener("click",()=>t.previous()),o.append(this.prevBtn)),s.seekButtons&&(this.seekBackBtn=b("imp-btn--seek-back",`${e.seekBack} ${u}s`,i.seekBack),this.addStepBadge(this.seekBackBtn,u,"back"),this.seekBackBtn.addEventListener("click",()=>t.skip(-u)),o.append(this.seekBackBtn)),s.play&&(this.playBtn=b("imp-btn--play",e.play,i.play),this.playBtn.addEventListener("click",()=>t.togglePlay()),o.append(this.playBtn)),s.seekButtons&&(this.seekFwdBtn=b("imp-btn--seek-forward",`${e.seekForward} ${f}s`,i.seekForward),this.addStepBadge(this.seekFwdBtn,f,"forward"),this.seekFwdBtn.addEventListener("click",()=>t.skip(f)),o.append(this.seekFwdBtn)),s.playlist&&t.hasPlaylist&&!s.hideNext&&(this.nextBtn=b("imp-btn--next",e.next,i.next),this.nextBtn.addEventListener("click",()=>t.next()),o.append(this.nextBtn)),s.volume){const d=a("div","imp-volume");this.muteBtn=b("imp-btn--mute",e.mute,i.volumeHigh),this.muteBtn.addEventListener("click",()=>t.toggleMute()),this.volumeSlider=a("input","imp-volume__slider",{type:"range",min:"0",max:"1",step:"0.05","aria-label":e.volume}),this.volumeSlider.addEventListener("input",()=>{t.setVolume(Number(this.volumeSlider.value))}),d.append(this.muteBtn,this.volumeSlider),o.append(d)}s.time&&(this.timeLabel=a("div","imp-controls__time"),this.timeCurrent=a("span","imp-controls__time-current"),this.timeTotal=a("span","imp-controls__time-total"),this.timeLabel.append(this.timeCurrent,this.timeTotal),this.liveBadge=a("span","imp-controls__live"),this.liveBadge.textContent=e.live,this.liveBadge.hidden=!0,o.append(this.timeLabel,this.liveBadge)),this.buildLikeDislike();for(const d of(t.actionsOptions.custom??[]).filter(k=>k.placement==="bar")){const k=b(`imp-btn--custom imp-btn--custom-${d.id}`,d.title,d.icon??i.more);k.addEventListener("click",()=>t.emit("customaction",{id:d.id})),this.rightItems.set(`custom:${d.id}`,k),this.registerCollapsible({key:`custom:${d.id}`,el:k,priority:55,available:()=>!0,section:()=>this.simpleSection(`custom:${d.id}`,d.title,d.icon??i.more,()=>t.emit("customaction",{id:d.id}))})}const p=d=>d===!1?"off":d==="bar"?"bar":"gear",m=p(s.subtitles),v=p(s.quality),y=p(s.speed);if(this.gear={speed:y==="gear",quality:v==="gear",subtitles:m==="gear"},m==="bar"){this.subtitlesBtn=b("imp-btn--subtitles",e.subtitles,i.subtitles),this.subtitlesMenu=new M(this.subtitlesBtn);const d=a("div","imp-controls__menu-anchor");d.append(this.subtitlesBtn,this.subtitlesMenu.root),this.subtitlesBtn.addEventListener("click",()=>this.toggleSubtitlesMenu()),this.rightItems.set("subtitles",d),this.registerCollapsible({key:"subtitles",el:d,priority:30,available:()=>t.subtitleTracks.length>0,section:()=>this.subtitlesSection()})}if(v==="bar"){this.qualityBtn=b("imp-btn--quality",e.quality,i.settings),this.qualityMenu=new M(this.qualityBtn);const d=a("div","imp-controls__menu-anchor");d.append(this.qualityBtn,this.qualityMenu.root),this.qualityBtn.addEventListener("click",()=>this.toggleQualityMenu()),this.rightItems.set("quality",d),this.registerCollapsible({key:"quality",el:d,priority:10,available:()=>t.qualityLevels.length>0,section:()=>this.qualitySection()})}if(y==="bar"){this.settingsBtn=b("imp-btn--speed",e.speed,i.speed),this.settingsMenu=new M(this.settingsBtn);const d=a("div","imp-controls__menu-anchor");d.append(this.settingsBtn,this.settingsMenu.root),this.settingsBtn.addEventListener("click",()=>this.toggleSettingsMenu()),this.rightItems.set("speed",d),this.registerCollapsible({key:"speed",el:d,priority:40,available:()=>!0,section:()=>this.speedSection()})}if(s.scenes&&(this.scenesBtn=b("imp-btn--scenes",e.scenes,i.scenes),this.scenesBtn.addEventListener("click",()=>t.toggleScenesPanel()),this.rightItems.set("scenes",this.scenesBtn),this.registerCollapsible({key:"scenes",el:this.scenesBtn,priority:25,available:()=>t.chapterList.length>0,section:()=>this.simpleSection("scenes",e.scenes,i.scenes,()=>t.toggleScenesPanel())})),s.sceneTypes!==!1){this.sceneTypeBtn=a("button","imp-btn imp-btn--scene-types",{type:"button"}),this.sceneTypeMenu=new M(this.sceneTypeBtn);const d=a("div","imp-controls__menu-anchor");d.append(this.sceneTypeBtn,this.sceneTypeMenu.root),this.sceneTypeBtn.addEventListener("click",()=>this.toggleSceneTypeMenu()),this.rightItems.set("sceneTypes",d),this.refreshSceneTypeButton(),this.registerCollapsible({key:"sceneTypes",el:d,priority:68,available:()=>t.sceneTypes.length>0,section:()=>this.sceneTypeSection()})}if(s.playlist&&t.hasPlaylist&&s.playlistButton!==!1){const d=b("imp-btn--list",e.playlist,i.list);d.addEventListener("click",()=>t.togglePlaylistPanel()),this.rightItems.set("playlist",d),this.registerCollapsible({key:"list",el:d,priority:50,available:()=>!0,section:()=>this.simpleSection("list",e.playlist,i.list,()=>t.togglePlaylistPanel())})}if(s.pip&&"requestPictureInPicture"in HTMLVideoElement.prototype){const d=b("imp-btn--pip",e.pip,i.pip);d.addEventListener("click",()=>void t.togglePip()),this.rightItems.set("pip",d),this.registerCollapsible({key:"pip",el:d,priority:20,available:()=>!0,section:()=>this.simpleSection("pip",e.pip,i.pip,()=>void t.togglePip())})}if(s.fullscreen&&(this.fullscreenBtn=b("imp-btn--fullscreen",e.fullscreen,i.fullscreen),this.fullscreenBtn.addEventListener("click",()=>void t.toggleFullscreen()),this.rightItems.set("fullscreen",this.fullscreenBtn)),this.prevBtn&&this.registerCollapsible({key:"prev",el:this.prevBtn,priority:70,available:()=>!0,section:()=>t.hasPrevious?this.simpleSection("prev",e.previous,i.previous,()=>t.previous()):null}),this.nextBtn&&this.registerCollapsible({key:"next",el:this.nextBtn,priority:72,available:()=>!0,section:()=>t.hasNext?this.simpleSection("next",e.next,i.next,()=>t.next()):null}),this.seekBackBtn){const d=this.seekBackBtn;this.registerCollapsible({key:"seekBack",el:d,priority:80,available:()=>Number.isFinite(t.duration)&&t.duration>0,section:()=>this.simpleSection("seekBack",`${e.seekBack} ${u}s`,i.seekBack,()=>t.skip(-u))})}if(this.seekFwdBtn){const d=this.seekFwdBtn;this.registerCollapsible({key:"seekFwd",el:d,priority:82,available:()=>Number.isFinite(t.duration)&&t.duration>0,section:()=>this.simpleSection("seekFwd",`${e.seekForward} ${f}s`,i.seekForward,()=>t.skip(f))})}if(this.center=a("div","imp-center-controls"),s.playlist&&t.hasPlaylist&&(this.centerPrevBtn=this.makeCenterButton("prev",e.previous,i.previous),this.centerPrevBtn.addEventListener("click",()=>t.previous()),this.center.append(this.centerPrevBtn)),s.seekButtons){const d=this.makeCenterButton("seek-back",`${e.seekBack} ${u}s`,i.seekBack);this.addStepBadge(d,u,"back"),d.addEventListener("click",()=>t.skip(-u)),this.center.append(d)}if(s.play&&(this.centerPlayBtn=this.makeCenterButton("play",e.play,i.play),this.centerPlayBtn.addEventListener("click",()=>t.togglePlay()),this.center.append(this.centerPlayBtn)),s.seekButtons){const d=this.makeCenterButton("seek-forward",`${e.seekForward} ${f}s`,i.seekForward);this.addStepBadge(d,f,"forward"),d.addEventListener("click",()=>t.skip(f)),this.center.append(d)}if(s.playlist&&t.hasPlaylist&&(this.centerNextBtn=this.makeCenterButton("next",e.next,i.next),this.centerNextBtn.addEventListener("click",()=>t.next()),this.center.append(this.centerNextBtn)),this.center.style.display="none",this.setupNextPreview(),this.gear.speed||this.gear.quality||this.gear.subtitles){this.gearBtn=b("imp-btn--settings",e.settings,i.settings),this.gearMenu=new M(this.gearBtn);const d=a("div","imp-controls__menu-anchor");d.append(this.gearBtn,this.gearMenu.root),this.gearBtn.addEventListener("click",()=>this.toggleGearMenu()),this.rightItems.set("gear",d),this.registerCollapsible({key:"gear",el:d,priority:40,available:()=>this.gearSections().length>0,section:()=>this.gearSections()})}this.layoutRightCluster(l),this.buildMoreDropdown(l),this.bind(),this.syncVolume(),this.syncPlayState(),this.setLikeState(t.actionsOptions.likeState??null),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.scheduleReflow()),this.resizeObserver.observe(t.container)),this.onWindowResize=()=>this.scheduleReflow(),window.addEventListener("resize",this.onWindowResize)}registerCollapsible(t){this.collapsibles.push(t)}layoutRightCluster(t){const e=[...this.rightItems.keys()],i=this.player.controlsOptions.order;let s=e;if(i.length>0){const n=new Set;s=[];for(const o of i)this.rightItems.has(o)&&!n.has(o)&&(s.push(o),n.add(o));for(const o of e)n.has(o)||s.push(o)}for(const n of s){const o=this.rightItems.get(n);o&&t.append(o)}}makeCenterButton(t,e,i){const s=a("button",`imp-center-btn imp-center-btn--${t}`,{type:"button","aria-label":e,title:e});return _(s,i),s}addStepBadge(t,e,i){const s=a("span","imp-seek-num");s.textContent=this.seekLabelFn?this.seekLabelFn(e,i):`${i==="back"?"−":"+"}${e}${this.player.labels.secondsShort}`,t.append(s)}gearSections(){const t=this.player,e=[];return this.gear.quality&&t.qualityLevels.length>0&&e.push(this.qualitySection()),this.gear.speed&&e.push(this.speedSection()),this.gear.subtitles&&t.subtitleTracks.length>0&&e.push(this.subtitlesSection()),e}gearEntries(){const t=this.player,e=[];if(t.hasPlaylist&&e.push({key:"autoplay",label:t.labels.autoplay,toggle:{value:t.autoAdvance,onChange:i=>t.setAutoAdvance(i)}}),this.gear.quality&&t.qualityLevels.length>0){const i=t.currentQuality===-1?t.labels.qualityAuto:t.qualityLevels.find(s=>s.index===t.currentQuality)?.label??t.labels.qualityAuto;e.push({key:"quality",label:t.labels.quality,value:i,section:()=>this.qualitySection()})}if(this.gear.speed){const i=t.playbackRate;e.push({key:"speed",label:t.labels.speed,value:i===1?t.labels.speedNormal:`${i}×`,section:()=>this.speedSection()})}if(this.gear.subtitles&&t.subtitleTracks.length>0){const i=t.activeSubtitle===-1?t.labels.subtitlesOff:t.subtitleTracks[t.activeSubtitle]?.label??t.labels.subtitlesOff;e.push({key:"subtitles",label:t.labels.subtitles,value:i,section:()=>this.subtitlesSection()})}return e}refreshSceneTypeButton(){const t=this.sceneTypeBtn;if(!t)return;const e=this.player.activeSceneType;if(t.textContent="",!e)return;if(e.icon){const s=a("span","imp-scene-type__icon");_(s,e.icon),t.append(s)}const i=a("span","imp-scene-type__label");i.textContent=e.title,t.append(i),t.setAttribute("aria-label",`${this.player.labels.sceneTypes}: ${e.title}`),t.title=e.title}sceneTypeSection(){const t=this.player;return{title:t.labels.sceneTypes,items:t.sceneTypes.map(e=>({label:e.title,value:e.id,icon:e.icon,active:e.id===(t.activeSceneType?.id??"")})),onSelect:e=>{t.setSceneGroup(e),this.refreshSceneTypeButton()}}}toggleSceneTypeMenu(){!this.sceneTypeMenu||this.player.sceneTypes.length===0||(this.closeMenus(this.sceneTypeMenu),this.sceneTypeMenu.toggle([this.sceneTypeSection()]))}toggleGearMenu(){if(!this.gearMenu)return;const t=this.gearEntries();t.length!==0&&(this.closeMenus(this.gearMenu),this.gearMenu.toggleSettings(this.player.labels.settings,t))}setupNextPreview(){const t=this.player,e=t.controlsOptions;if(e.nextPreview===!1||!e.playlist||!t.hasPlaylist)return;const i=typeof e.nextPreview=="object"?e.nextPreview:{};this.nextPreviewOpts={thumbnail:i.thumbnail??!0,title:i.title??!0,duration:i.duration??!0,meta:i.meta??!0},this.nextPreviewEl=a("div","imp-next-preview"),this.nextPreviewEl.hidden=!0,t.container.append(this.nextPreviewEl),this.nextBtn&&this.bindNextPreview(this.nextBtn),this.centerNextBtn&&this.bindNextPreview(this.centerNextBtn)}bindNextPreview(t){t.addEventListener("pointerenter",e=>{e.pointerType==="mouse"&&this.showNextPreview(t)}),t.addEventListener("pointerleave",()=>this.hideNextPreview()),t.addEventListener("click",()=>this.hideNextPreview())}showNextPreview(t){const e=this.nextPreviewEl,i=this.nextPreviewOpts;if(!e||!i)return;const s=this.player.nextSource;if(!s){this.hideNextPreview();return}e.textContent="";const n=a("div","imp-next-preview__kicker");n.textContent=this.player.labels.next,e.append(n);const o=$.posterSrc(s.poster);if(i.thumbnail&&o){const m=a("div","imp-next-preview__thumb"),v=T(o);if(v.addEventListener("error",()=>{this.player.markSourceDead(s),this.nextPreviewEl&&!this.nextPreviewEl.hidden&&this.showNextPreview(t)},{once:!0}),m.append(v),i.duration&&s.duration){const y=a("span","imp-next-preview__duration");y.textContent=L(s.duration),m.append(y)}e.append(m)}if(i.title&&s.title){const m=a("div","imp-next-preview__title");m.textContent=s.title,e.append(m)}i.meta&&s.previewMeta?.length&&e.append(Y(s.previewMeta,"imp-next-preview")),e.hidden=!1;const l=this.player.container.getBoundingClientRect(),h=t.getBoundingClientRect(),c=8,u=e.offsetWidth,f=h.left-l.left+h.width/2-u/2,p=Math.max(c,Math.min(f,l.width-u-c));e.style.left=`${p}px`,e.style.bottom=`${l.height-(h.top-l.top)+10}px`}hideNextPreview(){this.nextPreviewEl&&(this.nextPreviewEl.hidden=!0)}buildLikeDislike(){const t=this.player,e=t.actionsOptions,{labels:i,icons:s}=t;if(e.like){this.likeBtn=b("imp-btn--like",i.like,s.like),this.likeBtn.addEventListener("click",()=>t.emit("action",{id:"like"})),this.likeCountEl=this.attachCountTooltip(this.likeBtn,e.likeCount);const n=this.wrapWithTooltip(this.likeBtn,this.likeCountEl);this.rightItems.set("like",n),this.registerCollapsible({key:"like",el:n,priority:62,available:()=>!0,section:()=>this.simpleSection("like",i.like,s.like,()=>t.emit("action",{id:"like"}))})}if(e.dislike){this.dislikeBtn=b("imp-btn--dislike",i.dislike,s.dislike),this.dislikeBtn.addEventListener("click",()=>t.emit("action",{id:"dislike"})),this.dislikeCountEl=this.attachCountTooltip(this.dislikeBtn,e.dislikeCount);const n=this.wrapWithTooltip(this.dislikeBtn,this.dislikeCountEl);this.rightItems.set("dislike",n),this.registerCollapsible({key:"dislike",el:n,priority:60,available:()=>!0,section:()=>this.simpleSection("dislike",i.dislike,s.dislike,()=>t.emit("action",{id:"dislike"}))})}}attachCountTooltip(t,e){const i=a("span","imp-count-tooltip");return this.setCountText(i,e),i}wrapWithTooltip(t,e){const i=a("div","imp-action");return i.append(t,e),i}setCountText(t,e){const i=e==null||e===""?"":String(e);t.textContent=i,t.hidden=i===""}setLikeCounts(t,e){this.likeCountEl&&t!==void 0&&this.setCountText(this.likeCountEl,t),this.dislikeCountEl&&e!==void 0&&this.setCountText(this.dislikeCountEl,e)}setLikeState(t){this.likeBtn?.classList.toggle("imp-btn--active",t==="like"),this.dislikeBtn?.classList.toggle("imp-btn--active",t==="dislike")}buildMoreDropdown(t){const e=this.player,i=e.actionsOptions,{labels:s,icons:n}=e;i.addTo&&this.actionItems.push({value:"addTo",label:s.addTo,icon:n.addTo,run:()=>e.emit("action",{id:"addTo"})}),i.share&&this.actionItems.push({value:"share",label:s.share,icon:n.share,run:()=>void e.share()}),i.report&&this.actionItems.push({value:"report",label:s.report,icon:n.report,run:()=>e.emit("action",{id:"report"})});for(const h of(i.custom??[]).filter(c=>c.placement!=="bar"))this.actionItems.push({value:`custom:${h.id}`,label:h.title,icon:h.icon,run:()=>e.emit("customaction",{id:h.id})});const o=b("imp-btn--more",s.more,n.more);this.moreMenu=new M(o);const l=a("div","imp-controls__menu-anchor imp-controls__more");l.append(o,this.moreMenu.root),o.addEventListener("click",()=>{this.closeMenus(this.moreMenu),this.moreMenu?.toggle(this.buildMoreSections())}),t.append(l),this.moreWrap=l}buildMoreSections(){const t=[],e=new Map,i=[],s=["prev","next","seekBack","seekFwd","like","dislike","scenes","sceneTypes","pip","list","subtitles","speed","quality","gear"],n=l=>{const h=s.indexOf(l);return h===-1?s.length:h},o=this.collapsibles.filter(l=>this.overflowed.has(l.key)&&l.available()).sort((l,h)=>n(l.key)-n(h.key));for(const l of o){const h=l.section();if(h)for(const c of Array.isArray(h)?h:[h])if(!c.title&&c.items.length===1){const u=c.items[0];i.push(u),e.set(u.value,()=>c.onSelect(u.value))}else t.push(c)}if(i.length>0&&t.unshift({title:"",items:i,onSelect:l=>e.get(l)?.()}),this.actionItems.length>0){const l=new Map(this.actionItems.map(h=>[h.value,h.run]));t.push({title:"",items:this.actionItems.map(({value:h,label:c,icon:u})=>({value:h,label:c,icon:u,active:!1})),onSelect:h=>l.get(h)?.()})}return t}simpleSection(t,e,i,s){return{title:"",items:[{value:t,label:e,icon:i,active:!1}],onSelect:()=>s()}}speedSection(){const t=this.player;return{title:t.labels.speed,items:t.playbackRates.map(e=>({label:e===1?t.labels.speedNormal:`${e}×`,value:String(e),active:t.playbackRate===e})),onSelect:e=>t.setPlaybackRate(Number(e))}}qualitySection(){const t=this.player;return{title:t.labels.quality,items:[...t.qualityAutoAvailable?[{label:t.labels.qualityAuto,value:"-1",active:t.currentQuality===-1}]:[],...t.qualityLevels.map(e=>({label:e.label,value:String(e.index),active:t.currentQuality===e.index}))],onSelect:e=>t.setQuality(Number(e))}}subtitlesSection(){const t=this.player;return{title:t.labels.subtitles,items:[{label:t.labels.subtitlesOff,value:"-1",active:t.activeSubtitle===-1},...t.subtitleTracks.map((e,i)=>({label:e.label,value:String(i),active:t.activeSubtitle===i}))],onSelect:e=>t.setSubtitle(Number(e))}}scheduleReflow(){this.reflowScheduled||(this.reflowScheduled=!0,requestAnimationFrame(()=>{this.reflowScheduled=!1,this.reflow()}))}reflow(){const t=window.innerWidth<=767,e=t&&this.player.controlsOptions.mobileLayout==="center",s=this.player.controlsOptions.seekPlacement!=="bar"||t;this.center.style.display=s?"flex":"none",this.centerPrevBtn&&(this.centerPrevBtn.style.display=e?"":"none"),this.centerNextBtn&&(this.centerNextBtn.style.display=e?"":"none"),this.playBtn&&(this.playBtn.style.display=e?"none":"");const n=h=>h==="seekBack"||h==="seekFwd"?s:h==="prev"||h==="next"?e:!1;this.overflowed.clear();for(const h of this.collapsibles){if(n(h.key)){h.el.style.display="none";continue}const c=h.available();h.el.style.display=c?"":"none",h.el.classList.remove("imp-collapsed")}const o=this.collapsibles.filter(h=>h.available()&&!n(h.key)).sort((h,c)=>h.priority-c.priority);let l=o.length;for(;l-- >0&&this.overflowsRow();){const h=o.find(c=>!this.overflowed.has(c.key));if(!h)break;h.el.style.display="none",h.el.classList.add("imp-collapsed"),this.overflowed.add(h.key)}if(this.moreWrap){const h=this.actionItems.length>0||this.overflowed.size>0;this.moreWrap.style.display=h?"":"none"}}overflowsRow(){const t=this.row.getBoundingClientRect().right;return this.rightGroup.getBoundingClientRect().right>t+1}bind(){const t=this.player;this.disposers.push(t.on("timeupdate",({currentTime:e,duration:i})=>{this.progress.update(e,i,t.bufferedEnd),this.timeLabel&&(t.live?(this.timeLabel.hidden=!0,this.liveBadge.hidden=!1):(this.timeLabel.hidden=!1,this.liveBadge.hidden=!0,this.timeCurrent.textContent=L(e),this.timeTotal.textContent=` / ${L(i)}`))}),t.on("play",()=>this.syncPlayState()),t.on("pause",()=>this.syncPlayState()),t.on("ended",()=>this.syncPlayState()),t.on("volumechange",()=>this.syncVolume()),t.on("chapterchange",({chapter:e})=>{this.chapterLabel.textContent=e?.title??""}),t.on("fullscreenchange",({active:e})=>{this.fullscreenBtn&&I(this.fullscreenBtn,e?t.icons.fullscreenExit:t.icons.fullscreen,e?t.labels.exitFullscreen:t.labels.fullscreen),this.scheduleReflow()}),t.on("playlistitemchange",()=>{this.syncPlaylistButtons(),this.scheduleReflow()}),t.on("sourcechange",()=>{this.syncPlaylistButtons(),this.scheduleReflow()})),this.syncPlaylistButtons(),this.reflow()}syncPlayState(){const t=this.player,[e,i]=t.ended?[t.icons.replay,t.labels.replay]:t.paused?[t.icons.play,t.labels.play]:[t.icons.pause,t.labels.pause];this.playBtn&&I(this.playBtn,e,i),this.centerPlayBtn&&I(this.centerPlayBtn,e,i)}syncVolume(){if(!this.muteBtn)return;const t=this.player,e=t.muted?0:t.volume,i=e===0?t.icons.volumeMute:e<.5?t.icons.volumeLow:t.icons.volumeHigh;I(this.muteBtn,i,t.muted?t.labels.unmute:t.labels.mute),this.volumeSlider.value=String(e),this.volumeSlider.style.setProperty("--imp-volume-fill",`${e*100}%`)}syncFeatureButtons(){this.refreshSceneTypeButton(),this.syncPlaylistButtons(),this.scheduleReflow()}syncPlaylistButtons(){const t=this.player;this.prevBtn&&(this.prevBtn.disabled=!t.hasPrevious),this.nextBtn&&(this.nextBtn.disabled=!t.hasNext),this.centerPrevBtn&&(this.centerPrevBtn.disabled=!t.hasPrevious),this.centerNextBtn&&(this.centerNextBtn.disabled=!t.hasNext)}closeMenus(t){for(const e of[this.gearMenu,this.settingsMenu,this.subtitlesMenu,this.qualityMenu,this.sceneTypeMenu,this.moreMenu])e&&e!==t&&e.close()}anyMenuOpen(){return[this.gearMenu,this.settingsMenu,this.subtitlesMenu,this.qualityMenu,this.sceneTypeMenu,this.moreMenu].some(t=>t?.open)}toggleSettingsMenu(){this.settingsMenu&&(this.closeMenus(this.settingsMenu),this.settingsMenu.toggle([this.speedSection()]))}toggleQualityMenu(){!this.qualityMenu||this.player.qualityLevels.length===0||(this.closeMenus(this.qualityMenu),this.qualityMenu.toggle([this.qualitySection()]))}toggleSubtitlesMenu(){!this.subtitlesMenu||this.player.subtitleTracks.length===0||(this.closeMenus(this.subtitlesMenu),this.subtitlesMenu.toggle([this.subtitlesSection()]))}destroy(){for(const t of this.disposers)t();this.disposers=[],this.resizeObserver?.disconnect(),this.onWindowResize&&window.removeEventListener("resize",this.onWindowResize),this.gearMenu?.destroy(),this.sceneTypeMenu?.destroy(),this.settingsMenu?.destroy(),this.subtitlesMenu?.destroy(),this.qualityMenu?.destroy(),this.moreMenu?.destroy(),this.nextPreviewEl?.remove(),this.root.remove()}}class $t{constructor(t){this.root=a("div","imp-poster"),this.image=a("div","imp-poster__image"),this.image.hidden=!0,this.img=T(""),this.image.append(this.img);const e=b("imp-poster__play",t.labels.play,t.icons.bigPlay);e.addEventListener("click",()=>void t.play()),this.root.append(this.image,e),this.root.addEventListener("pointerup",i=>{i.target!==this.root&&i.target!==this.image&&i.target!==this.img||i.pointerType==="touch"&&t.posterTapReveal()||t.play()})}setSource(t){const e=t?.poster;if(e){const i=typeof e=="string"?{src:e}:e;this.img.src=i.src,i.srcset?this.img.srcset=i.srcset:this.img.removeAttribute("srcset"),i.sizes?this.img.sizes=i.sizes:this.img.removeAttribute("sizes"),i.width?this.img.width=i.width:this.img.removeAttribute("width"),i.height?this.img.height=i.height:this.img.removeAttribute("height"),this.img.alt=i.alt??"",this.img.fetchPriority="high",this.image.hidden=!1}else this.img.removeAttribute("src"),this.image.hidden=!0}show(){this.root.hidden=!1}hide(){this.root.hidden=!0}}class Vt{constructor(t){this.labels=t,this.channelUrl=null,this.custom=null,this.visible={title:!0,description:!0,sponsor:!0},this.root=a("div","imp-pause-screen"),this.root.hidden=!0,this.defaultContent=a("div","imp-pause-screen__default"),this.channel=a("button","imp-channel",{type:"button"}),this.channel.hidden=!0,this.channelAvatar=a("div","imp-channel__avatar"),this.channelName=a("div","imp-channel__name"),this.channel.append(this.channelName,this.channelAvatar),this.channel.addEventListener("click",()=>{this.channelUrl&&window.open(this.channelUrl,"_blank","noopener")});const e=a("div","imp-pause-screen__heading");this.title=a("div","imp-pause-screen__title"),this.description=a("div","imp-pause-screen__description"),this.sponsor=a("a","imp-sponsor",{target:"_blank",rel:"nofollow noopener"}),this.sponsor.hidden=!0,this.sponsorLabel=a("span","imp-sponsor__label"),this.sponsorText=a("span","imp-sponsor__text"),this.sponsor.append(this.sponsorLabel,this.sponsorText),this.sponsor.addEventListener("click",i=>i.stopPropagation()),e.append(this.sponsor,this.title,this.description),this.defaultContent.append(e,this.channel),this.root.append(this.defaultContent)}setCustomContent(t){this.custom?.remove(),this.custom=t,t&&(t.classList.add("imp-pause-screen__custom"),this.root.append(t)),this.defaultContent.hidden=t!==null,this.root.classList.toggle("imp-pause-screen--custom",t!==null)}get hasCustom(){return this.custom!==null}setVisibility(t){this.visible={title:t.title??this.visible.title,description:t.description??this.visible.description,sponsor:t.sponsor??this.visible.sponsor}}setSource(t){this.title.textContent=t?.title??"",this.description.textContent=t?.description??"",this.title.hidden=!this.visible.title||!t?.title,this.description.hidden=!this.visible.description||!t?.description;const e=this.visible.sponsor?t?.sponsor:void 0;this.sponsor.hidden=!e,e&&(this.sponsor.href=e.url,this.sponsorText.textContent=e.text,this.sponsorLabel.textContent=e.label??this.labels.sponsored);const i=t?.channel;this.channel.hidden=!i,this.channelUrl=i?.url??null,this.channel.classList.toggle("imp-channel--link",!!i?.url),i&&(this.channelName.textContent=i.name,this.channelAvatar.className=`imp-channel__avatar imp-channel__avatar--${i.avatarShape??"circle"}`,i.avatar?(this.channelAvatar.textContent="",this.channelAvatar.append(T(i.avatar,i.name))):this.channelAvatar.textContent=(i.name.trim()[0]??"?").toUpperCase())}show(){this.root.hidden=!1}hide(){this.root.hidden=!0}}class Ot{constructor(t){this.player=t,this.clickBehavior="player",this.root=a("div","imp-related"),this.root.hidden=!0,this.heading=a("div","imp-related__title"),this.grid=a("div","imp-related__grid");const e=b("imp-related__close",t.labels.close,t.icons.close);e.addEventListener("click",()=>this.hide()),this.root.append(e,this.heading,this.grid)}setOptions(t){if(this.grid.textContent="",!!t){this.clickBehavior=t.clickBehavior??"player",this.heading.textContent=t.title??this.player.labels.related;for(const e of t.items)this.grid.append(this.buildCard(e))}}buildCard(t){const e=a("button","imp-related__card",{type:"button"}),i=a("div","imp-related__thumb");if(t.poster&&i.append(T(t.poster)),t.duration){const n=a("span","imp-related__duration");n.textContent=t.duration,i.append(n)}const s=a("div","imp-related__card-title");return s.textContent=t.title,e.append(i,s),e.addEventListener("click",()=>{this.player.emit("relatedclick",{item:t}),this.hide(),this.activate(t)}),e}activate(t){const e=t.url??t.source?.src;switch(this.clickBehavior){case"newWindow":e&&window.open(e,"_blank","noopener");break;case"currentTab":e&&(window.location.href=e);break;case"player":default:t.source?(this.player.load(t.source),this.player.play()):t.url&&window.open(t.url,"_blank","noopener")}}get visible(){return!this.root.hidden}show(){this.grid.childElementCount!==0&&(this.root.hidden=!1,this.player.emit("relatedshow",void 0))}hide(){this.root.hidden=!0}}class Ht{constructor(t){this.player=t,this.root=a("div","imp-upnext"),this.root.hidden=!0}get visible(){return!this.root.hidden}show(){const t=this.player.nextSource;if(!t){this.hide();return}const{labels:e}=this.player;this.root.textContent="";const i=a("div","imp-upnext__card"),s=a("div","imp-upnext__kicker");s.textContent=e.nextVideo,i.append(s);const n=$.posterSrc(t.poster);if(n){const l=a("button","imp-upnext__thumb",{type:"button","aria-label":e.playNext}),h=T(n);if(h.addEventListener("error",()=>{this.player.markSourceDead(t),this.root.hidden||this.show()},{once:!0}),l.append(h),t.duration){const u=a("span","imp-upnext__duration");u.textContent=L(t.duration),l.append(u)}const c=a("span","imp-upnext__thumb-play");_(c,this.player.icons.bigPlay),l.append(c),l.addEventListener("click",()=>this.player.next()),i.append(l)}if(t.title){const l=a("div","imp-upnext__title");l.textContent=t.title,i.append(l)}t.previewMeta?.length&&i.append(Y(t.previewMeta,"imp-upnext"));const o=a("button","imp-upnext__btn",{type:"button"});o.textContent=e.playNext,o.addEventListener("click",()=>this.player.next()),i.append(o),this.root.append(i),this.root.hidden=!1}hide(){this.root.hidden=!0}}class Zt{constructor(t,e="sidebar",i){this.player=t,this.root=a("div",`imp-playlist imp-playlist--${e}`),this.root.hidden=!0;const s=a("div","imp-playlist__header"),n=a("div","imp-playlist__heading");if(i){const h=a("div","imp-playlist__kicker");h.textContent=t.labels.playlist;const c=a("div","imp-playlist__name");c.textContent=i,n.append(h,c)}else n.textContent=t.labels.playlist;const o=a("div","imp-playlist__tools");this.shuffleBtn=b("imp-playlist__shuffle",t.labels.shuffle,t.icons.shuffle),this.shuffleBtn.addEventListener("click",()=>{t.setShuffle(!t.shuffle),this.syncModes()}),this.repeatBtn=b("imp-playlist__repeat",t.labels.repeat,t.icons.repeat),this.repeatBtn.addEventListener("click",()=>{t.setRepeat(!t.repeat),this.syncModes()});const l=b("imp-playlist__close",t.labels.close,t.icons.close);l.addEventListener("click",()=>this.hide()),o.append(this.shuffleBtn,this.repeatBtn,l),s.append(n,o),this.list=a("div","imp-playlist__list"),this.root.append(s,this.list),this.rebuild(),this.syncModes()}syncModes(){this.shuffleBtn.classList.toggle("imp-btn--active",this.player.shuffle),this.repeatBtn.classList.toggle("imp-btn--active",this.player.repeat)}rebuild(){this.list.textContent="",this.player.playlist.forEach((t,e)=>{const i=a("button","imp-playlist__item",{type:"button"});e===this.player.index&&i.classList.add("imp-playlist__item--active");const s=a("div","imp-playlist__thumb"),n=$.posterSrc(t.poster);n&&s.append(T(n));const o=a("div","imp-playlist__meta"),l=a("div","imp-playlist__title");if(l.textContent=t.title??`#${e+1}`,o.append(l),t.duration){const h=a("div","imp-playlist__duration");h.textContent=L(t.duration),o.append(h)}i.append(s,o),i.addEventListener("click",()=>{this.player.playItem(e),window.innerWidth<=767&&this.hide()}),this.list.append(i)})}get visible(){return!this.root.hidden}show(){this.rebuild(),this.root.hidden=!1}hide(){this.root.hidden=!0}toggle(){this.visible?this.hide():this.show()}}class Dt{constructor(t,e="bottom"){this.player=t,this.items=[],this.root=a("div",`imp-playlist imp-scenes imp-playlist--${e}`),this.root.hidden=!0;const i=a("div","imp-playlist__header"),s=a("span");s.textContent=t.labels.scenes;const n=b("imp-playlist__close",t.labels.close,t.icons.close);n.addEventListener("click",()=>this.hide()),i.append(s,n),this.list=a("div","imp-playlist__list"),this.root.append(i,this.list),t.on("chapterchange",()=>this.syncActive())}rebuild(){this.list.textContent="",this.items=[];const t=this.player.thumbnails;for(const e of this.player.chapterList){const i=a("button","imp-playlist__item",{type:"button"}),s=a("div","imp-playlist__thumb"),n=t?.cueAt(e.start+.01)??null;if(n?.xywh){const c=a("div","imp-scenes__sprite");c.style.width=`${n.xywh.w}px`,c.style.height=`${n.xywh.h}px`,c.style.backgroundImage=`url("${n.src}")`,c.style.backgroundPosition=`-${n.xywh.x}px -${n.xywh.y}px`,c.style.setProperty("--imp-sprite-w",String(n.xywh.w)),s.append(c)}else n&&s.append(T(n.src));const o=a("div","imp-playlist__meta"),l=a("div","imp-playlist__title");l.textContent=e.title||L(e.start);const h=a("div","imp-playlist__duration");h.textContent=L(e.start),o.append(l,h),i.append(s,o),i.addEventListener("click",()=>{this.player.seek(e.start),this.player.play(),window.innerWidth<=767&&this.hide()}),this.list.append(i),this.items.push(i)}this.syncActive()}syncActive(){const t=this.player.chapter,e=this.player.chapterList;this.items.forEach((i,s)=>{i.classList.toggle("imp-playlist__item--active",t!==null&&e[s]===t)})}get visible(){return!this.root.hidden}show(){this.rebuild(),this.root.hidden=!1}hide(){this.root.hidden=!0}toggle(){this.visible?this.hide():this.show()}}let dt=0;function ut(r){const t=r.reason;t?.name==="AbortError"&&/interrupted by a (new load request|call to pause)/i.test(t.message??"")&&r.preventDefault()}function Gt(){typeof window<"u"&&++dt===1&&window.addEventListener("unhandledrejection",ut)}function Wt(){typeof window<"u"&&--dt===0&&window.removeEventListener("unhandledrejection",ut)}function q(r){console.debug("[itube-player] play() rejected:",r)}function J(r){return r?typeof r=="string"?[{src:r,label:"Subtitles"}]:Array.isArray(r)?r:[r]:[]}const zt={play:!0,progress:!0,time:!0,volume:!0,fullscreen:!0,pip:!0,speed:"gear",settings:"gear",quality:"gear",scenes:!0,sceneTypes:!0,heatmap:!0,subtitles:"gear",seekButtons:!0,seekPlacement:"overlay",mobileLayout:"bar",order:[],playlist:!0,hidePrev:!0,hideNext:!1,playlistButton:!0,nextPreview:!0,hideDelay:2500,revealBeforePlay:!0};class jt{constructor(t,e={}){this.scrubbing=!1,this.emitter=new et,this.externalAdvance=!1,this.abort=new AbortController,this.sources=[],this.deadSources=new WeakSet,this.currentIndex=-1,this.sourceController=null,this.loadToken=0,this.chapters=[],this.currentChapter=null,this.sceneGroupList=[],this.activeSceneGroupId="",this.progressiveQuality=-1,this.thumbTrack=null,this.shuffleMode=!1,this.autoAdvanceEnabled=!0,this.persistKey=null,this.persistVolume=!1,this.persistAutoAdvance=!1,this.decodeRecoveries=0,this.adManager=null,this.playedOnce=!1,this.idleTimer=null,this.peekTimer=null,this.lastRetryAt=0,this.retryTimer=null,this.errorResumeTime=0,this.lastPlayheadTime=0,this.pendingSeek=null,this.destroyed=!1,this.persistTimer=null;const i=typeof t=="string"?document.querySelector(t):t;if(!i)throw new Error(`[itube-player] mount target not found: ${String(t)}`);this.mount=i,this.options=e,this.labels={...V.defaultLabels,...st(e.language),...e.labels},this.icons={...it,...e.icons};const s=e.controls??{},n=s.speed??s.settings??"gear";if(this.controlsOptions={...zt,...s,speed:n,settings:n},this.actionsOptions=e.actions??{},this.playbackRates=e.playbackRates??[.5,1,1.5,2],this.seekStep=e.seekStep??15,this.playlistOptions={title:"",autoAdvance:!0,loop:!1,shuffle:!1,startIndex:0,layout:"sidebar",externalAdvance:!1,...e.playlist},this.shuffleMode=this.playlistOptions.shuffle,this.externalAdvance=this.playlistOptions.externalAdvance,e.persist){const y=e.persist===!0?{}:e.persist;this.persistKey=y.key??"itube-player",this.persistVolume=y.volume!==!1,this.persistAutoAdvance=y.autoAdvance!==!1}const o=this.readPersisted();this.autoAdvanceEnabled=this.persistAutoAdvance&&typeof o?.autoAdvance=="boolean"?o.autoAdvance:this.playlistOptions.autoAdvance,this.sources=e.source?Array.isArray(e.source)?[...e.source]:[e.source]:[],this.container=a("div","imp-player",{tabindex:"0"}),e.className&&this.container.classList.add(e.className);const l=e.styling;if(l?.themeColor&&this.container.style.setProperty("--imp-accent",l.themeColor),l?.likeColor&&this.container.style.setProperty("--imp-like",l.likeColor),l?.dislikeColor&&this.container.style.setProperty("--imp-dislike",l.dislikeColor),l?.fontFamily&&this.container.style.setProperty("--imp-font",l.fontFamily),l?.borderRadius!==void 0){const y=typeof l.borderRadius=="number"?`${l.borderRadius}px`:l.borderRadius;this.container.style.setProperty("--imp-radius",y)}l?.playButtonStyle==="inverted"&&this.container.classList.add("imp-player--play-inverted"),this.video=e.videoElement??a("video","imp-video"),this.video.classList.add("imp-video"),e.playsInline!==!1&&this.video.setAttribute("playsinline",""),e.crossOrigin!==void 0&&(this.video.crossOrigin=e.crossOrigin),this.video.preload="metadata",e.loop&&(this.video.loop=!0);const h=this.persistVolume?o:null;this.video.volume=x(h?.volume??e.volume??1,0,1),(h?.muted??e.muted)&&(this.video.muted=!0);const c=a("div","imp-layer");this.spinner=a("div","imp-spinner"),this.spinner.hidden=!0,this.errorBox=a("div","imp-error"),this.errorBox.hidden=!0,this.errorText=a("div","imp-error__text"),this.retryBtn=a("button","imp-error__retry",{type:"button"});const u=a("span","imp-error__retry-label");u.textContent=this.labels.tryAgain,this.retryBtn.append(u,a("span","imp-error__retry-spinner")),this.retryBtn.addEventListener("click",()=>this.retry()),this.errorNextBtn=a("button","imp-error__next",{type:"button"}),this.errorNextBtn.textContent=this.labels.nextVideo,this.errorNextBtn.addEventListener("click",()=>{this.clearError(),this.next()});const f=a("div","imp-error__actions");f.append(this.retryBtn,this.errorNextBtn),this.errorBox.append(this.errorText,f),this.pauseScreen=new Vt(this.labels),this.poster=new $t(this),this.related=new Ot(this),this.related.setOptions(e.related),this.upNext=new Ht(this),this.controls=new qt(this),this.playlistPanel=new Zt(this,this.playlistOptions.layout,this.playlistOptions.title||void 0),this.scenesPanel=new Dt(this,e.scenes?.layout??"bottom");const p=a("div","imp-layer__middle");p.append(this.spinner,this.errorBox,this.controls.center);const m=a("div","imp-layer__bottom");m.append(this.controls.root),c.append(this.pauseScreen.root,this.related.root,this.upNext.root,p,m),this.container.append(this.video,c,this.poster.root,this.playlistPanel.root,this.scenesPanel.root),this.mount.append(this.container),e.pauseScreen instanceof HTMLElement?this.pauseScreen.setCustomContent(e.pauseScreen):typeof e.pauseScreen=="function"?this.pauseScreen.setCustomContent(e.pauseScreen(this)):e.pauseScreen&&typeof e.pauseScreen=="object"&&this.pauseScreen.setVisibility(e.pauseScreen);const v=e.adConfig??e.ads;v&&v.adList.length>0&&(this.adManager=new Ct({container:this.container,contentVideo:this.video,emitter:this.emitter,labels:this.labels,closeIcon:this.icons.close},v)),this.emitter.on("error",({fatal:y})=>{if(!y)return;const d=this.lastPlayheadTime||this.video.currentTime;Number.isFinite(d)&&d>0&&(this.errorResumeTime=d),this.errorText.textContent=this.labels.videoNotFound,this.errorNextBtn.hidden=!this.hasNext,this.errorBox.hidden=!1,this.spinner.hidden=!0,this.poster.hide(),this.container.classList.add("imp-player--error")}),Gt(),this.bindVideoEvents(),this.bindIdleHide(),e.keyboard!==!1&&this.bindKeyboard(),this.video.addEventListener("pointerup",y=>{if(!(this.adPlaying||!this.playedOnce)){if(y.pointerType==="mouse"){this.togglePlay();return}this.container.classList.contains("imp-player--idle")?(this.showControlsNow(),this.scheduleIdle()):this.video.paused||this.container.classList.add("imp-player--idle")}},{signal:this.abort.signal}),this.pauseScreen.root.addEventListener("click",y=>{this.pauseScreen.hasCustom||y.target===this.pauseScreen.root&&this.togglePlay()},{signal:this.abort.signal}),this.sources.length>0&&this.loadItem(x(this.playlistOptions.startIndex,0,this.sources.length-1),!!(e.playOnInit??e.autoplay)),queueMicrotask(()=>{this.destroyed||this.emitter.emit("ready",{player:this})})}on(t,e){return this.emitter.on(t,e)}once(t,e){return this.emitter.once(t,e)}off(t,e){this.emitter.off(t,e)}emit(t,e){this.emitter.emit(t,e)}get paused(){return this.video.paused}get ended(){return this.video.ended}get currentTime(){return this.video.currentTime}get duration(){return this.video.duration||0}get live(){return this.video.duration===1/0}get bufferedEnd(){const t=this.video.buffered;return t.length>0?t.end(t.length-1):0}get adPlaying(){return this.adManager?.adPlaying??!1}async play(t=!1){if(!(this.destroyed||this.adPlaying)&&!(this.adManager&&!t&&(await this.adManager.playPreRoll(),this.destroyed||!this.video.paused)))try{await this.video.play()}catch(e){const i=e?.name;if(i==="NotSupportedError"&&this.video.readyState===0){const s=this.loadToken;this.video.addEventListener("loadedmetadata",()=>{s===this.loadToken&&this.video.play().catch(q)},{once:!0,signal:this.abort.signal});return}i!=="AbortError"&&(q(e),this.playedOnce||this.poster.show())}}pause(){this.adPlaying||this.video.pause()}togglePlay(){this.video.paused||this.video.ended?this.play():this.pause()}retry(){const t=this.options.retryThrottle??5e3,e=Date.now();if(e-this.lastRetryAt<t)return;this.lastRetryAt=e,this.retryBtn.disabled=!0,this.retryBtn.classList.add("imp-error__retry--loading"),this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>{this.destroyed||(this.retryBtn.disabled=!1,this.retryBtn.classList.remove("imp-error__retry--loading"))},t);const i=this.errorResumeTime;if(this.loadItem(this.currentIndex,!0,!0),this.errorResumeTime=i,i>0){const s=this.loadToken;this.video.addEventListener("loadedmetadata",()=>{if(s===this.loadToken)try{this.video.currentTime=i}catch{}},{once:!0,signal:this.abort.signal})}}clearError(){this.errorBox.hidden=!0,this.container.classList.remove("imp-player--error")}get started(){return this.playedOnce}seek(t){if(Number.isFinite(this.video.duration)){this.video.currentTime=x(t,0,this.video.duration);return}const e=this.source?.duration;typeof e=="number"&&e>0&&(this.pendingSeek=x(t,0,e))}skip(t){this.seek(this.video.currentTime+t)}get volume(){return this.video.volume}get muted(){return this.video.muted}setVolume(t){this.video.volume=x(t,0,1),t>0&&(this.video.muted=!1)}setMuted(t){this.video.muted=t}toggleMute(){this.video.muted=!this.video.muted}readPersisted(){if(!this.persistKey)return null;try{const t=localStorage.getItem(this.persistKey),e=t?JSON.parse(t):null;return e&&typeof e=="object"?e:null}catch{return null}}schedulePersist(){this.persistTimer&&clearTimeout(this.persistTimer),this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.destroyed||this.persistState()},300)}persistState(){if(this.persistKey)try{const t={};this.persistVolume&&(t.volume=this.video.volume,t.muted=this.video.muted),this.persistAutoAdvance&&(t.autoAdvance=this.autoAdvanceEnabled),localStorage.setItem(this.persistKey,JSON.stringify(t))}catch{}}get playbackRate(){return this.video.playbackRate}setPlaybackRate(t){this.video.playbackRate=t,this.emitter.emit("ratechange",{rate:t})}get qualityLevels(){if(this.sourceController?.kind==="hls")return this.sourceController.levels;const t=this.source?.qualities;return t?t.map((e,i)=>({index:i,label:e.label??String(e.quality??i)})):[]}get qualityAutoAvailable(){return this.sourceController?.kind==="hls"}get currentQuality(){return this.sourceController?.kind==="hls"?this.sourceController.selected:this.progressiveQuality}setQuality(t){if(this.sourceController?.kind==="hls"){this.sourceController.setLevel(t);const o=t===-1?this.labels.qualityAuto:this.sourceController.levels.find(l=>l.index===t)?.label??String(t);this.emitter.emit("qualitychange",{label:o});return}const e=this.source?.qualities;if(!e||!e[t]||t===this.progressiveQuality)return;const i=this.video.currentTime,s=!this.video.paused&&!this.video.ended;this.progressiveQuality=t,this.video.src=e[t].src;const n=this.loadToken;this.video.addEventListener("loadedmetadata",()=>{if(n===this.loadToken){try{this.video.currentTime=i}catch{}s&&this.video.play().catch(q)}},{once:!0,signal:this.abort.signal}),this.emitter.emit("qualitychange",{label:e[t].label??String(e[t].quality??t)})}get subtitleTracks(){return J(this.source?.subtitles)}get activeSubtitle(){const t=this.video.textTracks;for(let e=0;e<t.length;e++)if(t[e].mode==="showing")return e;return-1}setSubtitle(t){const e=this.video.textTracks;for(let i=0;i<e.length;i++)e[i].mode=i===t?"showing":"disabled";this.emitter.emit("subtitlechange",{track:this.subtitleTracks[t]??null})}get playlist(){return this.sources}get index(){return this.currentIndex}get source(){return this.sources[this.currentIndex]??null}markSourceDead(t){this.deadSources.add(t),this.controls.syncFeatureButtons()}nextAliveIndex(){const t=this.sources.length;if(t<2)return-1;for(let e=1;e<t;e++){const i=this.currentIndex+e;if(i>=t&&!this.playlistOptions.loop)return-1;const s=i%t;if(!this.deadSources.has(this.sources[s]))return s}return-1}get nextSource(){if(this.shuffleMode||this.sources.length<2)return null;const t=this.nextAliveIndex();return t===-1?null:this.sources[t]}get hasPlaylist(){return this.sources.length>1||this.externalAdvance}get hasNext(){return this.externalAdvance?!0:this.shuffleMode?this.sources.length>1:this.nextAliveIndex()!==-1}get hasPrevious(){return this.externalAdvance?!0:this.playlistOptions.loop?this.sources.length>1:this.currentIndex>0}get shuffle(){return this.shuffleMode}setShuffle(t){this.shuffleMode=t}get repeat(){return this.playlistOptions.loop}setRepeat(t){this.playlistOptions.loop=t}emitAdvanceRequest(t,e){if(!this.externalAdvance)return!1;const i=e!==null&&e>=0&&e<this.sources.length;return this.emitter.emit("advancerequest",{direction:t,index:i?e:null,source:i?this.sources[e]:null}),!0}next(){if(!this.hasNext||this.emitAdvanceRequest("next",this.sources.length>1?(this.currentIndex+1)%this.sources.length:null))return;if(this.shuffleMode&&this.sources.length>1){const e=this.sources.map((s,n)=>({s,i:n})).filter(({s,i:n})=>n!==this.currentIndex&&!this.deadSources.has(s)),i=e.length>0?e.map(({i:s})=>s):this.sources.map((s,n)=>n).filter(s=>s!==this.currentIndex);this.playItem(i[Math.floor(Math.random()*i.length)]);return}const t=this.nextAliveIndex();t!==-1&&this.playItem(t)}previous(){this.hasPrevious&&(this.emitAdvanceRequest("previous",this.sources.length>1?(this.currentIndex-1+this.sources.length)%this.sources.length:null)||this.playItem((this.currentIndex-1+this.sources.length)%this.sources.length))}playItem(t){t<0||t>=this.sources.length||t!==this.currentIndex&&this.emitAdvanceRequest("select",t)||this.loadItem(t,!0).then(()=>{this.emitter.emit("playlistitemchange",{source:this.sources[t],index:t})})}togglePlaylistPanel(){this.scenesPanel.hide(),this.playlistPanel.toggle()}toggleScenesPanel(){this.playlistPanel.hide(),this.scenesPanel.toggle()}get thumbnails(){return this.thumbTrack}load(t,e=0){this.sources=Array.isArray(t)?[...t]:[t],this.playlistPanel.rebuild(),this.loadItem(x(e,0,this.sources.length-1),!1)}get isFullscreen(){return document.fullscreenElement===this.container}async toggleFullscreen(){try{this.isFullscreen?await document.exitFullscreen():this.container.requestFullscreen?await this.container.requestFullscreen():this.video.webkitEnterFullscreen?.()}catch{}}async togglePip(){try{document.pictureInPictureElement===this.video?await document.exitPictureInPicture():await this.video.requestPictureInPicture()}catch{}}get chapterList(){return this.chapters}get chapter(){return this.currentChapter}get sceneTypes(){return this.sceneGroupList}get activeSceneType(){return this.sceneGroupList.find(t=>t.id===this.activeSceneGroupId)??null}setSceneGroup(t){t===this.activeSceneGroupId||!this.sceneGroupList.some(e=>e.id===t)||(this.activeSceneGroupId=t,this.applyActiveSceneGroup(),this.emitter.emit("scenetypechange",{group:this.activeSceneType}))}get knownDuration(){const t=this.video.duration;if(Number.isFinite(t)&&t>0)return t;const e=this.source?.duration;return typeof e=="number"&&e>0?e:NaN}applyActiveSceneGroup(){this.chapters=z(this.activeSceneType?.scenes??[],this.knownDuration),this.currentChapter=null,this.controls.progress.setChapters(this.chapters),this.controls.syncFeatureButtons(),this.scenesPanel.visible&&this.scenesPanel.rebuild()}async share(){const t={title:this.source?.title??document.title,url:window.location.href};if(typeof navigator.share=="function"){try{await navigator.share(t)}catch{}return}this.emitter.emit("action",{id:"share"})}setLikeState(t){this.controls.setLikeState(t)}setLikeCounts(t,e){this.controls.setLikeCounts(t,e)}setPauseScreenContent(t){this.pauseScreen.setCustomContent(t)}destroy(){this.destroyed||(this.destroyed=!0,this.loadToken++,this.adManager?.destroy(),this.controls.destroy(),this.sourceController?.destroy(),this.abort.abort(),this.idleTimer&&clearTimeout(this.idleTimer),this.peekTimer&&clearTimeout(this.peekTimer),this.retryTimer&&clearTimeout(this.retryTimer),this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null,this.persistState()),this.container.remove(),Wt(),this.emitter.emit("destroy",void 0),this.emitter.removeAll())}async loadItem(t,e,i=!1){const s=++this.loadToken,n=this.sources[t];if(!n)return;this.currentIndex=t,this.sourceController?.destroy(),this.sourceController=null,this.chapters=[],this.currentChapter=null,this.sceneGroupList=[],this.activeSceneGroupId="",this.progressiveQuality=-1,this.playedOnce=!1,this.lastPlayheadTime=0,this.errorResumeTime=0,this.pendingSeek=null,this.endPeek();for(const p of[...this.video.querySelectorAll("track")])p.remove();this.adManager?.resetForNewSource(),this.related.hide(),this.upNext.hide(),this.pauseScreen.hide(),this.scenesPanel.hide(),this.thumbTrack=null,this.decodeRecoveries=0,this.video.poster=$.posterSrc(n.poster)??"",this.poster.setSource(n),this.pauseScreen.setSource(n),this.controls.progress.setChapters([]),this.controls.progress.setThumbnails(null),this.controls.progress.setHeatmap([]),typeof n.duration=="number"&&n.duration>0&&this.controls.progress.update(0,n.duration,0),e?this.poster.hide():this.poster.show(),this.playlistPanel.rebuild();for(const p of J(n.subtitles)){const m=a("track","",{kind:"subtitles",src:p.src,label:p.label,...p.srclang?{srclang:p.srclang}:{}});p.default&&m.setAttribute("default",""),this.video.append(m)}let o=n.src,l=n.type;if(n.qualities&&n.qualities.length>0){const p=Math.max(0,n.qualities.findIndex(m=>m.src===n.src));this.progressiveQuality=p,o=n.qualities[p].src,l=n.qualities[p].type??l}this.video.preload=this.adManager?.hasPendingPreRoll?"auto":"metadata";const h=await At(this.video,o,l,{onLevels:()=>{s===this.loadToken&&this.controls.syncFeatureButtons()},onLevelSwitch:p=>this.emitter.emit("qualitychange",{label:p}),onError:(p,m)=>this.emitter.emit("error",{message:p,cause:m,fatal:!0})});if(s!==this.loadToken){h.destroy();return}if(this.sourceController=h,this.emitter.emit("sourcechange",{source:n,index:t}),n.thumbnails&&H.load(n.thumbnails).then(p=>{s===this.loadToken&&(this.thumbTrack=p,this.controls.progress.setThumbnails(p),this.scenesPanel.visible&&this.scenesPanel.rebuild())}).catch(p=>this.emitter.emit("error",{message:"Failed to load thumbnails track",cause:p})),n.sceneGroups&&n.sceneGroups.length>0)this.sceneGroupList=n.sceneGroups,this.activeSceneGroupId=n.sceneGroups[0].id,this.applyActiveSceneGroup(),Number.isFinite(this.video.duration)&&this.video.duration>0||this.video.addEventListener("loadedmetadata",()=>{s===this.loadToken&&this.applyActiveSceneGroup()},{once:!0,signal:this.abort.signal});else if(n.chapters){const p=m=>{const v=()=>{s===this.loadToken&&(this.chapters=z(m,this.knownDuration),this.controls.progress.setChapters(this.chapters),this.controls.syncFeatureButtons(),this.scenesPanel.visible&&this.scenesPanel.rebuild())};Number.isFinite(this.video.duration)&&this.video.duration>0?v():this.video.addEventListener("loadedmetadata",v,{once:!0,signal:this.abort.signal})};typeof n.chapters=="string"?ht(n.chapters).then(m=>p(m)).catch(m=>this.emitter.emit("error",{message:"Failed to load chapters track",cause:m})):p(n.chapters)}const c=n.heatmap,u=c&&!Array.isArray(c),f=u?c.values.length>0:!!(c&&c.length>0);if(c&&f&&this.controlsOptions.heatmap){const p=()=>{if(s!==this.loadToken)return;const m=u?Tt(c.values,c.mode):rt(c,this.video.duration);this.controls.progress.setHeatmap(m,u?c.smoothing??1:1)};u||Number.isFinite(this.video.duration)&&this.video.duration>0?p():this.video.addEventListener("loadedmetadata",p,{once:!0,signal:this.abort.signal})}e&&this.play(i)}bindVideoEvents(){const{signal:t}=this.abort,e=this.video;e.addEventListener("play",()=>{this.playedOnce=!0,this.endPeek(),this.poster.hide(),this.pauseScreen.hide(),this.related.visible||this.related.hide(),this.related.hide(),this.upNext.hide(),e.readyState<3&&(this.spinner.hidden=!1),this.emitter.emit("play",void 0),this.scheduleIdle()},{signal:t}),e.addEventListener("pause",()=>{this.spinner.hidden=!0,this.emitter.emit("pause",void 0),this.showControlsNow(),!(this.video.ended||this.scrubbing||this.adPlaying||!this.playedOnce)&&(this.options.pauseScreen!==!1&&this.pauseScreen.show(),this.options.related?.showOn?.includes("pause")&&this.related.show())},{signal:t}),e.addEventListener("ended",()=>{this.handleEnded()},{signal:t}),e.addEventListener("timeupdate",()=>{!this.adPlaying&&e.currentTime>0&&(this.lastPlayheadTime=e.currentTime),this.emitter.emit("timeupdate",{currentTime:e.currentTime,duration:e.duration||0}),this.adManager?.checkMidRolls(e.currentTime);const i=j(this.chapters,e.currentTime);i!==this.currentChapter&&(this.currentChapter=i,this.emitter.emit("chapterchange",{chapter:i}))},{signal:t}),e.addEventListener("progress",()=>{this.emitter.emit("progress",{buffered:this.bufferedEnd})},{signal:t}),e.addEventListener("volumechange",()=>{this.emitter.emit("volumechange",{volume:e.volume,muted:e.muted}),this.persistVolume&&this.schedulePersist()},{signal:t}),e.addEventListener("loadedmetadata",()=>{if(this.pendingSeek!==null){const i=x(this.pendingSeek,0,Number.isFinite(e.duration)?e.duration:this.pendingSeek);this.pendingSeek=null;try{e.currentTime=i}catch{}}!this.playedOnce&&Number.isFinite(e.duration)&&this.controls.progress.update(e.currentTime,e.duration,this.bufferedEnd)},{signal:t}),e.addEventListener("seeking",()=>this.emitter.emit("seeking",{currentTime:e.currentTime}),{signal:t}),e.addEventListener("seeked",()=>this.emitter.emit("seeked",{currentTime:e.currentTime}),{signal:t}),e.addEventListener("waiting",()=>{this.spinner.hidden=!1},{signal:t});for(const i of["playing","canplay","seeked"])e.addEventListener(i,()=>{this.spinner.hidden=!0,this.decodeRecoveries=0,i==="playing"&&this.clearError()},{signal:t});e.addEventListener("error",()=>{const i=e.error;if(!i||this.sourceController?.kind==="hls"||e.getAttribute("src")===null&&!e.currentSrc)return;if((i.code===MediaError.MEDIA_ERR_DECODE||/DEMUXER|PARSE|DECODE/i.test(i.message||""))&&this.decodeRecoveries<2&&Number.isFinite(e.duration)){this.decodeRecoveries++;const n=e.currentTime,o=!e.paused;e.load();const l=()=>{try{e.currentTime=n}catch{}o&&e.play().catch(q)};e.readyState>=1?l():e.addEventListener("loadedmetadata",l,{once:!0,signal:this.abort.signal});return}this.emitter.emit("error",{message:i.message||`Media error (code ${i.code})`,cause:i,fatal:!0})},{signal:t}),e.addEventListener("enterpictureinpicture",()=>this.emitter.emit("pipchange",{active:!0}),{signal:t}),e.addEventListener("leavepictureinpicture",()=>this.emitter.emit("pipchange",{active:!1}),{signal:t}),document.addEventListener("fullscreenchange",()=>{this.emitter.emit("fullscreenchange",{active:this.isFullscreen}),this.container.classList.toggle("imp-player--fullscreen",this.isFullscreen)},{signal:t}),e.addEventListener("webkitbeginfullscreen",()=>{this.emitter.emit("fullscreenchange",{active:!0}),this.container.classList.add("imp-player--fullscreen")},{signal:t}),e.addEventListener("webkitendfullscreen",()=>{this.emitter.emit("fullscreenchange",{active:!1}),this.container.classList.remove("imp-player--fullscreen")},{signal:t})}async handleEnded(){if(this.emitter.emit("ended",void 0),this.showControlsNow(),!(this.adManager&&(await this.adManager.playPostRoll(),this.destroyed))){if(this.autoAdvanceEnabled&&this.hasNext){if(this.emitAdvanceRequest("ended",this.sources.length>1?(this.currentIndex+1)%this.sources.length:null))return;this.next();return}if(!this.autoAdvanceEnabled&&this.hasNext){this.upNext.show();return}(this.options.related?.showOn?.includes("ended")??!!this.options.related)&&this.related.show()}}get autoAdvance(){return this.autoAdvanceEnabled}setAutoAdvance(t){this.autoAdvanceEnabled=t,t&&this.upNext.hide(),this.persistAutoAdvance&&this.persistState()}bindIdleHide(){const{signal:t}=this.abort,e=()=>{this.showControlsNow(),this.scheduleIdle()};this.container.addEventListener("pointermove",i=>{i.pointerType!=="touch"&&(e(),this.playedOnce||this.revealPeek(!1))},{signal:t}),this.container.addEventListener("pointerdown",i=>{i.pointerType!=="touch"&&e()},{signal:t}),this.container.addEventListener("keydown",e,{signal:t}),this.container.addEventListener("pointerleave",i=>{i.pointerType!=="touch"&&(this.controls.anyMenuOpen()||(this.playedOnce?this.video.paused||this.container.classList.add("imp-player--idle"):this.endPeek()))},{signal:t})}showControlsNow(){this.container.classList.remove("imp-player--idle")}revealPeek(t){this.playedOnce||!this.controlsOptions.revealBeforePlay||(this.container.classList.add("imp-player--peek"),this.peekTimer&&clearTimeout(this.peekTimer),this.peekTimer=null,t&&(this.peekTimer=setTimeout(()=>{!this.playedOnce&&!this.destroyed&&!this.controls.anyMenuOpen()&&this.container.classList.remove("imp-player--peek")},3e3)))}endPeek(){this.peekTimer&&clearTimeout(this.peekTimer),this.peekTimer=null,this.container.classList.remove("imp-player--peek")}posterTapReveal(){return this.playedOnce||!this.controlsOptions.revealBeforePlay?!1:(this.revealPeek(!0),!0)}scheduleIdle(){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{!this.video.paused&&!this.destroyed&&this.container.classList.add("imp-player--idle")},this.controlsOptions.hideDelay)}bindKeyboard(){this.container.addEventListener("keydown",t=>{const e=t.target;if(e.closest("input, select, textarea, [contenteditable]"))return;const s=e.closest("button")!==null;switch(t.key){case" ":case"k":if(t.key===" "&&s)return;t.preventDefault(),this.togglePlay();break;case"ArrowLeft":t.preventDefault(),this.skip(-this.seekStep);break;case"ArrowRight":t.preventDefault(),this.skip(this.seekStep);break;case"ArrowUp":t.preventDefault(),this.setVolume(this.volume+.1);break;case"ArrowDown":t.preventDefault(),this.setVolume(this.volume-.1);break;case"m":this.toggleMute();break;case"f":this.toggleFullscreen();break;case"Home":this.seek(0);break;case"End":this.seek(this.duration);break;default:/^[0-9]$/.test(t.key)&&Number.isFinite(this.video.duration)&&this.seek(Number(t.key)/10*this.video.duration)}},{signal:this.abort.signal})}}exports.defaultLabels=V.defaultLabels;exports.Emitter=et;exports.Player=jt;exports.ThumbnailTrack=H;exports.buildHeatmapValues=rt;exports.chapterAt=j;exports.defaultIcons=it;exports.formatTime=L;exports.getLocale=st;exports.heatmapPath=ot;exports.isHlsSource=ct;exports.loadChaptersVtt=ht;exports.normalizeChapters=z;exports.registerLocale=wt;exports.registerLocales=xt;exports.registeredLanguages=Lt;exports.resolveVast=at;
4
+ `).trim();u&&t.push({start:h,end:c,text:u})}return t}function kt(r,t){try{return new URL(r,new URL(t,window.location.href)).toString()}catch{return r}}class et{constructor(){this.listeners=new Map}on(t,e){let i=this.listeners.get(t);return i||(i=new Set,this.listeners.set(t,i)),i.add(e),()=>this.off(t,e)}once(t,e){const i=this.on(t,s=>{i(),e(s)});return i}off(t,e){this.listeners.get(t)?.delete(e)}emit(t,e){const i=this.listeners.get(t);if(i)for(const s of[...i])try{s(e)}catch(n){console.error("[itube-player] listener error",n)}}removeAll(){this.listeners.clear()}}const g=(r,t="0 0 24 24")=>`<svg viewBox="${t}" fill="currentColor" aria-hidden="true" focusable="false">${r}</svg>`,it={play:g('<path d="M8 5.14v13.72c0 .8.87 1.3 1.56.88l10.54-6.86a1.05 1.05 0 0 0 0-1.76L9.56 4.26C8.87 3.84 8 4.34 8 5.14Z"/>'),pause:g('<rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/>'),replay:g('<path d="M12 5V2.5L7.5 6 12 9.5V7a5 5 0 1 1-5 5H5a7 7 0 1 0 7-7Z"/>'),bigPlay:g('<path d="M8 5.14v13.72c0 .8.87 1.3 1.56.88l10.54-6.86a1.05 1.05 0 0 0 0-1.76L9.56 4.26C8.87 3.84 8 4.34 8 5.14Z"/>'),volumeHigh:g('<path d="M4 9v6h3.5L12 19.5v-15L7.5 9H4Z"/><path d="M14.5 8.6a4.5 4.5 0 0 1 0 6.8v-1.9a2.5 2.5 0 0 0 0-3v-1.9Z"/><path d="M14.5 5.2a8 8 0 0 1 0 13.6v-2a6 6 0 0 0 0-9.6v-2Z"/>'),volumeLow:g('<path d="M4 9v6h3.5L12 19.5v-15L7.5 9H4Z"/><path d="M14.5 8.6a4.5 4.5 0 0 1 0 6.8v-1.9a2.5 2.5 0 0 0 0-3v-1.9Z"/>'),volumeMute:g('<path d="M4 9v6h3.5L12 19.5v-15L7.5 9H4Z"/><path d="m15.3 9.3 1.4 1.4 1.4-1.4 1.4 1.4-1.4 1.4 1.4 1.4-1.4 1.4-1.4-1.4-1.4 1.4-1.4-1.4 1.4-1.4-1.4-1.4 1.4-1.4Z"/>'),fullscreen:g('<path d="M5 5h5v2H7v3H5V5Zm9 0h5v5h-2V7h-3V5ZM5 14h2v3h3v2H5v-5Zm12 0h2v5h-5v-2h3v-3Z"/>'),fullscreenExit:g('<path d="M10 10H5V8h3V5h2v5Zm4 0V5h2v3h3v2h-5Zm-4 4v5H8v-3H5v-2h5Zm4 0h5v2h-3v3h-2v-5Z"/>'),pip:g('<path d="M3 5h18v14H3V5Zm2 2v10h14V7H5Z"/><rect x="12" y="11" width="6" height="4"/>'),settings:g('<path d="M12 8.5A3.5 3.5 0 1 0 12 15.5 3.5 3.5 0 0 0 12 8.5Zm0 2a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3Z"/><path d="M10.3 2.8 9.9 5.1a7 7 0 0 0-1.5.86l-2.2-.8-1.7 3 1.8 1.5a7 7 0 0 0 0 1.7l-1.8 1.5 1.7 3 2.2-.8c.46.36.97.65 1.5.86l.4 2.3h3.4l.4-2.3a7 7 0 0 0 1.5-.86l2.2.8 1.7-3-1.8-1.5a7 7 0 0 0 0-1.7l1.8-1.5-1.7-3-2.2.8a7 7 0 0 0-1.5-.86l-.4-2.3h-3.4Zm1.7 5.7a3.5 3.5 0 1 1 0 7 3.5 3.5 0 0 1 0-7Z"/>'),speed:g('<path d="M12 4a9 9 0 0 0-9 9 8.96 8.96 0 0 0 1.62 5.16l1.64-1.15A7 7 0 0 1 5 13a7 7 0 1 1 12.74 4.01l1.64 1.15A8.96 8.96 0 0 0 21 13a9 9 0 0 0-9-9Z"/><path d="m15.6 8.3-3.95 3.13a1.5 1.5 0 1 0 1.92 1.92L16.7 9.4a.78.78 0 0 0-1.1-1.1Z"/>'),scenes:g('<path d="M3 5h18v14H3V5Zm2 2v10h3V7H5Zm5 0v10h9V7h-9Zm-5 3h3v1H5v-1Zm0 3h3v1H5v-1Z"/>'),shuffle:g('<path d="M4 6h2.6c1.5 0 2.9.7 3.8 1.9l4.1 5.4a2.75 2.75 0 0 0 2.2 1.1H19l-1.8-1.8 1.4-1.4 4.2 4.2-4.2 4.2-1.4-1.4L19 16.4h-2.3a4.75 4.75 0 0 1-3.8-1.9L8.8 9.1A2.75 2.75 0 0 0 6.6 8H4V6Z"/><path d="M19 7.6h-2.3c-.86 0-1.67.41-2.18 1.1l-.93 1.23-1.25-1.65.58-.77A4.75 4.75 0 0 1 16.7 5.6H19L17.2 3.8l1.4-1.4 4.2 4.2-4.2 4.2-1.4-1.4L19 7.6Z" transform="translate(0 1.2)"/>'),repeat:g('<path d="M7 7h10v2.5L21 6l-4-3.5V5H5v6h2V7Zm10 10H7v-2.5L3 18l4 3.5V19h12v-6h-2v4Z"/>'),subtitles:g('<path d="M3 5h18v14H3V5Zm2 2v10h14V7H5Zm2 3h6v2H7v-2Zm8 0h2v2h-2v-2ZM7 14h2v2H7v-2Zm4 0h6v2h-6v-2Z"/>'),list:g('<path d="M4 6h2v2H4V6Zm4 0h12v2H8V6ZM4 11h2v2H4v-2Zm4 0h12v2H8v-2ZM4 16h2v2H4v-2Zm4 0h12v2H8v-2Z"/>'),next:g('<path d="M6 5.5v13c0 .77.84 1.25 1.5.85l9-6.5a1 1 0 0 0 0-1.7l-9-6.5c-.66-.4-1.5.08-1.5.85Z"/><rect x="17" y="5" width="2.5" height="14" rx="1"/>'),previous:g('<path d="M18 5.5v13c0 .77-.84 1.25-1.5.85l-9-6.5a1 1 0 0 1 0-1.7l9-6.5c.66-.4 1.5.08 1.5.85Z"/><rect x="4.5" y="5" width="2.5" height="14" rx="1"/>'),seekForward:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>',seekBack:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg>',like:g('<path d="M9 21H5a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h4v11Zm2 0h7.1a2 2 0 0 0 2-1.6l1.3-7a2 2 0 0 0-2-2.4H14V5.5A2.5 2.5 0 0 0 11.5 3l-.5.1V10h-.9L11 21Z"/>'),dislike:g('<path d="M15 3h4a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2h-4V3Zm-2 0H5.9a2 2 0 0 0-2 1.6l-1.3 7a2 2 0 0 0 2 2.4H10v4.5A2.5 2.5 0 0 0 12.5 21l.5-.1V14h.9L13 3Z"/>'),addTo:g('<path d="M4 6h12v2H4V6Zm0 4h12v2H4v-2Zm0 4h8v2H4v-2Zm14 0v-4h2v4h4v2h-4v4h-2v-4h-4v-2h4Z"/>'),share:g('<path d="M18 8a3 3 0 1 0-2.83-4H15a3 3 0 0 0 .14 1.06L8.4 8.94a3 3 0 1 0 0 6.12l6.74 3.88A3 3 0 1 0 16 16.6l-6.74-3.88a3.03 3.03 0 0 0 0-1.44L16 7.4c.55.38 1.24.6 2 .6Z"/>'),report:g('<path d="M5 3h2v18H5V3Zm4 1h10l-2.5 4L19 12H9V4Z"/>'),more:g('<circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/>'),close:g('<path d="m6.4 5 5.6 5.6L17.6 5 19 6.4 13.4 12l5.6 5.6-1.4 1.4-5.6-5.6L6.4 19 5 17.6 10.6 12 5 6.4 6.4 5Z"/>'),user:g('<path d="M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm0 2c-3.6 0-8 1.8-8 4.4V21h16v-2.6c0-2.6-4.4-4.4-8-4.4Z"/>'),channel:g('<path d="M3 5h18a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm7 3.5v7l6-3.5-6-3.5Z"/>')},O={en:V.defaultLabels};function wt(r,t){O[r]=t}function xt(r){for(const[t,e]of Object.entries(r))e&&(O[t]=e)}function st(r){return r&&O[r]||V.defaultLabels}function Lt(){return Object.keys(O)}function St(r){const t=[.06,.24,.4,.24,.06],e=r.length;return r.map((i,s)=>t.reduce((n,o,l)=>{const h=Math.min(e-1,Math.max(0,s+l-2));return n+o*r[h]},0))}function _t(r,t){if(r.length===0)return 0;const e=Math.min(r.length-1,Math.max(0,Math.round((r.length-1)*t)));return r[e]}function nt(r,t){if(r.length===0||r.every(n=>n<=0))return[];const e=St(r),i=t==="retention"?_t([...e].sort((n,o)=>n-o),.95):Math.max(...e);if(i<=0)return[];const s=.08;return e.map(n=>s+(1-s)*Math.min(1,Math.max(0,n/i)))}function rt(r,t,e=100){if(r.length===0||!Number.isFinite(t)||t<=0)return[];const i=new Array(e).fill(0);let s=!1;for(const n of r){if(!Number.isFinite(n.time)||n.time<0||n.time>t)continue;const o=Math.max(0,n.value);o!==0&&(i[Math.min(e-1,Math.floor(n.time/t*e))]+=o,s=!0)}return s?nt(i,"peaks"):[]}function Tt(r,t="peaks",e=200){let i=r.map(s=>Number.isFinite(s)?Math.max(0,s):0);if(i.length>e){const s=new Array(e).fill(0),n=new Array(e).fill(0);for(let o=0;o<i.length;o++){const l=Math.min(e-1,Math.floor(o/i.length*e));s[l]+=i[o],n[l]++}i=s.map((o,l)=>n[l]>0?o/n[l]:0)}return nt(i,t)}function ot(r,t=1,e=1e3,i=100){const s=r.length;if(s===0)return"";const n=e/(s-1||1),o=Math.max(0,t)/6,l=u=>{const f=Math.min(s-1,Math.max(0,u));return[f*n,i-r[f]*i]},[,h]=l(0);let c=`M 0 ${i} L 0 ${h.toFixed(1)}`;for(let u=0;u<s-1;u++){const[f,p]=l(u-1),[m,v]=l(u),[y,d]=l(u+1),[k,C]=l(u+2),A=m+(y-f)*o,Z=Math.min(i,Math.max(0,v+(d-p)*o)),P=y-(k-m)*o,R=Math.min(i,Math.max(0,d-(C-v)*o));c+=` C ${A.toFixed(1)} ${Z.toFixed(1)} ${P.toFixed(1)} ${R.toFixed(1)} ${y.toFixed(1)} ${d.toFixed(1)}`}return c+=` L ${e} ${i} Z`,c}async function at(r,t){if(r.src)return{roll:r.roll,mediaUrl:r.src,clickThrough:r.clickUrl,impressions:[],tracking:{}};if(!r.vastTag)throw new Error('Ad roll has neither "vastTag" nor "src"');return lt(r,r.vastTag,t,0,{impressions:[],tracking:{}})}async function lt(r,t,e,i,s){if(i>e.maxWrapperDepth)throw new Error("VAST wrapper depth limit exceeded");const n=new AbortController,o=setTimeout(()=>n.abort(),e.requestTimeout);let l;try{const v=await fetch(t,{signal:n.signal,credentials:"omit"});if(!v.ok)throw new Error(`VAST request failed (${v.status})`);l=await v.text()}finally{clearTimeout(o)}const h=new DOMParser().parseFromString(l,"text/xml");if(h.querySelector("parsererror"))throw new Error("VAST response is not valid XML");const c=h.querySelector("VAST > Ad");if(!c)throw new Error("VAST response contains no ads");Bt(c,s);const u=c.querySelector(":scope > Wrapper");if(u){const v=S(u.querySelector("VASTAdTagURI"));if(!v)throw new Error("VAST wrapper without VASTAdTagURI");return lt(r,v,e,i+1,s)}const f=c.querySelector(":scope > InLine");if(!f)throw new Error("VAST ad has neither InLine nor Wrapper");const p=f.querySelector("Creatives > Creative > Linear");if(!p)throw new Error("VAST ad has no Linear creative");const m=Et(p);if(!m)throw new Error("VAST ad has no playable MediaFile");return{roll:r.roll,mediaUrl:m.url,mediaType:m.type,clickThrough:S(p.querySelector("VideoClicks > ClickThrough"))??r.clickUrl,duration:W(S(p.querySelector(":scope > Duration"))),skipOffset:Mt(p.getAttribute("skipoffset"),W(S(p.querySelector(":scope > Duration")))),impressions:s.impressions,tracking:s.tracking,adTitle:S(f.querySelector(":scope > AdTitle"))??void 0}}function Bt(r,t){var e,i;for(const s of r.querySelectorAll("Impression")){const n=S(s);n&&t.impressions.push(n)}for(const s of r.querySelectorAll("Linear > TrackingEvents > Tracking")){const n=s.getAttribute("event"),o=S(s);!n||!o||["start","firstQuartile","midpoint","thirdQuartile","complete","skip","pause","resume"].includes(n)&&((e=t.tracking)[n]??(e[n]=[])).push(o)}for(const s of r.querySelectorAll("Linear > VideoClicks > ClickTracking")){const n=S(s);n&&((i=t.tracking).click??(i.click=[])).push(n)}}function Et(r){const e=[...r.querySelectorAll("MediaFiles > MediaFile")].map(o=>({url:S(o)??"",type:o.getAttribute("type")??void 0,delivery:o.getAttribute("delivery")??"",bitrate:Number(o.getAttribute("bitrate")??0),apiFramework:o.getAttribute("apiFramework")??""})).filter(o=>o.url&&o.apiFramework.toUpperCase()!=="VPAID").filter(o=>!o.type||/(video\/(mp4|webm|ogg)|application\/(x-mpegurl|vnd\.apple\.mpegurl))/i.test(o.type));if(e.length===0)return null;e.sort((o,l)=>o.bitrate-l.bitrate);const i=e.filter(o=>o.delivery!=="streaming"),s=i.length>0?i:e,n=s[Math.floor(s.length/2)];return{url:n.url,type:n.type}}function W(r){if(!r)return;const t=r.trim().match(/^(?:(\d+):)?(\d{1,2}):(\d{2})(?:\.(\d{1,3}))?$/);if(t)return(t[1]?Number(t[1])*3600:0)+Number(t[2])*60+Number(t[3])+(t[4]?Number(t[4].padEnd(3,"0"))/1e3:0)}function Mt(r,t){if(!r)return;const e=r.trim().match(/^(\d+(?:\.\d+)?)%$/);return e?t!==void 0?Number(e[1])/100*t:void 0:W(r)}function F(r){if(r)for(const t of r)try{new Image().src=t}catch{}}function S(r){return r?.textContent?.trim().replace(/^<!\[CDATA\[|\]\]>$/g,"").trim()||null}class Ct{constructor(t,e){this.host=t,this.playedRolls=new Set,this.sourcesSeen=0,this.activeBreak=null,this.layer=null,this.adVideo=null,this.destroyed=!1,this.opts={skipDelay:5,maxWrapperDepth:3,requestTimeout:8e3,mediaTimeout:1e4,playOn:"every",...e}}ensureAdVideo(){if(!this.adVideo){this.adVideo=a("video","imp-ad__video",{playsinline:""});try{this.adVideo.load()}catch{}}return this.adVideo}get adPlaying(){return this.activeBreak!==null}get hasPendingPreRoll(){return this.pending("preRoll").length>0}resetForNewSource(){if(this.sourcesSeen++,this.opts.playOn==="first"&&this.sourcesSeen>1){for(const t of this.opts.adList)this.playedRolls.add(t);return}this.playedRolls.clear()}async playPreRoll(){await this.playRolls(this.pending("preRoll"))}async playPostRoll(){await this.playRolls(this.pending("postRoll"))}checkMidRolls(t){if(this.adPlaying)return;const e=this.pending("midRoll").filter(i=>i.timer!==void 0&&t>=i.timer);e.length>0&&this.playRolls(e)}pending(t){return this.opts.adList.filter(e=>e.roll===t&&!this.playedRolls.has(e))}async playRolls(t){if(t.length===0||this.destroyed)return;if(this.activeBreak)return this.activeBreak;this.ensureAdVideo();const e=(async()=>{const i=this.host.contentVideo,s=!i.paused&&!i.ended;i.pause();for(const n of t){this.playedRolls.add(n);try{const o=await at(n,this.opts);await this.playAd(o)}catch(o){const l=o instanceof Error?o:new Error(String(o));this.host.emitter.emit("aderror",{roll:n,error:l})}if(this.destroyed)return}(s||t[0].roll==="preRoll")&&i.play().catch(()=>{})})();return this.activeBreak=e.finally(()=>{this.activeBreak=null}),this.activeBreak}playAd(t){return new Promise(e=>{const{labels:i}=this.host,s=a("div","imp-ad"),n=this.ensureAdVideo(),o=new AbortController,l=o.signal;n.src=t.mediaUrl,n.muted=this.host.contentVideo.muted,n.volume=this.host.contentVideo.volume;const h=a("div","imp-spinner imp-ad__spinner"),c=a("div","imp-ad__hud"),u=a("span","imp-ad__badge");u.textContent=t.adTitle?`${i.adLabel} · ${t.adTitle}`:i.adLabel;const f=a("span","imp-ad__countdown");c.append(u,f);const p=a("div","imp-ad__actions");let m=null;t.clickThrough&&(m=a("button","imp-ad__visit",{type:"button"}),m.textContent=i.visitAdvertiser,p.append(m));const v=a("button","imp-ad__skip",{type:"button"});v.hidden=!0,p.append(v),s.append(n,h,c,p),this.host.container.append(s),this.layer=s;const y=t.skipOffset??this.opts.skipDelay,d=new Set,k=w=>{d.has(w)||(d.add(w),F(t.tracking[w]))};let C=Date.now(),A=-1;const Z=setInterval(()=>{if(n.paused){C=Date.now();return}if(n.currentTime!==A){A=n.currentTime,C=Date.now();return}Date.now()-C>=this.opts.mediaTimeout&&(this.host.emitter.emit("aderror",{roll:{roll:t.roll},error:new Error(`Ad media stalled for ${this.opts.mediaTimeout} ms — skipping`)}),P())},500),P=()=>{clearInterval(Z),o.abort(),n.pause(),n.removeAttribute("src"),n.load(),s.remove(),this.layer=null,e()},R=w=>{w?(k("skip"),this.host.emitter.emit("adskip",{ad:t})):k("complete"),this.host.emitter.emit("adend",{ad:t}),P()};n.addEventListener("playing",()=>{F(t.impressions),k("start"),this.host.emitter.emit("adstart",{ad:t})},{once:!0,signal:l}),n.addEventListener("playing",()=>{h.hidden=!0},{signal:l}),n.addEventListener("waiting",()=>{h.hidden=!1},{signal:l}),n.addEventListener("timeupdate",()=>{const w=n.currentTime,B=n.duration;if(Number.isFinite(B)&&B>0&&(f.textContent=L(Math.max(0,B-w)),w/B>=.25&&k("firstQuartile"),w/B>=.5&&k("midpoint"),w/B>=.75&&k("thirdQuartile")),y>=0){const K=Math.ceil(y-w);K>0?(v.hidden=!1,v.disabled=!0,v.textContent=`${i.skipAdIn} ${K}`):(v.hidden=!1,v.disabled=!1,v.textContent=i.skipAd)}},{signal:l}),n.addEventListener("ended",()=>R(!1),{signal:l}),n.addEventListener("error",()=>{this.host.emitter.emit("aderror",{roll:{roll:t.roll},error:new Error("Ad media failed to play")}),P()},{signal:l}),v.addEventListener("click",()=>R(!0));const Q=()=>{t.clickThrough&&(k("click"),this.host.emitter.emit("adclick",{ad:t}),window.open(t.clickThrough,"_blank","noopener"),n.pause())};n.addEventListener("click",Q,{signal:l}),m?.addEventListener("click",Q);let U=!1,N=!1;n.addEventListener("playing",()=>{U=!0},{once:!0,signal:l}),n.addEventListener("pause",()=>{n.ended||!s.isConnected||(s.classList.add("imp-ad--paused"),U&&!N&&(N=!0,F(t.tracking.pause),this.host.emitter.emit("adpause",{ad:t})))},{signal:l}),n.addEventListener("play",()=>{s.classList.remove("imp-ad--paused"),N&&(N=!1,F(t.tracking.resume),this.host.emitter.emit("adresume",{ad:t}))},{signal:l}),s.addEventListener("click",w=>{(w.target===s||s.classList.contains("imp-ad--paused"))&&n.paused&&n.play().catch(()=>{})}),n.play().catch(()=>{s.classList.add("imp-ad--paused")})})}get closeIcon(){return this.host.closeIcon}destroy(){this.destroyed=!0,this.adVideo?.pause(),this.layer?.remove(),this.layer=null,this.adVideo=null}}function z(r,t){const e=[...r].sort((s,n)=>s.start-n.start),i=[];for(let s=0;s<e.length;s++){const n=Math.max(0,e[s].start);if(Number.isFinite(t)&&n>=t)continue;let o=e[s].end??e[s+1]?.start??t;Number.isFinite(t)&&(o=Math.min(o,t)),!(!Number.isFinite(o)||o<=n)&&i.push({start:n,end:o,title:e[s].title})}return i}async function ht(r){const t=await fetch(r);if(!t.ok)throw new Error(`Failed to load chapters VTT (${t.status})`);const e=await t.text();return tt(e).map(i=>({start:i.start,end:i.end,title:i.text}))}function j(r,t){for(const e of r)if(t>=e.start&&t<e.end)return e;return null}function ct(r,t){return t?/application\/(x-mpegurl|vnd\.apple\.mpegurl)/i.test(t):/\.m3u8(\?|#|$)/i.test(r)}let E;async function Pt(){if(E!==void 0)return E;const r=globalThis.Hls;if(r)return E=r,E;try{return E=(await import("hls.js/light")).default,E}catch{return null}}async function At(r,t,e,i){if(ct(t,e)){const s=r.canPlayType("application/vnd.apple.mpegurl"),n=s?null:await Pt();return n&&n.isSupported()?Rt(n,r,t,i):s?(r.src=t,G(r)):(i.onError("HLS is not supported in this browser and hls.js could not be loaded."),G(r))}return r.src=t,G(r)}function G(r){return{kind:"native",levels:[],selected:-1,setLevel(){},destroy(){r.removeAttribute("src"),r.load()}}}function Rt(r,t,e,i){const s=new r({enableWorker:!0}),n={kind:"hls",levels:[],selected:-1,setLevel(c){n.selected=c,s.currentLevel=c},destroy(){s.destroy(),t.removeAttribute("src"),t.load()}};s.on(r.Events.MANIFEST_PARSED,()=>{n.levels=s.levels.map((c,u)=>({index:u,label:c.height?`${c.height}p`:`${Math.round(c.bitrate/1e3)} kbps`})).reverse(),i.onLevels(n.levels)}),s.on(r.Events.LEVEL_SWITCHED,(c,u)=>{const f=s.levels[u.level];f&&i.onLevelSwitch(f.height?`${f.height}p`:`${Math.round(f.bitrate/1e3)} kbps`)});let o=0,l=0,h=!1;return s.on(r.Events.FRAG_BUFFERED,()=>{l=0}),s.on(r.Events.ERROR,(c,u)=>{if(u.fatal)switch(u.type){case r.ErrorTypes.NETWORK_ERROR:l<3?(l++,s.startLoad()):(i.onError(`HLS network error: ${u.details}`,u),s.destroy());break;case r.ErrorTypes.MEDIA_ERROR:o<3?(o++,s.recoverMediaError()):(i.onError(`HLS media error: ${u.details}`,u),s.destroy());break;default:if(h)i.onError(`HLS fatal error: ${u.details}`,u),s.destroy();else{h=!0;try{s.loadSource(e),s.startLoad()}catch{i.onError(`HLS fatal error: ${u.details}`,u),s.destroy()}}}}),s.loadSource(e),s.attachMedia(t),n}class H{constructor(t){this.cues=t}static async load(t){const e=await fetch(t);if(!e.ok)throw new Error(`Failed to load thumbnails VTT (${e.status})`);const i=await e.text(),s=[];for(const n of tt(i)){const[o,l]=n.text.trim().split("#");if(!o)continue;const h={start:n.start,end:n.end,src:kt(o,t)},c=l?.match(/xywh=(\d+),(\d+),(\d+),(\d+)/);c&&(h.xywh={x:Number(c[1]),y:Number(c[2]),w:Number(c[3]),h:Number(c[4])}),s.push(h)}return s.sort((n,o)=>n.start-o.start),new H(s)}cueAt(t){let e=0,i=this.cues.length-1;for(;e<=i;){const s=e+i>>1,n=this.cues[s];if(t<n.start)i=s-1;else if(t>=n.end)e=s+1;else return n}return null}}const Nt='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 6 6 6-6 6"/></svg>',It='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 6-6 6 6 6"/></svg>';class M{constructor(t){this.anchor=t,this.outsideListener=null,this.escListener=null,this.root=a("div","imp-menu"),this.root.hidden=!0,this.backdrop=a("div","imp-menu__backdrop"),this.backdrop.hidden=!0,this.backdrop.addEventListener("pointerdown",e=>{e.preventDefault(),this.close()})}get open(){return!this.root.hidden}toggle(t){this.open?this.close():this.show(t)}show(t){this.root.textContent="";for(const e of t)e.items.length!==0&&this.root.append(this.renderSection(e));this.reveal()}toggleSettings(t,e){this.open?this.close():this.showSettings(t,e)}showSettings(t,e){this.root.classList.add("imp-menu--wide"),this.renderSettingsRoot(e),this.reveal()}renderSettingsRoot(t){this.root.textContent="";const e=a("div","imp-menu__section");for(const i of t){if(i.toggle){e.append(this.buildToggleRow(i,i.toggle));continue}const s=a("button","imp-menu__item imp-menu__row",{type:"button"}),n=a("span","imp-menu__label");n.textContent=i.label;const o=a("span","imp-menu__value");o.textContent=i.value??"";const l=a("span","imp-menu__chevron");l.innerHTML=Nt,s.append(n,o,l),s.addEventListener("click",()=>this.renderSettingsDetail(t,i)),e.append(s)}this.root.append(e)}buildToggleRow(t,e){const i=a("button","imp-menu__item imp-menu__row imp-menu__toggle",{type:"button",role:"switch","aria-checked":String(e.value)}),s=a("span","imp-menu__label");s.textContent=t.label;const n=a("span","imp-switch");return n.append(a("span","imp-switch__knob")),i.classList.toggle("imp-menu__toggle--on",e.value),i.append(s,n),i.addEventListener("click",()=>{const o=i.getAttribute("aria-checked")!=="true";i.setAttribute("aria-checked",String(o)),i.classList.toggle("imp-menu__toggle--on",o),e.onChange(o)}),i}renderSettingsDetail(t,e){if(!e.section)return;this.root.textContent="";const i=a("button","imp-menu__item imp-menu__back",{type:"button"}),s=a("span","imp-menu__chevron");s.innerHTML=It;const n=a("span","imp-menu__label");n.textContent=e.label,i.append(s,n),i.addEventListener("click",()=>this.renderSettingsRoot(t)),this.root.append(i),this.root.append(this.renderSection(e.section())),this.root.scrollTop=0}renderSection(t){const e=a("div","imp-menu__section");if(t.title){const i=a("div","imp-menu__title");i.textContent=t.title,e.append(i)}for(const i of t.items){const s=a("button","imp-menu__item",{type:"button",role:"menuitemradio"});if(s.setAttribute("aria-checked",String(i.active)),i.active&&s.classList.add("imp-menu__item--active"),i.icon){const o=a("span","imp-menu__icon");_(o,i.icon),s.append(o)}const n=a("span","imp-menu__label");n.textContent=i.label,s.append(n),s.addEventListener("click",()=>{t.onSelect(i.value),this.close()}),e.append(s)}return e}reveal(){const t=this.root.parentElement;t&&this.backdrop.parentElement!==t&&t.insertBefore(this.backdrop,this.root),this.root.hidden=!1,this.backdrop.hidden=!1,this.outsideListener=e=>{const i=e.target;!this.root.contains(i)&&!this.anchor.contains(i)&&this.close()},this.escListener=e=>{e.key==="Escape"&&this.close()},document.addEventListener("keydown",this.escListener),setTimeout(()=>{this.outsideListener&&document.addEventListener("pointerdown",this.outsideListener)},0)}close(){this.root.hidden=!0,this.root.classList.remove("imp-menu--wide"),this.backdrop.hidden=!0,this.outsideListener&&(document.removeEventListener("pointerdown",this.outsideListener),this.outsideListener=null),this.escListener&&(document.removeEventListener("keydown",this.escListener),this.escListener=null)}destroy(){this.close(),this.backdrop.remove(),this.root.remove()}}class Ft{constructor(t,e="Seek"){this.cb=t,this.segments=[],this.duration=0,this.chapters=[],this.thumbnails=null,this.scrubbing=!1,this.root=a("div","imp-progress",{role:"slider","aria-label":e,tabindex:"-1"}),this.buffered=a("div","imp-progress__buffered"),this.track=a("div","imp-progress__track"),this.handle=a("div","imp-progress__handle"),this.tooltipThumb=a("div","imp-progress__thumb"),this.tooltipChapter=a("div","imp-progress__tooltip-chapter"),this.tooltipTime=a("div","imp-progress__tooltip-time"),this.tooltipCaption=a("div","imp-progress__caption"),this.tooltipCaption.append(this.tooltipChapter,this.tooltipTime),this.tooltip=a("div","imp-progress__tooltip"),this.tooltip.append(this.tooltipThumb,this.tooltipCaption),this.heatmap=a("div","imp-progress__heatmap"),this.heatmap.hidden=!0,this.root.append(this.heatmap,this.buffered,this.track,this.handle,this.tooltip),this.setChapters([]),this.bindPointer()}setHeatmap(t,e=1){if(t.length===0){this.heatmap.hidden=!0,this.heatmap.textContent="";return}this.heatmap.innerHTML=`<svg viewBox="0 0 1000 100" preserveAspectRatio="none" aria-hidden="true"><path d="${ot(t,e)}"/></svg>`,this.heatmap.hidden=!1}setDuration(t){this.duration=Number.isFinite(t)?t:0,this.root.classList.toggle("imp-progress--live",!Number.isFinite(t)),this.chapters.length===0&&this.setChapters([])}setChapters(t){this.chapters=t,this.track.textContent="",this.segments=[];const e=t.length>0?t:[{start:0,end:this.duration||1,title:""}],i=[];let s=0;for(const n of e)n.start>s&&i.push({start:s,end:n.start,title:""}),i.push(n),s=n.end;this.duration>0&&s<this.duration&&i.push({start:s,end:this.duration,title:""});for(const n of i){const o=a("div","imp-progress__segment");o.style.flexGrow=String(Math.max(n.end-n.start,.01));const l=a("div","imp-progress__fill");o.append(l),this.track.append(o),this.segments.push({chapter:n,root:o,fill:l})}}setThumbnails(t){this.thumbnails=t}update(t,e,i){if(e!==this.duration&&Number.isFinite(e)&&this.setDuration(e),this.scrubbing)return;this.render(t);const s=this.duration>0?x(i/this.duration,0,1):0;this.buffered.style.width=`${s*100}%`,this.root.setAttribute("aria-valuemin","0"),this.root.setAttribute("aria-valuemax",String(Math.round(this.duration))),this.root.setAttribute("aria-valuenow",String(Math.round(t))),this.root.setAttribute("aria-valuetext",`${L(t)} / ${L(this.duration)}`)}render(t){for(const{chapter:i,fill:s}of this.segments){const n=i.end-i.start,o=n>0?x((t-i.start)/n,0,1):0;s.style.transform=`scaleX(${o})`}const e=this.duration>0?x(t/this.duration,0,1):0;this.handle.style.left=`${e*100}%`}timeFromEvent(t){const e=this.root.getBoundingClientRect();return(e.width>0?x((t.clientX-e.left)/e.width,0,1):0)*this.duration}bindPointer(){this.root.addEventListener("pointerdown",t=>{this.duration<=0||(t.preventDefault(),this.scrubbing=!0,this.root.classList.add("imp-progress--scrubbing"),this.root.setPointerCapture(t.pointerId),this.cb.onScrubStart(),this.render(this.timeFromEvent(t)),this.showTooltip(t))}),this.root.addEventListener("pointermove",t=>{this.duration<=0||(this.showTooltip(t),this.scrubbing&&this.render(this.timeFromEvent(t)))}),this.root.addEventListener("pointerup",t=>{this.scrubbing&&(this.scrubbing=!1,this.root.classList.remove("imp-progress--scrubbing"),this.cb.onSeek(this.timeFromEvent(t)),this.cb.onScrubEnd())}),this.root.addEventListener("pointercancel",()=>{this.scrubbing=!1,this.root.classList.remove("imp-progress--scrubbing"),this.cb.onScrubEnd()}),this.root.addEventListener("pointerleave",()=>this.hideTooltip())}showTooltip(t){const e=this.timeFromEvent(t);this.tooltipTime.textContent=L(e);const i=j(this.chapters,e),s=!!i?.title;this.tooltipChapter.textContent=i?.title??"",this.tooltipChapter.hidden=!s,this.tooltipCaption.classList.toggle("imp-progress__caption--time-only",!s);const n=this.thumbnails?.cueAt(e)??null;this.tooltip.classList.toggle("imp-progress__tooltip--thumb",!!n),n?(this.tooltipThumb.hidden=!1,this.tooltipThumb.style.backgroundImage=`url("${n.src}")`,n.xywh?(this.tooltipThumb.style.width=`${n.xywh.w}px`,this.tooltipThumb.style.height=`${n.xywh.h}px`,this.tooltipThumb.style.backgroundPosition=`-${n.xywh.x}px -${n.xywh.y}px`,this.tooltipThumb.style.backgroundSize="auto"):(this.tooltipThumb.style.width="160px",this.tooltipThumb.style.height="90px",this.tooltipThumb.style.backgroundPosition="center",this.tooltipThumb.style.backgroundSize="cover")):this.tooltipThumb.hidden=!0,this.tooltip.classList.add("imp-progress__tooltip--visible");const o=this.root.getBoundingClientRect(),l=x(t.clientX-o.left,0,o.width),h=this.tooltip.offsetWidth/2;this.tooltip.style.left=`${x(l,h,Math.max(h,o.width-h))}px`}hideTooltip(){this.tooltip.classList.remove("imp-progress__tooltip--visible")}}class qt{constructor(t){this.player=t,this.rightItems=new Map,this.subtitlesBtn=null,this.settingsBtn=null,this.settingsMenu=null,this.subtitlesMenu=null,this.moreMenu=null,this.moreWrap=null,this.qualityBtn=null,this.qualityMenu=null,this.gearBtn=null,this.gearMenu=null,this.gear={speed:!1,quality:!1,subtitles:!1},this.nextPreviewEl=null,this.nextPreviewOpts=null,this.scenesBtn=null,this.sceneTypeBtn=null,this.sceneTypeMenu=null,this.likeBtn=null,this.dislikeBtn=null,this.likeCountEl=null,this.dislikeCountEl=null,this.prevBtn=null,this.nextBtn=null,this.seekBackBtn=null,this.seekFwdBtn=null,this.centerPlayBtn=null,this.centerPrevBtn=null,this.centerNextBtn=null,this.collapsibles=[],this.overflowed=new Set,this.resizeObserver=null,this.reflowScheduled=!1,this.actionItems=[],this.wasPlayingBeforeScrub=!1,this.disposers=[],this.onWindowResize=null;const{labels:e,icons:i}=t,s=t.controlsOptions;this.root=a("div","imp-controls"),this.progress=new Ft({onSeek:d=>t.seek(d),onScrubStart:()=>{t.scrubbing=!0,this.wasPlayingBeforeScrub=!t.paused,t.pause()},onScrubEnd:()=>{t.scrubbing=!1,this.wasPlayingBeforeScrub?t.play(!0):t.started||t.play()}},t.labels.seek),s.progress&&this.root.append(this.progress.root);const n=a("div","imp-controls__row");this.row=n,this.root.append(n);const o=a("div","imp-controls__group"),l=a("div","imp-controls__group");this.rightGroup=l;const h=a("div","imp-controls__spacer");this.chapterLabel=a("div","imp-controls__chapter"),n.append(o,h,l),h.append(this.chapterLabel);const c=typeof s.seekButtons=="object"?s.seekButtons:{},u=c.back??t.seekStep,f=c.forward??t.seekStep;if(this.seekLabelFn=c.label,s.playlist&&t.hasPlaylist&&!s.hidePrev&&(this.prevBtn=b("imp-btn--prev",e.previous,i.previous),this.prevBtn.addEventListener("click",()=>t.previous()),o.append(this.prevBtn)),s.seekButtons&&(this.seekBackBtn=b("imp-btn--seek-back",`${e.seekBack} ${u}s`,i.seekBack),this.addStepBadge(this.seekBackBtn,u,"back"),this.seekBackBtn.addEventListener("click",()=>t.skip(-u)),o.append(this.seekBackBtn)),s.play&&(this.playBtn=b("imp-btn--play",e.play,i.play),this.playBtn.addEventListener("click",()=>t.togglePlay()),o.append(this.playBtn)),s.seekButtons&&(this.seekFwdBtn=b("imp-btn--seek-forward",`${e.seekForward} ${f}s`,i.seekForward),this.addStepBadge(this.seekFwdBtn,f,"forward"),this.seekFwdBtn.addEventListener("click",()=>t.skip(f)),o.append(this.seekFwdBtn)),s.playlist&&t.hasPlaylist&&!s.hideNext&&(this.nextBtn=b("imp-btn--next",e.next,i.next),this.nextBtn.addEventListener("click",()=>t.next()),o.append(this.nextBtn)),s.volume){const d=a("div","imp-volume");this.muteBtn=b("imp-btn--mute",e.mute,i.volumeHigh),this.muteBtn.addEventListener("click",()=>t.toggleMute()),this.volumeSlider=a("input","imp-volume__slider",{type:"range",min:"0",max:"1",step:"0.05","aria-label":e.volume}),this.volumeSlider.addEventListener("input",()=>{t.setVolume(Number(this.volumeSlider.value))}),d.append(this.muteBtn,this.volumeSlider),o.append(d)}s.time&&(this.timeLabel=a("div","imp-controls__time"),this.timeCurrent=a("span","imp-controls__time-current"),this.timeTotal=a("span","imp-controls__time-total"),this.timeLabel.append(this.timeCurrent,this.timeTotal),this.liveBadge=a("span","imp-controls__live"),this.liveBadge.textContent=e.live,this.liveBadge.hidden=!0,o.append(this.timeLabel,this.liveBadge)),this.buildLikeDislike();for(const d of(t.actionsOptions.custom??[]).filter(k=>k.placement==="bar")){const k=b(`imp-btn--custom imp-btn--custom-${d.id}`,d.title,d.icon??i.more);k.addEventListener("click",()=>t.emit("customaction",{id:d.id})),this.rightItems.set(`custom:${d.id}`,k),this.registerCollapsible({key:`custom:${d.id}`,el:k,priority:55,available:()=>!0,section:()=>this.simpleSection(`custom:${d.id}`,d.title,d.icon??i.more,()=>t.emit("customaction",{id:d.id}))})}const p=d=>d===!1?"off":d==="bar"?"bar":"gear",m=p(s.subtitles),v=p(s.quality),y=p(s.speed);if(this.gear={speed:y==="gear",quality:v==="gear",subtitles:m==="gear"},m==="bar"){this.subtitlesBtn=b("imp-btn--subtitles",e.subtitles,i.subtitles),this.subtitlesMenu=new M(this.subtitlesBtn);const d=a("div","imp-controls__menu-anchor");d.append(this.subtitlesBtn,this.subtitlesMenu.root),this.subtitlesBtn.addEventListener("click",()=>this.toggleSubtitlesMenu()),this.rightItems.set("subtitles",d),this.registerCollapsible({key:"subtitles",el:d,priority:30,available:()=>t.subtitleTracks.length>0,section:()=>this.subtitlesSection()})}if(v==="bar"){this.qualityBtn=b("imp-btn--quality",e.quality,i.settings),this.qualityMenu=new M(this.qualityBtn);const d=a("div","imp-controls__menu-anchor");d.append(this.qualityBtn,this.qualityMenu.root),this.qualityBtn.addEventListener("click",()=>this.toggleQualityMenu()),this.rightItems.set("quality",d),this.registerCollapsible({key:"quality",el:d,priority:10,available:()=>t.qualityLevels.length>0,section:()=>this.qualitySection()})}if(y==="bar"){this.settingsBtn=b("imp-btn--speed",e.speed,i.speed),this.settingsMenu=new M(this.settingsBtn);const d=a("div","imp-controls__menu-anchor");d.append(this.settingsBtn,this.settingsMenu.root),this.settingsBtn.addEventListener("click",()=>this.toggleSettingsMenu()),this.rightItems.set("speed",d),this.registerCollapsible({key:"speed",el:d,priority:40,available:()=>!0,section:()=>this.speedSection()})}if(s.scenes&&(this.scenesBtn=b("imp-btn--scenes",e.scenes,i.scenes),this.scenesBtn.addEventListener("click",()=>t.toggleScenesPanel()),this.rightItems.set("scenes",this.scenesBtn),this.registerCollapsible({key:"scenes",el:this.scenesBtn,priority:25,available:()=>t.chapterList.length>0,section:()=>this.simpleSection("scenes",e.scenes,i.scenes,()=>t.toggleScenesPanel())})),s.sceneTypes!==!1){this.sceneTypeBtn=a("button","imp-btn imp-btn--scene-types",{type:"button"}),this.sceneTypeMenu=new M(this.sceneTypeBtn);const d=a("div","imp-controls__menu-anchor");d.append(this.sceneTypeBtn,this.sceneTypeMenu.root),this.sceneTypeBtn.addEventListener("click",()=>this.toggleSceneTypeMenu()),this.rightItems.set("sceneTypes",d),this.refreshSceneTypeButton(),this.registerCollapsible({key:"sceneTypes",el:d,priority:68,available:()=>t.sceneTypes.length>0,section:()=>this.sceneTypeSection()})}if(s.playlist&&t.hasPlaylist&&s.playlistButton!==!1){const d=b("imp-btn--list",e.playlist,i.list);d.addEventListener("click",()=>t.togglePlaylistPanel()),this.rightItems.set("playlist",d),this.registerCollapsible({key:"list",el:d,priority:50,available:()=>!0,section:()=>this.simpleSection("list",e.playlist,i.list,()=>t.togglePlaylistPanel())})}if(s.pip&&"requestPictureInPicture"in HTMLVideoElement.prototype){const d=b("imp-btn--pip",e.pip,i.pip);d.addEventListener("click",()=>void t.togglePip()),this.rightItems.set("pip",d),this.registerCollapsible({key:"pip",el:d,priority:20,available:()=>!0,section:()=>this.simpleSection("pip",e.pip,i.pip,()=>void t.togglePip())})}if(s.fullscreen&&(this.fullscreenBtn=b("imp-btn--fullscreen",e.fullscreen,i.fullscreen),this.fullscreenBtn.addEventListener("click",()=>void t.toggleFullscreen()),this.rightItems.set("fullscreen",this.fullscreenBtn)),this.prevBtn&&this.registerCollapsible({key:"prev",el:this.prevBtn,priority:70,available:()=>!0,section:()=>t.hasPrevious?this.simpleSection("prev",e.previous,i.previous,()=>t.previous()):null}),this.nextBtn&&this.registerCollapsible({key:"next",el:this.nextBtn,priority:72,available:()=>!0,section:()=>t.hasNext?this.simpleSection("next",e.next,i.next,()=>t.next()):null}),this.seekBackBtn){const d=this.seekBackBtn;this.registerCollapsible({key:"seekBack",el:d,priority:80,available:()=>Number.isFinite(t.duration)&&t.duration>0,section:()=>this.simpleSection("seekBack",`${e.seekBack} ${u}s`,i.seekBack,()=>t.skip(-u))})}if(this.seekFwdBtn){const d=this.seekFwdBtn;this.registerCollapsible({key:"seekFwd",el:d,priority:82,available:()=>Number.isFinite(t.duration)&&t.duration>0,section:()=>this.simpleSection("seekFwd",`${e.seekForward} ${f}s`,i.seekForward,()=>t.skip(f))})}if(this.center=a("div","imp-center-controls"),s.playlist&&t.hasPlaylist&&(this.centerPrevBtn=this.makeCenterButton("prev",e.previous,i.previous),this.centerPrevBtn.addEventListener("click",()=>t.previous()),this.center.append(this.centerPrevBtn)),s.seekButtons){const d=this.makeCenterButton("seek-back",`${e.seekBack} ${u}s`,i.seekBack);this.addStepBadge(d,u,"back"),d.addEventListener("click",()=>t.skip(-u)),this.center.append(d)}if(s.play&&(this.centerPlayBtn=this.makeCenterButton("play",e.play,i.play),this.centerPlayBtn.addEventListener("click",()=>t.togglePlay()),this.center.append(this.centerPlayBtn)),s.seekButtons){const d=this.makeCenterButton("seek-forward",`${e.seekForward} ${f}s`,i.seekForward);this.addStepBadge(d,f,"forward"),d.addEventListener("click",()=>t.skip(f)),this.center.append(d)}if(s.playlist&&t.hasPlaylist&&(this.centerNextBtn=this.makeCenterButton("next",e.next,i.next),this.centerNextBtn.addEventListener("click",()=>t.next()),this.center.append(this.centerNextBtn)),this.center.style.display="none",this.setupNextPreview(),this.gear.speed||this.gear.quality||this.gear.subtitles){this.gearBtn=b("imp-btn--settings",e.settings,i.settings),this.gearMenu=new M(this.gearBtn);const d=a("div","imp-controls__menu-anchor");d.append(this.gearBtn,this.gearMenu.root),this.gearBtn.addEventListener("click",()=>this.toggleGearMenu()),this.rightItems.set("gear",d),this.registerCollapsible({key:"gear",el:d,priority:40,available:()=>this.gearSections().length>0,section:()=>this.gearSections()})}this.layoutRightCluster(l),this.buildMoreDropdown(l),this.bind(),this.syncVolume(),this.syncPlayState(),this.setLikeState(t.actionsOptions.likeState??null),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.scheduleReflow()),this.resizeObserver.observe(t.container)),this.onWindowResize=()=>this.scheduleReflow(),window.addEventListener("resize",this.onWindowResize)}registerCollapsible(t){this.collapsibles.push(t)}layoutRightCluster(t){const e=[...this.rightItems.keys()],i=this.player.controlsOptions.order;let s=e;if(i.length>0){const n=new Set;s=[];for(const o of i)this.rightItems.has(o)&&!n.has(o)&&(s.push(o),n.add(o));for(const o of e)n.has(o)||s.push(o)}for(const n of s){const o=this.rightItems.get(n);o&&t.append(o)}}makeCenterButton(t,e,i){const s=a("button",`imp-center-btn imp-center-btn--${t}`,{type:"button","aria-label":e,title:e});return _(s,i),s}addStepBadge(t,e,i){const s=a("span","imp-seek-num");s.textContent=this.seekLabelFn?this.seekLabelFn(e,i):`${i==="back"?"−":"+"}${e}${this.player.labels.secondsShort}`,t.append(s)}gearSections(){const t=this.player,e=[];return this.gear.quality&&t.qualityLevels.length>0&&e.push(this.qualitySection()),this.gear.speed&&e.push(this.speedSection()),this.gear.subtitles&&t.subtitleTracks.length>0&&e.push(this.subtitlesSection()),e}gearEntries(){const t=this.player,e=[];if(t.hasPlaylist&&e.push({key:"autoplay",label:t.labels.autoplay,toggle:{value:t.autoAdvance,onChange:i=>t.setAutoAdvance(i)}}),this.gear.quality&&t.qualityLevels.length>0){const i=t.currentQuality===-1?t.labels.qualityAuto:t.qualityLevels.find(s=>s.index===t.currentQuality)?.label??t.labels.qualityAuto;e.push({key:"quality",label:t.labels.quality,value:i,section:()=>this.qualitySection()})}if(this.gear.speed){const i=t.playbackRate;e.push({key:"speed",label:t.labels.speed,value:i===1?t.labels.speedNormal:`${i}×`,section:()=>this.speedSection()})}if(this.gear.subtitles&&t.subtitleTracks.length>0){const i=t.activeSubtitle===-1?t.labels.subtitlesOff:t.subtitleTracks[t.activeSubtitle]?.label??t.labels.subtitlesOff;e.push({key:"subtitles",label:t.labels.subtitles,value:i,section:()=>this.subtitlesSection()})}return e}refreshSceneTypeButton(){const t=this.sceneTypeBtn;if(!t)return;const e=this.player.activeSceneType;if(t.textContent="",!e)return;if(e.icon){const s=a("span","imp-scene-type__icon");_(s,e.icon),t.append(s)}const i=a("span","imp-scene-type__label");i.textContent=e.title,t.append(i),t.setAttribute("aria-label",`${this.player.labels.sceneTypes}: ${e.title}`),t.title=e.title}sceneTypeSection(){const t=this.player;return{title:t.labels.sceneTypes,items:t.sceneTypes.map(e=>({label:e.title,value:e.id,icon:e.icon,active:e.id===(t.activeSceneType?.id??"")})),onSelect:e=>{t.setSceneGroup(e),this.refreshSceneTypeButton()}}}toggleSceneTypeMenu(){!this.sceneTypeMenu||this.player.sceneTypes.length===0||(this.closeMenus(this.sceneTypeMenu),this.sceneTypeMenu.toggle([this.sceneTypeSection()]))}toggleGearMenu(){if(!this.gearMenu)return;const t=this.gearEntries();t.length!==0&&(this.closeMenus(this.gearMenu),this.gearMenu.toggleSettings(this.player.labels.settings,t))}setupNextPreview(){const t=this.player,e=t.controlsOptions;if(e.nextPreview===!1||!e.playlist||!t.hasPlaylist)return;const i=typeof e.nextPreview=="object"?e.nextPreview:{};this.nextPreviewOpts={thumbnail:i.thumbnail??!0,title:i.title??!0,duration:i.duration??!0,meta:i.meta??!0},this.nextPreviewEl=a("div","imp-next-preview"),this.nextPreviewEl.hidden=!0,t.container.append(this.nextPreviewEl),this.nextBtn&&this.bindNextPreview(this.nextBtn),this.centerNextBtn&&this.bindNextPreview(this.centerNextBtn)}bindNextPreview(t){t.addEventListener("pointerenter",e=>{e.pointerType==="mouse"&&this.showNextPreview(t)}),t.addEventListener("pointerleave",()=>this.hideNextPreview()),t.addEventListener("click",()=>this.hideNextPreview())}showNextPreview(t){const e=this.nextPreviewEl,i=this.nextPreviewOpts;if(!e||!i)return;const s=this.player.nextSource;if(!s){this.hideNextPreview();return}e.textContent="";const n=a("div","imp-next-preview__kicker");n.textContent=this.player.labels.next,e.append(n);const o=$.posterSrc(s.poster);if(i.thumbnail&&o){const m=a("div","imp-next-preview__thumb"),v=T(o);if(v.addEventListener("error",()=>{this.player.markSourceDead(s),this.nextPreviewEl&&!this.nextPreviewEl.hidden&&this.showNextPreview(t)},{once:!0}),m.append(v),i.duration&&s.duration){const y=a("span","imp-next-preview__duration");y.textContent=L(s.duration),m.append(y)}e.append(m)}if(i.title&&s.title){const m=a("div","imp-next-preview__title");m.textContent=s.title,e.append(m)}i.meta&&s.previewMeta?.length&&e.append(Y(s.previewMeta,"imp-next-preview")),e.hidden=!1;const l=this.player.container.getBoundingClientRect(),h=t.getBoundingClientRect(),c=8,u=e.offsetWidth,f=h.left-l.left+h.width/2-u/2,p=Math.max(c,Math.min(f,l.width-u-c));e.style.left=`${p}px`,e.style.bottom=`${l.height-(h.top-l.top)+10}px`}hideNextPreview(){this.nextPreviewEl&&(this.nextPreviewEl.hidden=!0)}buildLikeDislike(){const t=this.player,e=t.actionsOptions,{labels:i,icons:s}=t;if(e.like){this.likeBtn=b("imp-btn--like",i.like,s.like),this.likeBtn.addEventListener("click",()=>t.emit("action",{id:"like"})),this.likeCountEl=this.attachCountTooltip(this.likeBtn,e.likeCount);const n=this.wrapWithTooltip(this.likeBtn,this.likeCountEl);this.rightItems.set("like",n),this.registerCollapsible({key:"like",el:n,priority:62,available:()=>!0,section:()=>this.simpleSection("like",i.like,s.like,()=>t.emit("action",{id:"like"}))})}if(e.dislike){this.dislikeBtn=b("imp-btn--dislike",i.dislike,s.dislike),this.dislikeBtn.addEventListener("click",()=>t.emit("action",{id:"dislike"})),this.dislikeCountEl=this.attachCountTooltip(this.dislikeBtn,e.dislikeCount);const n=this.wrapWithTooltip(this.dislikeBtn,this.dislikeCountEl);this.rightItems.set("dislike",n),this.registerCollapsible({key:"dislike",el:n,priority:60,available:()=>!0,section:()=>this.simpleSection("dislike",i.dislike,s.dislike,()=>t.emit("action",{id:"dislike"}))})}}attachCountTooltip(t,e){const i=a("span","imp-count-tooltip");return this.setCountText(i,e),i}wrapWithTooltip(t,e){const i=a("div","imp-action");return i.append(t,e),i}setCountText(t,e){const i=e==null||e===""?"":String(e);t.textContent=i,t.hidden=i===""}setLikeCounts(t,e){this.likeCountEl&&t!==void 0&&this.setCountText(this.likeCountEl,t),this.dislikeCountEl&&e!==void 0&&this.setCountText(this.dislikeCountEl,e)}setLikeState(t){this.likeBtn?.classList.toggle("imp-btn--active",t==="like"),this.dislikeBtn?.classList.toggle("imp-btn--active",t==="dislike")}buildMoreDropdown(t){const e=this.player,i=e.actionsOptions,{labels:s,icons:n}=e;i.addTo&&this.actionItems.push({value:"addTo",label:s.addTo,icon:n.addTo,run:()=>e.emit("action",{id:"addTo"})}),i.share&&this.actionItems.push({value:"share",label:s.share,icon:n.share,run:()=>void e.share()}),i.report&&this.actionItems.push({value:"report",label:s.report,icon:n.report,run:()=>e.emit("action",{id:"report"})});for(const h of(i.custom??[]).filter(c=>c.placement!=="bar"))this.actionItems.push({value:`custom:${h.id}`,label:h.title,icon:h.icon,run:()=>e.emit("customaction",{id:h.id})});const o=b("imp-btn--more",s.more,n.more);this.moreMenu=new M(o);const l=a("div","imp-controls__menu-anchor imp-controls__more");l.append(o,this.moreMenu.root),o.addEventListener("click",()=>{this.closeMenus(this.moreMenu),this.moreMenu?.toggle(this.buildMoreSections())}),t.append(l),this.moreWrap=l}buildMoreSections(){const t=[],e=new Map,i=[],s=["prev","next","seekBack","seekFwd","like","dislike","scenes","sceneTypes","pip","list","subtitles","speed","quality","gear"],n=l=>{const h=s.indexOf(l);return h===-1?s.length:h},o=this.collapsibles.filter(l=>this.overflowed.has(l.key)&&l.available()).sort((l,h)=>n(l.key)-n(h.key));for(const l of o){const h=l.section();if(h)for(const c of Array.isArray(h)?h:[h])if(!c.title&&c.items.length===1){const u=c.items[0];i.push(u),e.set(u.value,()=>c.onSelect(u.value))}else t.push(c)}if(i.length>0&&t.unshift({title:"",items:i,onSelect:l=>e.get(l)?.()}),this.actionItems.length>0){const l=new Map(this.actionItems.map(h=>[h.value,h.run]));t.push({title:"",items:this.actionItems.map(({value:h,label:c,icon:u})=>({value:h,label:c,icon:u,active:!1})),onSelect:h=>l.get(h)?.()})}return t}simpleSection(t,e,i,s){return{title:"",items:[{value:t,label:e,icon:i,active:!1}],onSelect:()=>s()}}speedSection(){const t=this.player;return{title:t.labels.speed,items:t.playbackRates.map(e=>({label:e===1?t.labels.speedNormal:`${e}×`,value:String(e),active:t.playbackRate===e})),onSelect:e=>t.setPlaybackRate(Number(e))}}qualitySection(){const t=this.player;return{title:t.labels.quality,items:[...t.qualityAutoAvailable?[{label:t.labels.qualityAuto,value:"-1",active:t.currentQuality===-1}]:[],...t.qualityLevels.map(e=>({label:e.label,value:String(e.index),active:t.currentQuality===e.index}))],onSelect:e=>t.setQuality(Number(e))}}subtitlesSection(){const t=this.player;return{title:t.labels.subtitles,items:[{label:t.labels.subtitlesOff,value:"-1",active:t.activeSubtitle===-1},...t.subtitleTracks.map((e,i)=>({label:e.label,value:String(i),active:t.activeSubtitle===i}))],onSelect:e=>t.setSubtitle(Number(e))}}scheduleReflow(){this.reflowScheduled||(this.reflowScheduled=!0,requestAnimationFrame(()=>{this.reflowScheduled=!1,this.reflow()}))}reflow(){const t=window.innerWidth<=767,e=t&&this.player.controlsOptions.mobileLayout==="center",s=this.player.controlsOptions.seekPlacement!=="bar"||t;this.center.style.display=s?"flex":"none",this.centerPrevBtn&&(this.centerPrevBtn.style.display=e?"":"none"),this.centerNextBtn&&(this.centerNextBtn.style.display=e?"":"none"),this.playBtn&&(this.playBtn.style.display=e?"none":"");const n=h=>h==="seekBack"||h==="seekFwd"?s:h==="prev"||h==="next"?e:!1;this.overflowed.clear();for(const h of this.collapsibles){if(n(h.key)){h.el.style.display="none";continue}const c=h.available();h.el.style.display=c?"":"none",h.el.classList.remove("imp-collapsed")}const o=this.collapsibles.filter(h=>h.available()&&!n(h.key)).sort((h,c)=>h.priority-c.priority);let l=o.length;for(;l-- >0&&this.overflowsRow();){const h=o.find(c=>!this.overflowed.has(c.key));if(!h)break;h.el.style.display="none",h.el.classList.add("imp-collapsed"),this.overflowed.add(h.key)}if(this.moreWrap){const h=this.actionItems.length>0||this.overflowed.size>0;this.moreWrap.style.display=h?"":"none"}}overflowsRow(){const t=this.row.getBoundingClientRect().right;return this.rightGroup.getBoundingClientRect().right>t+1}bind(){const t=this.player;this.disposers.push(t.on("timeupdate",({currentTime:e,duration:i})=>{this.progress.update(e,i,t.bufferedEnd),this.timeLabel&&(t.live?(this.timeLabel.hidden=!0,this.liveBadge.hidden=!1):(this.timeLabel.hidden=!1,this.liveBadge.hidden=!0,this.timeCurrent.textContent=L(e),this.timeTotal.textContent=` / ${L(i)}`))}),t.on("play",()=>this.syncPlayState()),t.on("pause",()=>this.syncPlayState()),t.on("ended",()=>this.syncPlayState()),t.on("volumechange",()=>this.syncVolume()),t.on("chapterchange",({chapter:e})=>{this.chapterLabel.textContent=e?.title??""}),t.on("fullscreenchange",({active:e})=>{this.fullscreenBtn&&I(this.fullscreenBtn,e?t.icons.fullscreenExit:t.icons.fullscreen,e?t.labels.exitFullscreen:t.labels.fullscreen),this.scheduleReflow()}),t.on("playlistitemchange",()=>{this.syncPlaylistButtons(),this.scheduleReflow()}),t.on("sourcechange",()=>{this.syncPlaylistButtons(),this.scheduleReflow()})),this.syncPlaylistButtons(),this.reflow()}syncPlayState(){const t=this.player,[e,i]=t.ended?[t.icons.replay,t.labels.replay]:t.paused?[t.icons.play,t.labels.play]:[t.icons.pause,t.labels.pause];this.playBtn&&I(this.playBtn,e,i),this.centerPlayBtn&&I(this.centerPlayBtn,e,i)}syncVolume(){if(!this.muteBtn)return;const t=this.player,e=t.muted?0:t.volume,i=e===0?t.icons.volumeMute:e<.5?t.icons.volumeLow:t.icons.volumeHigh;I(this.muteBtn,i,t.muted?t.labels.unmute:t.labels.mute),this.volumeSlider.value=String(e),this.volumeSlider.style.setProperty("--imp-volume-fill",`${e*100}%`)}syncFeatureButtons(){this.refreshSceneTypeButton(),this.syncPlaylistButtons(),this.scheduleReflow()}syncPlaylistButtons(){const t=this.player;this.prevBtn&&(this.prevBtn.disabled=!t.hasPrevious),this.nextBtn&&(this.nextBtn.disabled=!t.hasNext),this.centerPrevBtn&&(this.centerPrevBtn.disabled=!t.hasPrevious),this.centerNextBtn&&(this.centerNextBtn.disabled=!t.hasNext)}closeMenus(t){for(const e of[this.gearMenu,this.settingsMenu,this.subtitlesMenu,this.qualityMenu,this.sceneTypeMenu,this.moreMenu])e&&e!==t&&e.close()}anyMenuOpen(){return[this.gearMenu,this.settingsMenu,this.subtitlesMenu,this.qualityMenu,this.sceneTypeMenu,this.moreMenu].some(t=>t?.open)}toggleSettingsMenu(){this.settingsMenu&&(this.closeMenus(this.settingsMenu),this.settingsMenu.toggle([this.speedSection()]))}toggleQualityMenu(){!this.qualityMenu||this.player.qualityLevels.length===0||(this.closeMenus(this.qualityMenu),this.qualityMenu.toggle([this.qualitySection()]))}toggleSubtitlesMenu(){!this.subtitlesMenu||this.player.subtitleTracks.length===0||(this.closeMenus(this.subtitlesMenu),this.subtitlesMenu.toggle([this.subtitlesSection()]))}destroy(){for(const t of this.disposers)t();this.disposers=[],this.resizeObserver?.disconnect(),this.onWindowResize&&window.removeEventListener("resize",this.onWindowResize),this.gearMenu?.destroy(),this.sceneTypeMenu?.destroy(),this.settingsMenu?.destroy(),this.subtitlesMenu?.destroy(),this.qualityMenu?.destroy(),this.moreMenu?.destroy(),this.nextPreviewEl?.remove(),this.root.remove()}}class $t{constructor(t){this.root=a("div","imp-poster"),this.image=a("div","imp-poster__image"),this.image.hidden=!0,this.img=T(""),this.image.append(this.img);const e=b("imp-poster__play",t.labels.play,t.icons.bigPlay);e.addEventListener("click",()=>void t.play()),this.root.append(this.image,e),this.root.addEventListener("pointerup",i=>{i.target!==this.root&&i.target!==this.image&&i.target!==this.img||i.pointerType==="touch"&&t.posterTapReveal()||t.play()})}setSource(t){const e=t?.poster;if(e){const i=typeof e=="string"?{src:e}:e;this.img.src=i.src,i.srcset?this.img.srcset=i.srcset:this.img.removeAttribute("srcset"),i.sizes?this.img.sizes=i.sizes:this.img.removeAttribute("sizes"),i.width?this.img.width=i.width:this.img.removeAttribute("width"),i.height?this.img.height=i.height:this.img.removeAttribute("height"),this.img.alt=i.alt??"",this.img.fetchPriority="high",this.image.hidden=!1}else this.img.removeAttribute("src"),this.image.hidden=!0}show(){this.root.hidden=!1}hide(){this.root.hidden=!0}}class Vt{constructor(t){this.labels=t,this.channelUrl=null,this.custom=null,this.visible={title:!0,description:!0,sponsor:!0},this.root=a("div","imp-pause-screen"),this.root.hidden=!0,this.defaultContent=a("div","imp-pause-screen__default"),this.channel=a("button","imp-channel",{type:"button"}),this.channel.hidden=!0,this.channelAvatar=a("div","imp-channel__avatar"),this.channelName=a("div","imp-channel__name"),this.channel.append(this.channelName,this.channelAvatar),this.channel.addEventListener("click",()=>{this.channelUrl&&window.open(this.channelUrl,"_blank","noopener")});const e=a("div","imp-pause-screen__heading");this.title=a("div","imp-pause-screen__title"),this.description=a("div","imp-pause-screen__description"),this.sponsor=a("a","imp-sponsor",{target:"_blank",rel:"nofollow noopener"}),this.sponsor.hidden=!0,this.sponsorLabel=a("span","imp-sponsor__label"),this.sponsorText=a("span","imp-sponsor__text"),this.sponsor.append(this.sponsorLabel,this.sponsorText),this.sponsor.addEventListener("click",i=>i.stopPropagation()),e.append(this.sponsor,this.title,this.description),this.defaultContent.append(e,this.channel),this.root.append(this.defaultContent)}setCustomContent(t){this.custom?.remove(),this.custom=t,t&&(t.classList.add("imp-pause-screen__custom"),this.root.append(t)),this.defaultContent.hidden=t!==null,this.root.classList.toggle("imp-pause-screen--custom",t!==null)}get hasCustom(){return this.custom!==null}setVisibility(t){this.visible={title:t.title??this.visible.title,description:t.description??this.visible.description,sponsor:t.sponsor??this.visible.sponsor}}setSource(t){this.title.textContent=t?.title??"",this.description.textContent=t?.description??"",this.title.hidden=!this.visible.title||!t?.title,this.description.hidden=!this.visible.description||!t?.description;const e=this.visible.sponsor?t?.sponsor:void 0;this.sponsor.hidden=!e,e&&(this.sponsor.href=e.url,this.sponsorText.textContent=e.text,this.sponsorLabel.textContent=e.label??this.labels.sponsored);const i=t?.channel;this.channel.hidden=!i,this.channelUrl=i?.url??null,this.channel.classList.toggle("imp-channel--link",!!i?.url),i&&(this.channelName.textContent=i.name,this.channelAvatar.className=`imp-channel__avatar imp-channel__avatar--${i.avatarShape??"circle"}`,i.avatar?(this.channelAvatar.textContent="",this.channelAvatar.append(T(i.avatar,i.name))):this.channelAvatar.textContent=(i.name.trim()[0]??"?").toUpperCase())}show(){this.root.hidden=!1}hide(){this.root.hidden=!0}}class Ot{constructor(t){this.player=t,this.clickBehavior="player",this.root=a("div","imp-related"),this.root.hidden=!0,this.heading=a("div","imp-related__title"),this.grid=a("div","imp-related__grid");const e=b("imp-related__close",t.labels.close,t.icons.close);e.addEventListener("click",()=>this.hide()),this.root.append(e,this.heading,this.grid)}setOptions(t){if(this.grid.textContent="",!!t){this.clickBehavior=t.clickBehavior??"player",this.heading.textContent=t.title??this.player.labels.related;for(const e of t.items)this.grid.append(this.buildCard(e))}}buildCard(t){const e=a("button","imp-related__card",{type:"button"}),i=a("div","imp-related__thumb");if(t.poster&&i.append(T(t.poster)),t.duration){const n=a("span","imp-related__duration");n.textContent=t.duration,i.append(n)}const s=a("div","imp-related__card-title");return s.textContent=t.title,e.append(i,s),e.addEventListener("click",()=>{this.player.emit("relatedclick",{item:t}),this.hide(),this.activate(t)}),e}activate(t){const e=t.url??t.source?.src;switch(this.clickBehavior){case"newWindow":e&&window.open(e,"_blank","noopener");break;case"currentTab":e&&(window.location.href=e);break;case"player":default:t.source?(this.player.load(t.source),this.player.play()):t.url&&window.open(t.url,"_blank","noopener")}}get visible(){return!this.root.hidden}show(){this.grid.childElementCount!==0&&(this.root.hidden=!1,this.player.emit("relatedshow",void 0))}hide(){this.root.hidden=!0}}class Ht{constructor(t){this.player=t,this.root=a("div","imp-upnext"),this.root.hidden=!0}get visible(){return!this.root.hidden}show(){const t=this.player.nextSource;if(!t){this.hide();return}const{labels:e}=this.player;this.root.textContent="";const i=a("div","imp-upnext__card"),s=a("div","imp-upnext__kicker");s.textContent=e.nextVideo,i.append(s);const n=$.posterSrc(t.poster);if(n){const l=a("button","imp-upnext__thumb",{type:"button","aria-label":e.playNext}),h=T(n);if(h.addEventListener("error",()=>{this.player.markSourceDead(t),this.root.hidden||this.show()},{once:!0}),l.append(h),t.duration){const u=a("span","imp-upnext__duration");u.textContent=L(t.duration),l.append(u)}const c=a("span","imp-upnext__thumb-play");_(c,this.player.icons.bigPlay),l.append(c),l.addEventListener("click",()=>this.player.next()),i.append(l)}if(t.title){const l=a("div","imp-upnext__title");l.textContent=t.title,i.append(l)}t.previewMeta?.length&&i.append(Y(t.previewMeta,"imp-upnext"));const o=a("button","imp-upnext__btn",{type:"button"});o.textContent=e.playNext,o.addEventListener("click",()=>this.player.next()),i.append(o),this.root.append(i),this.root.hidden=!1}hide(){this.root.hidden=!0}}class Zt{constructor(t,e="sidebar",i){this.player=t,this.root=a("div",`imp-playlist imp-playlist--${e}`),this.root.hidden=!0;const s=a("div","imp-playlist__header"),n=a("div","imp-playlist__heading");if(i){const h=a("div","imp-playlist__kicker");h.textContent=t.labels.playlist;const c=a("div","imp-playlist__name");c.textContent=i,n.append(h,c)}else n.textContent=t.labels.playlist;const o=a("div","imp-playlist__tools");this.shuffleBtn=b("imp-playlist__shuffle",t.labels.shuffle,t.icons.shuffle),this.shuffleBtn.addEventListener("click",()=>{t.setShuffle(!t.shuffle),this.syncModes()}),this.repeatBtn=b("imp-playlist__repeat",t.labels.repeat,t.icons.repeat),this.repeatBtn.addEventListener("click",()=>{t.setRepeat(!t.repeat),this.syncModes()});const l=b("imp-playlist__close",t.labels.close,t.icons.close);l.addEventListener("click",()=>this.hide()),o.append(this.shuffleBtn,this.repeatBtn,l),s.append(n,o),this.list=a("div","imp-playlist__list"),this.root.append(s,this.list),this.rebuild(),this.syncModes()}syncModes(){this.shuffleBtn.classList.toggle("imp-btn--active",this.player.shuffle),this.repeatBtn.classList.toggle("imp-btn--active",this.player.repeat)}rebuild(){this.list.textContent="",this.player.playlist.forEach((t,e)=>{const i=a("button","imp-playlist__item",{type:"button"});e===this.player.index&&i.classList.add("imp-playlist__item--active");const s=a("div","imp-playlist__thumb"),n=$.posterSrc(t.poster);n&&s.append(T(n));const o=a("div","imp-playlist__meta"),l=a("div","imp-playlist__title");if(l.textContent=t.title??`#${e+1}`,o.append(l),t.duration){const h=a("div","imp-playlist__duration");h.textContent=L(t.duration),o.append(h)}i.append(s,o),i.addEventListener("click",()=>{this.player.playItem(e),window.innerWidth<=767&&this.hide()}),this.list.append(i)})}get visible(){return!this.root.hidden}show(){this.rebuild(),this.root.hidden=!1}hide(){this.root.hidden=!0}toggle(){this.visible?this.hide():this.show()}}class Dt{constructor(t,e="bottom"){this.player=t,this.items=[],this.root=a("div",`imp-playlist imp-scenes imp-playlist--${e}`),this.root.hidden=!0;const i=a("div","imp-playlist__header"),s=a("span");s.textContent=t.labels.scenes;const n=b("imp-playlist__close",t.labels.close,t.icons.close);n.addEventListener("click",()=>this.hide()),i.append(s,n),this.list=a("div","imp-playlist__list"),this.root.append(i,this.list),t.on("chapterchange",()=>this.syncActive())}rebuild(){this.list.textContent="",this.items=[];const t=this.player.thumbnails;for(const e of this.player.chapterList){const i=a("button","imp-playlist__item",{type:"button"}),s=a("div","imp-playlist__thumb"),n=t?.cueAt(e.start+.01)??null;if(n?.xywh){const c=a("div","imp-scenes__sprite");c.style.width=`${n.xywh.w}px`,c.style.height=`${n.xywh.h}px`,c.style.backgroundImage=`url("${n.src}")`,c.style.backgroundPosition=`-${n.xywh.x}px -${n.xywh.y}px`,c.style.setProperty("--imp-sprite-w",String(n.xywh.w)),s.append(c)}else n&&s.append(T(n.src));const o=a("div","imp-playlist__meta"),l=a("div","imp-playlist__title");l.textContent=e.title||L(e.start);const h=a("div","imp-playlist__duration");h.textContent=L(e.start),o.append(l,h),i.append(s,o),i.addEventListener("click",()=>{this.player.seek(e.start),this.player.play(),window.innerWidth<=767&&this.hide()}),this.list.append(i),this.items.push(i)}this.syncActive()}syncActive(){const t=this.player.chapter,e=this.player.chapterList;this.items.forEach((i,s)=>{i.classList.toggle("imp-playlist__item--active",t!==null&&e[s]===t)})}get visible(){return!this.root.hidden}show(){this.rebuild(),this.root.hidden=!1}hide(){this.root.hidden=!0}toggle(){this.visible?this.hide():this.show()}}let dt=0;function ut(r){const t=r.reason;t?.name==="AbortError"&&/interrupted by a (new load request|call to pause)/i.test(t.message??"")&&r.preventDefault()}function Gt(){typeof window<"u"&&++dt===1&&window.addEventListener("unhandledrejection",ut)}function Wt(){typeof window<"u"&&--dt===0&&window.removeEventListener("unhandledrejection",ut)}function q(r){console.debug("[itube-player] play() rejected:",r)}function J(r){return r?typeof r=="string"?[{src:r,label:"Subtitles"}]:Array.isArray(r)?r:[r]:[]}const zt={play:!0,progress:!0,time:!0,volume:!0,fullscreen:!0,pip:!0,speed:"gear",settings:"gear",quality:"gear",scenes:!0,sceneTypes:!0,heatmap:!0,subtitles:"gear",seekButtons:!0,seekPlacement:"overlay",mobileLayout:"bar",order:[],playlist:!0,hidePrev:!0,hideNext:!1,playlistButton:!0,nextPreview:!0,hideDelay:2500,revealBeforePlay:!0};class jt{constructor(t,e={}){this.scrubbing=!1,this.emitter=new et,this.externalAdvance=!1,this.abort=new AbortController,this.sources=[],this.deadSources=new WeakSet,this.currentIndex=-1,this.sourceController=null,this.loadToken=0,this.chapters=[],this.currentChapter=null,this.sceneGroupList=[],this.activeSceneGroupId="",this.progressiveQuality=-1,this.thumbTrack=null,this.shuffleMode=!1,this.autoAdvanceEnabled=!0,this.persistKey=null,this.persistVolume=!1,this.persistAutoAdvance=!1,this.decodeRecoveries=0,this.adManager=null,this.playedOnce=!1,this.idleTimer=null,this.peekTimer=null,this.lastRetryAt=0,this.retryTimer=null,this.errorResumeTime=0,this.lastPlayheadTime=0,this.pendingSeek=null,this.destroyed=!1,this.persistTimer=null;const i=typeof t=="string"?document.querySelector(t):t;if(!i)throw new Error(`[itube-player] mount target not found: ${String(t)}`);this.mount=i,this.options=e,this.labels={...V.defaultLabels,...st(e.language),...e.labels},this.icons={...it,...e.icons};const s=e.controls??{},n=s.speed??s.settings??"gear";if(this.controlsOptions={...zt,...s,speed:n,settings:n},this.actionsOptions=e.actions??{},this.playbackRates=e.playbackRates??[.5,1,1.5,2],this.seekStep=e.seekStep??15,this.playlistOptions={title:"",autoAdvance:!0,loop:!1,shuffle:!1,startIndex:0,layout:"sidebar",externalAdvance:!1,...e.playlist},this.shuffleMode=this.playlistOptions.shuffle,this.externalAdvance=this.playlistOptions.externalAdvance,e.persist){const y=e.persist===!0?{}:e.persist;this.persistKey=y.key??"itube-player",this.persistVolume=y.volume!==!1,this.persistAutoAdvance=y.autoAdvance!==!1}const o=this.readPersisted();this.autoAdvanceEnabled=this.persistAutoAdvance&&typeof o?.autoAdvance=="boolean"?o.autoAdvance:this.playlistOptions.autoAdvance,this.sources=e.source?Array.isArray(e.source)?[...e.source]:[e.source]:[],this.container=a("div","imp-player",{tabindex:"0"}),e.className&&this.container.classList.add(e.className);const l=e.styling;if(l?.themeColor&&this.container.style.setProperty("--imp-accent",l.themeColor),l?.likeColor&&this.container.style.setProperty("--imp-like",l.likeColor),l?.dislikeColor&&this.container.style.setProperty("--imp-dislike",l.dislikeColor),l?.fontFamily&&this.container.style.setProperty("--imp-font",l.fontFamily),l?.borderRadius!==void 0){const y=typeof l.borderRadius=="number"?`${l.borderRadius}px`:l.borderRadius;this.container.style.setProperty("--imp-radius",y)}if(l?.playButtonStyle==="inverted"&&this.container.classList.add("imp-player--play-inverted"),this.video=e.videoElement??a("video","imp-video"),this.video.classList.add("imp-video"),e.videoElement&&!e.videoElement.paused)try{e.videoElement.pause()}catch{}e.playsInline!==!1&&this.video.setAttribute("playsinline",""),e.crossOrigin!==void 0&&(this.video.crossOrigin=e.crossOrigin),this.video.preload="metadata",e.loop&&(this.video.loop=!0);const h=this.persistVolume?o:null;this.video.volume=x(h?.volume??e.volume??1,0,1),(h?.muted??e.muted)&&(this.video.muted=!0);const c=a("div","imp-layer");this.spinner=a("div","imp-spinner"),this.spinner.hidden=!0,this.errorBox=a("div","imp-error"),this.errorBox.hidden=!0,this.errorText=a("div","imp-error__text"),this.retryBtn=a("button","imp-error__retry",{type:"button"});const u=a("span","imp-error__retry-label");u.textContent=this.labels.tryAgain,this.retryBtn.append(u,a("span","imp-error__retry-spinner")),this.retryBtn.addEventListener("click",()=>this.retry()),this.errorNextBtn=a("button","imp-error__next",{type:"button"}),this.errorNextBtn.textContent=this.labels.nextVideo,this.errorNextBtn.addEventListener("click",()=>{this.clearError(),this.next()});const f=a("div","imp-error__actions");f.append(this.retryBtn,this.errorNextBtn),this.errorBox.append(this.errorText,f),this.pauseScreen=new Vt(this.labels),this.poster=new $t(this),this.related=new Ot(this),this.related.setOptions(e.related),this.upNext=new Ht(this),this.controls=new qt(this),this.playlistPanel=new Zt(this,this.playlistOptions.layout,this.playlistOptions.title||void 0),this.scenesPanel=new Dt(this,e.scenes?.layout??"bottom");const p=a("div","imp-layer__middle");p.append(this.spinner,this.errorBox,this.controls.center);const m=a("div","imp-layer__bottom");m.append(this.controls.root),c.append(this.pauseScreen.root,this.related.root,this.upNext.root,p,m),this.container.append(this.video,c,this.poster.root,this.playlistPanel.root,this.scenesPanel.root),this.mount.append(this.container),e.pauseScreen instanceof HTMLElement?this.pauseScreen.setCustomContent(e.pauseScreen):typeof e.pauseScreen=="function"?this.pauseScreen.setCustomContent(e.pauseScreen(this)):e.pauseScreen&&typeof e.pauseScreen=="object"&&this.pauseScreen.setVisibility(e.pauseScreen);const v=e.adConfig??e.ads;v&&v.adList.length>0&&(this.adManager=new Ct({container:this.container,contentVideo:this.video,emitter:this.emitter,labels:this.labels,closeIcon:this.icons.close},v)),this.emitter.on("error",({fatal:y})=>{if(!y)return;const d=this.lastPlayheadTime||this.video.currentTime;Number.isFinite(d)&&d>0&&(this.errorResumeTime=d),this.errorText.textContent=this.labels.videoNotFound,this.errorNextBtn.hidden=!this.hasNext,this.errorBox.hidden=!1,this.spinner.hidden=!0,this.poster.hide(),this.container.classList.add("imp-player--error")}),Gt(),this.bindVideoEvents(),this.bindIdleHide(),e.keyboard!==!1&&this.bindKeyboard(),this.video.addEventListener("pointerup",y=>{if(!(this.adPlaying||!this.playedOnce)){if(y.pointerType==="mouse"){this.togglePlay();return}this.container.classList.contains("imp-player--idle")?(this.showControlsNow(),this.scheduleIdle()):this.video.paused||this.container.classList.add("imp-player--idle")}},{signal:this.abort.signal}),this.pauseScreen.root.addEventListener("click",y=>{this.pauseScreen.hasCustom||y.target===this.pauseScreen.root&&this.togglePlay()},{signal:this.abort.signal}),this.sources.length>0&&this.loadItem(x(this.playlistOptions.startIndex,0,this.sources.length-1),!!(e.playOnInit??e.autoplay)),queueMicrotask(()=>{this.destroyed||this.emitter.emit("ready",{player:this})})}on(t,e){return this.emitter.on(t,e)}once(t,e){return this.emitter.once(t,e)}off(t,e){this.emitter.off(t,e)}emit(t,e){this.emitter.emit(t,e)}get paused(){return this.video.paused}get ended(){return this.video.ended}get currentTime(){return this.video.currentTime}get duration(){return this.video.duration||0}get live(){return this.video.duration===1/0}get bufferedEnd(){const t=this.video.buffered;return t.length>0?t.end(t.length-1):0}get adPlaying(){return this.adManager?.adPlaying??!1}async play(t=!1){if(!(this.destroyed||this.adPlaying)&&!(this.adManager&&!t&&(await this.adManager.playPreRoll(),this.destroyed||!this.video.paused)))try{await this.video.play()}catch(e){const i=e?.name;if(i==="NotSupportedError"&&this.video.readyState===0){const s=this.loadToken;this.video.addEventListener("loadedmetadata",()=>{s===this.loadToken&&this.video.play().catch(q)},{once:!0,signal:this.abort.signal});return}i!=="AbortError"&&(q(e),this.playedOnce||this.poster.show())}}pause(){this.adPlaying||this.video.pause()}togglePlay(){this.video.paused||this.video.ended?this.play():this.pause()}retry(){const t=this.options.retryThrottle??5e3,e=Date.now();if(e-this.lastRetryAt<t)return;this.lastRetryAt=e,this.retryBtn.disabled=!0,this.retryBtn.classList.add("imp-error__retry--loading"),this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>{this.destroyed||(this.retryBtn.disabled=!1,this.retryBtn.classList.remove("imp-error__retry--loading"))},t);const i=this.errorResumeTime;if(this.loadItem(this.currentIndex,!0,!0),this.errorResumeTime=i,i>0){const s=this.loadToken;this.video.addEventListener("loadedmetadata",()=>{if(s===this.loadToken)try{this.video.currentTime=i}catch{}},{once:!0,signal:this.abort.signal})}}clearError(){this.errorBox.hidden=!0,this.container.classList.remove("imp-player--error")}get started(){return this.playedOnce}seek(t){if(Number.isFinite(this.video.duration)){this.video.currentTime=x(t,0,this.video.duration);return}const e=this.source?.duration;typeof e=="number"&&e>0&&(this.pendingSeek=x(t,0,e))}skip(t){this.seek(this.video.currentTime+t)}get volume(){return this.video.volume}get muted(){return this.video.muted}setVolume(t){this.video.volume=x(t,0,1),t>0&&(this.video.muted=!1)}setMuted(t){this.video.muted=t}toggleMute(){this.video.muted=!this.video.muted}readPersisted(){if(!this.persistKey)return null;try{const t=localStorage.getItem(this.persistKey),e=t?JSON.parse(t):null;return e&&typeof e=="object"?e:null}catch{return null}}schedulePersist(){this.persistTimer&&clearTimeout(this.persistTimer),this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.destroyed||this.persistState()},300)}persistState(){if(this.persistKey)try{const t={};this.persistVolume&&(t.volume=this.video.volume,t.muted=this.video.muted),this.persistAutoAdvance&&(t.autoAdvance=this.autoAdvanceEnabled),localStorage.setItem(this.persistKey,JSON.stringify(t))}catch{}}get playbackRate(){return this.video.playbackRate}setPlaybackRate(t){this.video.playbackRate=t,this.emitter.emit("ratechange",{rate:t})}get qualityLevels(){if(this.sourceController?.kind==="hls")return this.sourceController.levels;const t=this.source?.qualities;return t?t.map((e,i)=>({index:i,label:e.label??String(e.quality??i)})):[]}get qualityAutoAvailable(){return this.sourceController?.kind==="hls"}get currentQuality(){return this.sourceController?.kind==="hls"?this.sourceController.selected:this.progressiveQuality}setQuality(t){if(this.sourceController?.kind==="hls"){this.sourceController.setLevel(t);const o=t===-1?this.labels.qualityAuto:this.sourceController.levels.find(l=>l.index===t)?.label??String(t);this.emitter.emit("qualitychange",{label:o});return}const e=this.source?.qualities;if(!e||!e[t]||t===this.progressiveQuality)return;const i=this.video.currentTime,s=!this.video.paused&&!this.video.ended;this.progressiveQuality=t,this.video.src=e[t].src;const n=this.loadToken;this.video.addEventListener("loadedmetadata",()=>{if(n===this.loadToken){try{this.video.currentTime=i}catch{}s&&this.video.play().catch(q)}},{once:!0,signal:this.abort.signal}),this.emitter.emit("qualitychange",{label:e[t].label??String(e[t].quality??t)})}get subtitleTracks(){return J(this.source?.subtitles)}get activeSubtitle(){const t=this.video.textTracks;for(let e=0;e<t.length;e++)if(t[e].mode==="showing")return e;return-1}setSubtitle(t){const e=this.video.textTracks;for(let i=0;i<e.length;i++)e[i].mode=i===t?"showing":"disabled";this.emitter.emit("subtitlechange",{track:this.subtitleTracks[t]??null})}get playlist(){return this.sources}get index(){return this.currentIndex}get source(){return this.sources[this.currentIndex]??null}markSourceDead(t){this.deadSources.add(t),this.controls.syncFeatureButtons()}nextAliveIndex(){const t=this.sources.length;if(t<2)return-1;for(let e=1;e<t;e++){const i=this.currentIndex+e;if(i>=t&&!this.playlistOptions.loop)return-1;const s=i%t;if(!this.deadSources.has(this.sources[s]))return s}return-1}get nextSource(){if(this.shuffleMode||this.sources.length<2)return null;const t=this.nextAliveIndex();return t===-1?null:this.sources[t]}get hasPlaylist(){return this.sources.length>1||this.externalAdvance}get hasNext(){return this.externalAdvance?!0:this.shuffleMode?this.sources.length>1:this.nextAliveIndex()!==-1}get hasPrevious(){return this.externalAdvance?!0:this.playlistOptions.loop?this.sources.length>1:this.currentIndex>0}get shuffle(){return this.shuffleMode}setShuffle(t){this.shuffleMode=t}get repeat(){return this.playlistOptions.loop}setRepeat(t){this.playlistOptions.loop=t}emitAdvanceRequest(t,e){if(!this.externalAdvance)return!1;const i=e!==null&&e>=0&&e<this.sources.length;return this.emitter.emit("advancerequest",{direction:t,index:i?e:null,source:i?this.sources[e]:null}),!0}next(){if(!this.hasNext||this.emitAdvanceRequest("next",this.sources.length>1?(this.currentIndex+1)%this.sources.length:null))return;if(this.shuffleMode&&this.sources.length>1){const e=this.sources.map((s,n)=>({s,i:n})).filter(({s,i:n})=>n!==this.currentIndex&&!this.deadSources.has(s)),i=e.length>0?e.map(({i:s})=>s):this.sources.map((s,n)=>n).filter(s=>s!==this.currentIndex);this.playItem(i[Math.floor(Math.random()*i.length)]);return}const t=this.nextAliveIndex();t!==-1&&this.playItem(t)}previous(){this.hasPrevious&&(this.emitAdvanceRequest("previous",this.sources.length>1?(this.currentIndex-1+this.sources.length)%this.sources.length:null)||this.playItem((this.currentIndex-1+this.sources.length)%this.sources.length))}playItem(t){t<0||t>=this.sources.length||t!==this.currentIndex&&this.emitAdvanceRequest("select",t)||this.loadItem(t,!0).then(()=>{this.emitter.emit("playlistitemchange",{source:this.sources[t],index:t})})}togglePlaylistPanel(){this.scenesPanel.hide(),this.playlistPanel.toggle()}toggleScenesPanel(){this.playlistPanel.hide(),this.scenesPanel.toggle()}get thumbnails(){return this.thumbTrack}load(t,e=0){this.sources=Array.isArray(t)?[...t]:[t],this.playlistPanel.rebuild(),this.loadItem(x(e,0,this.sources.length-1),!1)}get isFullscreen(){return document.fullscreenElement===this.container}async toggleFullscreen(){try{this.isFullscreen?await document.exitFullscreen():this.container.requestFullscreen?await this.container.requestFullscreen():this.video.webkitEnterFullscreen?.()}catch{}}async togglePip(){try{document.pictureInPictureElement===this.video?await document.exitPictureInPicture():await this.video.requestPictureInPicture()}catch{}}get chapterList(){return this.chapters}get chapter(){return this.currentChapter}get sceneTypes(){return this.sceneGroupList}get activeSceneType(){return this.sceneGroupList.find(t=>t.id===this.activeSceneGroupId)??null}setSceneGroup(t){t===this.activeSceneGroupId||!this.sceneGroupList.some(e=>e.id===t)||(this.activeSceneGroupId=t,this.applyActiveSceneGroup(),this.emitter.emit("scenetypechange",{group:this.activeSceneType}))}get knownDuration(){const t=this.video.duration;if(Number.isFinite(t)&&t>0)return t;const e=this.source?.duration;return typeof e=="number"&&e>0?e:NaN}applyActiveSceneGroup(){this.chapters=z(this.activeSceneType?.scenes??[],this.knownDuration),this.currentChapter=null,this.controls.progress.setChapters(this.chapters),this.controls.syncFeatureButtons(),this.scenesPanel.visible&&this.scenesPanel.rebuild()}async share(){const t={title:this.source?.title??document.title,url:window.location.href};if(typeof navigator.share=="function"){try{await navigator.share(t)}catch{}return}this.emitter.emit("action",{id:"share"})}setLikeState(t){this.controls.setLikeState(t)}setLikeCounts(t,e){this.controls.setLikeCounts(t,e)}setPauseScreenContent(t){this.pauseScreen.setCustomContent(t)}destroy(){this.destroyed||(this.destroyed=!0,this.loadToken++,this.adManager?.destroy(),this.controls.destroy(),this.sourceController?.destroy(),this.abort.abort(),this.idleTimer&&clearTimeout(this.idleTimer),this.peekTimer&&clearTimeout(this.peekTimer),this.retryTimer&&clearTimeout(this.retryTimer),this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null,this.persistState()),this.container.remove(),Wt(),this.emitter.emit("destroy",void 0),this.emitter.removeAll())}async loadItem(t,e,i=!1){const s=++this.loadToken,n=this.sources[t];if(!n)return;this.currentIndex=t,this.sourceController?.destroy(),this.sourceController=null,this.chapters=[],this.currentChapter=null,this.sceneGroupList=[],this.activeSceneGroupId="",this.progressiveQuality=-1,this.playedOnce=!1,this.lastPlayheadTime=0,this.errorResumeTime=0,this.pendingSeek=null,this.endPeek();for(const p of[...this.video.querySelectorAll("track")])p.remove();this.adManager?.resetForNewSource(),this.related.hide(),this.upNext.hide(),this.pauseScreen.hide(),this.scenesPanel.hide(),this.thumbTrack=null,this.decodeRecoveries=0,this.video.poster=$.posterSrc(n.poster)??"",this.poster.setSource(n),this.pauseScreen.setSource(n),this.controls.progress.setChapters([]),this.controls.progress.setThumbnails(null),this.controls.progress.setHeatmap([]),typeof n.duration=="number"&&n.duration>0&&this.controls.progress.update(0,n.duration,0),e?this.poster.hide():this.poster.show(),this.playlistPanel.rebuild();for(const p of J(n.subtitles)){const m=a("track","",{kind:"subtitles",src:p.src,label:p.label,...p.srclang?{srclang:p.srclang}:{}});p.default&&m.setAttribute("default",""),this.video.append(m)}let o=n.src,l=n.type;if(n.qualities&&n.qualities.length>0){const p=Math.max(0,n.qualities.findIndex(m=>m.src===n.src));this.progressiveQuality=p,o=n.qualities[p].src,l=n.qualities[p].type??l}this.video.preload=this.adManager?.hasPendingPreRoll?"auto":"metadata";const h=await At(this.video,o,l,{onLevels:()=>{s===this.loadToken&&this.controls.syncFeatureButtons()},onLevelSwitch:p=>this.emitter.emit("qualitychange",{label:p}),onError:(p,m)=>this.emitter.emit("error",{message:p,cause:m,fatal:!0})});if(s!==this.loadToken){h.destroy();return}if(this.sourceController=h,this.emitter.emit("sourcechange",{source:n,index:t}),n.thumbnails&&H.load(n.thumbnails).then(p=>{s===this.loadToken&&(this.thumbTrack=p,this.controls.progress.setThumbnails(p),this.scenesPanel.visible&&this.scenesPanel.rebuild())}).catch(p=>this.emitter.emit("error",{message:"Failed to load thumbnails track",cause:p})),n.sceneGroups&&n.sceneGroups.length>0)this.sceneGroupList=n.sceneGroups,this.activeSceneGroupId=n.sceneGroups[0].id,this.applyActiveSceneGroup(),Number.isFinite(this.video.duration)&&this.video.duration>0||this.video.addEventListener("loadedmetadata",()=>{s===this.loadToken&&this.applyActiveSceneGroup()},{once:!0,signal:this.abort.signal});else if(n.chapters){const p=m=>{const v=()=>{s===this.loadToken&&(this.chapters=z(m,this.knownDuration),this.controls.progress.setChapters(this.chapters),this.controls.syncFeatureButtons(),this.scenesPanel.visible&&this.scenesPanel.rebuild())};Number.isFinite(this.video.duration)&&this.video.duration>0?v():this.video.addEventListener("loadedmetadata",v,{once:!0,signal:this.abort.signal})};typeof n.chapters=="string"?ht(n.chapters).then(m=>p(m)).catch(m=>this.emitter.emit("error",{message:"Failed to load chapters track",cause:m})):p(n.chapters)}const c=n.heatmap,u=c&&!Array.isArray(c),f=u?c.values.length>0:!!(c&&c.length>0);if(c&&f&&this.controlsOptions.heatmap){const p=()=>{if(s!==this.loadToken)return;const m=u?Tt(c.values,c.mode):rt(c,this.video.duration);this.controls.progress.setHeatmap(m,u?c.smoothing??1:1)};u||Number.isFinite(this.video.duration)&&this.video.duration>0?p():this.video.addEventListener("loadedmetadata",p,{once:!0,signal:this.abort.signal})}e&&this.play(i)}bindVideoEvents(){const{signal:t}=this.abort,e=this.video;e.addEventListener("play",()=>{this.playedOnce=!0,this.endPeek(),this.poster.hide(),this.pauseScreen.hide(),this.related.visible||this.related.hide(),this.related.hide(),this.upNext.hide(),e.readyState<3&&(this.spinner.hidden=!1),this.emitter.emit("play",void 0),this.scheduleIdle()},{signal:t}),e.addEventListener("pause",()=>{this.spinner.hidden=!0,this.emitter.emit("pause",void 0),this.showControlsNow(),!(this.video.ended||this.scrubbing||this.adPlaying||!this.playedOnce)&&(this.options.pauseScreen!==!1&&this.pauseScreen.show(),this.options.related?.showOn?.includes("pause")&&this.related.show())},{signal:t}),e.addEventListener("ended",()=>{this.handleEnded()},{signal:t}),e.addEventListener("timeupdate",()=>{!this.adPlaying&&e.currentTime>0&&(this.lastPlayheadTime=e.currentTime),this.emitter.emit("timeupdate",{currentTime:e.currentTime,duration:e.duration||0}),this.adManager?.checkMidRolls(e.currentTime);const i=j(this.chapters,e.currentTime);i!==this.currentChapter&&(this.currentChapter=i,this.emitter.emit("chapterchange",{chapter:i}))},{signal:t}),e.addEventListener("progress",()=>{this.emitter.emit("progress",{buffered:this.bufferedEnd})},{signal:t}),e.addEventListener("volumechange",()=>{this.emitter.emit("volumechange",{volume:e.volume,muted:e.muted}),this.persistVolume&&this.schedulePersist()},{signal:t}),e.addEventListener("loadedmetadata",()=>{if(this.pendingSeek!==null){const i=x(this.pendingSeek,0,Number.isFinite(e.duration)?e.duration:this.pendingSeek);this.pendingSeek=null;try{e.currentTime=i}catch{}}!this.playedOnce&&Number.isFinite(e.duration)&&this.controls.progress.update(e.currentTime,e.duration,this.bufferedEnd)},{signal:t}),e.addEventListener("seeking",()=>this.emitter.emit("seeking",{currentTime:e.currentTime}),{signal:t}),e.addEventListener("seeked",()=>this.emitter.emit("seeked",{currentTime:e.currentTime}),{signal:t}),e.addEventListener("waiting",()=>{this.spinner.hidden=!1},{signal:t});for(const i of["playing","canplay","seeked"])e.addEventListener(i,()=>{this.spinner.hidden=!0,this.decodeRecoveries=0,i==="playing"&&this.clearError()},{signal:t});e.addEventListener("error",()=>{const i=e.error;if(!i||this.sourceController?.kind==="hls"||e.getAttribute("src")===null&&!e.currentSrc)return;if((i.code===MediaError.MEDIA_ERR_DECODE||/DEMUXER|PARSE|DECODE/i.test(i.message||""))&&this.decodeRecoveries<2&&Number.isFinite(e.duration)){this.decodeRecoveries++;const n=e.currentTime,o=!e.paused;e.load();const l=()=>{try{e.currentTime=n}catch{}o&&e.play().catch(q)};e.readyState>=1?l():e.addEventListener("loadedmetadata",l,{once:!0,signal:this.abort.signal});return}this.emitter.emit("error",{message:i.message||`Media error (code ${i.code})`,cause:i,fatal:!0})},{signal:t}),e.addEventListener("enterpictureinpicture",()=>this.emitter.emit("pipchange",{active:!0}),{signal:t}),e.addEventListener("leavepictureinpicture",()=>this.emitter.emit("pipchange",{active:!1}),{signal:t}),document.addEventListener("fullscreenchange",()=>{this.emitter.emit("fullscreenchange",{active:this.isFullscreen}),this.container.classList.toggle("imp-player--fullscreen",this.isFullscreen)},{signal:t}),e.addEventListener("webkitbeginfullscreen",()=>{this.emitter.emit("fullscreenchange",{active:!0}),this.container.classList.add("imp-player--fullscreen")},{signal:t}),e.addEventListener("webkitendfullscreen",()=>{this.emitter.emit("fullscreenchange",{active:!1}),this.container.classList.remove("imp-player--fullscreen")},{signal:t})}async handleEnded(){if(this.emitter.emit("ended",void 0),this.showControlsNow(),!(this.adManager&&(await this.adManager.playPostRoll(),this.destroyed))){if(this.autoAdvanceEnabled&&this.hasNext){if(this.emitAdvanceRequest("ended",this.sources.length>1?(this.currentIndex+1)%this.sources.length:null))return;this.next();return}if(!this.autoAdvanceEnabled&&this.hasNext){this.upNext.show();return}(this.options.related?.showOn?.includes("ended")??!!this.options.related)&&this.related.show()}}get autoAdvance(){return this.autoAdvanceEnabled}setAutoAdvance(t){this.autoAdvanceEnabled=t,t&&this.upNext.hide(),this.persistAutoAdvance&&this.persistState()}bindIdleHide(){const{signal:t}=this.abort,e=()=>{this.showControlsNow(),this.scheduleIdle()};this.container.addEventListener("pointermove",i=>{i.pointerType!=="touch"&&(e(),this.playedOnce||this.revealPeek(!1))},{signal:t}),this.container.addEventListener("pointerdown",i=>{i.pointerType!=="touch"&&e()},{signal:t}),this.container.addEventListener("keydown",e,{signal:t}),this.container.addEventListener("pointerleave",i=>{i.pointerType!=="touch"&&(this.controls.anyMenuOpen()||(this.playedOnce?this.video.paused||this.container.classList.add("imp-player--idle"):this.endPeek()))},{signal:t})}showControlsNow(){this.container.classList.remove("imp-player--idle")}revealPeek(t){this.playedOnce||!this.controlsOptions.revealBeforePlay||(this.container.classList.add("imp-player--peek"),this.peekTimer&&clearTimeout(this.peekTimer),this.peekTimer=null,t&&(this.peekTimer=setTimeout(()=>{!this.playedOnce&&!this.destroyed&&!this.controls.anyMenuOpen()&&this.container.classList.remove("imp-player--peek")},3e3)))}endPeek(){this.peekTimer&&clearTimeout(this.peekTimer),this.peekTimer=null,this.container.classList.remove("imp-player--peek")}posterTapReveal(){return this.playedOnce||!this.controlsOptions.revealBeforePlay?!1:(this.revealPeek(!0),!0)}scheduleIdle(){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{!this.video.paused&&!this.destroyed&&this.container.classList.add("imp-player--idle")},this.controlsOptions.hideDelay)}bindKeyboard(){this.container.addEventListener("keydown",t=>{const e=t.target;if(e.closest("input, select, textarea, [contenteditable]"))return;const s=e.closest("button")!==null;switch(t.key){case" ":case"k":if(t.key===" "&&s)return;t.preventDefault(),this.togglePlay();break;case"ArrowLeft":t.preventDefault(),this.skip(-this.seekStep);break;case"ArrowRight":t.preventDefault(),this.skip(this.seekStep);break;case"ArrowUp":t.preventDefault(),this.setVolume(this.volume+.1);break;case"ArrowDown":t.preventDefault(),this.setVolume(this.volume-.1);break;case"m":this.toggleMute();break;case"f":this.toggleFullscreen();break;case"Home":this.seek(0);break;case"End":this.seek(this.duration);break;default:/^[0-9]$/.test(t.key)&&Number.isFinite(this.video.duration)&&this.seek(Number(t.key)/10*this.video.duration)}},{signal:this.abort.signal})}}exports.defaultLabels=V.defaultLabels;exports.Emitter=et;exports.Player=jt;exports.ThumbnailTrack=H;exports.buildHeatmapValues=rt;exports.chapterAt=j;exports.defaultIcons=it;exports.formatTime=L;exports.getLocale=st;exports.heatmapPath=ot;exports.isHlsSource=ct;exports.loadChaptersVtt=ht;exports.normalizeChapters=z;exports.registerLocale=wt;exports.registerLocales=xt;exports.registeredLanguages=Lt;exports.resolveVast=at;
5
5
  //# sourceMappingURL=core.cjs.map