itube-modern-player 0.2.2 → 0.3.0

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
@@ -151,6 +151,7 @@ const source: VideoSource = {
151
151
  description: 'Описание — показывается в экране паузы',
152
152
  poster: 'poster.jpg', // превью-постер до первого запуска
153
153
  duration: 1284, // для плашки в плейлисте до загрузки метаданных
154
+ previewMeta: ['2.3K просмотров', 'User uploaded'], // строки для ховер-превью следующего ролика
154
155
 
155
156
  // канал/автор — рендерится в экране паузы
156
157
  channel: {
@@ -228,7 +229,7 @@ new Player('#mount', {
228
229
  loop: false,
229
230
  volume: 1,
230
231
  playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], // пункты меню скорости
231
- seekStep: 10, // секунды для стрелок/кнопок перемотки
232
+ seekStep: 15, // секунды для стрелок/кнопок перемотки (по умолчанию 15; показывается на кнопке)
232
233
  keyboard: true, // горячие клавиши (на контейнере, не на document!)
233
234
  className: 'my-player', // свой класс на контейнер — хук для темизации
234
235
  crossOrigin: 'anonymous', // если VTT/постеры на другом домене
@@ -272,20 +273,31 @@ new Player('#mount', {
272
273
  volume: true,
273
274
  fullscreen: true,
274
275
  pip: true,
275
- settings: true, // меню скорости (иконка-спидометр)
276
- quality: false, // меню качества (иконка-шестерёнка); ВЫКЛЮЧЕНО по умолчанию,
277
- // кнопка появляется при наличии source.qualities или HLS-уровней
276
+ // Настройки. Каждая: 'gear' (в едином дропдауне-шестерёнке, по умолчанию) | 'bar'
277
+ // (отдельной кнопкой в баре) | false (выкл). true = 'gear'. Шестерёнка скрыта,
278
+ // если внутри нет ни одной доступной опции.
279
+ speed: 'gear', // скорость воспроизведения (бывш. `settings`; алиас ещё работает)
280
+ quality: 'gear', // качество; пункт/кнопка появляется при source.qualities или HLS-уровнях
281
+ subtitles: 'gear', // субтитры; появляется только если у источника есть треки
278
282
  scenes: true, // кнопка списка сцен (появляется при наличии chapters)
279
283
  heatmap: true, // диаграмма популярности (нужны данные source.heatmap)
280
- subtitles: true, // кнопка появляется только если у источника есть треки
281
284
  seekButtons: true, // или { back: 5, forward: 15 }
285
+ seekPlacement: 'overlay', // 'overlay' (default) — ±N и play поверх видео на всех экранах
286
+ // (prev/next в оверлее только на мобиле; на десктопе play/prev/next
287
+ // в баре) | 'bar' — seek-кнопки в нижнем баре (поведение до 0.3)
282
288
  playlist: true, // prev/next/список — рендерятся ТОЛЬКО в режиме плейлиста
289
+ hidePrev: true, // скрыть кнопку «prev» в баре (бар = только next); false — вернуть.
290
+ // На мобиле центр-кластер всё равно показывает prev
291
+ nextPreview: true, // ховер-превью следующего ролика над кнопкой next (десктоп).
292
+ // объект: { thumbnail?, title?, duration?, meta? } — какие поля показывать
283
293
  hideDelay: 2500, // мс до скрытия контролов при воспроизведении
284
294
  },
285
295
 
286
296
  // ---- экран паузы ----
287
- // true (по умолчанию) — заголовок/описание/канал текущего видео
297
+ // true (по умолчанию) — заголовок/описание/канал текущего видео (порядок: спонсор → тайтл → описание)
288
298
  // false — выключить
299
+ // { title?, description?, sponsor? } — дефолтный экран, но скрыть отдельные части
300
+ // (напр. { title: false, description: false } — когда сайт выводит их вне плеера)
289
301
  // HTMLElement или (player) => HTMLElement — свой контент (full-cover оверлей,
290
302
  // напр. реклама с «Закрыть и продолжить»; фабрика получает плеер).
291
303
  // Во Vue — scoped-слот #pauseScreen="{ player, close }". См. раздел про кастомный экран паузы.
@@ -333,9 +345,10 @@ new Player('#mount', {
333
345
  share: true, // в дропдауне ⋯: нативный share-диалог устройства,
334
346
  // если его нет — событие action {id:'share'}
335
347
  report: true, // в дропдауне ⋯ → action {id:'report'}
336
- // свои пункты дропдауна: клик эмитит customaction {id}
348
+ // свои пункты: клик эмитит customaction {id}
337
349
  custom: [
338
- { id: 'download', title: 'Скачать', icon: '<svg ...>...</svg>' }, // icon: URL картинки или raw SVG
350
+ { id: 'download', title: 'Скачать', icon: '<svg ...>...</svg>' }, // в дропдауне (placement: 'menu' по умолчанию)
351
+ { id: 'theater', title: 'Театр', icon: '<svg ...>', placement: 'bar' }, // отдельной кнопкой в баре (нужна icon, тултип = title)
339
352
  ],
340
353
  },
341
354
 
@@ -668,6 +681,24 @@ npm publish # prepublishOnly прогонит typecheck + build
668
681
 
669
682
  Версионирование по [SemVer](https://semver.org/lang/ru/): `major.minor.patch`.
670
683
 
684
+ ### 0.3.0
685
+
686
+ Крупный апдейт UI и набора пропсов (есть смена дефолтов — см. «Миграция»).
687
+
688
+ - **Единый дропдаун-шестерёнка для настроек.** Скорость, качество и субтитры по умолчанию собраны в одну кнопку ⚙. Меню — drill-down (как у больших плееров): сначала список настроек строками с текущим значением (`Качество — Авто ›`, `Скорость — 1× ›`, `Субтитры — Русский ›`), клик по строке открывает её опции, «‹» — назад. Каждый пункт можно вынести отдельной кнопкой в бар (`controls.speed/quality/subtitles: 'bar'`) или убрать (`false`). Кнопка-шестерёнка не показывается, если внутри нет ни одной доступной опции. Сцены и плейлист остаются отдельными кнопками (это управление воспроизведением).
689
+ - **В контрол-баре по умолчанию только «next»** (кнопка «prev» в баре скрыта — `controls.hidePrev: true` по умолчанию; `false` возвращает её). На мобиле центр-кластер по-прежнему показывает и prev, и next.
690
+ - **Перемотка ±N и большая кнопка play — оверлеем поверх видео** на всех экранах (раньше только на мобиле). prev/next в оверлее — только на мобиле; на десктопе play/prev/next остаются в контрол-баре (рядом друг с другом). Управляется `controls.seekPlacement` (`'overlay'` по умолчанию, `'bar'` — прежнее десктоп-поведение с seek в нижнем баре). Шаг перемотки виден на кнопке (число в стрелке).
691
+ - **Шаг перемотки по умолчанию 15 сек** (был 10) и **показывается на кнопке** (число внутри стрелки). Меняется через `seekStep` или `controls.seekButtons: { back, forward }`.
692
+ - **Кастом-кнопки прямо в контрол-баре.** У `actions.custom[]` появился `placement: 'bar'` (иконка + тултип из `title`); `'menu'` (дефолт) — как раньше, пункт в ⋯.
693
+ - **Превью следующего ролика по ховеру** на кнопке next (десктоп): обложка, тайтл, длительность и доп. строки из `source.previewMeta`. Конфиг полей — `controls.nextPreview`.
694
+ - **Пауз-скрин: порядок спонсор → тайтл → описание** (рекламная ссылка теперь сверху). Новый объект-вариант `pauseScreen: { title?, description?, sponsor? }` — скрыть отдельные части (когда сайт выводит их вне плеера).
695
+
696
+ **Миграция:**
697
+ - `controls.settings` (булев, включал меню скорости) → переименован в `controls.speed` со значениями `'gear' | 'bar' | false`. Старый `settings` ещё работает как алиас.
698
+ - `controls.quality` / `controls.subtitles` теперь `boolean | 'gear' | 'bar'` (булевы значения совместимы: `true` = в шестерёнке).
699
+ - `seekStep` по умолчанию 15 вместо 10 — задайте `seekStep: 10`, чтобы вернуть прежний шаг.
700
+ - Seek-кнопки по умолчанию в оверлее, а не в нижнем баре — верните `controls: { seekPlacement: 'bar' }` при необходимости.
701
+
671
702
  ### 0.2.2
672
703
 
673
704
  Фиксы UX на реальных iOS-устройствах (в десктоп-девтулзах не воспроизводились):
@@ -676,6 +707,8 @@ npm publish # prepublishOnly прогонит typecheck + build
676
707
  - **Кнопки рекламы реагируют на первый тап** — `touch-action: manipulation` убирает 300-мс задержку и дабл-тап-зум iOS.
677
708
  - **Адекватная тач-модель контролов.** На тач-устройствах тап по видео показывает/скрывает контролы (play/pause — центральной кнопкой), а не дёргает воспроизведение. Раньше одно касание порождало сразу несколько событий (показ контролов + переключение play). Поведение мыши на десктопе не изменилось.
678
709
  - Скрытые контролы (авто-idle) перестали перехватывать тап «вслепую» — первое касание сначала показывает их.
710
+ - **Скрытые контролы полностью неактивны.** Кнопки ±10 сек и панель управления больше нельзя нажать в невидимом (idle) состоянии во время проигрывания: `pointer-events:none` на родителе не отключал потомков с `pointer-events:auto`, теперь инертен весь скрытый сабтри.
711
+ - **Панели сцен и плейлиста на мобиле закрываются при выборе.** Раньше после выбора сцены/видео нужно было вручную закрывать full-screen лист крестиком, чтобы увидеть видео. Теперь на мобиле (≤767px) лист закрывается сразу по тапу; десктоп-сайдбар остаётся открытым (видео и так видно рядом).
679
712
 
680
713
  ### 0.2.1
681
714
 
package/dist/core.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var lt=Object.create;var U=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var ht=Object.getOwnPropertyNames;var ct=Object.getPrototypeOf,dt=Object.prototype.hasOwnProperty;var ut=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ht(t))!dt.call(r,s)&&s!==e&&U(r,s,{get:()=>t[s],enumerable:!(i=at(t,s))||i.enumerable});return r};var pt=(r,t,e)=>(e=r!=null?lt(ct(r)):{},ut(t||!r||!r.__esModule?U(e,"default",{value:r,enumerable:!0}):e,r));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const M=require("./labels-DTgTxMuq.cjs");function l(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 m(r,t,e){const i=l("button",`imp-btn ${r}`,{type:"button","aria-label":t,title:t});return i.innerHTML=e,i}function E(r,t,e){r.innerHTML=t,e!==void 0&&(r.setAttribute("aria-label",e),r.setAttribute("title",e))}function y(r,t,e){return Math.min(e,Math.max(t,r))}function k(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 $(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 K(r){const t=[],e=r.replace(/\r\n?/g,`
1
+ "use strict";var rt=Object.create;var z=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var at=Object.getPrototypeOf,ht=Object.prototype.hasOwnProperty;var ct=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of lt(t))!ht.call(r,s)&&s!==e&&z(r,s,{get:()=>t[s],enumerable:!(i=ot(t,s))||i.enumerable});return r};var dt=(r,t,e)=>(e=r!=null?rt(at(r)):{},ct(t||!r||!r.__esModule?z(e,"default",{value:r,enumerable:!0}):e,r));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("./labels-DTgTxMuq.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 f(r,t,e){const i=a("button",`imp-btn ${r}`,{type:"button","aria-label":t,title:t});return i.innerHTML=e,i}function M(r,t,e){r.innerHTML=t,e!==void 0&&(r.setAttribute("aria-label",e),r.setAttribute("title",e))}function w(r,t,e){return Math.min(e,Math.max(t,r))}function x(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 V(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 U(r){const t=[],e=r.replace(/\r\n?/g,`
2
2
  `).split(/\n\n+/);for(const i of e){const s=i.split(`
3
- `).filter(f=>f.trim()!=="");if(s.length===0)continue;let n=s.findIndex(f=>f.includes("-->"));if(n===-1)continue;const[o,a]=s[n].split("-->"),c=$(o),h=$((a??"").split(" ")[1]??a??"")??$(a??"");if(c===null||h===null)continue;const u=s.slice(n+1).join(`
4
- `).trim();u&&t.push({start:c,end:h,text:u})}return t}function mt(r,t){try{return new URL(r,new URL(t,window.location.href)).toString()}catch{return r}}class X{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 p=(r,t="0 0 24 24")=>`<svg viewBox="${t}" fill="currentColor" aria-hidden="true" focusable="false">${r}</svg>`,G={play:p('<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:p('<rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/>'),replay:p('<path d="M12 5V2.5L7.5 6 12 9.5V7a5 5 0 1 1-5 5H5a7 7 0 1 0 7-7Z"/>'),bigPlay:p('<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:p('<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:p('<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:p('<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:p('<path d="M5 5h5v2H7v3H5V5Zm9 0h5v5h-2V7h-3V5ZM5 14h2v3h3v2H5v-5Zm12 0h2v5h-5v-2h3v-3Z"/>'),fullscreenExit:p('<path d="M10 10H5V8h3V5h2v5Zm4 0V5h2v3h3v2h-5Zm-4 4v5H8v-3H5v-2h5Zm4 0h5v2h-3v3h-2v-5Z"/>'),pip:p('<path d="M3 5h18v14H3V5Zm2 2v10h14V7H5Z"/><rect x="12" y="11" width="6" height="4"/>'),settings:p('<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:p('<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:p('<path d="M3 5h18v14H3V5Zm2 2v10h3V7H5Zm5 0v10h9V7h-9Zm-5 3h3v1H5v-1Zm0 3h3v1H5v-1Z"/>'),shuffle:p('<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:p('<path d="M7 7h10v2.5L21 6l-4-3.5V5H5v6h2V7Zm10 10H7v-2.5L3 18l4 3.5V19h12v-6h-2v4Z"/>'),subtitles:p('<path d="M3 5h18v14H3V5Zm2 2v10h14V7H5Zm2 3h6v2H7v-2Zm8 0h2v2h-2v-2ZM7 14h2v2H7v-2Zm4 0h6v2h-6v-2Z"/>'),list:p('<path d="M4 6h2v2H4V6Zm4 0h12v2H8V6ZM4 11h2v2H4v-2Zm4 0h12v2H8v-2ZM4 16h2v2H4v-2Zm4 0h12v2H8v-2Z"/>'),next:p('<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:p('<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:p('<path d="M12 4V1.5L17 5.5 12 9.5V7a5.5 5.5 0 1 0 5.5 5.5H20A8 8 0 1 1 12 4Z"/>'),seekBack:p('<path d="M12 4V1.5L7 5.5 12 9.5V7a5.5 5.5 0 1 1-5.5 5.5H4A8 8 0 1 0 12 4Z"/>'),like:p('<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:p('<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:p('<path d="M4 6h12v2H4V6Zm0 4h12v2H4v-2Zm0 4h8v2H4v-2Zm14 0v-4h2v4h4v2h-4v4h-2v-4h-4v-2h4Z"/>'),share:p('<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:p('<path d="M5 3h2v18H5V3Zm4 1h10l-2.5 4L19 12H9V4Z"/>'),more:p('<circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/>'),close:p('<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"/>')},P={en:M.defaultLabels};function ft(r,t){P[r]=t}function vt(r){for(const[t,e]of Object.entries(r))e&&(P[t]=e)}function Y(r){return r&&P[r]||M.defaultLabels}function gt(){return Object.keys(P)}function J(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 h of r){if(!Number.isFinite(h.time)||h.time<0||h.time>t)continue;const u=Math.max(0,h.value);if(u===0)continue;const f=Math.min(e-1,Math.floor(h.time/t*e));i[f]+=u,s=!0}if(!s)return[];const n=[.06,.24,.4,.24,.06],o=i.map((h,u)=>n.reduce((f,d,b)=>f+d*(i[u+b-2]??0),0)),a=Math.max(...o);if(a<=0)return[];const c=.08;return o.map(h=>c+(1-c)*(h/a))}function tt(r,t=1e3,e=100){if(r.length===0)return"";const i=t/(r.length-1||1);let s=`M 0 ${e}`;return r.forEach((n,o)=>{s+=` L ${(o*i).toFixed(1)} ${(e-n*e).toFixed(1)}`}),s+=` L ${t} ${e} Z`,s}async function et(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 it(r,r.vastTag,t,0,{impressions:[],tracking:{}})}async function it(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 a;try{const v=await fetch(t,{signal:n.signal,credentials:"omit"});if(!v.ok)throw new Error(`VAST request failed (${v.status})`);a=await v.text()}finally{clearTimeout(o)}const c=new DOMParser().parseFromString(a,"text/xml");if(c.querySelector("parsererror"))throw new Error("VAST response is not valid XML");const h=c.querySelector("VAST > Ad");if(!h)throw new Error("VAST response contains no ads");yt(h,s);const u=h.querySelector(":scope > Wrapper");if(u){const v=w(u.querySelector("VASTAdTagURI"));if(!v)throw new Error("VAST wrapper without VASTAdTagURI");return it(r,v,e,i+1,s)}const f=h.querySelector(":scope > InLine");if(!f)throw new Error("VAST ad has neither InLine nor Wrapper");const d=f.querySelector("Creatives > Creative > Linear");if(!d)throw new Error("VAST ad has no Linear creative");const b=bt(d);if(!b)throw new Error("VAST ad has no playable MediaFile");return{roll:r.roll,mediaUrl:b.url,mediaType:b.type,clickThrough:w(d.querySelector("VideoClicks > ClickThrough"))??r.clickUrl,duration:F(w(d.querySelector(":scope > Duration"))),skipOffset:kt(d.getAttribute("skipoffset"),F(w(d.querySelector(":scope > Duration")))),impressions:s.impressions,tracking:s.tracking,adTitle:w(f.querySelector(":scope > AdTitle"))??void 0}}function yt(r,t){var e,i;for(const s of r.querySelectorAll("Impression")){const n=w(s);n&&t.impressions.push(n)}for(const s of r.querySelectorAll("Linear > TrackingEvents > Tracking")){const n=s.getAttribute("event"),o=w(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=w(s);n&&((i=t.tracking).click??(i.click=[])).push(n)}}function bt(r){const e=[...r.querySelectorAll("MediaFiles > MediaFile")].map(o=>({url:w(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,a)=>o.bitrate-a.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 F(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 kt(r,t){if(!r)return;const e=r.trim().match(/^(\d+(?:\.\d+)?)%$/);return e?t!==void 0?Number(e[1])/100*t:void 0:F(r)}function C(r){if(r)for(const t of r)try{new Image().src=t}catch{}}function w(r){return r?.textContent?.trim().replace(/^<!\[CDATA\[|\]\]>$/g,"").trim()||null}class wt{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=l("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 et(n,this.opts);await this.playAd(o)}catch(o){const a=o instanceof Error?o:new Error(String(o));this.host.emitter.emit("aderror",{roll:n,error:a})}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=l("div","imp-ad"),n=this.ensureAdVideo(),o=new AbortController,a=o.signal;n.src=t.mediaUrl,n.muted=this.host.contentVideo.muted,n.volume=this.host.contentVideo.volume;const c=l("div","imp-spinner imp-ad__spinner"),h=l("div","imp-ad__hud"),u=l("span","imp-ad__badge");u.textContent=t.adTitle?`${i.adLabel} · ${t.adTitle}`:i.adLabel;const f=l("span","imp-ad__countdown");h.append(u,f);const d=l("div","imp-ad__actions");let b=null;t.clickThrough&&(b=l("button","imp-ad__visit",{type:"button"}),b.textContent=i.visitAdvertiser,d.append(b));const v=l("button","imp-ad__skip",{type:"button"});v.hidden=!0,d.append(v),s.append(n,c,h,d),this.host.container.append(s),this.layer=s;const N=t.skipOffset??this.opts.skipDelay,Z=new Set,L=g=>{Z.has(g)||(Z.add(g),C(t.tracking[g]))};let R=Date.now(),O=-1;const ot=setInterval(()=>{if(n.paused){R=Date.now();return}if(n.currentTime!==O){O=n.currentTime,R=Date.now();return}Date.now()-R>=this.opts.mediaTimeout&&(this.host.emitter.emit("aderror",{roll:{roll:t.roll},error:new Error(`Ad media stalled for ${this.opts.mediaTimeout} ms — skipping`)}),V())},500),V=()=>{clearInterval(ot),o.abort(),n.pause(),n.removeAttribute("src"),n.load(),s.remove(),this.layer=null,e()},D=g=>{g?(L("skip"),this.host.emitter.emit("adskip",{ad:t})):L("complete"),this.host.emitter.emit("adend",{ad:t}),V()};n.addEventListener("playing",()=>{C(t.impressions),L("start"),this.host.emitter.emit("adstart",{ad:t})},{once:!0,signal:a}),n.addEventListener("playing",()=>{c.hidden=!0},{signal:a}),n.addEventListener("waiting",()=>{c.hidden=!1},{signal:a}),n.addEventListener("timeupdate",()=>{const g=n.currentTime,x=n.duration;if(Number.isFinite(x)&&x>0&&(f.textContent=k(Math.max(0,x-g)),g/x>=.25&&L("firstQuartile"),g/x>=.5&&L("midpoint"),g/x>=.75&&L("thirdQuartile")),N>=0){const Q=Math.ceil(N-g);Q>0?(v.hidden=!1,v.disabled=!0,v.textContent=`${i.skipAdIn} ${Q}`):(v.hidden=!1,v.disabled=!1,v.textContent=i.skipAd)}},{signal:a}),n.addEventListener("ended",()=>D(!1),{signal:a}),n.addEventListener("error",()=>{this.host.emitter.emit("aderror",{roll:{roll:t.roll},error:new Error("Ad media failed to play")}),V()},{signal:a}),v.addEventListener("click",()=>D(!0));const W=()=>{t.clickThrough&&(L("click"),this.host.emitter.emit("adclick",{ad:t}),window.open(t.clickThrough,"_blank","noopener"),n.pause())};n.addEventListener("click",W,{signal:a}),b?.addEventListener("click",W);let z=!1,B=!1;n.addEventListener("playing",()=>{z=!0},{once:!0,signal:a}),n.addEventListener("pause",()=>{n.ended||!s.isConnected||(s.classList.add("imp-ad--paused"),z&&!B&&(B=!0,C(t.tracking.pause),this.host.emitter.emit("adpause",{ad:t})))},{signal:a}),n.addEventListener("play",()=>{s.classList.remove("imp-ad--paused"),B&&(B=!1,C(t.tracking.resume),this.host.emitter.emit("adresume",{ad:t}))},{signal:a}),s.addEventListener("click",g=>{(g.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 st(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)),!(o<=n)&&i.push({start:n,end:o,title:e[s].title})}return i}async function nt(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 K(e).map(i=>({start:i.start,end:i.end,title:i.text}))}function H(r,t){for(const e of r)if(t>=e.start&&t<e.end)return e;return null}function rt(r,t){return t?/application\/(x-mpegurl|vnd\.apple\.mpegurl)/i.test(t):/\.m3u8(\?|#|$)/i.test(r)}let S;async function Lt(){if(S!==void 0)return S;const r=globalThis.Hls;if(r)return S=r,S;try{S=(await import("hls.js/light")).default}catch{S=null}return S}async function St(r,t,e,i){if(rt(t,e)){const s=r.canPlayType("application/vnd.apple.mpegurl"),n=s?null:await Lt();return n&&n.isSupported()?xt(n,r,t,i):s?(r.src=t,I(r)):(i.onError("HLS is not supported in this browser and hls.js could not be loaded."),I(r))}return r.src=t,I(r)}function I(r){return{kind:"native",levels:[],selected:-1,setLevel(){},destroy(){r.removeAttribute("src"),r.load()}}}function xt(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,h)=>({index:h,label:c.height?`${c.height}p`:`${Math.round(c.bitrate/1e3)} kbps`})).reverse(),i.onLevels(n.levels)}),s.on(r.Events.LEVEL_SWITCHED,(c,h)=>{const u=s.levels[h.level];u&&i.onLevelSwitch(u.height?`${u.height}p`:`${Math.round(u.bitrate/1e3)} kbps`)});let o=0,a=!1;return s.on(r.Events.ERROR,(c,h)=>{if(h.fatal)switch(h.type){case r.ErrorTypes.NETWORK_ERROR:s.startLoad();break;case r.ErrorTypes.MEDIA_ERROR:o<3?(o++,s.recoverMediaError()):(i.onError(`HLS media error: ${h.details}`,h),s.destroy());break;default:if(a)i.onError(`HLS fatal error: ${h.details}`,h),s.destroy();else{a=!0;try{s.loadSource(e),s.startLoad()}catch{i.onError(`HLS fatal error: ${h.details}`,h),s.destroy()}}}}),s.loadSource(e),s.attachMedia(t),n}class A{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 K(i)){const[o,a]=n.text.trim().split("#");if(!o)continue;const c={start:n.start,end:n.end,src:mt(o,t)},h=a?.match(/xywh=(\d+),(\d+),(\d+),(\d+)/);h&&(c.xywh={x:Number(h[1]),y:Number(h[2]),w:Number(h[3]),h:Number(h[4])}),s.push(c)}return s.sort((n,o)=>n.start-o.start),new A(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}}class T{constructor(t){this.anchor=t,this.outsideListener=null,this.root=l("div","imp-menu"),this.root.hidden=!0,this.backdrop=l("div","imp-menu__backdrop"),this.backdrop.hidden=!0,this.backdrop.addEventListener("pointerdown",e=>{e.preventDefault(),this.close()}),t.append(this.backdrop)}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){if(e.items.length===0)continue;const i=l("div","imp-menu__section");if(e.title){const s=l("div","imp-menu__title");s.textContent=e.title,i.append(s)}for(const s of e.items){const n=l("button","imp-menu__item",{type:"button",role:"menuitemradio"});if(n.setAttribute("aria-checked",String(s.active)),s.active&&n.classList.add("imp-menu__item--active"),s.icon){const a=l("span","imp-menu__icon");s.icon.trimStart().startsWith("<svg")?a.innerHTML=s.icon:a.append(l("img","",{src:s.icon,alt:""})),n.append(a)}const o=l("span","imp-menu__label");o.textContent=s.label,n.append(o),n.addEventListener("click",()=>{e.onSelect(s.value),this.close()}),i.append(n)}this.root.append(i)}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()},setTimeout(()=>{this.outsideListener&&document.addEventListener("pointerdown",this.outsideListener)},0)}close(){this.root.hidden=!0,this.backdrop.hidden=!0,this.outsideListener&&(document.removeEventListener("pointerdown",this.outsideListener),this.outsideListener=null)}destroy(){this.close(),this.root.remove()}}class _t{constructor(t){this.cb=t,this.segments=[],this.duration=0,this.chapters=[],this.thumbnails=null,this.scrubbing=!1,this.root=l("div","imp-progress",{role:"slider","aria-label":"Seek",tabindex:"-1"}),this.buffered=l("div","imp-progress__buffered"),this.track=l("div","imp-progress__track"),this.handle=l("div","imp-progress__handle"),this.tooltipThumb=l("div","imp-progress__thumb"),this.tooltipChapter=l("div","imp-progress__tooltip-chapter"),this.tooltipTime=l("div","imp-progress__tooltip-time"),this.tooltip=l("div","imp-progress__tooltip"),this.tooltip.append(this.tooltipThumb,this.tooltipChapter,this.tooltipTime),this.heatmap=l("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){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="${tt(t)}"/></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=l("div","imp-progress__segment");o.style.flexGrow=String(Math.max(n.end-n.start,.01));const a=l("div","imp-progress__fill");o.append(a),this.track.append(o),this.segments.push({chapter:n,root:o,fill:a})}}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?y(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",`${k(t)} / ${k(this.duration)}`)}render(t){for(const{chapter:i,fill:s}of this.segments){const n=i.end-i.start,o=n>0?y((t-i.start)/n,0,1):0;s.style.transform=`scaleX(${o})`}const e=this.duration>0?y(t/this.duration,0,1):0;this.handle.style.left=`${e*100}%`}timeFromEvent(t){const e=this.root.getBoundingClientRect();return(e.width>0?y((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=k(e);const i=H(this.chapters,e);this.tooltipChapter.textContent=i?.title??"",this.tooltipChapter.hidden=!i?.title;const s=this.thumbnails?.cueAt(e)??null;s?(this.tooltipThumb.hidden=!1,this.tooltipThumb.style.backgroundImage=`url("${s.src}")`,s.xywh?(this.tooltipThumb.style.width=`${s.xywh.w}px`,this.tooltipThumb.style.height=`${s.xywh.h}px`,this.tooltipThumb.style.backgroundPosition=`-${s.xywh.x}px -${s.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 n=this.root.getBoundingClientRect(),o=y(t.clientX-n.left,0,n.width),a=this.tooltip.offsetWidth/2;this.tooltip.style.left=`${y(o,a,Math.max(a,n.width-a))}px`}hideTooltip(){this.tooltip.classList.remove("imp-progress__tooltip--visible")}}const _=class _{constructor(t){this.player=t,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.scenesBtn=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=l("div","imp-controls"),this.progress=new _t({onSeek:d=>t.seek(d),onScrubStart:()=>{this.wasPlayingBeforeScrub=!t.paused,t.pause()},onScrubEnd:()=>{this.wasPlayingBeforeScrub&&t.play()}}),s.progress&&this.root.append(this.progress.root);const n=l("div","imp-controls__row");this.row=n,this.root.append(n);const o=l("div","imp-controls__group"),a=l("div","imp-controls__group");this.rightGroup=a;const c=l("div","imp-controls__spacer");this.chapterLabel=l("div","imp-controls__chapter"),n.append(o,c,a),c.append(this.chapterLabel);const h=typeof s.seekButtons=="object"?s.seekButtons:{},u=h.back??t.seekStep,f=h.forward??t.seekStep;if(s.playlist&&t.hasPlaylist&&(this.prevBtn=m("imp-btn--prev",e.previous,i.previous),this.prevBtn.addEventListener("click",()=>t.previous()),o.append(this.prevBtn)),s.seekButtons&&(this.seekBackBtn=m("imp-btn--seek-back",`${e.seekBack} ${u}s`,i.seekBack),this.seekBackBtn.addEventListener("click",()=>t.skip(-u)),o.append(this.seekBackBtn)),s.play&&(this.playBtn=m("imp-btn--play",e.play,i.play),this.playBtn.addEventListener("click",()=>t.togglePlay()),o.append(this.playBtn)),s.seekButtons&&(this.seekFwdBtn=m("imp-btn--seek-forward",`${e.seekForward} ${f}s`,i.seekForward),this.seekFwdBtn.addEventListener("click",()=>t.skip(f)),o.append(this.seekFwdBtn)),s.playlist&&t.hasPlaylist&&(this.nextBtn=m("imp-btn--next",e.next,i.next),this.nextBtn.addEventListener("click",()=>t.next()),o.append(this.nextBtn)),s.volume){const d=l("div","imp-volume");this.muteBtn=m("imp-btn--mute",e.mute,i.volumeHigh),this.muteBtn.addEventListener("click",()=>t.toggleMute()),this.volumeSlider=l("input","imp-volume__slider",{type:"range",min:"0",max:"1",step:"0.05","aria-label":"Volume"}),this.volumeSlider.addEventListener("input",()=>{t.setVolume(Number(this.volumeSlider.value))}),d.append(this.muteBtn,this.volumeSlider),o.append(d)}if(s.time&&(this.timeLabel=l("div","imp-controls__time"),this.liveBadge=l("span","imp-controls__live"),this.liveBadge.textContent=e.live,this.liveBadge.hidden=!0,o.append(this.timeLabel,this.liveBadge)),this.buildLikeDislike(a),s.subtitles){this.subtitlesBtn=m("imp-btn--subtitles",e.subtitles,i.subtitles),this.subtitlesMenu=new T(this.subtitlesBtn);const d=l("div","imp-controls__menu-anchor");d.append(this.subtitlesBtn,this.subtitlesMenu.root),this.subtitlesBtn.addEventListener("click",()=>this.toggleSubtitlesMenu()),a.append(d),this.registerCollapsible({key:"subtitles",el:d,priority:30,available:()=>t.subtitleTracks.length>0,section:()=>this.subtitlesSection()})}if(s.settings){this.settingsBtn=m("imp-btn--settings",e.settings,i.speed),this.settingsMenu=new T(this.settingsBtn);const d=l("div","imp-controls__menu-anchor");d.append(this.settingsBtn,this.settingsMenu.root),this.settingsBtn.addEventListener("click",()=>this.toggleSettingsMenu()),a.append(d),this.registerCollapsible({key:"settings",el:d,priority:40,available:()=>!0,section:()=>this.speedSection()})}if(s.quality){this.qualityBtn=m("imp-btn--quality",e.quality,i.settings),this.qualityMenu=new T(this.qualityBtn);const d=l("div","imp-controls__menu-anchor");d.append(this.qualityBtn,this.qualityMenu.root),this.qualityBtn.addEventListener("click",()=>this.toggleQualityMenu()),a.append(d),this.registerCollapsible({key:"quality",el:d,priority:10,available:()=>t.qualityLevels.length>0,section:()=>this.qualitySection()})}if(s.scenes&&(this.scenesBtn=m("imp-btn--scenes",e.scenes,i.scenes),this.scenesBtn.addEventListener("click",()=>t.toggleScenesPanel()),a.append(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.playlist&&t.hasPlaylist){const d=m("imp-btn--list",e.playlist,i.list);d.addEventListener("click",()=>t.togglePlaylistPanel()),a.append(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=m("imp-btn--pip",e.pip,i.pip);d.addEventListener("click",()=>void t.togglePip()),a.append(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=m("imp-btn--fullscreen",e.fullscreen,i.fullscreen),this.fullscreenBtn.addEventListener("click",()=>void t.toggleFullscreen()),a.append(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=l("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);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);d.addEventListener("click",()=>t.skip(f)),this.center.append(d)}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.buildMoreDropdown(a),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)}makeCenterButton(t,e,i){const s=l("button",`imp-center-btn imp-center-btn--${t}`,{type:"button","aria-label":e,title:e});return s.innerHTML=i,s}buildLikeDislike(t){const e=this.player,i=e.actionsOptions,{labels:s,icons:n}=e;if(i.like){this.likeBtn=m("imp-btn--like",s.like,n.like),this.likeBtn.addEventListener("click",()=>e.emit("action",{id:"like"})),this.likeCountEl=this.attachCountTooltip(this.likeBtn,i.likeCount);const o=this.wrapWithTooltip(this.likeBtn,this.likeCountEl);t.append(o),this.registerCollapsible({key:"like",el:o,priority:62,available:()=>!0,section:()=>this.simpleSection("like",s.like,n.like,()=>e.emit("action",{id:"like"}))})}if(i.dislike){this.dislikeBtn=m("imp-btn--dislike",s.dislike,n.dislike),this.dislikeBtn.addEventListener("click",()=>e.emit("action",{id:"dislike"})),this.dislikeCountEl=this.attachCountTooltip(this.dislikeBtn,i.dislikeCount);const o=this.wrapWithTooltip(this.dislikeBtn,this.dislikeCountEl);t.append(o),this.registerCollapsible({key:"dislike",el:o,priority:60,available:()=>!0,section:()=>this.simpleSection("dislike",s.dislike,n.dislike,()=>e.emit("action",{id:"dislike"}))})}}attachCountTooltip(t,e){const i=l("span","imp-count-tooltip");return this.setCountText(i,e),i}wrapWithTooltip(t,e){const i=l("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 c of i.custom??[])this.actionItems.push({value:`custom:${c.id}`,label:c.title,icon:c.icon,run:()=>e.emit("customaction",{id:c.id})});const o=m("imp-btn--more",s.more,n.more);this.moreMenu=new T(o);const a=l("div","imp-controls__menu-anchor imp-controls__more");a.append(o,this.moreMenu.root),o.addEventListener("click",()=>{this.closeMenus(this.moreMenu),this.moreMenu?.toggle(this.buildMoreSections())}),t.append(a),this.moreWrap=a}buildMoreSections(){const t=[],e=new Map,i=[],s=["prev","next","seekBack","seekFwd","like","dislike","scenes","pip","list","subtitles","settings","quality"],n=this.collapsibles.filter(o=>this.overflowed.has(o.key)&&o.available()).sort((o,a)=>s.indexOf(o.key)-s.indexOf(a.key));for(const o of n){const a=o.section();if(a)if(!a.title&&a.items.length===1){const c=a.items[0];i.push(c),e.set(c.value,()=>a.onSelect(c.value))}else t.push(a)}if(i.length>0&&t.unshift({title:"",items:i,onSelect:o=>e.get(o)?.()}),this.actionItems.length>0){const o=new Map(this.actionItems.map(a=>[a.value,a.run]));t.push({title:"",items:this.actionItems.map(({value:a,label:c,icon:h})=>({value:a,label:c,icon:h,active:!1})),onSelect:a=>o.get(a)?.()})}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?"1× (normal)":`${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;this.center.style.display=t?"flex":"none",this.playBtn&&(this.playBtn.style.display=t?"none":""),this.overflowed.clear();for(const s of this.collapsibles){if(t&&_.CENTER_KEYS.has(s.key)){s.el.style.display="none";continue}const n=s.available();s.el.style.display=n?"":"none",s.el.classList.remove("imp-collapsed")}const e=this.collapsibles.filter(s=>s.available()&&!(t&&_.CENTER_KEYS.has(s.key))).sort((s,n)=>s.priority-n.priority);let i=e.length;for(;i-- >0&&this.overflowsRow();){const s=e.find(n=>!this.overflowed.has(n.key));if(!s)break;s.el.style.display="none",s.el.classList.add("imp-collapsed"),this.overflowed.add(s.key)}if(this.moreWrap){const s=this.actionItems.length>0||this.overflowed.size>0;this.moreWrap.style.display=s?"":"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.timeLabel.textContent=`${k(e)} / ${k(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&&E(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&&E(this.playBtn,e,i),this.centerPlayBtn&&E(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;E(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.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.settingsMenu,this.subtitlesMenu,this.qualityMenu,this.moreMenu])e&&e!==t&&e.close()}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.settingsMenu?.destroy(),this.subtitlesMenu?.destroy(),this.qualityMenu?.destroy(),this.moreMenu?.destroy(),this.root.remove()}};_.CENTER_KEYS=new Set(["seekBack","seekFwd","prev","next"]);let q=_;class Bt{constructor(t){this.root=l("div","imp-poster"),this.image=l("img","imp-poster__image",{alt:"",decoding:"async"}),this.image.hidden=!0;const e=m("imp-poster__play",t.labels.play,t.icons.bigPlay);e.addEventListener("click",()=>void t.play()),this.root.append(this.image,e),this.root.addEventListener("click",i=>{(i.target===this.root||i.target===this.image)&&t.play()})}setSource(t){t?.poster?(this.image.src=t.poster,this.image.fetchPriority="high",this.image.hidden=!1):(this.image.removeAttribute("src"),this.image.hidden=!0)}show(){this.root.hidden=!1}hide(){this.root.hidden=!0}}class Et{constructor(t){this.labels=t,this.channelUrl=null,this.custom=null,this.root=l("div","imp-pause-screen"),this.root.hidden=!0,this.defaultContent=l("div","imp-pause-screen__default"),this.channel=l("button","imp-channel",{type:"button"}),this.channel.hidden=!0,this.channelAvatar=l("div","imp-channel__avatar"),this.channelName=l("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=l("div","imp-pause-screen__heading");this.title=l("div","imp-pause-screen__title"),this.description=l("div","imp-pause-screen__description"),this.sponsor=l("a","imp-sponsor",{target:"_blank",rel:"nofollow noopener"}),this.sponsor.hidden=!0,this.sponsorLabel=l("span","imp-sponsor__label"),this.sponsorText=l("span","imp-sponsor__text"),this.sponsor.append(this.sponsorLabel,this.sponsorText),this.sponsor.addEventListener("click",i=>i.stopPropagation()),e.append(this.title,this.description,this.sponsor),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}setSource(t){this.title.textContent=t?.title??"",this.description.textContent=t?.description??"";const e=t?.sponsor;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.style.backgroundImage=`url("${i.avatar}")`):(this.channelAvatar.style.backgroundImage="",this.channelAvatar.textContent=(i.name.trim()[0]??"?").toUpperCase()))}show(){this.root.hidden=!1}hide(){this.root.hidden=!0}}class Ct{constructor(t){this.player=t,this.clickBehavior="player",this.root=l("div","imp-related"),this.root.hidden=!0,this.heading=l("div","imp-related__title"),this.grid=l("div","imp-related__grid");const e=m("imp-related__close","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=l("button","imp-related__card",{type:"button"}),i=l("div","imp-related__thumb");if(t.poster&&(i.style.backgroundImage=`url("${t.poster}")`),t.duration){const n=l("span","imp-related__duration");n.textContent=t.duration,i.append(n)}const s=l("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 Tt{constructor(t,e="sidebar",i){this.player=t,this.root=l("div",`imp-playlist imp-playlist--${e}`),this.root.hidden=!0;const s=l("div","imp-playlist__header"),n=l("div","imp-playlist__heading");if(i){const c=l("div","imp-playlist__kicker");c.textContent=t.labels.playlist;const h=l("div","imp-playlist__name");h.textContent=i,n.append(c,h)}else n.textContent=t.labels.playlist;const o=l("div","imp-playlist__tools");this.shuffleBtn=m("imp-playlist__shuffle",t.labels.shuffle,t.icons.shuffle),this.shuffleBtn.addEventListener("click",()=>{t.setShuffle(!t.shuffle),this.syncModes()}),this.repeatBtn=m("imp-playlist__repeat",t.labels.repeat,t.icons.repeat),this.repeatBtn.addEventListener("click",()=>{t.setRepeat(!t.repeat),this.syncModes()});const a=m("imp-playlist__close","Close",t.icons.close);a.addEventListener("click",()=>this.hide()),o.append(this.shuffleBtn,this.repeatBtn,a),s.append(n,o),this.list=l("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=l("button","imp-playlist__item",{type:"button"});e===this.player.index&&i.classList.add("imp-playlist__item--active");const s=l("div","imp-playlist__thumb");t.poster&&(s.style.backgroundImage=`url("${t.poster}")`);const n=l("div","imp-playlist__meta"),o=l("div","imp-playlist__title");if(o.textContent=t.title??`#${e+1}`,n.append(o),t.duration){const a=l("div","imp-playlist__duration");a.textContent=k(t.duration),n.append(a)}i.append(s,n),i.addEventListener("click",()=>{this.player.playItem(e)}),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 Mt{constructor(t,e="bottom"){this.player=t,this.items=[],this.root=l("div",`imp-playlist imp-scenes imp-playlist--${e}`),this.root.hidden=!0;const i=l("div","imp-playlist__header"),s=l("span");s.textContent=t.labels.scenes;const n=m("imp-playlist__close","Close",t.icons.close);n.addEventListener("click",()=>this.hide()),i.append(s,n),this.list=l("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=l("button","imp-playlist__item",{type:"button"}),s=l("div","imp-playlist__thumb"),n=t?.cueAt(e.start+.01)??null;if(n?.xywh){const h=l("div","imp-scenes__sprite");h.style.width=`${n.xywh.w}px`,h.style.height=`${n.xywh.h}px`,h.style.backgroundImage=`url("${n.src}")`,h.style.backgroundPosition=`-${n.xywh.x}px -${n.xywh.y}px`,h.style.setProperty("--imp-sprite-w",String(n.xywh.w)),s.append(h)}else n&&(s.style.backgroundImage=`url("${n.src}")`);const o=l("div","imp-playlist__meta"),a=l("div","imp-playlist__title");a.textContent=e.title||k(e.start);const c=l("div","imp-playlist__duration");c.textContent=k(e.start),o.append(a,c),i.append(s,o),i.addEventListener("click",()=>{this.player.seek(e.start),this.player.play()}),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()}}function j(r){return r?typeof r=="string"?[{src:r,label:"Subtitles"}]:Array.isArray(r)?r:[r]:[]}const Pt={play:!0,progress:!0,time:!0,volume:!0,fullscreen:!0,pip:!0,settings:!0,quality:!1,scenes:!0,heatmap:!0,subtitles:!0,seekButtons:!0,playlist:!0,hideDelay:2500};class At{constructor(t,e={}){this.scrubbing=!1,this.emitter=new X,this.abort=new AbortController,this.sources=[],this.currentIndex=-1,this.sourceController=null,this.loadToken=0,this.chapters=[],this.currentChapter=null,this.progressiveQuality=-1,this.thumbTrack=null,this.shuffleMode=!1,this.decodeRecoveries=0,this.adManager=null,this.playedOnce=!1,this.idleTimer=null,this.destroyed=!1;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={...M.defaultLabels,...Y(e.language),...e.labels},this.icons={...G,...e.icons},this.controlsOptions={...Pt,...e.controls},this.actionsOptions=e.actions??{},this.playbackRates=e.playbackRates??[.5,.75,1,1.25,1.5,2],this.seekStep=e.seekStep??10,this.playlistOptions={title:"",autoAdvance:!0,loop:!1,shuffle:!1,startIndex:0,layout:"sidebar",...e.playlist},this.shuffleMode=this.playlistOptions.shuffle,this.sources=e.source?Array.isArray(e.source)?[...e.source]:[e.source]:[],this.container=l("div","imp-player",{tabindex:"0"}),e.className&&this.container.classList.add(e.className);const s=e.styling;if(s?.themeColor&&this.container.style.setProperty("--imp-accent",s.themeColor),s?.likeColor&&this.container.style.setProperty("--imp-like",s.likeColor),s?.dislikeColor&&this.container.style.setProperty("--imp-dislike",s.dislikeColor),s?.borderRadius!==void 0){const h=typeof s.borderRadius=="number"?`${s.borderRadius}px`:s.borderRadius;this.container.style.setProperty("--imp-radius",h)}s?.playButtonStyle==="inverted"&&this.container.classList.add("imp-player--play-inverted"),this.video=l("video","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),e.muted&&(this.video.muted=!0),this.video.volume=y(e.volume??1,0,1);const n=l("div","imp-layer");this.spinner=l("div","imp-spinner"),this.spinner.hidden=!0,this.errorBox=l("div","imp-error"),this.errorBox.hidden=!0,this.pauseScreen=new Et(this.labels),this.poster=new Bt(this),this.related=new Ct(this),this.related.setOptions(e.related),this.controls=new q(this),this.playlistPanel=new Tt(this,this.playlistOptions.layout,this.playlistOptions.title||void 0),this.scenesPanel=new Mt(this,e.scenes?.layout??"bottom");const o=l("div","imp-layer__middle");o.append(this.spinner,this.errorBox,this.controls.center);const a=l("div","imp-layer__bottom");a.append(this.controls.root),n.append(this.pauseScreen.root,this.related.root,o,a),this.container.append(this.video,n,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));const c=e.adConfig??e.ads;c&&c.adList.length>0&&(this.adManager=new wt({container:this.container,contentVideo:this.video,emitter:this.emitter,labels:this.labels,closeIcon:this.icons.close},c)),this.emitter.on("error",({message:h})=>{this.errorBox.textContent=h,this.errorBox.hidden=!1,this.spinner.hidden=!0,this.poster.hide()}),this.bindVideoEvents(),this.bindIdleHide(),e.keyboard!==!1&&this.bindKeyboard(),this.video.addEventListener("pointerup",h=>{if(!(this.adPlaying||!this.playedOnce)){if(h.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",h=>{this.pauseScreen.hasCustom||h.target===this.pauseScreen.root&&this.togglePlay()},{signal:this.abort.signal}),this.sources.length>0&&this.loadItem(y(this.playlistOptions.startIndex,0,this.sources.length-1),!!e.autoplay),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(){this.destroyed||this.adPlaying||this.adManager&&(await this.adManager.playPreRoll(),this.destroyed||!this.video.paused)||await this.video.play()}pause(){this.adPlaying||this.video.pause()}togglePlay(){this.video.paused||this.video.ended?this.play():this.pause()}seek(t){Number.isFinite(this.video.duration)&&(this.video.currentTime=y(t,0,this.video.duration))}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=y(t,0,1),t>0&&(this.video.muted=!1)}setMuted(t){this.video.muted=t}toggleMute(){this.video.muted=!this.video.muted}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 n=t===-1?this.labels.qualityAuto:this.sourceController.levels.find(o=>o.index===t)?.label??String(t);this.emitter.emit("qualitychange",{label:n});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,this.video.currentTime=i,s&&this.video.play().catch(()=>{}),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}get hasPlaylist(){return this.sources.length>1}get hasNext(){return this.shuffleMode||this.playlistOptions.loop?this.sources.length>1:this.currentIndex<this.sources.length-1}get hasPrevious(){return 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}next(){if(this.hasNext){if(this.shuffleMode&&this.sources.length>1){let t=this.currentIndex;for(;t===this.currentIndex;)t=Math.floor(Math.random()*this.sources.length);this.playItem(t);return}this.playItem((this.currentIndex+1)%this.sources.length)}}previous(){this.hasPrevious&&this.playItem((this.currentIndex-1+this.sources.length)%this.sources.length)}playItem(t){t<0||t>=this.sources.length||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(y(e,0,this.sources.length-1),!1)}get isFullscreen(){return document.fullscreenElement===this.container}async toggleFullscreen(){this.isFullscreen?await document.exitFullscreen():this.container.requestFullscreen?await this.container.requestFullscreen():this.video.webkitEnterFullscreen?.()}async togglePip(){document.pictureInPictureElement===this.video?await document.exitPictureInPicture():await this.video.requestPictureInPicture()}get chapterList(){return this.chapters}get chapter(){return this.currentChapter}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.container.remove(),this.emitter.emit("destroy",void 0),this.emitter.removeAll())}async loadItem(t,e){const i=++this.loadToken,s=this.sources[t];if(!s)return;this.currentIndex=t,this.sourceController?.destroy(),this.sourceController=null,this.chapters=[],this.currentChapter=null,this.progressiveQuality=-1,this.playedOnce=!1;for(const c of[...this.video.querySelectorAll("track")])c.remove();this.adManager?.resetForNewSource(),this.related.hide(),this.pauseScreen.hide(),this.scenesPanel.hide(),this.thumbTrack=null,this.errorBox.hidden=!0,this.decodeRecoveries=0,this.video.poster=s.poster??"",this.poster.setSource(s),this.pauseScreen.setSource(s),this.controls.progress.setChapters([]),this.controls.progress.setThumbnails(null),this.controls.progress.setHeatmap([]),e?this.poster.hide():this.poster.show(),this.playlistPanel.rebuild();for(const c of j(s.subtitles)){const h=l("track","",{kind:"subtitles",src:c.src,label:c.label,...c.srclang?{srclang:c.srclang}:{}});c.default&&h.setAttribute("default",""),this.video.append(h)}let n=s.src,o=s.type;if(s.qualities&&s.qualities.length>0){const c=Math.max(0,s.qualities.findIndex(h=>h.src===s.src));this.progressiveQuality=c,n=s.qualities[c].src,o=s.qualities[c].type??o}this.video.preload=this.adManager?.hasPendingPreRoll?"auto":"metadata";const a=await St(this.video,n,o,{onLevels:()=>{i===this.loadToken&&this.controls.syncFeatureButtons()},onLevelSwitch:c=>this.emitter.emit("qualitychange",{label:c}),onError:(c,h)=>this.emitter.emit("error",{message:c,cause:h})});if(i!==this.loadToken){a.destroy();return}if(this.sourceController=a,this.emitter.emit("sourcechange",{source:s,index:t}),s.thumbnails&&A.load(s.thumbnails).then(c=>{i===this.loadToken&&(this.thumbTrack=c,this.controls.progress.setThumbnails(c),this.scenesPanel.visible&&this.scenesPanel.rebuild())}).catch(c=>this.emitter.emit("error",{message:"Failed to load thumbnails track",cause:c})),s.chapters){const c=h=>{const u=()=>{i===this.loadToken&&(this.chapters=st(h,this.video.duration),this.controls.progress.setChapters(this.chapters),this.controls.syncFeatureButtons(),this.scenesPanel.visible&&this.scenesPanel.rebuild())};Number.isFinite(this.video.duration)&&this.video.duration>0?u():this.video.addEventListener("loadedmetadata",u,{once:!0,signal:this.abort.signal})};typeof s.chapters=="string"?nt(s.chapters).then(h=>c(h)).catch(h=>this.emitter.emit("error",{message:"Failed to load chapters track",cause:h})):c(s.chapters)}if(s.heatmap&&s.heatmap.length>0&&this.controlsOptions.heatmap){const c=s.heatmap,h=()=>{i===this.loadToken&&this.controls.progress.setHeatmap(J(c,this.video.duration))};Number.isFinite(this.video.duration)&&this.video.duration>0?h():this.video.addEventListener("loadedmetadata",h,{once:!0,signal:this.abort.signal})}e&&this.play().catch(()=>{i===this.loadToken&&this.poster.show()})}bindVideoEvents(){const{signal:t}=this.abort,e=this.video;e.addEventListener("play",()=>{this.playedOnce=!0,this.poster.hide(),this.pauseScreen.hide(),this.related.visible||this.related.hide(),this.related.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.emitter.emit("timeupdate",{currentTime:e.currentTime,duration:e.duration||0}),this.adManager?.checkMidRolls(e.currentTime);const i=H(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})},{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.errorBox.hidden=!0,this.decodeRecoveries=0},{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 a=()=>{try{e.currentTime=n}catch{}o&&e.play().catch(()=>{})};e.readyState>=1?a():e.addEventListener("loadedmetadata",a,{once:!0,signal:this.abort.signal});return}this.emitter.emit("error",{message:i.message||`Media error (code ${i.code})`,cause:i})},{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})}async handleEnded(){if(this.emitter.emit("ended",void 0),this.showControlsNow(),!(this.adManager&&(await this.adManager.playPostRoll(),this.destroyed))){if(this.playlistOptions.autoAdvance&&this.hasNext){this.next();return}(this.options.related?.showOn?.includes("ended")??!!this.options.related)&&this.related.show()}}bindIdleHide(){const{signal:t}=this.abort,e=()=>{this.showControlsNow(),this.scheduleIdle()};this.container.addEventListener("pointermove",i=>{i.pointerType!=="touch"&&e()},{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.video.paused||this.container.classList.add("imp-player--idle"))},{signal:t})}showControlsNow(){this.container.classList.remove("imp-player--idle")}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=M.defaultLabels;exports.Emitter=X;exports.Player=At;exports.ThumbnailTrack=A;exports.buildHeatmapValues=J;exports.chapterAt=H;exports.defaultIcons=G;exports.formatTime=k;exports.getLocale=Y;exports.heatmapPath=tt;exports.isHlsSource=rt;exports.loadChaptersVtt=nt;exports.normalizeChapters=st;exports.registerLocale=ft;exports.registerLocales=vt;exports.registeredLanguages=gt;exports.resolveVast=et;
3
+ `).filter(p=>p.trim()!=="");if(s.length===0)continue;let n=s.findIndex(p=>p.includes("-->"));if(n===-1)continue;const[o,l]=s[n].split("-->"),h=V(o),c=V((l??"").split(" ")[1]??l??"")??V(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 ut(r,t){try{return new URL(r,new URL(t,window.location.href)).toString()}catch{return r}}class j{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 v=(r,t="0 0 24 24")=>`<svg viewBox="${t}" fill="currentColor" aria-hidden="true" focusable="false">${r}</svg>`,G={play:v('<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:v('<rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/>'),replay:v('<path d="M12 5V2.5L7.5 6 12 9.5V7a5 5 0 1 1-5 5H5a7 7 0 1 0 7-7Z"/>'),bigPlay:v('<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:v('<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:v('<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:v('<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:v('<path d="M5 5h5v2H7v3H5V5Zm9 0h5v5h-2V7h-3V5ZM5 14h2v3h3v2H5v-5Zm12 0h2v5h-5v-2h3v-3Z"/>'),fullscreenExit:v('<path d="M10 10H5V8h3V5h2v5Zm4 0V5h2v3h3v2h-5Zm-4 4v5H8v-3H5v-2h5Zm4 0h5v2h-3v3h-2v-5Z"/>'),pip:v('<path d="M3 5h18v14H3V5Zm2 2v10h14V7H5Z"/><rect x="12" y="11" width="6" height="4"/>'),settings:v('<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:v('<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:v('<path d="M3 5h18v14H3V5Zm2 2v10h3V7H5Zm5 0v10h9V7h-9Zm-5 3h3v1H5v-1Zm0 3h3v1H5v-1Z"/>'),shuffle:v('<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:v('<path d="M7 7h10v2.5L21 6l-4-3.5V5H5v6h2V7Zm10 10H7v-2.5L3 18l4 3.5V19h12v-6h-2v4Z"/>'),subtitles:v('<path d="M3 5h18v14H3V5Zm2 2v10h14V7H5Zm2 3h6v2H7v-2Zm8 0h2v2h-2v-2ZM7 14h2v2H7v-2Zm4 0h6v2h-6v-2Z"/>'),list:v('<path d="M4 6h2v2H4V6Zm4 0h12v2H8V6ZM4 11h2v2H4v-2Zm4 0h12v2H8v-2ZM4 16h2v2H4v-2Zm4 0h12v2H8v-2Z"/>'),next:v('<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:v('<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:v('<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:v('<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:v('<path d="M4 6h12v2H4V6Zm0 4h12v2H4v-2Zm0 4h8v2H4v-2Zm14 0v-4h2v4h4v2h-4v4h-2v-4h-4v-2h4Z"/>'),share:v('<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:v('<path d="M5 3h2v18H5V3Zm4 1h10l-2.5 4L19 12H9V4Z"/>'),more:v('<circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/>'),close:v('<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"/>')},A={en:P.defaultLabels};function pt(r,t){A[r]=t}function mt(r){for(const[t,e]of Object.entries(r))e&&(A[t]=e)}function X(r){return r&&A[r]||P.defaultLabels}function vt(){return Object.keys(A)}function K(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 c of r){if(!Number.isFinite(c.time)||c.time<0||c.time>t)continue;const u=Math.max(0,c.value);if(u===0)continue;const p=Math.min(e-1,Math.floor(c.time/t*e));i[p]+=u,s=!0}if(!s)return[];const n=[.06,.24,.4,.24,.06],o=i.map((c,u)=>n.reduce((p,m,b)=>p+m*(i[u+b-2]??0),0)),l=Math.max(...o);if(l<=0)return[];const h=.08;return o.map(c=>h+(1-h)*(c/l))}function J(r,t=1e3,e=100){if(r.length===0)return"";const i=t/(r.length-1||1);let s=`M 0 ${e}`;return r.forEach((n,o)=>{s+=` L ${(o*i).toFixed(1)} ${(e-n*e).toFixed(1)}`}),s+=` L ${t} ${e} Z`,s}async function Y(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 tt(r,r.vastTag,t,0,{impressions:[],tracking:{}})}async function tt(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 g=await fetch(t,{signal:n.signal,credentials:"omit"});if(!g.ok)throw new Error(`VAST request failed (${g.status})`);l=await g.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");ft(c,s);const u=c.querySelector(":scope > Wrapper");if(u){const g=L(u.querySelector("VASTAdTagURI"));if(!g)throw new Error("VAST wrapper without VASTAdTagURI");return tt(r,g,e,i+1,s)}const p=c.querySelector(":scope > InLine");if(!p)throw new Error("VAST ad has neither InLine nor Wrapper");const m=p.querySelector("Creatives > Creative > Linear");if(!m)throw new Error("VAST ad has no Linear creative");const b=gt(m);if(!b)throw new Error("VAST ad has no playable MediaFile");return{roll:r.roll,mediaUrl:b.url,mediaType:b.type,clickThrough:L(m.querySelector("VideoClicks > ClickThrough"))??r.clickUrl,duration:I(L(m.querySelector(":scope > Duration"))),skipOffset:bt(m.getAttribute("skipoffset"),I(L(m.querySelector(":scope > Duration")))),impressions:s.impressions,tracking:s.tracking,adTitle:L(p.querySelector(":scope > AdTitle"))??void 0}}function ft(r,t){var e,i;for(const s of r.querySelectorAll("Impression")){const n=L(s);n&&t.impressions.push(n)}for(const s of r.querySelectorAll("Linear > TrackingEvents > Tracking")){const n=s.getAttribute("event"),o=L(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=L(s);n&&((i=t.tracking).click??(i.click=[])).push(n)}}function gt(r){const e=[...r.querySelectorAll("MediaFiles > MediaFile")].map(o=>({url:L(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 I(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 bt(r,t){if(!r)return;const e=r.trim().match(/^(\d+(?:\.\d+)?)%$/);return e?t!==void 0?Number(e[1])/100*t:void 0:I(r)}function T(r){if(r)for(const t of r)try{new Image().src=t}catch{}}function L(r){return r?.textContent?.trim().replace(/^<!\[CDATA\[|\]\]>$/g,"").trim()||null}class yt{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 Y(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 p=a("span","imp-ad__countdown");c.append(u,p);const m=a("div","imp-ad__actions");let b=null;t.clickThrough&&(b=a("button","imp-ad__visit",{type:"button"}),b.textContent=i.visitAdvertiser,m.append(b));const g=a("button","imp-ad__skip",{type:"button"});g.hidden=!0,m.append(g),s.append(n,h,c,m),this.host.container.append(s),this.layer=s;const B=t.skipOffset??this.opts.skipDelay,d=new Set,y=k=>{d.has(k)||(d.add(k),T(t.tracking[k]))};let $=Date.now(),H=-1;const nt=setInterval(()=>{if(n.paused){$=Date.now();return}if(n.currentTime!==H){H=n.currentTime,$=Date.now();return}Date.now()-$>=this.opts.mediaTimeout&&(this.host.emitter.emit("aderror",{roll:{roll:t.roll},error:new Error(`Ad media stalled for ${this.opts.mediaTimeout} ms — skipping`)}),q())},500),q=()=>{clearInterval(nt),o.abort(),n.pause(),n.removeAttribute("src"),n.load(),s.remove(),this.layer=null,e()},O=k=>{k?(y("skip"),this.host.emitter.emit("adskip",{ad:t})):y("complete"),this.host.emitter.emit("adend",{ad:t}),q()};n.addEventListener("playing",()=>{T(t.impressions),y("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 k=n.currentTime,_=n.duration;if(Number.isFinite(_)&&_>0&&(p.textContent=x(Math.max(0,_-k)),k/_>=.25&&y("firstQuartile"),k/_>=.5&&y("midpoint"),k/_>=.75&&y("thirdQuartile")),B>=0){const W=Math.ceil(B-k);W>0?(g.hidden=!1,g.disabled=!0,g.textContent=`${i.skipAdIn} ${W}`):(g.hidden=!1,g.disabled=!1,g.textContent=i.skipAd)}},{signal:l}),n.addEventListener("ended",()=>O(!1),{signal:l}),n.addEventListener("error",()=>{this.host.emitter.emit("aderror",{roll:{roll:t.roll},error:new Error("Ad media failed to play")}),q()},{signal:l}),g.addEventListener("click",()=>O(!0));const Z=()=>{t.clickThrough&&(y("click"),this.host.emitter.emit("adclick",{ad:t}),window.open(t.clickThrough,"_blank","noopener"),n.pause())};n.addEventListener("click",Z,{signal:l}),b?.addEventListener("click",Z);let D=!1,E=!1;n.addEventListener("playing",()=>{D=!0},{once:!0,signal:l}),n.addEventListener("pause",()=>{n.ended||!s.isConnected||(s.classList.add("imp-ad--paused"),D&&!E&&(E=!0,T(t.tracking.pause),this.host.emitter.emit("adpause",{ad:t})))},{signal:l}),n.addEventListener("play",()=>{s.classList.remove("imp-ad--paused"),E&&(E=!1,T(t.tracking.resume),this.host.emitter.emit("adresume",{ad:t}))},{signal:l}),s.addEventListener("click",k=>{(k.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 et(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)),!(o<=n)&&i.push({start:n,end:o,title:e[s].title})}return i}async function it(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 U(e).map(i=>({start:i.start,end:i.end,title:i.text}))}function F(r,t){for(const e of r)if(t>=e.start&&t<e.end)return e;return null}function st(r,t){return t?/application\/(x-mpegurl|vnd\.apple\.mpegurl)/i.test(t):/\.m3u8(\?|#|$)/i.test(r)}let S;async function kt(){if(S!==void 0)return S;const r=globalThis.Hls;if(r)return S=r,S;try{S=(await import("hls.js/light")).default}catch{S=null}return S}async function wt(r,t,e,i){if(st(t,e)){const s=r.canPlayType("application/vnd.apple.mpegurl"),n=s?null:await kt();return n&&n.isSupported()?xt(n,r,t,i):s?(r.src=t,N(r)):(i.onError("HLS is not supported in this browser and hls.js could not be loaded."),N(r))}return r.src=t,N(r)}function N(r){return{kind:"native",levels:[],selected:-1,setLevel(){},destroy(){r.removeAttribute("src"),r.load()}}}function xt(r,t,e,i){const s=new r({enableWorker:!0}),n={kind:"hls",levels:[],selected:-1,setLevel(h){n.selected=h,s.currentLevel=h},destroy(){s.destroy(),t.removeAttribute("src"),t.load()}};s.on(r.Events.MANIFEST_PARSED,()=>{n.levels=s.levels.map((h,c)=>({index:c,label:h.height?`${h.height}p`:`${Math.round(h.bitrate/1e3)} kbps`})).reverse(),i.onLevels(n.levels)}),s.on(r.Events.LEVEL_SWITCHED,(h,c)=>{const u=s.levels[c.level];u&&i.onLevelSwitch(u.height?`${u.height}p`:`${Math.round(u.bitrate/1e3)} kbps`)});let o=0,l=!1;return s.on(r.Events.ERROR,(h,c)=>{if(c.fatal)switch(c.type){case r.ErrorTypes.NETWORK_ERROR:s.startLoad();break;case r.ErrorTypes.MEDIA_ERROR:o<3?(o++,s.recoverMediaError()):(i.onError(`HLS media error: ${c.details}`,c),s.destroy());break;default:if(l)i.onError(`HLS fatal error: ${c.details}`,c),s.destroy();else{l=!0;try{s.loadSource(e),s.startLoad()}catch{i.onError(`HLS fatal error: ${c.details}`,c),s.destroy()}}}}),s.loadSource(e),s.attachMedia(t),n}class R{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 U(i)){const[o,l]=n.text.trim().split("#");if(!o)continue;const h={start:n.start,end:n.end,src:ut(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 R(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 Lt='<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>',St='<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 C{constructor(t){this.anchor=t,this.outsideListener=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()}),t.append(this.backdrop)}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){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=Lt,s.append(n,o,l),s.addEventListener("click",()=>this.renderSettingsDetail(t,i)),e.append(s)}this.root.append(e)}renderSettingsDetail(t,e){this.root.textContent="";const i=a("button","imp-menu__item imp-menu__back",{type:"button"}),s=a("span","imp-menu__chevron");s.innerHTML=St;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");i.icon.trimStart().startsWith("<svg")?o.innerHTML=i.icon:o.append(a("img","",{src:i.icon,alt:""})),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(){this.root.hidden=!1,this.backdrop.hidden=!1,this.outsideListener=t=>{const e=t.target;!this.root.contains(e)&&!this.anchor.contains(e)&&this.close()},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)}destroy(){this.close(),this.root.remove()}}class _t{constructor(t){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":"Seek",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.tooltip=a("div","imp-progress__tooltip"),this.tooltip.append(this.tooltipThumb,this.tooltipChapter,this.tooltipTime),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){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="${J(t)}"/></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?w(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",`${x(t)} / ${x(this.duration)}`)}render(t){for(const{chapter:i,fill:s}of this.segments){const n=i.end-i.start,o=n>0?w((t-i.start)/n,0,1):0;s.style.transform=`scaleX(${o})`}const e=this.duration>0?w(t/this.duration,0,1):0;this.handle.style.left=`${e*100}%`}timeFromEvent(t){const e=this.root.getBoundingClientRect();return(e.width>0?w((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=x(e);const i=F(this.chapters,e);this.tooltipChapter.textContent=i?.title??"",this.tooltipChapter.hidden=!i?.title;const s=this.thumbnails?.cueAt(e)??null;s?(this.tooltipThumb.hidden=!1,this.tooltipThumb.style.backgroundImage=`url("${s.src}")`,s.xywh?(this.tooltipThumb.style.width=`${s.xywh.w}px`,this.tooltipThumb.style.height=`${s.xywh.h}px`,this.tooltipThumb.style.backgroundPosition=`-${s.xywh.x}px -${s.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 n=this.root.getBoundingClientRect(),o=w(t.clientX-n.left,0,n.width),l=this.tooltip.offsetWidth/2;this.tooltip.style.left=`${w(o,l,Math.max(l,n.width-l))}px`}hideTooltip(){this.tooltip.classList.remove("imp-progress__tooltip--visible")}}class Bt{constructor(t){this.player=t,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.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 _t({onSeek:d=>t.seek(d),onScrubStart:()=>{this.wasPlayingBeforeScrub=!t.paused,t.pause()},onScrubEnd:()=>{this.wasPlayingBeforeScrub&&t.play()}}),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,p=c.forward??t.seekStep;if(s.playlist&&t.hasPlaylist&&!s.hidePrev&&(this.prevBtn=f("imp-btn--prev",e.previous,i.previous),this.prevBtn.addEventListener("click",()=>t.previous()),o.append(this.prevBtn)),s.seekButtons&&(this.seekBackBtn=f("imp-btn--seek-back",`${e.seekBack} ${u}s`,i.seekBack),this.addStepBadge(this.seekBackBtn,u),this.seekBackBtn.addEventListener("click",()=>t.skip(-u)),o.append(this.seekBackBtn)),s.play&&(this.playBtn=f("imp-btn--play",e.play,i.play),this.playBtn.addEventListener("click",()=>t.togglePlay()),o.append(this.playBtn)),s.seekButtons&&(this.seekFwdBtn=f("imp-btn--seek-forward",`${e.seekForward} ${p}s`,i.seekForward),this.addStepBadge(this.seekFwdBtn,p),this.seekFwdBtn.addEventListener("click",()=>t.skip(p)),o.append(this.seekFwdBtn)),s.playlist&&t.hasPlaylist&&(this.nextBtn=f("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=f("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":"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.liveBadge=a("span","imp-controls__live"),this.liveBadge.textContent=e.live,this.liveBadge.hidden=!0,o.append(this.timeLabel,this.liveBadge)),this.buildLikeDislike(l);for(const d of(t.actionsOptions.custom??[]).filter(y=>y.placement==="bar")){const y=f(`imp-btn--custom imp-btn--custom-${d.id}`,d.title,d.icon??i.more);y.addEventListener("click",()=>t.emit("customaction",{id:d.id})),l.append(y),this.registerCollapsible({key:`custom:${d.id}`,el:y,priority:55,available:()=>!0,section:()=>this.simpleSection(`custom:${d.id}`,d.title,d.icon??i.more,()=>t.emit("customaction",{id:d.id}))})}const m=d=>d===!1?"off":d==="bar"?"bar":"gear",b=m(s.subtitles),g=m(s.quality),B=m(s.speed);if(this.gear={speed:B==="gear",quality:g==="gear",subtitles:b==="gear"},b==="bar"){this.subtitlesBtn=f("imp-btn--subtitles",e.subtitles,i.subtitles),this.subtitlesMenu=new C(this.subtitlesBtn);const d=a("div","imp-controls__menu-anchor");d.append(this.subtitlesBtn,this.subtitlesMenu.root),this.subtitlesBtn.addEventListener("click",()=>this.toggleSubtitlesMenu()),l.append(d),this.registerCollapsible({key:"subtitles",el:d,priority:30,available:()=>t.subtitleTracks.length>0,section:()=>this.subtitlesSection()})}if(g==="bar"){this.qualityBtn=f("imp-btn--quality",e.quality,i.settings),this.qualityMenu=new C(this.qualityBtn);const d=a("div","imp-controls__menu-anchor");d.append(this.qualityBtn,this.qualityMenu.root),this.qualityBtn.addEventListener("click",()=>this.toggleQualityMenu()),l.append(d),this.registerCollapsible({key:"quality",el:d,priority:10,available:()=>t.qualityLevels.length>0,section:()=>this.qualitySection()})}if(B==="bar"){this.settingsBtn=f("imp-btn--speed",e.speed,i.speed),this.settingsMenu=new C(this.settingsBtn);const d=a("div","imp-controls__menu-anchor");d.append(this.settingsBtn,this.settingsMenu.root),this.settingsBtn.addEventListener("click",()=>this.toggleSettingsMenu()),l.append(d),this.registerCollapsible({key:"speed",el:d,priority:40,available:()=>!0,section:()=>this.speedSection()})}if(s.scenes&&(this.scenesBtn=f("imp-btn--scenes",e.scenes,i.scenes),this.scenesBtn.addEventListener("click",()=>t.toggleScenesPanel()),l.append(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.playlist&&t.hasPlaylist){const d=f("imp-btn--list",e.playlist,i.list);d.addEventListener("click",()=>t.togglePlaylistPanel()),l.append(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=f("imp-btn--pip",e.pip,i.pip);d.addEventListener("click",()=>void t.togglePip()),l.append(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=f("imp-btn--fullscreen",e.fullscreen,i.fullscreen),this.fullscreenBtn.addEventListener("click",()=>void t.toggleFullscreen()),l.append(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} ${p}s`,i.seekForward,()=>t.skip(p))})}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),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} ${p}s`,i.seekForward);this.addStepBadge(d,p),d.addEventListener("click",()=>t.skip(p)),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=f("imp-btn--settings",e.settings,i.settings),this.gearMenu=new C(this.gearBtn);const d=a("div","imp-controls__menu-anchor");d.append(this.gearBtn,this.gearMenu.root),this.gearBtn.addEventListener("click",()=>this.toggleGearMenu()),l.append(d),this.registerCollapsible({key:"gear",el:d,priority:40,available:()=>this.gearSections().length>0,section:()=>this.gearSections()})}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)}makeCenterButton(t,e,i){const s=a("button",`imp-center-btn imp-center-btn--${t}`,{type:"button","aria-label":e,title:e});return s.innerHTML=i,s}addStepBadge(t,e){const i=a("span","imp-seek-num");i.textContent=String(e),t.append(i)}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(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?"1×":`${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}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)return;e.textContent="";const n=a("div","imp-next-preview__kicker");if(n.textContent=this.player.labels.next,e.append(n),i.thumbnail&&s.poster){const m=a("div","imp-next-preview__thumb");if(m.style.backgroundImage=`url("${s.poster}")`,i.duration&&s.duration){const b=a("span","imp-next-preview__duration");b.textContent=x(s.duration),m.append(b)}e.append(m)}if(i.title&&s.title){const m=a("div","imp-next-preview__title");m.textContent=s.title,e.append(m)}if(i.meta&&s.previewMeta?.length){const m=a("div","imp-next-preview__meta");m.textContent=s.previewMeta.join(" · "),e.append(m)}e.hidden=!1;const o=this.player.container.getBoundingClientRect(),l=t.getBoundingClientRect(),h=8,c=e.offsetWidth,u=l.left-o.left+l.width/2-c/2,p=Math.max(h,Math.min(u,o.width-c-h));e.style.left=`${p}px`,e.style.bottom=`${o.height-(l.top-o.top)+10}px`}hideNextPreview(){this.nextPreviewEl&&(this.nextPreviewEl.hidden=!0)}buildLikeDislike(t){const e=this.player,i=e.actionsOptions,{labels:s,icons:n}=e;if(i.like){this.likeBtn=f("imp-btn--like",s.like,n.like),this.likeBtn.addEventListener("click",()=>e.emit("action",{id:"like"})),this.likeCountEl=this.attachCountTooltip(this.likeBtn,i.likeCount);const o=this.wrapWithTooltip(this.likeBtn,this.likeCountEl);t.append(o),this.registerCollapsible({key:"like",el:o,priority:62,available:()=>!0,section:()=>this.simpleSection("like",s.like,n.like,()=>e.emit("action",{id:"like"}))})}if(i.dislike){this.dislikeBtn=f("imp-btn--dislike",s.dislike,n.dislike),this.dislikeBtn.addEventListener("click",()=>e.emit("action",{id:"dislike"})),this.dislikeCountEl=this.attachCountTooltip(this.dislikeBtn,i.dislikeCount);const o=this.wrapWithTooltip(this.dislikeBtn,this.dislikeCountEl);t.append(o),this.registerCollapsible({key:"dislike",el:o,priority:60,available:()=>!0,section:()=>this.simpleSection("dislike",s.dislike,n.dislike,()=>e.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=f("imp-btn--more",s.more,n.more);this.moreMenu=new C(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","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?"1× (normal)":`${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,i=this.player.controlsOptions.seekPlacement!=="bar"||t;this.center.style.display=i?"flex":"none",this.centerPrevBtn&&(this.centerPrevBtn.style.display=t?"":"none"),this.centerNextBtn&&(this.centerNextBtn.style.display=t?"":"none"),this.playBtn&&(this.playBtn.style.display=t?"none":"");const s=l=>l==="seekBack"||l==="seekFwd"?i:l==="prev"||l==="next"?t:!1;this.overflowed.clear();for(const l of this.collapsibles){if(s(l.key)){l.el.style.display="none";continue}const h=l.available();l.el.style.display=h?"":"none",l.el.classList.remove("imp-collapsed")}const n=this.collapsibles.filter(l=>l.available()&&!s(l.key)).sort((l,h)=>l.priority-h.priority);let o=n.length;for(;o-- >0&&this.overflowsRow();){const l=n.find(h=>!this.overflowed.has(h.key));if(!l)break;l.el.style.display="none",l.el.classList.add("imp-collapsed"),this.overflowed.add(l.key)}if(this.moreWrap){const l=this.actionItems.length>0||this.overflowed.size>0;this.moreWrap.style.display=l?"":"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.timeLabel.textContent=`${x(e)} / ${x(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&&M(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&&M(this.playBtn,e,i),this.centerPlayBtn&&M(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;M(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.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.moreMenu])e&&e!==t&&e.close()}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.settingsMenu?.destroy(),this.subtitlesMenu?.destroy(),this.qualityMenu?.destroy(),this.moreMenu?.destroy(),this.nextPreviewEl?.remove(),this.root.remove()}}class Ct{constructor(t){this.root=a("div","imp-poster"),this.image=a("img","imp-poster__image",{alt:"",decoding:"async"}),this.image.hidden=!0;const e=f("imp-poster__play",t.labels.play,t.icons.bigPlay);e.addEventListener("click",()=>void t.play()),this.root.append(this.image,e),this.root.addEventListener("click",i=>{(i.target===this.root||i.target===this.image)&&t.play()})}setSource(t){t?.poster?(this.image.src=t.poster,this.image.fetchPriority="high",this.image.hidden=!1):(this.image.removeAttribute("src"),this.image.hidden=!0)}show(){this.root.hidden=!1}hide(){this.root.hidden=!0}}class Et{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.style.backgroundImage=`url("${i.avatar}")`):(this.channelAvatar.style.backgroundImage="",this.channelAvatar.textContent=(i.name.trim()[0]??"?").toUpperCase()))}show(){this.root.hidden=!1}hide(){this.root.hidden=!0}}class Mt{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=f("imp-related__close","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.style.backgroundImage=`url("${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 Tt{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=f("imp-playlist__shuffle",t.labels.shuffle,t.icons.shuffle),this.shuffleBtn.addEventListener("click",()=>{t.setShuffle(!t.shuffle),this.syncModes()}),this.repeatBtn=f("imp-playlist__repeat",t.labels.repeat,t.icons.repeat),this.repeatBtn.addEventListener("click",()=>{t.setRepeat(!t.repeat),this.syncModes()});const l=f("imp-playlist__close","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");t.poster&&(s.style.backgroundImage=`url("${t.poster}")`);const n=a("div","imp-playlist__meta"),o=a("div","imp-playlist__title");if(o.textContent=t.title??`#${e+1}`,n.append(o),t.duration){const l=a("div","imp-playlist__duration");l.textContent=x(t.duration),n.append(l)}i.append(s,n),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 Pt{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=f("imp-playlist__close","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.style.backgroundImage=`url("${n.src}")`);const o=a("div","imp-playlist__meta"),l=a("div","imp-playlist__title");l.textContent=e.title||x(e.start);const h=a("div","imp-playlist__duration");h.textContent=x(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()}}function Q(r){return r?typeof r=="string"?[{src:r,label:"Subtitles"}]:Array.isArray(r)?r:[r]:[]}const At={play:!0,progress:!0,time:!0,volume:!0,fullscreen:!0,pip:!0,speed:"gear",settings:"gear",quality:"gear",scenes:!0,heatmap:!0,subtitles:"gear",seekButtons:!0,seekPlacement:"overlay",playlist:!0,hidePrev:!0,nextPreview:!0,hideDelay:2500};class Rt{constructor(t,e={}){this.scrubbing=!1,this.emitter=new j,this.abort=new AbortController,this.sources=[],this.currentIndex=-1,this.sourceController=null,this.loadToken=0,this.chapters=[],this.currentChapter=null,this.progressiveQuality=-1,this.thumbTrack=null,this.shuffleMode=!1,this.decodeRecoveries=0,this.adManager=null,this.playedOnce=!1,this.idleTimer=null,this.destroyed=!1;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={...P.defaultLabels,...X(e.language),...e.labels},this.icons={...G,...e.icons};const s=e.controls??{},n=s.speed??s.settings??"gear";this.controlsOptions={...At,...s,speed:n,settings:n},this.actionsOptions=e.actions??{},this.playbackRates=e.playbackRates??[.5,.75,1,1.25,1.5,2],this.seekStep=e.seekStep??15,this.playlistOptions={title:"",autoAdvance:!0,loop:!1,shuffle:!1,startIndex:0,layout:"sidebar",...e.playlist},this.shuffleMode=this.playlistOptions.shuffle,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 o=e.styling;if(o?.themeColor&&this.container.style.setProperty("--imp-accent",o.themeColor),o?.likeColor&&this.container.style.setProperty("--imp-like",o.likeColor),o?.dislikeColor&&this.container.style.setProperty("--imp-dislike",o.dislikeColor),o?.borderRadius!==void 0){const p=typeof o.borderRadius=="number"?`${o.borderRadius}px`:o.borderRadius;this.container.style.setProperty("--imp-radius",p)}o?.playButtonStyle==="inverted"&&this.container.classList.add("imp-player--play-inverted"),this.video=a("video","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),e.muted&&(this.video.muted=!0),this.video.volume=w(e.volume??1,0,1);const l=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.pauseScreen=new Et(this.labels),this.poster=new Ct(this),this.related=new Mt(this),this.related.setOptions(e.related),this.controls=new Bt(this),this.playlistPanel=new Tt(this,this.playlistOptions.layout,this.playlistOptions.title||void 0),this.scenesPanel=new Pt(this,e.scenes?.layout??"bottom");const h=a("div","imp-layer__middle");h.append(this.spinner,this.errorBox,this.controls.center);const c=a("div","imp-layer__bottom");c.append(this.controls.root),l.append(this.pauseScreen.root,this.related.root,h,c),this.container.append(this.video,l,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 u=e.adConfig??e.ads;u&&u.adList.length>0&&(this.adManager=new yt({container:this.container,contentVideo:this.video,emitter:this.emitter,labels:this.labels,closeIcon:this.icons.close},u)),this.emitter.on("error",({message:p})=>{this.errorBox.textContent=p,this.errorBox.hidden=!1,this.spinner.hidden=!0,this.poster.hide()}),this.bindVideoEvents(),this.bindIdleHide(),e.keyboard!==!1&&this.bindKeyboard(),this.video.addEventListener("pointerup",p=>{if(!(this.adPlaying||!this.playedOnce)){if(p.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",p=>{this.pauseScreen.hasCustom||p.target===this.pauseScreen.root&&this.togglePlay()},{signal:this.abort.signal}),this.sources.length>0&&this.loadItem(w(this.playlistOptions.startIndex,0,this.sources.length-1),!!e.autoplay),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(){this.destroyed||this.adPlaying||this.adManager&&(await this.adManager.playPreRoll(),this.destroyed||!this.video.paused)||await this.video.play()}pause(){this.adPlaying||this.video.pause()}togglePlay(){this.video.paused||this.video.ended?this.play():this.pause()}seek(t){Number.isFinite(this.video.duration)&&(this.video.currentTime=w(t,0,this.video.duration))}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=w(t,0,1),t>0&&(this.video.muted=!1)}setMuted(t){this.video.muted=t}toggleMute(){this.video.muted=!this.video.muted}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 n=t===-1?this.labels.qualityAuto:this.sourceController.levels.find(o=>o.index===t)?.label??String(t);this.emitter.emit("qualitychange",{label:n});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,this.video.currentTime=i,s&&this.video.play().catch(()=>{}),this.emitter.emit("qualitychange",{label:e[t].label??String(e[t].quality??t)})}get subtitleTracks(){return Q(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}get nextSource(){if(this.shuffleMode||this.sources.length<2)return null;const t=this.currentIndex+1;return t<this.sources.length?this.sources[t]:this.playlistOptions.loop?this.sources[0]??null:null}get hasPlaylist(){return this.sources.length>1}get hasNext(){return this.shuffleMode||this.playlistOptions.loop?this.sources.length>1:this.currentIndex<this.sources.length-1}get hasPrevious(){return 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}next(){if(this.hasNext){if(this.shuffleMode&&this.sources.length>1){let t=this.currentIndex;for(;t===this.currentIndex;)t=Math.floor(Math.random()*this.sources.length);this.playItem(t);return}this.playItem((this.currentIndex+1)%this.sources.length)}}previous(){this.hasPrevious&&this.playItem((this.currentIndex-1+this.sources.length)%this.sources.length)}playItem(t){t<0||t>=this.sources.length||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(w(e,0,this.sources.length-1),!1)}get isFullscreen(){return document.fullscreenElement===this.container}async toggleFullscreen(){this.isFullscreen?await document.exitFullscreen():this.container.requestFullscreen?await this.container.requestFullscreen():this.video.webkitEnterFullscreen?.()}async togglePip(){document.pictureInPictureElement===this.video?await document.exitPictureInPicture():await this.video.requestPictureInPicture()}get chapterList(){return this.chapters}get chapter(){return this.currentChapter}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.container.remove(),this.emitter.emit("destroy",void 0),this.emitter.removeAll())}async loadItem(t,e){const i=++this.loadToken,s=this.sources[t];if(!s)return;this.currentIndex=t,this.sourceController?.destroy(),this.sourceController=null,this.chapters=[],this.currentChapter=null,this.progressiveQuality=-1,this.playedOnce=!1;for(const h of[...this.video.querySelectorAll("track")])h.remove();this.adManager?.resetForNewSource(),this.related.hide(),this.pauseScreen.hide(),this.scenesPanel.hide(),this.thumbTrack=null,this.errorBox.hidden=!0,this.decodeRecoveries=0,this.video.poster=s.poster??"",this.poster.setSource(s),this.pauseScreen.setSource(s),this.controls.progress.setChapters([]),this.controls.progress.setThumbnails(null),this.controls.progress.setHeatmap([]),e?this.poster.hide():this.poster.show(),this.playlistPanel.rebuild();for(const h of Q(s.subtitles)){const c=a("track","",{kind:"subtitles",src:h.src,label:h.label,...h.srclang?{srclang:h.srclang}:{}});h.default&&c.setAttribute("default",""),this.video.append(c)}let n=s.src,o=s.type;if(s.qualities&&s.qualities.length>0){const h=Math.max(0,s.qualities.findIndex(c=>c.src===s.src));this.progressiveQuality=h,n=s.qualities[h].src,o=s.qualities[h].type??o}this.video.preload=this.adManager?.hasPendingPreRoll?"auto":"metadata";const l=await wt(this.video,n,o,{onLevels:()=>{i===this.loadToken&&this.controls.syncFeatureButtons()},onLevelSwitch:h=>this.emitter.emit("qualitychange",{label:h}),onError:(h,c)=>this.emitter.emit("error",{message:h,cause:c})});if(i!==this.loadToken){l.destroy();return}if(this.sourceController=l,this.emitter.emit("sourcechange",{source:s,index:t}),s.thumbnails&&R.load(s.thumbnails).then(h=>{i===this.loadToken&&(this.thumbTrack=h,this.controls.progress.setThumbnails(h),this.scenesPanel.visible&&this.scenesPanel.rebuild())}).catch(h=>this.emitter.emit("error",{message:"Failed to load thumbnails track",cause:h})),s.chapters){const h=c=>{const u=()=>{i===this.loadToken&&(this.chapters=et(c,this.video.duration),this.controls.progress.setChapters(this.chapters),this.controls.syncFeatureButtons(),this.scenesPanel.visible&&this.scenesPanel.rebuild())};Number.isFinite(this.video.duration)&&this.video.duration>0?u():this.video.addEventListener("loadedmetadata",u,{once:!0,signal:this.abort.signal})};typeof s.chapters=="string"?it(s.chapters).then(c=>h(c)).catch(c=>this.emitter.emit("error",{message:"Failed to load chapters track",cause:c})):h(s.chapters)}if(s.heatmap&&s.heatmap.length>0&&this.controlsOptions.heatmap){const h=s.heatmap,c=()=>{i===this.loadToken&&this.controls.progress.setHeatmap(K(h,this.video.duration))};Number.isFinite(this.video.duration)&&this.video.duration>0?c():this.video.addEventListener("loadedmetadata",c,{once:!0,signal:this.abort.signal})}e&&this.play().catch(()=>{i===this.loadToken&&this.poster.show()})}bindVideoEvents(){const{signal:t}=this.abort,e=this.video;e.addEventListener("play",()=>{this.playedOnce=!0,this.poster.hide(),this.pauseScreen.hide(),this.related.visible||this.related.hide(),this.related.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.emitter.emit("timeupdate",{currentTime:e.currentTime,duration:e.duration||0}),this.adManager?.checkMidRolls(e.currentTime);const i=F(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})},{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.errorBox.hidden=!0,this.decodeRecoveries=0},{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(()=>{})};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})},{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})}async handleEnded(){if(this.emitter.emit("ended",void 0),this.showControlsNow(),!(this.adManager&&(await this.adManager.playPostRoll(),this.destroyed))){if(this.playlistOptions.autoAdvance&&this.hasNext){this.next();return}(this.options.related?.showOn?.includes("ended")??!!this.options.related)&&this.related.show()}}bindIdleHide(){const{signal:t}=this.abort,e=()=>{this.showControlsNow(),this.scheduleIdle()};this.container.addEventListener("pointermove",i=>{i.pointerType!=="touch"&&e()},{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.video.paused||this.container.classList.add("imp-player--idle"))},{signal:t})}showControlsNow(){this.container.classList.remove("imp-player--idle")}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=P.defaultLabels;exports.Emitter=j;exports.Player=Rt;exports.ThumbnailTrack=R;exports.buildHeatmapValues=K;exports.chapterAt=F;exports.defaultIcons=G;exports.formatTime=x;exports.getLocale=X;exports.heatmapPath=J;exports.isHlsSource=st;exports.loadChaptersVtt=it;exports.normalizeChapters=et;exports.registerLocale=pt;exports.registerLocales=mt;exports.registeredLanguages=vt;exports.resolveVast=Y;
5
5
  //# sourceMappingURL=core.cjs.map