@serifpersia/dango 3.8.6 → 3.8.7

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.
Files changed (60) hide show
  1. package/README.md +1 -1
  2. package/client/dist/assets/{AnimeCard-DWKuN1cB.js → AnimeCard-DeOILoQY.js} +1 -1
  3. package/client/dist/assets/{AnimeInfo-BvNA7-QZ.js → AnimeInfo-CEWjWNK4.js} +1 -1
  4. package/client/dist/assets/{AnimeInfoPage-BGg76ExO.js → AnimeInfoPage-BBB8hD_-.js} +2 -2
  5. package/client/dist/assets/{Asmr-C8pvBHUO.js → Asmr-BJjmJorV.js} +1 -1
  6. package/client/dist/assets/{AsmrPopup-BV5rbWXg.js → AsmrPopup-BW-iFW3L.js} +1 -1
  7. package/client/dist/assets/{AsmrResetProgressModal-Cs5wzgRU.js → AsmrResetProgressModal-BAp7wa4X.js} +1 -1
  8. package/client/dist/assets/{Home-C3k84yqn.js → Home-BqE0OcxM.js} +1 -1
  9. package/client/dist/assets/{Insights-RSd-4osN.js → Insights-D3-riQFt.js} +1 -1
  10. package/client/dist/assets/{LibraryListPage-CHHjw4Jz.js → LibraryListPage-CKEWlzgR.js} +1 -1
  11. package/client/dist/assets/{ListeningList-DkgZaFkg.js → ListeningList-WhGQuOYx.js} +1 -1
  12. package/client/dist/assets/{Manga-BAI78oiq.js → Manga-XJEPnce1.js} +1 -1
  13. package/client/dist/assets/{MangaInfoPage-CPYfuLAg.js → MangaInfoPage-B3xV4o8C.js} +1 -1
  14. package/client/dist/assets/{MangaReadPage-DvznQu_2.js → MangaReadPage-BdmcONww.js} +1 -1
  15. package/client/dist/assets/{MangaResetProgressModal-BPci6zSM.js → MangaResetProgressModal-C1Bfn9O_.js} +1 -1
  16. package/client/dist/assets/{Mature-Cob1Zmtu.js → Mature-VH_PWwEN.js} +1 -1
  17. package/client/dist/assets/{MatureConsentModal-BrKd4CBZ.js → MatureConsentModal-Do1CtwDw.js} +1 -1
  18. package/client/dist/assets/{MediaCard-CXZJ8wr7.js → MediaCard-BikTKuG3.js} +1 -1
  19. package/client/dist/assets/{OptionListMenu-ClUReC8J.js → OptionListMenu-BReFoLC2.js} +1 -1
  20. package/client/dist/assets/Player-CUTDxVY5.js +56 -0
  21. package/client/dist/assets/{PlayerProvider-DzaMVhFX.js → PlayerProvider-D60eCjik.js} +1 -1
  22. package/client/dist/assets/{PlayerSettings-DnFjoot8.js → PlayerSettings-C2pu0sQt.js} +1 -1
  23. package/client/dist/assets/{QueueOptionsButton-BdAz_Gn-.js → QueueOptionsButton-CUyJPdwg.js} +1 -1
  24. package/client/dist/assets/{QueueRail-BMLyoeAe.js → QueueRail-DqyZVaD-.js} +1 -1
  25. package/client/dist/assets/{ReadingList-B62vvh4_.js → ReadingList-BXR1JrJ_.js} +1 -1
  26. package/client/dist/assets/{ResetProgressModal-CXDZfCap.js → ResetProgressModal-YVCqneQ5.js} +1 -1
  27. package/client/dist/assets/{Search-CfNUqNi0.js → Search-C27b6qOV.js} +1 -1
  28. package/client/dist/assets/Settings-DEWZN-A-.js +21 -0
  29. package/client/dist/assets/{SkeletonGrid-CmHR4_Fc.js → SkeletonGrid-BpsynMj7.js} +1 -1
  30. package/client/dist/assets/{Trackers-BnvqfI9T.js → Trackers-B3EMJMgo.js} +1 -1
  31. package/client/dist/assets/Tv-BfDkrKuI.js +4 -0
  32. package/client/dist/assets/{Tv-D3vXCsSC.css → Tv-DT3m2nZs.css} +1 -1
  33. package/client/dist/assets/{TvInfo-6fZeQsh1.js → TvInfo-BkABl1xJ.js} +1 -1
  34. package/client/dist/assets/{TvPopup-CIMgMYf0.js → TvPopup-RchqnXJt.js} +1 -1
  35. package/client/dist/assets/{TvSearch-DGG4xRiv.js → TvSearch-C9oRGjgC.js} +1 -1
  36. package/client/dist/assets/{TvWatchlist-B6DLkxqi.js → TvWatchlist-ClRCXsXi.js} +1 -1
  37. package/client/dist/assets/{VirtualKeyboard-D8TvygKk.js → VirtualKeyboard-C0Yf-_br.js} +1 -1
  38. package/client/dist/assets/{WatchAlong-ivfsMGhR.js → WatchAlong-CIBT0VHg.js} +1 -1
  39. package/client/dist/assets/{WatchAlongPanel-CvUFCFll.js → WatchAlongPanel-D87h_8qM.js} +1 -1
  40. package/client/dist/assets/{Watchlist-dsmIAzsH.js → Watchlist-1rn0IRne.js} +1 -1
  41. package/client/dist/assets/{index-npJ4Ahxa.js → index-Cd1-bH35.js} +4 -4
  42. package/client/dist/assets/{libraryInvalidation-CHlEJU7b.js → libraryInvalidation-BHknhNAw.js} +1 -1
  43. package/client/dist/assets/{playbackCompletion-DB_c1lex.js → playbackCompletion-ZhAwimeL.js} +1 -1
  44. package/client/dist/assets/{useAnimeInfoData-DrWgr6PK.js → useAnimeInfoData-l7nCKCe5.js} +1 -1
  45. package/client/dist/assets/{useMangaLibrary-sGh96sdT.js → useMangaLibrary-DAPvo2xZ.js} +1 -1
  46. package/client/dist/assets/{useMangaPopup-CWDMFbSD.js → useMangaPopup-B5LPCa2N.js} +1 -1
  47. package/client/dist/assets/{useProviders-DphwZjpZ.js → useProviders-DsY_iifL.js} +1 -1
  48. package/client/dist/assets/{useTv-DatZ0tof.js → useTv-olJK7WfQ.js} +1 -1
  49. package/client/dist/assets/{useTvLibrary-efdd6TIy.js → useTvLibrary-Deie_gJF.js} +1 -1
  50. package/client/dist/assets/useWatchAlongPlayer-CkSxIqXL.css +1 -0
  51. package/client/dist/assets/{useWatchAlongPlayer-CRf0zHFj.js → useWatchAlongPlayer-cl8kIOvd.js} +3 -3
  52. package/client/dist/index.html +1 -1
  53. package/package.json +2 -2
  54. package/server/dist/config.js +1 -1
  55. package/server/dist/server.js +146 -146
  56. package/server/package.json +1 -1
  57. package/client/dist/assets/Player-7iroOb7T.js +0 -56
  58. package/client/dist/assets/Settings-CxC4k-nB.js +0 -21
  59. package/client/dist/assets/Tv-Dht8h84V.js +0 -4
  60. package/client/dist/assets/useWatchAlongPlayer-CzQyysyL.css +0 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dango-server",
3
3
  "private": true,
4
- "version": "3.8.6",
4
+ "version": "3.8.7",
5
5
  "type": "module",
6
6
  "engines": {
7
7
  "node": ">=22.12.0"
@@ -1,56 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PlayerSettings-DnFjoot8.js","assets/vendor-core-DfaOB3Rn.js","assets/index-npJ4Ahxa.js","assets/vendor-query-BBT5_sHx.js","assets/vendor-icons-DrybRNxP.js","assets/index-Ej7BS74s.css","assets/OptionListMenu-ClUReC8J.js","assets/useWatchAlongPlayer-CRf0zHFj.js","assets/PlayerProvider-DzaMVhFX.js","assets/PlayerProvider-ZeplRma-.css","assets/playbackCompletion-DB_c1lex.js","assets/useWatchAlongPlayer-CzQyysyL.css","assets/PlayerSettings-CbGkvNJq.css"])))=>i.map(i=>d[i]);
2
- import{u as t,g as ct,h as U,P as er,z as tr,d as ie,A as R,q,y as rr,T as Ce,o as nr,a as sr,c as or,_ as ar,S as it}from"./vendor-core-DfaOB3Rn.js";import{p as J,a2 as Bt,a3 as Ze,o as ir,q as ae,t as me,J as Pe,a4 as lr,a5 as ze,Q as ut,a6 as cr,e as ur,x as dr,y as mr,z as pr,A as fr,d as hr,u as vr,B as lt,a7 as gr,a8 as br,f as yr}from"./index-npJ4Ahxa.js";import{P as Sr,a as kr,b as Er,F as wr,s as Tr,c as Cr}from"./PlayerProvider-DzaMVhFX.js";import{u as Dt,b as At,a as kt}from"./vendor-query-BBT5_sHx.js";import{p as wt,s as Mr,C as Rr,a as Nr,P as Pr,b as Fe,c as xt,f as $t,d as _r,e as Ar,g as xr,r as Lr,u as Br,h as Dr,i as $r,j as Ir,k as Fr,l as Or,m as Wr,n as Ur,o as Te,A as Vr,q as Qr,R as Kr,E as qr,t as Gr,v as S,w as zr,x as Hr,y as jr}from"./useWatchAlongPlayer-CRf0zHFj.js";import{I as be}from"./vendor-icons-DrybRNxP.js";import{l as Yr,i as dt,s as Xr}from"./playbackCompletion-DB_c1lex.js";import{M as Jr}from"./MatureConsentModal-BrKd4CBZ.js";import{u as Zr}from"./useIsMobile-Dvx1uJ82.js";import{s as Ne,Q as en}from"./QueueRail-BMLyoeAe.js";import{u as tn,Q as rn}from"./QueueOptionsButton-BdAz_Gn-.js";import{u as It}from"./useProviders-DphwZjpZ.js";import{A as nn}from"./AnimeMetaDetails-B3-A7O5H.js";import{S as sn}from"./SynopsisText-B3Sa5pRv.js";import{W as on}from"./WatchAlongPanel-CvUFCFll.js";import"./vendor-ui-3qrARCPr.js";const an="_controlsOverlay_6uapd_1",ln="_hidden_6uapd_21",cn="_topControls_6uapd_27",un="_backBtn_6uapd_47",dn="_videoTitleInfo_6uapd_67",mn="_animeTitle_6uapd_73",pn="_episodeNumber_6uapd_83",fn="_bottomControls_6uapd_91",hn="_progressBarContainer_6uapd_110",vn="_progressBar_6uapd_110",gn="_thumb_6uapd_129",bn="_scrubbing_6uapd_144",yn="_watchedBar_6uapd_148",Sn="_bufferedBar_6uapd_149",kn="_timeBubble_6uapd_191",En="_skipSegment_6uapd_225",wn="_op_6uapd_235",Tn="_mixed_op_6uapd_236",Cn="_ed_6uapd_240",Mn="_mixed_ed_6uapd_241",Rn="_recap_6uapd_245",Nn="_mixed_recap_6uapd_246",Pn="_bottomControlsRow_6uapd_250",_n="_leftControls_6uapd_258",An="_rightControls_6uapd_259",xn="_controlBtn_6uapd_266",Ln="_theaterBtn_6uapd_307",Bn="_nextEpisodeBtn_6uapd_311",Dn="_active_6uapd_332",$n="_timeDisplay_6uapd_336",In="_skipControls_6uapd_344",L={controlsOverlay:an,hidden:ln,topControls:cn,backBtn:un,videoTitleInfo:dn,animeTitle:mn,episodeNumber:pn,bottomControls:fn,progressBarContainer:hn,progressBar:vn,thumb:gn,scrubbing:bn,watchedBar:yn,bufferedBar:Sn,timeBubble:kn,skipSegment:En,op:wn,mixed_op:Tn,ed:Cn,mixed_ed:Mn,recap:Rn,mixed_recap:Nn,bottomControlsRow:Pn,leftControls:_n,rightControls:An,controlBtn:xn,theaterBtn:Ln,nextEpisodeBtn:Bn,active:Dn,timeDisplay:$n,skipControls:In},Fn=({player:r,handlers:o,visible:c,skipIntervals:m,showNextEpisodeButton:T,onNextEpisode:a,isTheaterMode:s,onTheaterModeToggle:n,settingsBtnRef:i,timeDisplayRef:p})=>{const{state:y,actions:f}=r,{showSettings:E}=y;return t("div",{className:`${L.controlsOverlay} ${c?"":L.hidden} `,"data-speed-boost-ignore":"true",style:{pointerEvents:"none",background:"none",justifyContent:"flex-end"},children:t("div",{className:L.bottomControls,"data-speed-boost-ignore":"true",onClick:w=>w.stopPropagation(),children:[t(Sr,{classes:{container:L.progressBarContainer,scrubbing:L.scrubbing,timeBubble:L.timeBubble,bar:L.progressBar,buffered:L.bufferedBar,watched:L.watchedBar,thumb:L.thumb},timeLabelRef:p,children:[y.duration>0&&r.state.currentSkipInterval&&t("div",{className:`${L.skipSegment} ${L[r.state.currentSkipInterval.skip_type]} `,style:{left:`${r.state.currentSkipInterval.start_time/y.duration*100}% `,width:`${(r.state.currentSkipInterval.end_time-r.state.currentSkipInterval.start_time)/y.duration*100}% `}}),m.map(w=>{const e=w.start_time/y.duration*100,v=(w.end_time-w.start_time)/y.duration*100;return t("div",{className:`${L.skipSegment} ${L[w.skip_type]} `,style:{left:`${e}% `,width:`${v}% `},title:w.skip_type.toUpperCase()},w.skip_id)})]}),t("div",{className:L.bottomControlsRow,children:[t("div",{className:L.leftControls,children:[t(kr,{className:L.controlBtn}),t(Er,{buttonClassName:L.controlBtn,onExpandedChange:f.setShowVolumeSlider}),t("span",{className:L.timeDisplay,ref:p,children:[f.formatTime(0)," / ",f.formatTime(y.duration)]}),y.currentSkipInterval&&!y.isAutoSkipEnabled&&!y.playbackLocked&&t("button",{className:L.controlBtn,onClick:()=>{y.currentSkipInterval&&(r.engine.seek(y.currentSkipInterval.end_time),f.setCurrentSkipInterval(null))},children:["Skip ",y.currentSkipInterval.skip_type==="op"?"Opening":"Ending"]})]}),t("div",{className:L.rightControls,children:[t("div",{className:L.skipControls,children:T&&t("button",{className:L.nextEpisodeBtn,onClick:a,title:"Play next episode",children:"Next EP"})}),t("button",{className:`${L.controlBtn} ${o.isSubtitleActive?L.active:""}`,onClick:o.handleCCToggle,title:o.isSubtitleActive?"Disable Subtitles":"Enable Subtitles","aria-label":"Toggle Subtitles",children:t(be,{name:"closed-captioning",size:22})}),t("button",{ref:i,className:`${L.controlBtn} ${E?L.active:""} `,onClick:()=>f.setShowSettings(!E),"aria-label":"Settings",children:t(be,{name:"cog"})}),t("button",{className:`${L.controlBtn} ${L.theaterBtn} ${s?L.active:""} `,onClick:w=>{w.stopPropagation(),n()},title:s?"Exit Theater Mode":"Theater Mode","aria-label":s?"Exit Theater Mode":"Theater Mode",children:t(be,{name:"tv"})}),t(wr,{className:L.controlBtn})]})]})]})})};function On(r){const{state:o,refs:c,actions:m}=r,T=n=>{if(!c.videoRef.current)return;m.setActiveSubtitleTrack(n);try{if(n===null||n==="off")J.setItem("playerSubtitlesEnabled","false");else{J.setItem("playerSubtitlesEnabled","true");const p=o.availableSubtitles.find(y=>y.label===n||y.lang===n);p?J.setItem("playerLastSubtitle",Mr(p)):J.setItem("playerLastSubtitle",n)}}catch{}let i=!1;Array.from(c.videoRef.current.textTracks).forEach(p=>{const f=n!==null&&n!=="off"&&(p.language===n||p.label===n)&&!i;p.mode=f?"showing":"hidden",f&&(i=!0)})},a=o.activeSubtitleTrack!==null&&o.activeSubtitleTrack!=="off";return{handleSubtitleSelection:T,isSubtitleActive:a,handleCCToggle:()=>{if(!c.videoRef.current)return;if(a){T("off");return}if(o.availableSubtitles.length===0)return;let n=null;try{n=J.getItem("playerLastSubtitle")}catch{}const i=wt(o.availableSubtitles,{lastKey:n,enabled:!0});if(i<0)return;const p=o.availableSubtitles[i];T(p.label||p.lang)}}}const Wn=tr(()=>Bt(()=>import("./PlayerSettings-DnFjoot8.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12]))),Un=({player:r,isAutoplayEnabled:o,onAutoplayChange:c,showNextEpisodeButton:m,onNextEpisode:T,videoSources:a,selectedSource:s,selectedLink:n,onSourceChange:i,loadingVideo:p,skipIntervals:y,animeTitle:f,episodeNumber:E,mode:w,isTheaterMode:e,onTheaterModeToggle:v,anime4kEnabled:N,onAnime4kToggle:_,anime4kSupported:x,anime4kProfile:g,onAnime4kProfileChange:d,anime4kInitializing:P,anime4kError:A,videoDelayEnabled:F,onVideoDelayToggle:V,videoDelayMs:b,onVideoDelayChange:h,onCalibrateAvSync:O,fallbackChoice:z,onFallbackChoiceChange:D,ambientSettings:B,onAmbientChange:H,children:j,overlays:pe,isInteractingExtra:$=!1,className:Q,hideChrome:ee=!1})=>{const{state:l,actions:M}=r,{showSettings:k}=l,{setShowSettings:C}=M,W=On(r),Y=ct.useRef(null),Me=ct.useRef(null),_e=ct.useRef(null);U(()=>{const le=xe=>{Y.current&&!Y.current.contains(xe.target)&&Me.current&&!Me.current.contains(xe.target)&&k&&C(!1)};return k&&document.addEventListener("mousedown",le),()=>{document.removeEventListener("mousedown",le)}},[k,C]);const ne=l.showControls||k||l.isScrubbing,X=l.activeSubtitleTrack!=="off"?l.availableSubtitles.find(le=>le.lang===l.activeSubtitleTrack||le.label===l.activeSubtitleTrack):void 0,Ae=t(Rr,{visible:ne,title:f,episode:E?`Episode ${E}`:void 0,mode:w,server:p?void 0:s?.sourceName,subtitles:p?void 0:X?.label||X?.lang,onBack:()=>window.history.back(),classes:{overlay:L.controlsOverlay,hidden:L.hidden,top:L.topControls,backBtn:L.backBtn,titleInfo:L.videoTitleInfo,title:L.animeTitle,episode:L.episodeNumber}}),De=!p&&!l.isBuffering&&l.duration>0?t(Nr,{}):null,se=t(Fn,{player:r,handlers:W,visible:ne,skipIntervals:y,showNextEpisodeButton:m,onNextEpisode:T,isTheaterMode:e,onTheaterModeToggle:v,settingsBtnRef:Me,timeDisplayRef:_e}),K=t(er,{fallback:null,children:t(Wn,{ref:Y,isOpen:k,onClose:()=>C(!1),videoSources:a,currentSource:s,currentLink:n,onSourceChange:i,subtitles:l.availableSubtitles,activeSubtitleTrack:l.activeSubtitleTrack,onSubtitleChange:W.handleSubtitleSelection,subtitleSettings:{fontSize:l.subtitleFontSize,position:l.subtitlePosition,bgOpacity:l.subtitleBgOpacity,bgColor:l.subtitleBgColor,textColor:l.subtitleTextColor,edge:l.subtitleEdge,bold:l.subtitleBold},onSubtitleSettingsChange:M.setSubtitleStyle,useNativeControls:!l.playbackLocked&&l.useNativeControls,onNativeControlsToggle:M.setUseNativeControls,anime4kEnabled:N,onAnime4kToggle:_,anime4kSupported:x,anime4kProfile:g,onAnime4kProfileChange:d,anime4kInitializing:P,anime4kError:A,videoDelayEnabled:F,onVideoDelayToggle:V,videoDelayMs:b,onVideoDelayChange:h,onCalibrateAvSync:O,isAutoSkipEnabled:l.isAutoSkipEnabled,onAutoSkipChange:le=>{M.setIsAutoSkipEnabled(le);try{J.setItem("autoSkipEnabled",le.toString())}catch{}},isAutoplayEnabled:o,onAutoplayChange:c,fallbackChoice:z,onFallbackChoiceChange:D,isTheaterMode:e,ambientSettings:B,onAmbientChange:H})}),fe=k?t("div",{"data-speed-boost-ignore":"true",onClick:le=>le.stopPropagation(),children:K}):null;return t(Pr,{engine:r.engine,topBar:Ae,centerControls:De,bottomBar:!p&&l.duration>0?se:null,settingsPanel:fe,overlays:pe,isInteracting:$||l.showSettings||l.showVolumeSlider,nativeControls:!l.playbackLocked&&l.useNativeControls,className:Q,chromeDisabled:ee,children:j})},Vn=({count:r=3})=>t("section",{className:Ne.section,children:[t("div",{className:Ne.header,children:t("button",{className:Ne.headerToggle,disabled:!0,children:[t("span",{className:Ne.title,children:t(Ze,{width:"60px",height:"1.2rem",variant:"text"})}),t(be,{name:"chevron-down",style:{opacity:.3}})]})}),t("div",{className:Ne.list,children:Array.from({length:r}).map((o,c)=>t("div",{className:Ne.item,style:{pointerEvents:"none"},children:[t("div",{className:Ne.dragHandle,style:{opacity:.2},children:t(Ze,{width:"16px",height:"16px",variant:"rectangular"})}),t("div",{className:Ne.thumbnail,style:{overflow:"hidden",background:"transparent"},children:t(Ze,{width:"100%",height:"100%",variant:"rectangular"})}),t("div",{className:Ne.meta,children:[t(Ze,{width:"80%",height:"1.2rem",variant:"text",className:Ne.metaGap}),t(Ze,{width:"40%",height:"0.8rem",variant:"rectangular",style:{borderRadius:"var(--radius-sm)"}})]})]},c))})]}),Qn={soft:"Softsub",hard:"Hardsub",mixed:"Mixed"},Kn={direct:"Direct",embed:"Embed",cookie:"Needs cookie"},qn=["direct","cookie","embed"],Gn=({selectedProvider:r,onProviderChange:o,isAdult:c,options:m})=>{const a=(m&&m.length>0?m:[]).filter(s=>s.mature===(c===!0));return t("div",{className:Fe.providerSelectContainer,children:[t("h4",{children:"Provider"}),t("select",{className:Fe.providerSelect,value:r,onChange:s=>o(s.currentTarget.value),children:qn.map(s=>{const n=a.filter(i=>(i.tier??"direct")===s);return n.length===0?null:t("optgroup",{label:Kn[s],children:n.map(i=>t("option",{value:i.id,children:i.sub?`${i.label} (${Qn[i.sub]})`:i.label},i.id))},s)})})]})},zn=({videoSources:r,selectedSource:o,selectedLink:c,onSourceChange:m,onLinkChange:T})=>{const a=Array.isArray(r)?r:[];if(a.length===0)return null;const s=o?.type==="iframe"&&(o.links?.length??0)>1;return t("div",{className:Fe.sourceSelectionContainer,children:[t("h4",{children:"Source"}),t("div",{className:Fe.sourceButtons,children:a.map((n,i)=>t("button",{className:`${Fe.sourceButton} ${o?.sourceName===n.sourceName?Fe.active:""} `,onClick:()=>m(n),children:n.sourceName},`${n.sourceName}-${i}`))}),s&&t("select",{className:Fe.sourceSelect,"aria-label":"Fallback embed quality",value:c?.link??o.links[0]?.link??"",onChange:n=>{const i=o.links.find(p=>p.link===n.currentTarget.value);i&&T(i)},children:o.links.map(n=>t("option",{value:n.link,children:n.resolutionStr},n.link))})]})},Hn=ct.memo(zn,(r,o)=>r.selectedSource?.sourceName===o.selectedSource?.sourceName&&r.selectedLink?.link===o.selectedLink?.link&&r.videoSources===o.videoSources),jn={low:{sd:1.5,hd:1.3,fhd:1.25},balanced:{sd:2,hd:1.5,fhd:1.25},high:{sd:2.5,hd:2,fhd:1.5},denoise:{sd:1.5,hd:1.5,fhd:1.5}},Yn={low:"ModeB",balanced:"ModeA",high:"ModeAA",denoise:"ModeC"},Xn=5,Jn=15e3,Zn=`
3
- @group(0) @binding(0) var extTex: texture_external;
4
- @group(0) @binding(1) var extSamp: sampler;
5
- struct VSOut {
6
- @builtin(position) pos: vec4f,
7
- @location(0) uv: vec2f,
8
- };
9
- @vertex
10
- fn vs(@builtin(vertex_index) idx: u32) -> VSOut {
11
- var positions = array<vec2f, 6>(
12
- vec2f(-1.0, -1.0), vec2f(1.0, -1.0), vec2f(-1.0, 1.0),
13
- vec2f(-1.0, 1.0), vec2f(1.0, -1.0), vec2f(1.0, 1.0)
14
- );
15
- var uvs = array<vec2f, 6>(
16
- vec2f(0.0, 1.0), vec2f(1.0, 1.0), vec2f(0.0, 0.0),
17
- vec2f(0.0, 0.0), vec2f(1.0, 1.0), vec2f(1.0, 0.0)
18
- );
19
- var out: VSOut;
20
- out.pos = vec4f(positions[idx], 0.0, 1.0);
21
- out.uv = uvs[idx];
22
- return out;
23
- }
24
- @fragment
25
- fn fs(@location(0) uv: vec2f) -> @location(0) vec4f {
26
- return textureSampleBaseClampToEdge(extTex, extSamp, uv);
27
- }
28
- `;function es({videoRef:r,canvasRef:o,profile:c="balanced",delayMs:m=0}){const[T,a]=ie(!1),[s,n]=ie(()=>{try{return J.getItem("anime4kEnabled")==="true"}catch{return!1}}),[i,p]=ie(!1),[y,f]=ie(null),[E,w]=ie(0),e=R(0),v=R(null),N=R(null),_=R(null),x=R(null),g=R(null),d=R(null),P=R(null),A=R(null),F=R(null),V=R(!1),b=R(-1),h=R(0),O=R(m);O.current=m;const z=R([]),D=R(!1),B=R(!1),H=R(!1),j=R(null),pe=R(-1),$=R(-1),Q=R(!1),ee=R(0);U(()=>{async function k(){if(typeof navigator>"u"||!navigator.gpu){a(!1);return}try{const C=await navigator.gpu.requestAdapter();a(!!C)}catch{a(!1)}}k()},[]),U(()=>{if(!s||!T)return;let k=!1;const C=++e.current,W=X=>{if(X)try{X.close()}catch{}},Y=()=>{for(const X of z.current)W(X.bitmap);z.current=[]},Me=X=>Math.max(8,Math.min(40,Math.ceil(X/16.7)+4));function _e(){F.current!==null&&(cancelAnimationFrame(F.current),F.current=null)}async function ne(){let X=r.current;const Ae=o.current;if(!X||!Ae||e.current!==C)return;const De=performance.now()+Jn;for(;(!X||X.videoWidth===0)&&performance.now()<De;){if(await new Promise(de=>requestAnimationFrame(de)),k||e.current!==C)return;X=r.current}if(!X||X.videoWidth===0){!k&&e.current===C&&(f("Timed out waiting for video metadata"),p(!1),n(!1));return}const se=X.videoWidth,K=X.videoHeight,fe=Math.max(se,K),le=window.innerWidth,xe=window.innerHeight,He=Math.max(le,xe),je=fe<He?He/fe:1,Oe=jn[c],mt=fe<=480?Oe.sd:fe<=720?Oe.hd:fe<=1080?Oe.fhd:1,Re=Math.min(mt,je);Ae.width=Math.round(se*Re),Ae.height=Math.round(K*Re),p(!0),f(null),h.current=0,b.current=-1,pe.current=-1,$.current=-1,Q.current=!1,ee.current=0,Y(),V.current=!1;try{let de=function(){k||e.current!==C||(_e(),F.current=requestAnimationFrame(()=>{gt()}))};const{ModeA:tt,ModeB:pt,ModeC:ft,ModeAA:ye}=await Bt(async()=>{const{ModeA:G,ModeB:te,ModeC:Se,ModeAA:ce}=await import("./index-BOKlZEHq.js").then(ue=>ue.i);return{ModeA:G,ModeB:te,ModeC:Se,ModeAA:ce}},[]);if(k||e.current!==C)return;if(!navigator.gpu)throw new Error("WebGPU not available");const Ye=await navigator.gpu.requestAdapter();if(k||e.current!==C)return;if(!Ye)throw new Error("No GPU adapter found");const I=await Ye.requestDevice();if(!I)throw new Error("Failed to get GPU device");if(k||e.current!==C){I.destroy();return}v.current=I;const he=Ae.getContext("webgpu");if(!he)throw new Error("Failed to get WebGPU context");N.current=he;const Xe=navigator.gpu.getPreferredCanvasFormat();he.configure({device:I,format:Xe,alphaMode:"premultiplied"});const ve=I.createTexture({size:[se,K],format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT}),ht=Yn[c],We=Math.round(se*Re),$e=Math.round(K*Re),Ue=(()=>{switch(ht){case"ModeB":return new pt({device:I,inputTexture:ve,nativeDimensions:{width:se,height:K},targetDimensions:{width:We,height:$e}});case"ModeC":return new ft({device:I,inputTexture:ve,nativeDimensions:{width:se,height:K},targetDimensions:{width:We,height:$e}});case"ModeAA":return new ye({device:I,inputTexture:ve,nativeDimensions:{width:se,height:K},targetDimensions:{width:We,height:$e}});default:return new tt({device:I,inputTexture:ve,nativeDimensions:{width:se,height:K},targetDimensions:{width:We,height:$e}})}})(),rt=Ue.getOutputTexture(),Ve=I.createSampler({magFilter:"linear",minFilter:"linear"}),nt=I.createShaderModule({code:`
29
- @group(0) @binding(0) var tex: texture_2d<f32>;
30
- @group(0) @binding(1) var samp: sampler;
31
- struct VertexOutput {
32
- @builtin(position) pos: vec4f,
33
- @location(0) uv: vec2f,
34
- }
35
- @vertex
36
- fn vs(@builtin(vertex_index) idx: u32) -> VertexOutput {
37
- var positions = array<vec2f, 6>(
38
- vec2f(-1.0, -1.0), vec2f(1.0, -1.0), vec2f(-1.0, 1.0),
39
- vec2f(-1.0, 1.0), vec2f(1.0, -1.0), vec2f(1.0, 1.0)
40
- );
41
- var uvs = array<vec2f, 6>(
42
- vec2f(0.0, 1.0), vec2f(1.0, 1.0), vec2f(0.0, 0.0),
43
- vec2f(0.0, 0.0), vec2f(1.0, 1.0), vec2f(1.0, 0.0)
44
- );
45
- var out: VertexOutput;
46
- out.pos = vec4f(positions[idx], 0.0, 1.0);
47
- out.uv = uvs[idx];
48
- return out;
49
- }
50
- @fragment
51
- fn fs(@location(0) uv: vec2f) -> @location(0) vec4f {
52
- return textureSample(tex, samp, uv);
53
- }
54
- `}),Qe=I.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),st=I.createRenderPipeline({layout:I.createPipelineLayout({bindGroupLayouts:[Qe]}),vertex:{module:nt,entryPoint:"vs"},fragment:{module:nt,entryPoint:"fs",targets:[{format:Xe}]},primitive:{topology:"triangle-list"}}),Ke=I.createBindGroup({layout:Qe,entries:[{binding:0,resource:rt.createView()},{binding:1,resource:Ve}]});try{const G=I.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,externalTexture:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),te=I.createShaderModule({code:Zn}),Se=I.createRenderPipeline({layout:I.createPipelineLayout({bindGroupLayouts:[G]}),vertex:{module:te,entryPoint:"vs"},fragment:{module:te,entryPoint:"fs",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list"}});j.current={pipeline:Se,layout:G,inputView:ve.createView()}}catch{j.current=null}_.current=Ue,x.current=ve,g.current=rt,d.current=st,P.current=Ve,A.current=Qe,B.current=!1,H.current=!1;async function vt(){const G=j.current;if(!G||B.current)return!1;const te=r.current;if(!te)return!1;const Se=!H.current;Se&&I.pushErrorScope("validation");try{const ce=I.importExternalTexture({source:te}),ue=I.createBindGroup({layout:G.layout,entries:[{binding:0,resource:ce},{binding:1,resource:Ve}]}),re=I.createCommandEncoder(),ke=re.beginRenderPass({colorAttachments:[{view:G.inputView,loadOp:"load",storeOp:"store"}]});ke.setPipeline(G.pipeline),ke.setBindGroup(0,ue),ke.draw(6),ke.end(),I.queue.submit([re.finish()])}catch{return B.current=!0,j.current=null,!1}if(Se){const ce=await I.popErrorScope().catch(()=>null);if(ce)return console.warn("[anime4k] blit probe failed:",ce.message),B.current=!0,j.current=null,!1;H.current=!0}return!0}p(!1);async function gt(){if(k||e.current!==C||!he)return;const G=r.current;if(!G||G.videoWidth===0){de();return}if(G!==X||G.videoWidth!==se||G.videoHeight!==K){w(ue=>ue+1);return}if(G.paused||G.ended||document.hidden||G.readyState<HTMLMediaElement.HAVE_CURRENT_DATA){de();return}const te=G.getVideoPlaybackQuality().totalVideoFrames;if(te===$.current){de();return}if(V.current){de();return}const Se=G.currentTime;(G.seeking||pe.current>=0&&Math.abs(Se-pe.current)>.5)&&(Y(),Q.current=!1,ee.current=0,$.current=-1),pe.current=Se;const ce=Math.max(0,O.current||0);ce>ee.current&&(Q.current=!1),V.current=!0;try{const ue=performance.now();let re=null,ke=!1;if(ce<=0){z.current.length>0&&Y(),Q.current=!1,ee.current=0;let Ee=!1;if(!D.current)try{I.queue.copyExternalImageToTexture({source:G},{texture:ve},[se,K]),$.current=te,Ee=!0}catch(oe){if(oe instanceof TypeError)D.current=!0;else throw oe}if(!Ee&&!B.current&&j.current&&await vt()&&($.current=te,Ee=!0),!Ee){const oe=await createImageBitmap(G);$.current=te,I.queue.copyExternalImageToTexture({source:oe},{texture:ve},[se,K]),W(oe)}}else{const Ee=await createImageBitmap(G);$.current=te;const oe=z.current;oe.push({bitmap:Ee,capture:ue});const bt=Me(ce);for(;oe.length>bt;)W(oe.shift()?.bitmap);let Je=-1;for(let ge=oe.length-1;ge>=0;ge--)if(ue-oe[ge].capture>=ce){Je=ge;break}if(Je!==-1){for(let ot=0;ot<Je;ot++)W(oe.shift()?.bitmap);const ge=oe.shift();ge?(re=ge.bitmap,Q.current=!0,ee.current=ce):(re=Ee,ke=!0)}else if(!Q.current)re=Ee,ke=!0;else{const ge=oe.shift();re=ge?ge.bitmap:Ee,ge||(ke=!0)}if(!re){V.current=!1,de();return}I.queue.copyExternalImageToTexture({source:re},{texture:ve},[se,K]),ke||W(re)}const qe=I.createCommandEncoder();await Ue.pass(qe);const Ge=qe.beginRenderPass({colorAttachments:[{view:he.getCurrentTexture().createView(),clearValue:{r:0,g:0,b:0,a:1},loadOp:"clear",storeOp:"store"}]});Ge.setPipeline(st),Ge.setBindGroup(0,Ke),Ge.draw(6),Ge.end(),I.queue.submit([qe.finish()]),b.current=te,h.current=0,I.queue.onSubmittedWorkDone().then(()=>{e.current===C&&(V.current=!1)})}catch(ue){if(V.current=!1,h.current+=1,h.current>=Xn&&!k&&e.current===C){console.error(ue),f(ue instanceof Error?ue.message:"Render error"),n(!1);return}}de()}de()}catch(de){!k&&e.current===C&&(N.current?.unconfigure(),v.current?.destroy(),v.current=null,N.current=null,f(de instanceof Error?de.message:"Failed to initialize upscaler"),p(!1),n(!1))}}return ne(),()=>{k=!0,e.current+=1,_e(),Y(),N.current?.unconfigure(),x.current&&(x.current.destroy(),x.current=null),g.current&&(g.current.destroy(),g.current=null),v.current&&(v.current.destroy(),v.current=null),_.current=null,d.current=null,P.current=null,A.current=null,j.current=null,N.current=null,V.current=!1}},[s,T,r,o,c,E]);const l=q(k=>{n(k);try{J.setItem("anime4kEnabled",String(k))}catch{}},[]),M=q(()=>{n(k=>{const C=!k;try{J.setItem("anime4kEnabled",String(C))}catch{}return C})},[]);return{isWebGPUSupported:T,isEnabled:s,isInitializing:i,error:y,toggle:M,setEnabled:l}}function ts({videoRef:r,episodeKey:o,isEnabled:c,isSupported:m,mediaReady:T,isIframeSource:a,setEnabled:s}){const n=R(null),i=R(!1),p=R(!1),y=R(s);y.current=s,U(()=>{const f=n.current;n.current=o,!(f===null||f===o)&&(!c||!m||(i.current=!0,p.current=!1,y.current(!1)))},[o,c,m]),U(()=>{if(!i.current)return;if(c){p.current&&(i.current=!1);return}if(p.current=!0,!T)return;if(a){i.current=!1,y.current(!0);return}const f=r.current;if(!f)return;let E,w=!1;const e=()=>{w||(w=!0,i.current=!1,y.current(!0))};if(f.readyState>=2)return E=window.setTimeout(e,500),()=>window.clearTimeout(E);const v=()=>{window.setTimeout(e,500)};return f.addEventListener("canplay",v,{once:!0}),f.addEventListener("playing",v,{once:!0}),E=window.setTimeout(e,5e3),()=>{window.clearTimeout(E),f.removeEventListener("canplay",v),f.removeEventListener("playing",v)}},[c,T,a,r])}const rs=()=>J.getItem("preferredMode")==="dub"?"dub":"sub",ns=/^[a-z0-9-]+$/i,Ft=r=>r?"preferredProviderMature":"preferredProvider",Ot=r=>{const o=J.getItem(Ft(r));return o&&ns.test(o)?o:null},Wt=(r,o)=>{J.setItem(Ft(o),r)},ss=()=>Ot(!1)??"megaplay",os=()=>({showMeta:{},episodes:[],watchedEpisodes:[],watchlistStatus:null,showCombinedDetails:!1,currentMode:rs(),inWatchlist:!1,videoSources:[],selectedSource:null,selectedLink:null,isAutoplayEnabled:Yr(),showResumeModal:!0,resumeProgressPending:!0,resumeTime:0,resumeDuration:0,skipIntervals:[],selectedProvider:ss(),loadingShowData:!0,loadingVideo:!1,error:null,showCookieModal:!1,cookieProvider:null});function as(r,o){switch(o.type){case"SET_STATE":return{...r,...o.payload};case"SET_MODE":return{...r,currentMode:o.payload,videoSources:[],selectedSource:null,selectedLink:null};case"SET_PROVIDER":return{...r,selectedProvider:o.payload};default:return r}}async function Lt(r,o,c,m,T=!1){if(!r||!o)throw new Error("Missing params");try{const[a,s,n,i]=await Promise.all([me.data.video.query({showId:r,episodeNumber:o,mode:c.currentMode,provider:c.selectedProvider}).catch(g=>{const d=g.data?.cause;return g.message==="AUTH_REQUIRED"&&d?.provider==="mkissa"&&m({type:"SET_STATE",payload:{showCookieModal:!0,cookieProvider:"mkissa"}}),null}),me.progress.getEpisode.query({showId:r,episodeNumber:o}).catch(()=>null),me.settings.getByKey.query({key:"preferredSource"}).catch(()=>null),me.data.skipTimes.query({showId:r,episodeNumber:o}).catch(()=>[])]),p=n?.value,y=a?.filter(g=>{const d=g.sourceName.toLowerCase();return c.currentMode==="dub"?d.includes("eng")||d.includes("dub"):d.includes("jpn")||d.includes("sub")||!d.includes("eng")&&!d.includes("dub")})??[],f=y.length>0?y:a??[];let E=f.length>0?f[0]:null;if(p){const g=f.find(d=>d.sourceName===p);g&&(E=g)}const w=E&&E.links.length>0?E.links.sort((g,d)=>(parseInt(d.resolutionStr)||0)-(parseInt(g.resolutionStr)||0))[0]:null,e=s?.currentTime||0,v=s?.duration||0,N=e,x=(Array.isArray(i)?i:i?.results||[]).map(g=>({skip_id:g.skip_id||"",skip_type:g.skip_type||"",start_time:g.interval?.start_time??g.start_time??0,end_time:g.interval?.end_time??g.end_time??0})).filter(g=>g.end_time>0);return(!a||a.length===0)&&(T||Pe.error(`No video sources found for ${c.selectedProvider}`)),{videoSources:a,selectedSource:E,selectedLink:w,resumeTime:N,resumeDuration:v,showResumeModal:N>5&&!dt(N,v)&&E?.type!=="iframe",skipIntervals:x,fetchedEpisodeNumber:o}}catch(a){const s=a;if(s.message==="AUTH_REQUIRED")return m({type:"SET_STATE",payload:{showCookieModal:!0,cookieProvider:s.provider}}),{videoSources:[],selectedSource:null,selectedLink:null,resumeTime:0,resumeDuration:0,showResumeModal:!1,skipIntervals:[],fetchedEpisodeNumber:o};throw a}}const is=(r,o,c,m)=>{const[T,a]=rr(as,c,l=>({...os(),showMeta:l?.name?{name:l.name,thumbnail:l.thumbnail,nativeName:l.nativeName,englishName:l.englishName,names:{romaji:l.name||l.englishName,english:l.englishName||l.name,native:l.nativeName}}:{}})),s=m?.watchSelection,n=Ce(()=>s?{...T,selectedProvider:s.provider,currentMode:s.mode}:T,[T,s]),i=Dt(),p=ir(),y=R(null),f=R(null),{options:E}=It(),w=Ce(()=>E.filter(l=>(l.kind??"anime")==="anime"),[E]),e=o||n.initialEpisode,v=`${r}:${e}`,N=R(v);U(()=>{N.current!==v&&(N.current=v,a({type:"SET_STATE",payload:{selectedSource:null,selectedLink:null}}))},[v,a]),U(()=>{!s&&r&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(r)&&n.selectedProvider!=="animepahe"&&y.current!==r&&(y.current=r,a({type:"SET_PROVIDER",payload:"animepahe"}))},[r,n.selectedProvider,s]);const{data:_,isLoading:x,error:g}=tn(r),{data:d}=At({queryKey:[ae.playerData,r,n.currentMode,n.selectedProvider],queryFn:async()=>{if(!r)throw new Error("No showId");const l=async()=>{try{const Y=await me.data.episodes.query({showId:r,mode:n.currentMode,provider:n.selectedProvider}).catch(()=>null);if(Y?.episodes?.length)return Y}catch{}return null},[M,k,C]=await Promise.all([l(),me.watchlist.check.query({showId:r}).catch(()=>({inWatchlist:!1,status:null})),me.progress.getWatchedEpisodes.query({showId:r}).catch(()=>[])]),W=M?.episodes?M.episodes.sort((Y,Me)=>parseFloat(Y)-parseFloat(Me)):[];return{description:M?.description||"",episodes:W,inWatchlist:k.inWatchlist,watchlistStatus:k.status??null,watchedEpisodes:C}},enabled:!!r});U(()=>{!o&&d?.episodes&&d.episodes.length>0&&!o&&a({type:"SET_STATE",payload:{initialEpisode:d.episodes[0]}})},[d,o]),U(()=>{if(s||_?.isAdult===void 0||f.current===r)return;const l=_.isAdult===!0,M=w.filter(C=>C.mature===l);if(M.length===0||w.find(C=>C.id===n.selectedProvider)?.mature===l)return;const k=Ot(l);f.current=r??null,a({type:"SET_PROVIDER",payload:M.find(C=>C.id===k)?.id??M[0].id})},[_?.isAdult,n.selectedProvider,r,w,s]),U(()=>{if(s||!r||!/^dango-mt-\d+$/.test(r)||f.current===`temp:${r}`)return;const l=_?.provider;l&&(f.current=`temp:${r}`,l!==n.selectedProvider&&a({type:"SET_PROVIDER",payload:l}))},[r,_,n.selectedProvider,s]);const{data:P,isLoading:A,isFetching:F,error:V}=At({queryKey:[ae.videoSources,r,e,n.selectedProvider,n.currentMode],queryFn:()=>Lt(r,e,n,a),enabled:!!r&&!!e&&!(n.showMeta?.isAdult===!0&&!m?.hasMatureConsent)}),{mutateAsync:b}=kt({mutationFn:async({wasIn:l,showMeta:M})=>{if(!r)throw new Error("Missing showId");if(l)await me.watchlist.remove.mutate({id:r});else{const k=M.name||M.names?.romaji;if(!k)throw new Error("Missing show name");await me.watchlist.add.mutate({id:r,name:k,thumbnail:M.thumbnail,nativeName:M.names?.native,englishName:M.names?.english,type:M.type,isAdult:M.isAdult})}return!l},onSuccess:l=>{Pe.success(l?"Added to watchlist":"Removed from watchlist"),i.invalidateQueries({queryKey:[ae.playerData,r]}),i.invalidateQueries({queryKey:[ae.showData,r]}),i.invalidateQueries({queryKey:[ae.watchlist]})},onError:l=>Pe.error(l instanceof Error?l.message:"Failed to update watchlist")}),h=q(async()=>{!r||!_||await b({wasIn:!!d?.inWatchlist,showMeta:_})},[r,_,d?.inWatchlist,b]),O=q(async l=>{try{await me.settings.set.mutate({key:"preferredSource",value:l})}catch(M){console.error(M)}},[]),{mutateAsync:z,isPending:D}=kt({mutationFn:async({status:l})=>{if(!r)throw new Error("Missing showId");if(d?.inWatchlist)return await me.watchlist.setStatus.mutate({id:r,status:l}),l;const M=_,k=M?.name||M?.names?.romaji;if(!M||!k)throw new Error("Missing show name");return await me.watchlist.add.mutate({id:r,name:k,thumbnail:M.thumbnail,nativeName:M.names?.native,englishName:M.names?.english,type:M.type,isAdult:M.isAdult,status:l}),l},onSuccess:l=>{a({type:"SET_STATE",payload:{inWatchlist:!0,watchlistStatus:l}}),Pe.success(`Moved to ${l}`),i.invalidateQueries({queryKey:[ae.showData,r]}),i.invalidateQueries({queryKey:[ae.watchlist]}),i.invalidateQueries({queryKey:[ae.continueWatching]})},onError:()=>Pe.error("Failed to update watchlist status")}),B=q(async()=>{await z({status:"Completed"})},[z]),{mutateAsync:H,isPending:j}=kt({mutationFn:async({episodeNumber:l,duration:M,showMeta:k,episodes:C})=>{await me.progress.updateProgress.mutate({showId:r??"",episodeNumber:l,currentTime:M,duration:M,showName:k.name,showThumbnail:k.thumbnail,nativeName:k.names?.native,englishName:k.names?.english,genres:k.genres?.map(W=>W.name),popularityScore:lr(k.score)??void 0,type:k.type,status:k.status,episodeCount:C.length,isAdult:k.isAdult})},onSuccess:(l,M)=>{Pe.success(`Episode ${M.episodeNumber} marked as watched`),i.invalidateQueries({queryKey:[ae.playerData,r]}),i.invalidateQueries({queryKey:[ae.showMeta,r]}),i.invalidateQueries({queryKey:[ae.videoSources,r,M.episodeNumber]}),i.invalidateQueries({queryKey:[ae.continueWatching]}),i.invalidateQueries({queryKey:[ae.thisWeekSchedule]}),i.invalidateQueries(p.continueWatching.pathFilter())},onError:()=>Pe.error("Failed to mark episode as watched")}),pe=q(async(l,M)=>{!r||!_||await H({episodeNumber:l,duration:M,showMeta:_,episodes:d?.episodes||[]})},[r,_,d?.episodes,H]),$=q(async()=>{a({type:"SET_STATE",payload:{showCombinedDetails:!n.showCombinedDetails}})},[n.showCombinedDetails]),Q=Ce(()=>{const l=g||V,M=l?l.message:null,k=M==="AUTH_REQUIRED"?null:M,C=P&&P.fetchedEpisodeNumber===e?P:null,W=!!P&&!C,Y=s?C?.videoSources?.find(ne=>ne.sourceName===s.source&&ne.type!=="iframe"&&ne.links.some(X=>X.hls))??null:null,_e=(n.selectedSource?.sourceName===Y?.sourceName?Y?.links.find(ne=>ne.hls&&ne.link===n.selectedLink?.link):null)??Y?.links.filter(ne=>ne.hls).slice().sort((ne,X)=>(parseInt(X.resolutionStr)||0)-(parseInt(ne.resolutionStr)||0))[0]??null;return{...n,currentEpisode:e,showMeta:{...n.showMeta||{},..._||{}},episodes:d?.episodes||[],watchedEpisodes:d?.watchedEpisodes||[],inWatchlist:!!d?.inWatchlist,watchlistStatus:d?.watchlistStatus??n.watchlistStatus??null,videoSources:C?.videoSources||[],selectedSource:s?Y:n.selectedSource||C?.selectedSource||null,selectedLink:s?_e:n.selectedLink||C?.selectedLink||null,resumeTime:s?0:C?.resumeTime||0,resumeDuration:C?.resumeDuration||0,resumeProgressPending:F,showResumeModal:!s&&n.showResumeModal&&(C?.showResumeModal??!1),skipIntervals:C?.skipIntervals||[],loadingShowData:x,loadingVideo:A||W,error:k,fetchedEpisodeNumber:C?.fetchedEpisodeNumber}},[n,_,d,P,x,A,F,g,V,e,s]),ee=q((l,M)=>{const k=M||r;if(!k||!l||k===r&&l===e)return;const W=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(k)&&n.selectedProvider!=="animepahe"?"animepahe":n.selectedProvider,Y=["video-sources",k,l,W,n.currentMode];i.getQueryState(Y)?.status!=="success"&&i.prefetchQuery({queryKey:Y,queryFn:()=>Lt(k,l,{selectedProvider:W,currentMode:n.currentMode},a,!0),staleTime:300*1e3,gcTime:1800*1e3})},[r,e,i,n,a]);return{state:Q,dispatch:a,toggleWatchlist:h,moveToCompleted:B,setPreferredSource:O,handleToggleDetails:$,markEpisodeWatched:pe,prefetchEpisodeSources:ee,isMarkingWatched:j,isUpdatingWatchlistStatus:D}};function ls({onPrevious:r,onNext:o,onToggleTheater:c,flashControls:m}){U(()=>{const T=a=>{a.defaultPrevented||a.ctrlKey||a.metaKey||a.altKey||a.repeat||a.target.closest('input, textarea, button, select, a, [role="button"], [role="slider"], [contenteditable="true"]')||(["arrowup","arrowdown","arrowleft","arrowright"].includes(a.key.toLowerCase())&&m(),a.key.toLowerCase()==="n"&&o(),a.key.toLowerCase()==="p"&&r(),a.key.toLowerCase()==="t"&&c())};return document.addEventListener("keydown",T),()=>{document.removeEventListener("keydown",T)}},[m,o,r,c])}const et=(r,o,c)=>r.showId===o||!!c&&r.showId===c;function cs({testClipActive:r,selectedSourceType:o,onEnded:c,queue:m,removeFromQueue:T,showId:a,showMetaId:s,currentEpisode:n,isAutoplayEnabled:i,nextEpisode:p,previousEpisode:y,navigate:f,invalidateContinueWatching:E,dispatch:w}){const[e,v]=ie(!1),[N,_]=ie(null),[x,g]=ie(null),d=R(T);d.current=T;const P=R(!1);U(()=>{P.current=!1,v(!1)},[a,n]);const A=q(()=>{if(r||P.current)return;P.current=!0,c();const D=m.find(B=>et(B,a,s)&&B.episodeNumber===n);if(m.length>0){const B=m.findIndex(j=>et(j,a,s)&&j.episodeNumber===n),H=B>=0?m[B+1]||null:m[0];g({nextItem:H,playedItem:D||null}),_(2);return}if(D&&d.current({showId:D.showId,episodeNumber:D.episodeNumber}),i&&p){E(),f(`/watch/${a}/${p}`);return}p||v(!0)},[c,f,m,a,s,n,p,i,E,r]),F=q(()=>{if(m.length===0)return;c();const D=m.find(j=>et(j,a,s)&&j.episodeNumber===n),B=m.findIndex(j=>et(j,a,s)&&j.episodeNumber===n),H=B>=0?m[B+1]||null:m[0];D&&T({showId:D.showId,episodeNumber:D.episodeNumber}),H?f(`/watch/${H.showId}/${H.episodeNumber}`):p||v(!0)},[c,f,m,T,a,s,n,p]),V=q(()=>{p&&(E(),f(`/watch/${a}/${p}`)),v(!1),w({type:"SET_STATE",payload:{showResumeModal:!1}})},[p,f,a,w,E]),b=q(()=>{m.length>0?F():p?V():Pe.error("No next episode available")},[m.length,F,V,p]),h=q(()=>v(!1),[]),O=q(()=>{g(null),_(null)},[]),z=q(()=>{y&&f(`/watch/${a}/${y}`)},[y,f,a]);return U(()=>{const D=B=>{B.origin===window.location.origin&&o==="iframe"&&B.data?.type==="ANI_WEB_MEDIA_ENDED"&&A()};return window.addEventListener("message",D),()=>window.removeEventListener("message",D)},[A,o]),U(()=>{if(!x||N===null)return;if(N<=0){const{nextItem:B,playedItem:H}=x;g(null),_(null),H&&d.current({showId:H.showId,episodeNumber:H.episodeNumber}),B?f(`/watch/${B.showId}/${B.episodeNumber}`):p||v(!0);return}const D=window.setTimeout(()=>{_(B=>B===null?null:B-1)},1e3);return()=>window.clearTimeout(D)},[x,N,f,p]),{showCompleteModal:e,queueCountdown:N,pendingQueueTransition:x,handleQueueTransition:F,handleNextEpisode:V,handleNShortcut:b,handlePreviousEpisode:z,handlePlaybackFinished:A,closeCompleteModal:h,cancelQueueTransition:O}}function us({videoRef:r,queue:o,showId:c,showMetaId:m,currentEpisode:T,selectedSource:a,hasNextEpisode:s,nextEpisode:n,prefetchEpisodeSources:i,matchesQueueItem:p}){const[y,f]=ie(!1),E=R(i);E.current=i;const w=R("");U(()=>{f(!1)},[T]);const e=q(()=>{const v=r.current;if(!v||a?.type==="iframe")return;const N=v.duration,_=v.currentTime;if(!N||Number.isNaN(N)){f(!1);return}if(N-_<=60){const x=o.findIndex(P=>p(P,c,m)&&P.episodeNumber===T),g=o.length>0?x>=0?o[x+1]||null:o[0]:null,d=g?`${g.showId}:${g.episodeNumber}`:s?`${c}:${n}`:"";d&&w.current!==d&&(w.current=d,g?E.current(g.episodeNumber,g.showId):E.current(n??""))}f(s&&dt(_,N))},[r,a,o,c,m,T,s,n,p]);return{showNextEpisodePrompt:y,handleThresholds:e}}const Et="fallbackChoice";function ds(){try{const r=J.getItem(Et);return r==="iframe"||r==="retry"?r:null}catch{return null}}function ms(r){try{r===null?J.removeItem(Et):J.setItem(Et,r)}catch{}}function ps({showId:r,episodeNumber:o,currentMode:c,selectedProvider:m,selectedSourceType:T,videoSources:a,isAdult:s,providerOrder:n,matureProviders:i,setPreferredSource:p,dispatch:y,showControls:f}){const E=R(!1),w=R([]),e=R(!1),[v,N]=ie(null),[_,x]=ie(!1),[g,d]=ie(!1),[P,A]=ie(()=>ds()??"ask"),F=q($=>{A($),ms($==="ask"?null:$)},[]),V=R(P);U(()=>{V.current=P},[P]);const b=R(a);b.current=a;const h=q(()=>{E.current=!1,w.current=[],e.current=!1,N(null),x(!1)},[]);U(()=>{h()},[h,r,o]);const O=q($=>{if(E.current)return;E.current=!0;const Q=$.links[0];p($.sourceName),y({type:"SET_STATE",payload:{selectedSource:$,selectedLink:Q}}),N(null)},[y,p]),z=q(()=>{const Q=b.current.find(ee=>ee.type==="iframe");return Q?.links?.length?Q:null},[]),D=q(async()=>{const $=n.filter(Q=>{if(w.current.includes(Q))return!1;const ee=i.has(Q);return s===void 0?!0:ee===s});x(!0);try{for(const Q of $){w.current.push(Q);let ee=null;try{ee=await me.data.video.query({showId:r,episodeNumber:o,mode:c,provider:Q})}catch{continue}const l=(ee??[]).filter(C=>{const W=C.sourceName.toLowerCase();return c==="dub"?W.includes("eng")||W.includes("dub"):W.includes("jpn")||W.includes("sub")||!W.includes("eng")&&!W.includes("dub")});if((l.length>0?l:ee??[]).find(C=>C.type!=="iframe"&&C.links?.length)){w.current=[m],e.current=!1,y({type:"SET_STATE",payload:{selectedProvider:Q,videoSources:[],selectedSource:null,selectedLink:null,loadingVideo:!0}}),Wt(Q,s===!0),N(null),Pe.success(`Switched to ${Q} (direct stream)`);return}}N({retryFailed:!0}),Pe.error("No working direct stream found on other providers")}finally{x(!1)}},[r,o,c,s,m,y,n,i]),B=q(()=>{if(E.current||e.current||T!=="player")return;const $=z();if(!$)return;w.current.includes(m)||w.current.push(m);const Q=V.current;if(Q==="iframe"){O($);return}if(Q==="retry"){D();return}f(!0),N({retryFailed:!1})},[T,m,z,O,D,f]),H=q(()=>{e.current=!0,N(null),d(!1)},[]),j=q(()=>{g&&F("iframe");const $=z();$?O($):N(null)},[g,F,z,O]),pe=q(()=>{g&&F("retry"),D()},[g,F,D]);return{fallbackPrompt:v,isRetryingProvider:_,rememberFallbackChoice:g,setRememberFallbackChoice:d,fallbackChoice:P,updateFallbackChoice:F,dismissFallbackPrompt:H,chooseIframeFallback:j,chooseProviderRetry:pe,handleVideoSourceError:B,resetFallback:h}}function fs({engine:r,videoRef:o,selectedSource:c,selectedLink:m,loadingVideo:T,testClipActive:a,resumeTime:s,resumeDuration:n=0,showResumeModal:i,calibReturnRef:p,setAvailableSubtitles:y,setActiveSubtitleTrack:f,onFatalError:E}){const w=R(null),e=R(s),v=R(n),N=R(i),_=R(E);return _.current=E,U(()=>{e.current=s,v.current=n,N.current=i},[s,n,i]),U(()=>{const x=o.current;if(!x)return;for(;x.firstChild;)x.removeChild(x.firstChild);if(a)return r.loadSource({url:"/av-sync-test.mp4"},{autoPlay:!0});if(T||!c||!m||c.type==="iframe"){r.unload();return}p.current!=null?(w.current=p.current,p.current=null):w.current===null&&e.current>5&&!N.current&&!dt(e.current,v.current)?w.current=e.current:w.current===null&&N.current&&(w.current=0);let g=m.link;if(g.startsWith("/api/proxy")||(g=`/api/proxy?url=${encodeURIComponent(g)}`,m.headers?.Referer&&(g+=`&referer=${encodeURIComponent(m.headers.Referer)}`)),c.subtitles){const A=J.getItem("playerSubtitlesEnabled")!=="false";let F=null;try{F=J.getItem("playerLastSubtitle")}catch{}const V=wt(c.subtitles,{lastKey:F,enabled:A}),b=V>=0?c.subtitles[V]:null;c.subtitles.forEach(h=>{const O=document.createElement("track");O.kind="subtitles",O.label=h.label,O.srclang=h.lang;const z=h.src??h.url;if(z){let D=`/api/subtitle-proxy?url=${encodeURIComponent(z)}`;const B=m.headers?.Referer;B&&(D+=`&referer=${encodeURIComponent(B)}`),O.src=D}b&&h.label===b.label&&h.lang===b.lang&&(O.default=!0),x.appendChild(O)}),A||f("off"),y(c.subtitles)}const d=w.current??0;w.current=null;const P=document.body.classList.contains("low-end");return r.loadSource({url:g,hls:m.hls},{initialTime:d,autoPlay:!(N.current&&e.current>5)&&!dt(e.current,v.current),hlsConfig:{maxBufferLength:P?15:30,maxMaxBufferLength:P?30:60,maxBufferSize:(P?25:60)*1e3*1e3,startLevel:-1},onHls:(A,F)=>{if(!c.subtitles?.length)return;const V=()=>{A.subtitleTrack!==-1&&(A.subtitleTrack=-1)};A.on(F.Events.SUBTITLE_TRACK_SWITCH,V),V()},onError:()=>_.current()})},[r,c,m,o,p,T,a,f,y]),{seekToTimeRef:w}}function hs({videoRef:r,availableSubtitles:o,activeSubtitleTrack:c,setAvailableSubtitles:m,setActiveSubtitleTrack:T}){U(()=>{const a=r.current;if(!a)return;const s=()=>{const n=Array.from(a.textTracks).map(i=>({label:i.label,lang:i.language,src:void 0,mode:i.mode}));m(n)};return a.textTracks.addEventListener("addtrack",s),a.textTracks.addEventListener("removetrack",s),s(),()=>{a.textTracks.removeEventListener("addtrack",s),a.textTracks.removeEventListener("removetrack",s)}},[r,m]),U(()=>{if(c===null&&o.length>0&&J.getItem("playerSubtitlesEnabled")!=="false"){let a=null;try{a=J.getItem("playerLastSubtitle")}catch{}const s=wt(o,{lastKey:a,enabled:!0});if(s<0){T("off");return}const n=o[s];T(n.lang||n.label)}},[c,o,T]),U(()=>{const a=r.current;if(!a||o.length===0)return;const s=c;if(!(J.getItem("playerSubtitlesEnabled")!=="false")||s==="off"||s===null){Array.from(a.textTracks).forEach(p=>{p.mode="hidden"});return}let i=!1;if(Array.from(a.textTracks).forEach(p=>{const f=(p.language===s||p.label===s)&&!i;p.mode=f?"showing":"hidden",f&&(i=!0)}),!i&&a.textTracks.length>0){const p=Array.from(a.textTracks).find(y=>y.language==="en"||y.label==="English")||a.textTracks[0];p&&(p.mode="showing")}},[c,o,r])}function vs({videoRef:r,videoBoxH:o,style:c,sourceKey:m,activeSubtitleTrack:T,availableSubtitles:a}){U(()=>{const s="dynamic-subtitle-styles";let n=document.getElementById(s);n||(n=document.createElement("style"),n.id=s,document.head.appendChild(n)),n.textContent=xt(c);const i=r.current;if(!i)return;const p=$t(c.fontSize,o||i.clientHeight||720);n.textContent=xt({...c,fontSize:p});const y=()=>{const d=Number(c.position),P=isNaN(d)?0:Math.max(0,Math.min(100,d));return Math.max(0,Math.min(100,100-P))},f=(d,P)=>{try{const A=d;A.snapToLines=!1,A.line=P}catch{}},E=()=>{const d=p*16,P=i.videoHeight||i.clientHeight||720,A=i.videoWidth||i.clientWidth||1280;return{step:d*1.3/P*100,chars:Math.max(20,Math.floor(A/(d*.55)))}},w=d=>{const P=y(),A=Array.from(d.activeCues??[]);if(A.length<=1){A.forEach(h=>f(h,P));return}const{step:F,chars:V}=E();let b=P;for(let h=A.length-1;h>=0;h--){const z=String(A[h].text??"").replace(/<[^>]*>/g,"").split(`
55
- `).reduce((B,H)=>B+Math.max(1,Math.ceil(H.length/V)),0),D=b-z*F;f(A[h],Math.max(0,D)),b=D-F*.4}},e=d=>{if(!d.cues)return;const P=y();Array.from(d.cues).forEach(A=>f(A,P)),d.mode==="showing"&&w(d)},v=()=>{Array.from(i.textTracks).forEach(e)};v();const N=d=>{const P=d.target;P.mode==="showing"&&w(P)};Array.from(i.textTracks).forEach(d=>{d.addEventListener("cuechange",N)});const _=()=>{Array.from(i.textTracks).forEach(d=>{d.removeEventListener("cuechange",N),d.addEventListener("cuechange",N)}),v()};i.textTracks.addEventListener("addtrack",_),i.textTracks.addEventListener("removetrack",_);const x=Array.from(i.querySelectorAll("track")),g=()=>{v()};return x.forEach(d=>{d.addEventListener("load",g)}),()=>{Array.from(i.textTracks).forEach(d=>{d.removeEventListener("cuechange",N)}),i.textTracks.removeEventListener("addtrack",_),i.textTracks.removeEventListener("removetrack",_),x.forEach(d=>{d.removeEventListener("load",g)})}},[c,o,r,m,T,a])}function gs({videoRef:r,overlayRef:o,style:c,activeSubtitleTrack:m,delayMs:T,enabled:a}){U(()=>{if(!a)return;const s=r.current,n=o.current;if(!s||!n)return;const i=J.getItem("playerSubtitlesEnabled")!=="false",p=()=>{if(n.innerHTML="",!i||m==="off"||m===null)return;const E=Array.from(s.textTracks).find(g=>g.language===m||g.label===m);if(!E||E.mode!=="showing")return;const w=T/1e3;let e;if(w>0&&E.cues){const g=s.currentTime-w;e=Array.from(E.cues).filter(d=>d.startTime<=g&&g<=d.endTime)}else e=Array.from(E.activeCues??[]);if(e.length===0)return;const v={...c,fontSize:$t(c.fontSize,s.clientHeight||0)},N=_r(v),_=Ar(s,v.position),x=Array.from(e);x.forEach((g,d)=>{const P=String(g.text??"");if(!xr(P).trim())return;const A=document.createElement("div"),F=(x.length-1-d)*1.7;A.style.cssText=`${N}
56
- bottom: calc(${_}px + ${F}em);`,A.innerHTML=Lr(P),n.appendChild(A)})},y=()=>p(),f=()=>p();return Array.from(s.textTracks).forEach(E=>{E.addEventListener("cuechange",y)}),s.addEventListener("timeupdate",f),p(),()=>{Array.from(s.textTracks).forEach(E=>{E.removeEventListener("cuechange",y)}),s.removeEventListener("timeupdate",f),n.innerHTML=""}},[m,T,a,o,c,r])}const bs=({isOpen:r,onClose:o,onSuccess:c})=>{const m=()=>{c?.(),o()};return t(ut,{isOpen:r,onClose:o,title:"MKissa Browser Verification",children:t("div",{className:ze.container,children:[t("p",{children:"Open MKissa in this browser, play an anime episode, and complete any Cloudflare verification it shows. Once playback works there, return to Dango and click Refresh."}),t("div",{className:ze.actions,children:t("a",{className:ze.link,href:"https://mkissa.to/anime",target:"_blank",rel:"noreferrer",children:"Open MKissa anime"})}),t("div",{className:ze.actions,children:[t("button",{className:ze.secondaryButton,onClick:o,children:"Cancel"}),t("button",{className:ze.button,onClick:m,children:"Refresh Dango"})]})]})})},$s=()=>{const{id:r,episodeNumber:o}=nr(),c=sr(),m=Dt(),T=or(),a=cr(),s=!!a.session,n=s&&!a.session?.host,{hasConsent:i,grant:p}=ur(),{options:y}=It(),f=Ce(()=>y.filter(u=>(u.kind??"anime")==="anime"),[y]),E=Ce(()=>f.map(u=>u.id),[f]),w=Ce(()=>new Set(f.filter(u=>u.mature).map(u=>u.id)),[f]),{state:e,dispatch:v,toggleWatchlist:N,moveToCompleted:_,setPreferredSource:x,handleToggleDetails:g,markEpisodeWatched:d,prefetchEpisodeSources:P,isMarkingWatched:A,isUpdatingWatchlistStatus:F}=is(r,o,T.state||null,{hasMatureConsent:i,watchSelection:n?a.room?.selection:null});U(()=>{if(r&&e.showMeta?.id&&e.showMeta.id!==r){const u=o?`/watch/${e.showMeta.id}/${o}${window.location.search}`:`/watch/${e.showMeta.id}${window.location.search}`;c(u,{replace:!0})}},[r,e.showMeta?.id,o,c]);const V=Ce(()=>{if(e.showMeta.name)return{name:e.showMeta.name,thumbnail:e.showMeta.thumbnail,names:e.showMeta.names,genres:e.showMeta.genres,score:e.showMeta.score,isAdult:e.showMeta.isAdult}},[e.showMeta.name,e.showMeta.thumbnail,e.showMeta.names,e.showMeta.genres,e.showMeta.score,e.showMeta.isAdult]),b=Br({skipIntervals:e.skipIntervals,showId:r,episodeNumber:e.currentEpisode?.toString(),episodeCount:e.episodes.length||void 0,sourceType:e.selectedSource?.type,showMeta:V}),{refs:h,actions:O}=b,z=Ce(()=>!r||r.startsWith("dango-mt-")||!e.currentEpisode||e.selectedSource?.type==="iframe"||!e.selectedLink?.hls||!e.selectedSource?null:{showId:r,episode:e.currentEpisode,provider:e.selectedProvider,mode:e.currentMode,source:e.selectedSource.sourceName,title:e.showMeta.name||r},[r,e.currentEpisode,e.selectedProvider,e.currentMode,e.selectedSource,e.selectedLink,e.showMeta.name]),D=Dr(b.engine,z,e.loadingVideo||e.loadingShowData),B=Zr(),H=R(null),j=R(null),pe=R(null),[$,Q]=ie(()=>{try{const u=J.getItem("anime4kProfile");return["low","balanced","high","denoise"].includes(u)?u:"balanced"}catch{return"balanced"}}),{videoDelayMs:ee,videoDelayEnabled:l,setDelayEnabled:M,handleVideoDelayChange:k,isCalibrating:C,testClipActive:W,stopCalibration:Y,openAvSyncCalibrator:Me,cancelAvSyncCalibrator:_e,applyAvSyncCalibrator:ne,toggleTestClip:X,calibReturnRef:Ae,effectiveVideoDelayMs:De}=$r(h.videoRef,()=>O.setShowSettings(!1)),se=R(null),K=es({videoRef:h.videoRef,canvasRef:j,profile:$,delayMs:De}),fe=K.isEnabled&&K.isWebGPUSupported;ts({videoRef:h.videoRef,episodeKey:`${r??""}:${e.currentEpisode??""}`,isEnabled:K.isEnabled,isSupported:K.isWebGPUSupported,mediaReady:!e.loadingVideo&&!!e.selectedLink,isIframeSource:e.selectedSource?.type==="iframe",setEnabled:K.setEnabled}),Ir({videoRef:h.videoRef,canvasRef:se,delayMs:De,enabled:l&&!fe});const le=l&&!fe,xe=fe||le,[He,je]=ie(!1),Oe=R(o);U(()=>{Oe.current!==o&&(Oe.current=o,Y())},[o,Y]);const mt=q(()=>{m.invalidateQueries({queryKey:[ae.continueWatching]})},[m]),{data:Re=[],isLoading:de}=dr(),tt=mr(),pt=pr(),ft=fr(),{isTheaterMode:ye,toggleTheaterMode:Ye,handleLayoutClick:I}=Fr();ar(()=>{if(b.state.isFullscreen||ye)return;const u=h.playerContainerRef.current,Z=H.current;if(!u||!Z)return;const Ie=()=>{const St=u.getBoundingClientRect().height;Z.style.height=`${St}px`};Ie();const Be=new ResizeObserver(Ie);return Be.observe(u),()=>Be.disconnect()},[b.state.isFullscreen,ye,h.playerContainerRef]);const he=Ce(()=>e.episodes.findIndex(u=>u===e.currentEpisode),[e.episodes,e.currentEpisode]),Xe=he>0?e.episodes[he-1]:null,ve=he>=0&&he<e.episodes.length-1?e.episodes[he+1]:null,ht=he>-1&&he<e.episodes.length-1,{showCompleteModal:We,queueCountdown:$e,pendingQueueTransition:Ue,handleQueueTransition:rt,handleNextEpisode:Ve,handleNShortcut:nt,handlePreviousEpisode:Qe,handlePlaybackFinished:st,closeCompleteModal:Ke,cancelQueueTransition:vt}=cs({testClipActive:W,selectedSourceType:e.selectedSource?.type,onEnded:O.onEnded,queue:Re,removeFromQueue:tt.mutate,showId:r,showMetaId:e.showMeta?.id,currentEpisode:e.currentEpisode,isAutoplayEnabled:!n&&e.isAutoplayEnabled,nextEpisode:ve,previousEpisode:Xe,navigate:c,invalidateContinueWatching:mt,dispatch:v}),{showNextEpisodePrompt:gt,handleThresholds:G}=us({videoRef:h.videoRef,queue:Re,showId:r,showMetaId:e.showMeta?.id,currentEpisode:e.currentEpisode,selectedSource:e.selectedSource,hasNextEpisode:ht,nextEpisode:ve,prefetchEpisodeSources:P,matchesQueueItem:et}),{checkEnd:te,logDuration:Se}=Or({videoRef:h.videoRef,sourceType:e.selectedSource?.type,resetKey:`${r}:${e.currentEpisode}`,onEnd:n?O.onEnded:st}),ce=!s&&e.showResumeModal&&!e.resumeProgressPending,ue=We,re=ce||ue;Wr(b,!!e.selectedLink&&!ye&&!re);const{fallbackPrompt:ke,isRetryingProvider:qe,rememberFallbackChoice:Ge,setRememberFallbackChoice:Ee,fallbackChoice:oe,updateFallbackChoice:bt,dismissFallbackPrompt:Je,chooseIframeFallback:ge,chooseProviderRetry:ot,handleVideoSourceError:Tt,resetFallback:Ct}=ps({showId:r,episodeNumber:e.currentEpisode??void 0,currentMode:e.currentMode,selectedProvider:e.selectedProvider,selectedSourceType:e.selectedSource?.type,videoSources:e.videoSources,isAdult:e.showMeta?.isAdult,providerOrder:E,matureProviders:w,setPreferredSource:x,showControls:O.setShowControls,dispatch:v}),{seekToTimeRef:Mt}=fs({engine:b.engine,videoRef:h.videoRef,selectedSource:e.selectedSource,selectedLink:e.selectedLink,loadingVideo:e.loadingVideo,testClipActive:!s&&W,resumeTime:s?0:e.resumeTime,resumeDuration:e.resumeDuration,showResumeModal:!s&&e.showResumeModal,calibReturnRef:Ae,setAvailableSubtitles:O.setAvailableSubtitles,setActiveSubtitleTrack:O.setActiveSubtitleTrack,onFatalError:s?()=>{}:Tt});U(()=>{re&&b.state.isFullscreen&&b.actions.toggleFullscreen()},[re,b.state.isFullscreen,b.actions]),U(()=>{re&&h.videoRef.current&&h.videoRef.current.pause()},[re,h.videoRef]);const{titlePreference:at}=hr(),{lowEndMode:Rt}=vr(),{settings:yt,update:Ut}=Ur(),Vt=ye&&yt.enabled&&!Rt&&e.selectedSource?.type!=="iframe"&&!!e.selectedLink,Le=Ce(()=>{if(!e.showMeta||e.loadingShowData)return"Loading...";const{name:u,names:Z}=e.showMeta;return at==="name"?u||"Loading...":at==="nativeName"?Z?.native||u||"Loading...":at==="englishName"?Z?.english||u||"Loading...":u||"Loading..."},[e.showMeta,at,e.loadingShowData]);U(()=>{Le&&Le!=="Loading..."&&e.currentEpisode&&(document.title=`► ${Le} Episode ${e.currentEpisode} - dango`)},[Le,e.currentEpisode]),ls({onPrevious:n?()=>{}:Qe,onNext:n?()=>{}:nt,onToggleTheater:Ye,flashControls:b.actions.flashControls});const{setAvailableSubtitles:Qt,setActiveSubtitleTrack:Kt}=O,Nt=Ce(()=>({fontSize:b.state.subtitleFontSize,position:b.state.subtitlePosition,bgOpacity:b.state.subtitleBgOpacity,bgColor:b.state.subtitleBgColor,textColor:b.state.subtitleTextColor,edge:b.state.subtitleEdge,bold:b.state.subtitleBold}),[b.state.subtitleFontSize,b.state.subtitlePosition,b.state.subtitleBgOpacity,b.state.subtitleBgColor,b.state.subtitleTextColor,b.state.subtitleEdge,b.state.subtitleBold]);hs({videoRef:h.videoRef,availableSubtitles:b.state.availableSubtitles,activeSubtitleTrack:b.state.activeSubtitleTrack,setAvailableSubtitles:Qt,setActiveSubtitleTrack:Kt});const[qt,Gt]=ie(0);U(()=>{const u=h.videoRef.current;if(!u)return;const Z=()=>Gt(u.clientHeight||0);Z();const Ie=new ResizeObserver(Z);return Ie.observe(u),()=>Ie.disconnect()},[h.videoRef,e.selectedSource,e.selectedLink]),vs({videoRef:h.videoRef,videoBoxH:qt,style:Nt,sourceKey:`${e.selectedSource?.sourceName??""}:${e.selectedLink?.link??""}`,activeSubtitleTrack:b.state.activeSubtitleTrack,availableSubtitles:b.state.availableSubtitles}),gs({videoRef:h.videoRef,overlayRef:pe,style:Nt,activeSubtitleTrack:b.state.activeSubtitleTrack,delayMs:De,enabled:xe}),U(()=>{try{J.setItem("anime4kProfile",$)}catch{}},[$]);const zt=()=>{h.videoRef.current&&(h.videoRef.current.currentTime=e.resumeTime,h.videoRef.current.play()),v({type:"SET_STATE",payload:{showResumeModal:!1}})},Ht=()=>{h.videoRef.current&&(h.videoRef.current.currentTime=0,h.videoRef.current.play()),v({type:"SET_STATE",payload:{showResumeModal:!1}})},jt=q(()=>{v({type:"SET_STATE",payload:{showResumeModal:!1}})},[v]),Yt=q(async()=>{try{await _(),Ke(),v({type:"SET_STATE",payload:{showResumeModal:!1}}),c("/")}catch{}},[_,Ke,v,c]),Pt=(u,Z)=>t("div",{className:u,children:[t("button",{className:`${S.episodeNavBtn} ${S.secondary}`,onClick:Qe,disabled:n||!Xe,type:"button",children:[t(be,{name:"chevron-left",size:12}),"Prev EP"]}),t("button",{className:`${S.episodeNavBtn} ${S.primary}`,onClick:Ve,disabled:n||!ve,type:"button",children:["Next EP",t(be,{name:"chevron-right",size:12})]}),Z==="mobile"&&B&&t("button",{className:`${S.episodeNavBtn} ${S.episodePickerBtn}`,onClick:()=>je(!0),type:"button",children:[t(be,{name:"list-ul",size:12}),"Episodes"]})]}),Xt=u=>{v({type:"SET_STATE",payload:{isAutoplayEnabled:u}}),Xr(u)},_t=!!(e.currentEpisode&&e.watchedEpisodes.includes(e.currentEpisode)),Jt=e.selectedProvider!=="megaplay"||e.selectedSource?.type==="iframe",Zt=q(async()=>{if(!r||!e.currentEpisode||!e.showMeta.name||A)return;const u=h.videoRef.current?.duration,Z=Math.max(u||0,e.resumeDuration||0,Number(e.showMeta.episodeDuration||0)*60,1);await d(e.currentEpisode,Z)},[r,e.currentEpisode,e.showMeta,e.resumeDuration,d,A,h.videoRef]);if(e.error&&!e.showMeta.name&&e.videoSources.length===0&&e.episodes.length===0)return t("p",{className:"error-message",children:["Error: ",e.error]});const we=e.loadingShowData||e.loadingVideo;return e.showMeta?.isAdult===!0&&!i?t("div",{className:Te.playerPageLayout,children:t(Jr,{isOpen:!0,onClose:()=>c("/home"),onGrant:p})}):t("div",{className:`${Te.playerPageLayout} ${ye?Te.theaterMode:""}`,onClick:I,children:[ye&&t(Vr,{videoRef:h.videoRef,active:Vt,settings:yt}),t(Qr,{isOpen:ue,onClose:Ke,title:"Show Completed!",heading:Le,message:"Congratulations! You finished all available episodes.",children:[t(lt,{variant:"secondary",onClick:Ke,children:"Close"}),t(lt,{onClick:Yt,disabled:F,children:F?"Saving...":"Move to Completed"})]}),t(Kr,{isOpen:ce,onClose:jt,title:"Resume Playback?",message:t(it,{children:["You were watching at ",t("strong",{children:b.actions.formatTime(e.resumeTime)}),". Would you like to continue?"]}),onResume:zt,onRestart:Ht}),t(ut,{isOpen:!!ke,onClose:Je,title:"Direct stream failed",width:"sm",children:[t(ut.Body,{children:[t("p",{children:[t("strong",{children:e.selectedProvider}),"'s direct stream failed for this episode."]}),ke?.retryFailed&&t("p",{children:"No working direct stream was found on the other providers either."}),t("p",{children:["You can continue with the embedded (iframe) player, but embedded players may show"," ",t("strong",{children:"ads and pop-ups"}),"."]}),t("label",{style:{display:"flex",alignItems:"center",gap:"8px",marginTop:"0.75rem",cursor:"pointer"},children:[t("input",{type:"checkbox",checked:Ge,onChange:u=>Ee(u.currentTarget.checked)}),"Remember my choice"]})]}),t(ut.Actions,{children:[t(lt,{variant:"secondary",onClick:ge,children:"Continue with iframe"}),t(lt,{onClick:ot,disabled:qe,children:qe?"Searching…":"Try another provider"})]})]}),t(gr,{isOpen:!!e.showCookieModal&&e.cookieProvider!=="mkissa",onClose:()=>v({type:"SET_STATE",payload:{showCookieModal:!1}}),onSuccess:()=>{m.invalidateQueries({queryKey:[ae.videoSources,r,e.currentEpisode,e.selectedProvider,e.currentMode]})}}),t(bs,{isOpen:!!e.showCookieModal&&e.cookieProvider==="mkissa",onClose:()=>v({type:"SET_STATE",payload:{showCookieModal:!1}}),onSuccess:()=>{m.invalidateQueries({queryKey:[ae.videoSources,r,e.currentEpisode,e.selectedProvider,e.currentMode]})}}),!ye&&t("aside",{ref:H,className:Te.episodeSidebar,children:e.loadingShowData?t(qr,{variant:"sidebar"}):t(Gr,{episodes:e.episodes,currentEpisode:e.currentEpisode??void 0,watchedEpisodes:e.watchedEpisodes,onEpisodeClick:u=>{n||c(`/watch/${r}/${u}`)}})}),t("div",{className:Te.playerMain,children:[t("div",{className:`${S.videoContainer} ${b.state.isFullscreen?"":Te.videoPlayerWrapper} ${b.state.isFullscreen?S.fullscreenActive:""}`,style:{...re?{visibility:"hidden"}:{}},onContextMenu:u=>u.preventDefault(),children:t(Un,{player:b,isAutoplayEnabled:e.isAutoplayEnabled,onAutoplayChange:Xt,fallbackChoice:oe,onFallbackChoiceChange:bt,ambientSettings:yt,onAmbientChange:Ut,showNextEpisodeButton:!n&&!re&&gt&&Re.length===0,onNextEpisode:Ve,videoSources:n?[]:s?e.videoSources.filter(u=>u.type!=="iframe"&&u.links.some(Z=>Z.hls)):e.videoSources,selectedSource:e.selectedSource,selectedLink:e.selectedLink,onSourceChange:(u,Z)=>{n&&u.sourceName!==a.room?.selection.source||s&&(u.type==="iframe"||!Z.hls)||(h.videoRef.current&&!isNaN(h.videoRef.current.currentTime)&&(Mt.current=h.videoRef.current.currentTime),x(u.sourceName),v({type:"SET_STATE",payload:{selectedSource:u,selectedLink:Z,showResumeModal:e.showResumeModal&&u.type!=="iframe"}}))},loadingVideo:we,skipIntervals:e.skipIntervals,animeTitle:Le,episodeNumber:e.currentEpisode??void 0,mode:e.currentMode,isTheaterMode:ye,onTheaterModeToggle:Ye,anime4kEnabled:K.isEnabled,onAnime4kToggle:K.toggle,anime4kSupported:K.isWebGPUSupported,anime4kProfile:$,onAnime4kProfileChange:Q,anime4kInitializing:K.isInitializing,anime4kError:K.error,videoDelayEnabled:l,onVideoDelayToggle:M,videoDelayMs:ee,onVideoDelayChange:k,onCalibrateAvSync:s?()=>{}:Me,isInteractingExtra:He||C,className:Tr.shellFill,hideChrome:e.selectedSource?.type==="iframe",overlays:t(it,{children:[b.state.isSpeedBoostActive&&t("div",{className:S.speedBoostBadge,"aria-hidden":"true",children:[t("span",{children:"2x"}),t(be,{name:"forward",size:12})]}),$e!==null&&Ue?.nextItem&&t("div",{className:S.queueCountdown,children:["Queue next in ",$e,"s"]})]}),children:[we&&t("div",{className:S.loadingOverlay,children:t("div",{className:S.loadingDots,children:[t("div",{className:S.dot}),t("div",{className:S.dot}),t("div",{className:S.dot})]})}),b.state.isBuffering&&!we&&e.selectedSource?.type!=="iframe"&&t("div",{className:S.bufferingOverlay,children:t("div",{className:S.bufferingSpinner})}),e.selectedSource?.type==="iframe"&&!s?!we&&t("iframe",{src:e.selectedLink?.link,className:S.videoIframe,allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0,sandbox:e.selectedSource.sandbox?`${e.selectedSource.sandbox} allow-fullscreen allow-popups allow-popups-to-escape-sandbox`:void 0}):t(it,{children:[!we&&e.videoSources.length===0&&t("div",{className:S.errorOverlay,children:[t("p",{children:["No sources found for this episode with ",e.selectedProvider,"."]}),t("p",{className:S.errorSubtext,children:"Please try selecting a different provider below."}),t("button",{className:S.retryButton,onClick:()=>window.location.reload(),"data-speed-boost-ignore":"true",style:{marginTop:8},children:"Retry"})]}),!we&&e.videoSources.length>0&&t(Cr,{controls:!b.state.playbackLocked&&b.state.useNativeControls,playsInline:!0,"webkit-playsinline":"true",disablePictureInPicture:!0,disableRemotePlayback:!0,onPlay:O.onPlay,onPause:O.onPause,onEnded:()=>{W||te(!0)},onDurationChange:()=>{Se()},onSeeked:()=>{W||(G(),te())},onLoadedMetadata:()=>{G(),Se(),W||te()},onTimeUpdate:()=>{W||(O.onTimeUpdate(),G(),te(),Ue&&h.videoRef.current&&h.videoRef.current.currentTime<h.videoRef.current.duration-1&&vt())},onError:s?void 0:Tt,onContextMenu:u=>u.preventDefault(),className:xe?S.videoElementHidden:""}),K.isWebGPUSupported&&!we&&e.videoSources.length>0&&t("canvas",{ref:j,className:`${S.upscalerCanvas} ${fe?S.upscalerActive:""}`}),!fe&&!we&&e.videoSources.length>0&&t("canvas",{ref:se,className:`${S.upscalerCanvas} ${le?S.upscalerActive:""}`}),K.isEnabled&&K.isWebGPUSupported&&K.isInitializing&&t("div",{className:S.upscalerStatusBadge,children:"Preparing upscaler…"}),xe&&t("div",{ref:pe,className:S.subtitleOverlay}),t(zr,{isOpen:C,ms:ee,onChange:k,onApply:ne,onClose:_e,testClipActive:W,onTestClip:X})]})]})}),t(on,{playback:z&&!we?{selection:z,position:h.videoRef.current?.currentTime||0,playing:!1,rate:b.engine.getState().playbackRate}:null,onCreate:()=>{Y(),b.engine.pause()},needsPlayback:D.needsPlayback,onEnablePlayback:D.enablePlayback}),s&&!we&&!z&&t("p",{role:"alert",children:"This room requires the host's direct HLS source. It is unavailable here. Retry the episode or leave the room to use another source."}),!ye&&t(Hr,{}),!ye&&t(it,{children:[de&&Re.length===0?t(Vn,{count:3}):t(en,{title:"Queue",items:Re,currentShowId:r,currentEpisode:e.currentEpisode??void 0,onNextQueue:n?()=>{}:rt,onRemove:u=>tt.mutate({showId:u.showId,episodeNumber:u.episodeNumber}),onClear:()=>pt.mutate(),showClearAll:!0,onReorder:u=>ft.mutate(u.map(Z=>({id:Z.id,showId:Z.showId,episodeNumber:Z.episodeNumber})))}),t("div",{className:S.streamPanel,children:[!n&&t(Gn,{selectedProvider:e.selectedProvider,isAdult:e.showMeta?.isAdult,options:f,onProviderChange:u=>{Ct(),v({type:"SET_STATE",payload:{selectedProvider:u,videoSources:[],selectedSource:null,selectedLink:null,loadingVideo:!0}}),Wt(u,e.showMeta?.isAdult===!0)}}),Pt(`${S.episodeActions} ${S.desktopEpisodeActions}`,"desktop"),we?t("div",{className:S.sourceLoader,children:t("div",{className:S.spinner})}):n?t("p",{children:["Provider: ",e.selectedProvider," · Source: ",a.room?.selection.source," ·"," ",e.currentMode]}):t(Hn,{videoSources:s?e.videoSources.filter(u=>u.type!=="iframe"&&u.links.some(Z=>Z.hls)):e.videoSources,selectedSource:e.selectedSource,selectedLink:e.selectedLink,onSourceChange:u=>{if(s&&(u.type==="iframe"||!u.links.some(Be=>Be.hls)))return;h.videoRef.current&&!isNaN(h.videoRef.current.currentTime)&&(Mt.current=h.videoRef.current.currentTime);const Ie=(s?u.links.filter(Be=>Be.hls):u.links||[]).sort((Be,St)=>(parseInt(St.resolutionStr)||0)-(parseInt(Be.resolutionStr)||0))[0]||null;x(u.sourceName),v({type:"SET_STATE",payload:{selectedSource:u,selectedLink:Ie,showResumeModal:e.showResumeModal&&u.type!=="iframe"}})},onLinkChange:u=>{e.selectedSource&&(x(e.selectedSource.sourceName),v({type:"SET_STATE",payload:{selectedLink:u}}))}})]}),t("div",{className:Te.playerInfoContainer,children:[t("div",{className:Te.playerInfoHeader,children:[t("div",{className:Te.playerAnimeCard,children:t(br,{src:yr(e.showMeta.thumbnail||""),alt:Le,loading:"lazy",decoding:"async",onError:u=>{u.target.src="/placeholder.svg"}})}),t("div",{className:Te.videoTitleSection,children:[t("div",{className:S.titleContainer,children:[t("h1",{children:Le}),t("div",{className:S.scheduleInfo,children:[e.showMeta.status&&t("span",{className:S.status,children:e.showMeta.status}),e.showMeta.nextEpisodeAirDate&&t("span",{className:S.nextEpisode,children:["Next episode: ",e.showMeta.nextEpisodeAirDate]})]})]}),t("div",{className:S.controls,children:[t("button",{className:`${S.watchlistBtn} ${e.inWatchlist?S.inList:""}`,onClick:N,children:[e.inWatchlist?t(be,{name:"check",size:14}):t(be,{name:"plus",size:14}),e.inWatchlist?"In Watchlist":"Add to Watchlist"]}),t(rn,{showId:r,showName:e.showMeta.name||e.showMeta.names?.romaji,showThumbnail:e.showMeta.thumbnail,nativeName:e.showMeta.names?.native,englishName:e.showMeta.names?.english,showType:e.showMeta.type,className:`${S.watchlistBtn} ${S.queueBtn}`,activeClassName:S.queueActive}),Jt&&t("button",{className:`${S.watchlistBtn} ${S.markWatchedBtn} ${_t?S.markWatchedDone:""}`,onClick:Zt,disabled:A||!e.currentEpisode,children:[t(be,{name:"check",size:14}),A?"Saving...":_t?"Watched":"Mark Watched"]}),t("button",{className:`${S.watchlistBtn} ${S.modeToggleBtn} ${e.currentMode==="dub"?S.modeToggleActive:""}`,disabled:n,onClick:()=>{const u=e.currentMode==="dub"?"sub":"dub";Ct(),v({type:"SET_MODE",payload:u}),J.setItem("preferredMode",u)},type:"button","aria-pressed":e.currentMode==="dub",children:e.currentMode==="dub"?"DUB":"SUB"}),Rt&&t("button",{disabled:n,className:`${S.watchlistBtn} ${S.modeToggleBtn} ${b.state.useNativeControls?S.modeToggleActive:""}`,onClick:()=>{const u=!b.state.useNativeControls;b.actions.setUseNativeControls(u),J.setItem("playerUseNativeControls",u.toString())},type:"button",children:b.state.useNativeControls?"NATIVE: ON":"NATIVE: OFF"})]})]})]}),Pt(`${S.episodeActions} ${S.mobileEpisodeActions}`,"mobile"),t("div",{className:Te.infoColumns,children:[t("div",{className:`${S.descriptionSection} ${S.synopsisFlat}`,children:[t("h3",{children:"Synopsis"}),t(sn,{text:e.showMeta.description?e.showMeta.description.replace(/<[^>]*>?/gm,""):"",emptyText:"No description available."}),t("button",{className:S.detailsToggleBtn,onClick:g,children:[e.showCombinedDetails?t(be,{name:"chevron-up"}):t(be,{name:"chevron-down"}),e.showCombinedDetails?"Hide Details":"Show Details"]})]}),e.showCombinedDetails&&t(nn,{showMeta:e.showMeta,styles:S})]})]})]})]}),t(jr,{isOpen:He,onClose:()=>je(!1),episodes:e.episodes,currentEpisode:e.currentEpisode??void 0,watchedEpisodes:e.watchedEpisodes,onEpisodeClick:u=>{je(!1),c(`/watch/${r}/${u}`)}})]})};export{$s as default};
@@ -1,21 +0,0 @@
1
- import{d as s,u as e,S as ge,A as Z,h as G,q as me,T as Me,p as qe,g as we,_ as ze}from"./vendor-core-DfaOB3Rn.js";import{b as pe,u as te}from"./vendor-query-BBT5_sHx.js";import{R as ee,S as J,U as K,V as be,B as S,W as Ke,Q as U,d as Ue,L as _e,t as C,v as Te,o as Ee,J as Ce,X,q as W,Y as ke,Z as Fe,_ as $e,u as We,e as He,$ as Be,K as le,p as je,a0 as Qe,a1 as Ve}from"./index-npJ4Ahxa.js";import{I as B}from"./vendor-icons-DrybRNxP.js";import{T as $}from"./ToggleSwitch-CN_ppEc9.js";import{M as Ye}from"./MatureConsentModal-BrKd4CBZ.js";const Je="_sectionCard_1vuib_1",Xe="_dangerCard_1vuib_20",Ze="_settingRow_1vuib_31",L={sectionCard:Je,dangerCard:Xe,settingRow:Ze};function et(){const{data:t}=pe(ee),{data:o}=pe({queryKey:["profiles"],queryFn:()=>J("/api/profiles/status"),enabled:!!t?.owner}),c=te(),[g,p]=s(null),[h,k]=s(""),[y,i]=s(""),[r,m]=s(""),[f,d]=s(""),[P,l]=s(""),[v,_]=s(!1),[T,O]=s(null),I=async a=>{_(!0),l("");try{await J("/api/profiles/update",{method:"POST",body:JSON.stringify(a)}),await c.invalidateQueries({queryKey:ee.queryKey}),k(""),i(""),l("Profile saved")}catch(N){l(N.message)}finally{_(!1)}};return t?e("section",{className:L.sectionCard,children:[e("h3",{children:"Your profile"}),e("p",{children:"Keep using this profile, rename it, or add another person with their own library and connections."}),e("div",{className:K.avatarRow,children:[e(be,{image:t.image,name:t.name}),e("label",{className:K.uploadButton,children:[e(B,{name:"upload"}),e("span",{children:"Upload image"}),e("input",{className:K.fileInput,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",disabled:v,onChange:async a=>{const N=a.currentTarget.files?.[0];if(a.currentTarget.value="",!N)return;if(N.size>2*1024*1024){l("Image must be smaller than 2 MB");return}const R=new FileReader;R.onerror=()=>l("Could not read image"),R.onload=()=>{I({avatar:R.result})},R.readAsDataURL(N)}})]}),t.avatar&&e(S,{variant:"secondary",disabled:v,onClick:()=>I({avatar:null}),children:"Clear uploaded image"})]}),e("p",{children:"Your uploaded image takes priority, followed by your active cloud account image, then the default user icon."}),e("form",{className:K.form,onSubmit:a=>{a.preventDefault(),I({name:g??t.name})},children:[e("label",{className:K.field,children:["Profile name",e("input",{value:g??t.name,maxLength:60,required:!0,onChange:a=>p(a.currentTarget.value)})]}),e(S,{type:"submit",disabled:v,children:"Save name"})]}),e("form",{className:K.form,onSubmit:a=>{a.preventDefault(),I({password:h,currentPassword:y})},children:[t.protected&&e("label",{className:K.field,children:["Current password",e("input",{type:"password",autoComplete:"current-password",value:y,required:!0,maxLength:256,onChange:a=>i(a.currentTarget.value)})]}),e("label",{className:K.field,children:[t.protected?"New password (empty removes protection)":"Protect this profile",e("input",{type:"password",autoComplete:"new-password",value:h,minLength:8,maxLength:256,onChange:a=>k(a.currentTarget.value)})]}),e(S,{type:"submit",disabled:v,children:"Save password"})]}),e(S,{variant:"secondary",disabled:v,onClick:async()=>{_(!0);try{await J("/api/profiles/logout",{method:"POST"}),Ke()}catch(a){l(a.message),_(!1)}},children:"Switch profile / sign out"}),t.owner&&e("form",{className:K.form,onSubmit:async a=>{a.preventDefault(),_(!0),l("");try{await J("/api/profiles/create",{method:"POST",body:JSON.stringify({name:r,password:f})}),m(""),d(""),await c.invalidateQueries({queryKey:["profiles"]}),l("Profile created. Sign out to switch to it.")}catch(N){l(N.message)}finally{_(!1)}},children:[e("h3",{children:"Add another profile"}),e("p",{children:"Protect your owner profile first. New profiles start empty and do not inherit your accounts. A profile without a password is accessible to anyone who passes the LAN lock."}),e("label",{className:K.field,children:["Name",e("input",{required:!0,maxLength:60,value:r,onChange:a=>m(a.currentTarget.value)})]}),e("label",{className:K.field,children:["Password (optional)",e("input",{type:"password",autoComplete:"new-password",minLength:8,maxLength:256,value:f,onChange:a=>d(a.currentTarget.value)})]}),e(S,{type:"submit",disabled:v||!t.protected,children:"Create profile"})]}),t.owner&&o?.profiles.some(a=>!a.owner)&&e(ge,{children:[e("h3",{children:"Other profiles"}),e("ul",{className:K.profileList,children:o.profiles.filter(a=>!a.owner).map(a=>e("li",{children:[e("span",{className:K.smallAvatar,children:e(be,{image:a.avatar??a.cloudAvatar,name:a.name})}),e("span",{className:K.profileName,children:a.name}),e(S,{variant:"danger",size:"sm",disabled:v,onClick:()=>{l(""),O(a)},children:"Delete"})]},a.id))})]}),e(U,{isOpen:!!T,onClose:v?void 0:()=>O(null),title:"Delete profile?",width:"sm",footer:e(ge,{children:[e(S,{variant:"secondary",disabled:v,onClick:()=>O(null),children:"Cancel"}),e(S,{variant:"danger",loading:v,onClick:async()=>{if(T){_(!0);try{await J("/api/profiles/delete",{method:"POST",body:JSON.stringify({id:T.id,confirm:!0})}),await c.invalidateQueries({queryKey:["profiles"]}),O(null),l("Profile deleted. Local files will be removed when Dango restarts.")}catch(a){l(a.message),O(null)}finally{_(!1)}}},children:"Delete profile"})]}),children:[e("p",{children:["Delete ",e("strong",{children:T?.name}),"? This signs them out immediately. Their local libraries, settings and connections will be removed when Dango next restarts."]}),e("p",{children:"Cloud backups and tracker lists will stay intact. Export any library you want to keep before deleting."})]}),P&&e("p",{role:"status",children:P})]}):null}const ce={"title-preference-container":"_title-preference-container_sdqgs_1","toggle-button":"_toggle-button_sdqgs_21","toggle-label":"_toggle-label_sdqgs_51"},de=["name","nativeName","englishName"],ue={name:"Default (Romaji)",nativeName:"Native",englishName:"English"},tt=()=>{const{titlePreference:t,setTitlePreference:o,loading:c}=Ue(),g=_e(),[p,h]=s(ue[t]),[k,y]=s(!1),i=Z(null);G(()=>{c||h(ue[t])},[t,c]);const r=async()=>{if(k)return;y(!0);const f=(de.indexOf(t)+1)%de.length,d=de[f],P=ue[d];i.current&&(i.current.style.transform="translateX(-100%)",i.current.style.opacity="0"),setTimeout(async()=>{h(P),o(d),i.current&&(i.current.style.transition="none",i.current.style.transform="translateX(100%)",i.current.style.opacity="0",i.current.offsetWidth,i.current.style.transition="transform 0.3s ease-out, opacity 0.3s ease-out",i.current.style.transform="translateX(0)",i.current.style.opacity="1");try{await g.mutateAsync({key:"titlePreference",value:d})}catch(l){console.error("Error saving title preference:",l)}finally{y(!1)}},300)};return c?e("p",{children:"Loading title preference..."}):e("div",{className:ce["title-preference-container"],children:[e("h4",{children:"Anime Title Display Preference"}),e("button",{onClick:r,className:ce["toggle-button"],disabled:k,children:e("span",{ref:i,className:ce["toggle-label"],children:p})})]})},at="_settingsHeader_gfwoa_1",nt="_pageTitle_gfwoa_6",rt="_pageSubtitle_gfwoa_14",st="_settingsLayout_gfwoa_20",it="_sidebar_gfwoa_27",ot="_sidebarIndicator_gfwoa_35",lt="_sidebarItem_gfwoa_50",ct="_active_gfwoa_72",dt="_mainContent_gfwoa_80",ut="_tabContent_gfwoa_85",ht="_settingItem_gfwoa_103",gt="_shortcutContainer_gfwoa_108",mt="_shortcutGroup_gfwoa_115",pt="_shortcutGroupTitle_gfwoa_121",ft="_shortcutGrid_gfwoa_130",yt="_shortcutCard_gfwoa_136",vt="_controls_gfwoa_170",wt="_status_gfwoa_176",u={settingsHeader:at,pageTitle:nt,pageSubtitle:rt,settingsLayout:st,sidebar:it,sidebarIndicator:ot,sidebarItem:lt,active:ct,mainContent:dt,tabContent:ut,settingItem:ht,shortcutContainer:gt,shortcutGroup:mt,shortcutGroupTitle:pt,shortcutGrid:ft,shortcutCard:yt,controls:vt,status:wt},bt="_title_tm30b_11",Ct="_signIn_tm30b_18",kt="_userInfo_tm30b_25",St="_warning_tm30b_47",Nt="_formGroup_tm30b_54",_t="_label_tm30b_58",Tt="_inputWrapper_tm30b_68",Lt="_input_tm30b_68",Pt="_select_tm30b_92",It="_actions_tm30b_109",xt="_hr_tm30b_117",w={title:bt,signIn:Ct,userInfo:kt,warning:St,formGroup:Nt,label:_t,inputWrapper:Tt,input:Lt,select:Pt,actions:It,hr:xt},Rt=()=>{const t=te(),[o,c]=s(!0),[g,p]=s(!1),[h,k]=s(!1),[y,i]=s(null),[r,m]=s({status:"idle"}),[f,d]=s(!1),[P,l]=s(""),[v,_]=s(!1),T=Z(null),[O,I]=s({show:!1,message:"",type:"info"}),a=()=>{T.current&&(window.clearInterval(T.current),T.current=null)},N=me(b=>{k(b.authenticated),i(b.user||b.device.user||null),m(b.device),d(!!b.hasCustomClientId)},[]),R=me(async()=>{const b=await C.auth.githubStatus.query();N(b)},[N]),q=async()=>{try{const b=await C.auth.githubPoll.query();m(b),b.status==="success"?(a(),await t.invalidateQueries({queryKey:ee.queryKey}),await R(),I({show:!0,message:"GitHub authentication complete. Sync has been initialized.",type:"success"})):b.status==="error"&&(a(),I({show:!0,message:b.error||"GitHub authentication failed.",type:"error"}))}catch{a(),I({show:!0,message:"Failed to poll GitHub authentication status.",type:"error"})}},x=(b=5)=>{a(),T.current=window.setInterval(q,Math.max(b,5)*1e3)};G(()=>(R().catch(()=>{I({show:!0,message:"Failed to load GitHub sync status.",type:"error"})}).finally(()=>c(!1)),a),[R]);const A=async()=>{p(!0);try{const b=await C.auth.githubStart.mutate();m(b),x(b.verification?.interval)}catch(b){I({show:!0,message:b instanceof Error?b.message:"Failed to start GitHub authentication.",type:"error"})}finally{p(!1)}},M=async()=>{try{await C.auth.githubLogout.mutate(),await t.invalidateQueries({queryKey:ee.queryKey}),k(!1),i(null),m({status:"idle"}),I({show:!0,message:"Signed out of GitHub sync.",type:"success"})}catch{I({show:!0,message:"Failed to sign out of GitHub.",type:"error"})}},j=async()=>{_(!0);try{await C.auth.saveGithubAuth.mutate({clientId:P}),l(""),await R(),I({show:!0,message:"Custom GitHub auth saved.",type:"success"})}catch{I({show:!0,message:"Failed to save override.",type:"error"})}finally{_(!1)}},Q=async()=>{_(!0);try{await C.auth.saveGithubAuth.mutate({clientId:""}),l(""),await R(),I({show:!0,message:"Custom auth cleared. Using dango defaults.",type:"success"})}catch{I({show:!0,message:"Failed to clear override.",type:"error"})}finally{_(!1)}};return o?e("div",{style:{color:"var(--text-secondary)",padding:"1.5rem"},children:"Loading..."}):e("div",{className:L.sectionCard,children:[e("h3",{className:w.title,children:"GitHub Cloud Sync"}),e("p",{className:w.signIn,children:"Sync local data through a private GitHub repository named dango-sync-data."}),h&&y?e("div",{className:w.userInfo,children:[e("p",{children:["Signed in as: ",e("strong",{children:y.name||y.login})]}),e(S,{variant:"danger",onClick:M,children:"Sign Out"})]}):e("div",{className:w.signIn,children:e(S,{onClick:A,disabled:g||r.status==="pending",children:g||r.status==="pending"?"Waiting for GitHub...":"Sign in with GitHub"})}),r.status==="pending"&&r.verification&&e(ge,{children:[e("hr",{className:w.hr}),e("div",{className:w.formGroup,children:[e("label",{className:w.label,children:"Verification URL"}),e("div",{className:w.inputWrapper,children:[e("input",{className:w.input,value:r.verification.verification_uri,readOnly:!0}),e(S,{onClick:()=>{const b=r.verification?.verification_uri;b&&/^https?:\/\//i.test(b)&&window.open(b,"_blank","noopener,noreferrer")},children:"Open"})]})]}),e("div",{className:w.formGroup,children:[e("label",{className:w.label,children:"Device Code"}),e("input",{className:w.input,value:r.verification.user_code,readOnly:!0})]})]}),r.status==="error"&&e("p",{className:w.warning,children:r.error}),e("details",{style:{marginTop:"1rem",fontSize:"var(--font-size-sm)"},children:[e("summary",{style:{cursor:"pointer",color:"var(--text-secondary)"},children:["Advanced: use your own auth ",f?"(override active)":""]}),e("div",{className:w.formGroup,style:{marginTop:"0.75rem"},children:[e("label",{className:w.label,children:"Client ID (optional)"}),e("input",{className:w.input,value:P,onChange:b=>l(b.currentTarget.value),placeholder:"Your GitHub OAuth app ID"})]}),e("div",{className:w.actions,children:[e(S,{onClick:j,disabled:v,children:"Save override"}),e(S,{variant:"secondary",onClick:Q,disabled:v,children:"Use dango defaults"})]})]}),e(U,{isOpen:O.show,onClose:()=>I(b=>({...b,show:!1})),width:"sm",children:[e(U.Body,{children:e("p",{children:O.message})}),e(U.Actions,{children:e(S,{onClick:()=>I(b=>({...b,show:!1})),children:"OK"})})]})]})},Dt=()=>{const[t,o]=s(!0),[c,g]=s(null),[p,h]=s(!1),[k,y]=s(!1),[i,r]=s(""),[m,f]=s(""),[d,P]=s(""),[l,v]=s(!1),[_,T]=s({show:!1,message:"",type:"info"}),O=async()=>{try{const A=await C.auth.user.query();g(A?.email?A:null)}catch{g(null)}},I=async()=>{try{const[x,A]=await Promise.all([C.auth.configStatus.query(),C.auth.googleAuth.query()]);h(!!x.hasConfig),y(!!(A.hasCustomWorkerUrl||A.hasCustomClientId||A.hasClientSecret))}catch(x){console.error("Failed to fetch config status",x)}};G(()=>{(async()=>{o(!0),await Promise.all([O(),I()]);try{new URLSearchParams(window.location.search).get("google_auth")==="success"&&(await O(),window.history.replaceState(null,"",window.location.pathname))}catch{}o(!1)})();const A=M=>{M.origin===window.location.origin&&typeof M.data=="object"&&M.data!==null&&M.data.type==="GOOGLE_AUTH_SUCCESS"&&(g(M.data.user),window.location.reload())};return window.addEventListener("message",A),()=>window.removeEventListener("message",A)},[]);const a=async()=>{try{const x=await C.auth.googleLogin.mutate();if(x.authenticated){window.location.reload();return}if(x.url){if(typeof window.DangoBridge<"u"){window.location.href=x.url;return}const M=600,j=700,Q=window.innerWidth/2-M/2,b=window.innerHeight/2-j/2;window.open(x.url,"GoogleAuth",`width=${M},height=${j},top=${b},left=${Q}`)}else throw new Error("Auth URL not available")}catch{T({show:!0,message:"Authentication failed. Ensure server is configured correctly.",type:"error"})}},N=async()=>{try{await C.auth.logout.mutate(),g(null),T({show:!0,message:"Successfully signed out.",type:"success"}),window.location.reload()}catch(x){console.error("Sign out failed",x),T({show:!0,message:"Failed to sign out.",type:"error"})}},R=async()=>{v(!0);try{await C.auth.saveGoogleAuth.mutate({workerUrl:i,clientId:m,clientSecret:d}),r(""),f(""),P(""),await I(),T({show:!0,message:"Custom auth saved. Restart may be required.",type:"success"})}catch{T({show:!0,message:"Failed to save override.",type:"error"})}finally{v(!1)}},q=async()=>{v(!0);try{await C.auth.saveGoogleAuth.mutate({workerUrl:"",clientId:"",clientSecret:""}),r(""),f(""),P(""),await I(),T({show:!0,message:"Custom auth cleared. Using dango defaults.",type:"success"})}catch{T({show:!0,message:"Failed to clear override.",type:"error"})}finally{v(!1)}};return t?e("div",{style:{color:"var(--text-secondary)",padding:"1.5rem"},children:"Loading..."}):e("div",{className:L.sectionCard,children:[e("h3",{className:w.title,children:"Google Drive Sync"}),c?e("div",{className:w.userInfo,children:[e("p",{children:["Signed in as: ",e("strong",{children:c.name})," (",c.email,")"]}),e(S,{variant:"danger",onClick:N,children:"Sign Out"})]}):e("div",{className:w.signIn,children:[e("p",{children:"Sign in with your Google account to enable synchronization features."}),e(S,{onClick:a,disabled:!p,children:"Sign in with Google"}),!p&&e("p",{className:w.warning,children:"Google sync is not configured on the server."})]}),e("details",{style:{marginTop:"1rem",fontSize:"var(--font-size-sm)"},children:[e("summary",{style:{cursor:"pointer",color:"var(--text-secondary)"},children:["Advanced: use your own auth ",k?"(override active)":""]}),e("div",{className:w.formGroup,style:{marginTop:"0.75rem"},children:[e("label",{className:w.label,children:"Worker URL (optional)"}),e("input",{className:w.input,value:i,onChange:x=>r(x.currentTarget.value),placeholder:"https://your-worker.workers.dev"})]}),e("div",{className:w.formGroup,children:[e("label",{className:w.label,children:"Client ID (optional)"}),e("input",{className:w.input,value:m,onChange:x=>f(x.currentTarget.value),placeholder:"Your Google OAuth client ID"})]}),e("div",{className:w.formGroup,children:[e("label",{className:w.label,children:"Client Secret (optional)"}),e("input",{type:"password",className:w.input,value:d,onChange:x=>P(x.currentTarget.value),placeholder:"Your Google OAuth secret"})]}),e("div",{className:w.actions,children:[e(S,{onClick:R,disabled:l,children:"Save override"}),e(S,{variant:"secondary",onClick:q,disabled:l,children:"Use dango defaults"})]})]}),e(U,{isOpen:_.show,onClose:()=>T(x=>({...x,show:!1})),width:"sm",children:[e(U.Body,{children:e("p",{children:_.message})}),e(U.Actions,{children:e(S,{onClick:()=>T(x=>({...x,show:!1})),children:"OK"})})]})]})},At="_settingItem_3qq0n_1",Ot="_modalOverlay_3qq0n_6",Gt="_modal_3qq0n_6",Mt="_modalActions_3qq0n_41",qt="_modalSecondary_3qq0n_47",zt="_modalPrimary_3qq0n_57",H={settingItem:At,modalOverlay:Ot,modal:Gt,modalActions:Mt,modalSecondary:qt,modalPrimary:zt},Kt={anime:{heading:"Watchlist Preferences",blurb:"Customize your experience when managing your watchlist and series entries.",skipKey:"skipRemoveConfirmation",ignoreKey:"ignoreAdultContent",listOnlyKey:"cwWatchlistOnly",skipLabel:"Skip confirmation when removing from watchlist",ignoreLabel:"Hide adult content from continue watching",listOnlyLabel:"Only show continue watching for shows in watchlist",listNoun:"watchlist",continueNoun:"continue watching",adultCountUrl:"/api/continue-watching/adult-count",purgeUrl:"/api/continue-watching/purge-adult",purgeDoneText:t=>`Removed ${t??0} entries from continue watching`,invalidateKeys:[["allContinueWatching"]]},manga:{heading:"Reading List Preferences",blurb:"Customize your experience when managing your reading list and manga entries.",skipKey:"mangaSkipRemoveConfirmation",ignoreKey:"mangaIgnoreAdultContent",listOnlyKey:"mangaCwWatchlistOnly",skipLabel:"Skip confirmation when removing from reading list",ignoreLabel:"Hide adult content from continue reading",listOnlyLabel:"Only show continue reading for manga in reading list",listNoun:"reading list",continueNoun:"continue reading",adultCountUrl:"/api/manga/continue-reading/adult-count",purgeUrl:"/api/manga/continue-reading/purge-adult",purgeDoneText:t=>`Removed ${t??0} entries from continue reading`,invalidateKeys:[["manga-continue-reading"]]},tv:{heading:"TV Watchlist Preferences",blurb:"Customize your experience when managing your TV watchlist and series entries.",skipKey:"tvSkipRemoveConfirmation",ignoreKey:"tvIgnoreAdultContent",listOnlyKey:"tvCwWatchlistOnly",skipLabel:"Skip confirmation when removing from TV watchlist",ignoreLabel:"Hide adult content from continue watching",listOnlyLabel:"Only show continue watching for shows in TV watchlist",listNoun:"TV watchlist",continueNoun:"continue watching",adultCountUrl:"/api/tv/continue-watching/adult-count",purgeUrl:"/api/tv/continue-watching/purge-adult",purgeDoneText:t=>`Removed ${t??0} entries from continue watching`,invalidateKeys:[["tv-continue-watching"]]},asmr:{heading:"Listening List Preferences",blurb:"Customize your experience when managing your listening list and work entries.",skipKey:"asmrSkipRemoveConfirmation",ignoreKey:"asmrIgnoreAdultContent",listOnlyKey:"asmrCwWatchlistOnly",skipLabel:"Skip confirmation when removing from listening list",ignoreLabel:"Hide adult content from continue listening",listOnlyLabel:"Only show continue listening for works in listening list",listNoun:"listening list",continueNoun:"continue listening",adultCountUrl:"/api/asmr/continue-listening/adult-count",purgeUrl:"/api/asmr/continue-listening/purge-adult",purgeDoneText:t=>`Removed ${t??0} entries from continue listening`,invalidateKeys:[["asmr-continue-listening"]]}},Ut=(t,o)=>{if(t==null)return o;const c=String(t);return c==="true"||c==="1"?!0:c==="false"||c==="0"?!1:o},Se=(t,o,c)=>{const[g,p]=s(o),[h,k]=s(!1),y=te();return G(()=>{(async()=>{try{const m=await C.settings.getByKey.query({key:t});p(Ut(m.value,o))}catch(m){console.error("Failed to fetch setting",m)}})()},[t,o]),{value:g,setValue:p,isUpdating:h,toggle:async()=>{if(h)return;k(!0);const r=!g;p(r);try{await C.settings.set.mutate({key:t,value:r});for(const m of c)y.invalidateQueries({queryKey:m})}catch(m){console.error("Error saving setting:",m),p(!r)}finally{k(!1)}}}},Et=()=>{const{contentType:t}=Te(),o=Kt[t],[c,g]=s(!1),[p,h]=s(!0),[k,y]=s(!1),i=Se(o.ignoreKey,!0,o.invalidateKeys),r=Se(o.listOnlyKey,!1,o.invalidateKeys),[m,f]=s(null),[d,P]=s(!1),l=te(),v=Ee();G(()=>{h(!0),(async()=>{try{const N=await C.settings.getByKey.query({key:o.skipKey});String(N.value)==="true"||String(N.value)==="1"?g(!0):g(!1)}catch(N){console.error("Failed to fetch setting",N)}finally{h(!1)}})()},[o.skipKey]);const _=async()=>{if(k)return;y(!0);const a=!c;g(a);try{await C.settings.set.mutate({key:o.skipKey,value:a})}catch(N){console.error("Error saving setting:",N),g(!a)}finally{y(!1)}},T=async()=>{if(!i.isUpdating){if(i.value)try{let a;if(t==="anime"?a=(await C.continueWatching.adultCount.query()).count:t==="manga"?a=(await C.mangaProgress.adultCount.query()).count:t==="asmr"?a=(await C.asmrProgress.adultCount.query()).count:a=(await C.tvProgress.adultCount.query()).count,typeof a=="number"&&a>0){f(a);return}}catch(a){console.error("Failed to fetch adult count",a)}i.toggle()}},O=()=>{f(null),i.toggle()},I=async()=>{if(!d){P(!0);try{let a;t==="anime"?a=(await C.continueWatching.purgeAdult.mutate()).removed:t==="manga"?a=(await C.mangaProgress.purgeAdult.mutate()).removed:t==="asmr"?a=(await C.asmrProgress.purgeAdult.mutate()).removed:a=(await C.tvProgress.purgeAdult.mutate()).removed,Ce.success(o.purgeDoneText(a??0));for(const N of o.invalidateKeys)l.invalidateQueries({queryKey:N});t==="anime"&&l.invalidateQueries(v.continueWatching.pathFilter()),t==="manga"&&l.invalidateQueries(v.mangaProgress.pathFilter()),t==="asmr"&&l.invalidateQueries(v.asmrProgress.pathFilter()),t==="tv"&&l.invalidateQueries(v.tvProgress.pathFilter())}catch(a){console.error("Failed to purge adult entries",a),Ce.error("Failed to remove adult entries")}finally{P(!1),f(null)}i.toggle()}};return p?e("div",{children:"Loading settings..."}):e("div",{className:L.sectionCard,children:[e("h3",{children:o.heading}),e("p",{children:o.blurb}),e("div",{className:H.settingItem,children:e("div",{className:L.settingRow,children:[e("label",{htmlFor:"skip-confirmation-toggle",children:o.skipLabel}),e($,{isChecked:c,onChange:_,id:"skip-confirmation-toggle",disabled:k})]})}),e("div",{className:H.settingItem,children:e("div",{className:L.settingRow,children:[e("label",{htmlFor:"ignore-adult-toggle",children:o.ignoreLabel}),e($,{isChecked:i.value,onChange:T,id:"ignore-adult-toggle",disabled:i.isUpdating})]})}),e("div",{className:H.settingItem,children:e("div",{className:L.settingRow,children:[e("label",{htmlFor:"cw-watchlist-only-toggle",children:o.listOnlyLabel}),e($,{isChecked:r.value,onChange:r.toggle,id:"cw-watchlist-only-toggle",disabled:r.isUpdating})]})}),m!==null&&e("div",{className:H.modalOverlay,onClick:()=>f(null),children:e("div",{className:H.modal,onClick:a=>a.stopPropagation(),children:[e("h4",{children:"Show adult entries?"}),e("p",{children:[m," adult ",m===1?"entry":"entries"," not in your"," ",o.listNoun," ",m===1?"is":"are"," currently hidden from"," ",o.continueNoun,". You can purge ",m===1?"it":"them"," from the database instead of showing ",m===1?"it":"them","."]}),e("div",{className:H.modalActions,children:[e("button",{type:"button",className:H.modalSecondary,onClick:O,disabled:d,children:"Show them"}),e("button",{type:"button",className:H.modalPrimary,onClick:I,disabled:d,children:d?"Purging...":`Purge ${m}`})]})]})})]})},Ft="_statsGrid_o4nf0_1",$t="_statCard_o4nf0_8",Wt="_statLabel_o4nf0_18",Ht="_statValue_o4nf0_26",Bt="_statMeta_o4nf0_32",jt="_statusBanner_o4nf0_38",Qt="_statusSuccess_o4nf0_49",Vt="_statusUpdating_o4nf0_55",Yt="_statusError_o4nf0_61",Jt="_sha_o4nf0_67",Xt="_settingItem_o4nf0_74",Zt="_settingTitle_o4nf0_79",ea="_settingSubtitle_o4nf0_85",ta="_actionsRow_o4nf0_92",D={statsGrid:Ft,statCard:$t,statLabel:Wt,statValue:Ht,statMeta:Bt,statusBanner:jt,statusSuccess:Qt,statusUpdating:Vt,statusError:Yt,sha:Jt,settingItem:Xt,settingTitle:Zt,settingSubtitle:ea,actionsRow:ta},aa=()=>{const[t,o]=s(null),[c,g]=s(!0),[p,h]=s(!1),[k,y]=s(!1),i=Z(null),r=async()=>{try{const l=await C.settings.offlineDbInfo.query();return o(l),l}catch(l){console.error("Failed to fetch offline DB info:",l)}finally{g(!1)}return null};G(()=>(r(),()=>{i.current&&window.clearInterval(i.current)}),[]),G(()=>{t?.isRefreshing?i.current||(i.current=window.setInterval(async()=>{const l=await r();l&&!l.isRefreshing&&i.current&&(window.clearInterval(i.current),i.current=null)},2e3)):i.current&&(window.clearInterval(i.current),i.current=null)},[t?.isRefreshing]);const m=async()=>{if(!t||p)return;const l=!t.autoUpdateEnabled;h(!0),o({...t,autoUpdateEnabled:l});try{await C.settings.setOfflineDbAutoUpdate.mutate({enabled:l})}catch(v){console.error("Failed to update auto update setting:",v),o({...t,autoUpdateEnabled:!l})}finally{h(!1)}},f=async()=>{if(!(t?.isRefreshing||k)){y(!0);try{await C.settings.triggerOfflineDbUpdate.mutate(),o(l=>l?{...l,isRefreshing:!0,lastStatus:"updating",lastMessage:"Downloading database..."}:null)}catch(l){console.error("Failed to trigger offline DB update:",l)}finally{y(!1)}}},d=l=>{if(!l)return"Never";try{return new Date(l).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})}catch{return l}},P=t?.isRefreshing||k;return e("div",{className:L.sectionCard,children:[e("h3",{children:"Offline Metadata Database"}),e("p",{children:"Local MAL to AniList ID map used for instant imports and metadata enrichment without hitting rate-limited APIs. Updates automatically every Saturday in the background."}),e("div",{className:D.statsGrid,children:[e("div",{className:D.statCard,children:[e("span",{className:D.statLabel,children:"MAL Mapped"}),e("span",{className:D.statValue,children:c?"-":(t?.totalMalMapped??0).toLocaleString()})]}),e("div",{className:D.statCard,children:[e("span",{className:D.statLabel,children:"Release"}),e("span",{className:D.statMeta,children:c?"-":t?.releaseTag??"Never"})]}),e("div",{className:D.statCard,children:[e("span",{className:D.statLabel,children:"Last Checked"}),e("span",{className:D.statMeta,children:c?"-":d(t?.lastCheckedAt??null)})]}),e("div",{className:D.statCard,children:[e("span",{className:D.statLabel,children:"Last Updated"}),e("span",{className:D.statMeta,children:c?"-":d(t?.lastUpdatedAt??null)})]})]}),t?.lastMessage&&e("div",{className:`${D.statusBanner} ${t.lastStatus==="failed"?D.statusError:t.lastStatus==="updating"?D.statusUpdating:D.statusSuccess}`,children:[e("span",{children:t.lastMessage}),t.contentSha256&&e("span",{className:D.sha,children:["sha:",t.contentSha256.slice(0,12)]})]}),e("div",{className:D.settingItem,children:e("div",{className:L.settingRow,children:[e("div",{children:[e("span",{className:D.settingTitle,children:"Weekly Automatic Updates (Saturdays)"}),e("div",{className:D.settingSubtitle,children:"Download and index new database releases in the background. Catches up on startup if the server was offline."})]}),e($,{id:"offline-db-auto-update-toggle",isChecked:t?t.autoUpdateEnabled:!0,onChange:m,disabled:c||p})]})}),e("div",{className:D.actionsRow,children:e(S,{onClick:f,disabled:c||P,children:P?"Updating Database...":"Update Offline Database Now"})})]})},na="_status_1wbo0_1",ra="_warningText_1wbo0_7",sa="_ackLabel_1wbo0_11",he={status:na,warningText:ra,ackLabel:sa},ia=()=>{const t=te(),[o,c]=s(!1),[g,p]=s(!1),[h,k]=s(!1),[y,i]=s(""),r=()=>{p(!1),i(""),c(!0)},m=()=>{h||(c(!1),p(!1))},f=async()=>{if(!(!g||h)){k(!0),i("");try{const d=await X("/api/database/clear",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})}),P=await d.json();if(!d.ok)throw new Error(P.error||"Failed to clear database");const l=P.deleted,v=P.deletedManga,_=P.deletedTv,T=P.deletedAsmr,O=Object.values(l).reduce((R,q)=>R+(q||0),0)+Object.values(v??{}).reduce((R,q)=>R+(q||0),0)+Object.values(_??{}).reduce((R,q)=>R+(q||0),0)+Object.values(T??{}).reduce((R,q)=>R+(q||0),0),I=(v?.manga_library??0)+(v?.manga_progress??0),a=(_?.tv_library??0)+(_?.tv_progress??0),N=(T?.asmr_library??0)+(T?.asmr_progress??0);i(`Library cleared - ${l.watchlist??0} watchlist entries, ${I} manga rows, ${a} TV rows, ${N} ASMR rows and ${O} total rows removed.`),t.invalidateQueries({queryKey:[W.watchlist]}),t.invalidateQueries({queryKey:[W.continueWatching]}),t.invalidateQueries({queryKey:[W.mangaLibrary]}),t.invalidateQueries({queryKey:[W.mangaContinueReading]}),t.invalidateQueries({queryKey:[W.tvLibrary]}),t.invalidateQueries({queryKey:[W.tvContinueWatching]}),t.invalidateQueries({queryKey:[W.asmrLibrary]}),t.invalidateQueries({queryKey:[W.asmrContinueListening]}),c(!1)}catch(d){i(d.message)}finally{k(!1),p(!1)}}};return e("div",{className:`${L.sectionCard} ${L.dangerCard}`,children:[e("h3",{children:"Danger Zone"}),e("p",{children:"Permanently delete your library (watchlist, watched episodes, queue, cached show metadata, manga reading list and reading progress, TV watchlist and watch progress, ASMR listening list and listening progress) to start fresh. Your settings, sync state and the offline metadata cache are preserved."}),e(S,{variant:"danger",onClick:r,children:"Clear Library Data"}),y&&e("p",{className:he.status,children:y}),e(U,{isOpen:o,onClose:m,title:"Clear library data?",width:"sm",children:[e(U.Body,{children:[e("p",{className:he.warningText,children:"This permanently deletes everything in your library. It acts on the active database (dev or prod, per server config) and cannot be undone. Settings, sync state and the offline metadata cache are kept."}),e("label",{className:he.ackLabel,children:[e("input",{type:"checkbox",checked:g,onChange:d=>p(d.currentTarget.checked),disabled:h}),e("span",{children:"I understand this permanently deletes my library"})]})]}),e(U.Actions,{children:[e(S,{variant:"secondary",onClick:m,disabled:h,children:"Cancel"}),e(S,{variant:"danger",onClick:f,disabled:!g||h,children:h?"Clearing...":"Yes, delete everything"})]})]})]})},oa=()=>{const[t,o]=s(""),[c,g]=s([]),[p,h]=s(null),[k,y]=s(!0),[i,r]=s({show:!1,message:"",type:"info"}),m=async()=>{try{y(!0);const d=await C.auth.rcloneSettings.query();o(d.remote||""),g(d.availableRemotes||[]),h(d.activeRemote||null)}catch(d){console.error("Failed to fetch Rclone settings",d)}finally{y(!1)}};G(()=>{m()},[]);const f=async()=>{try{await C.auth.saveRclone.mutate({remote:t}),r({show:!0,message:"Rclone configuration saved successfully. You must restart the server for these changes to take effect.",type:"success"}),m()}catch{r({show:!0,message:"Failed to save Rclone configuration.",type:"error"})}};return k?e("div",{style:{color:"var(--text-secondary)",padding:"1.5rem"},children:"Loading..."}):e("div",{className:L.sectionCard,children:[e("h3",{className:w.title,children:"Rclone Cloud Sync"}),e("p",{className:w.signIn,children:"Configure which Rclone remote to use for database synchronization."}),p?e("div",{className:w.userInfo,children:e("p",{children:["Current Active Remote: ",e("strong",{children:p})]})}):e("p",{className:w.warning,style:{marginBottom:"1.5rem"},children:"Rclone sync is not currently active. Ensure rclone is installed and a remote is configured."}),e("div",{className:w.formGroup,children:[e("label",{className:w.label,children:"Remote Name"}),e("div",{className:w.inputWrapper,children:e("select",{className:w.select,value:t,onChange:d=>o(d.currentTarget.value),children:[e("option",{value:"",children:"(Disabled / None)"}),c.map(d=>e("option",{value:d,children:d},d)),t&&!c.includes(t)&&e("option",{value:t,children:[t," (Manual)"]})]})}),e("p",{className:w.warning,style:{marginTop:"12px"},children:[e("strong",{children:"Note:"})," You can choose which provider is active using the selector at the top of the page."]})]}),e("div",{className:w.actions,children:e(S,{onClick:f,children:"Save Rclone Settings"})}),e(U,{isOpen:i.show,onClose:()=>r(d=>({...d,show:!1})),width:"sm",children:[e(U.Body,{children:e("p",{children:i.message})}),e(U.Actions,{children:e(S,{onClick:()=>r(d=>({...d,show:!1})),children:"OK"})})]})]})},la=()=>{const t=te(),[o,c]=s(null),[g,p]=s(!0),h=async()=>{try{const r=await C.auth.syncSettings.query();c(r)}catch(r){console.error("Failed to fetch sync settings",r)}finally{p(!1)}};G(()=>{h()},[]);const k=async r=>{const m=r.currentTarget.value;try{const f=await C.auth.saveSyncProvider.mutate({provider:m});c(d=>d?{...d,activeProvider:f.activeProvider}:null),await h(),await t.invalidateQueries({queryKey:ee.queryKey}),ke.success(`Sync provider updated to ${m==="default"?"Default Order":m}`)}catch{ke.error("Failed to update sync provider")}};if(g||!o)return null;const y=[{value:"default",label:"Default (Priority Based)"}];o.authenticatedProviders.github&&y.push({value:"github",label:"GitHub"}),o.authenticatedProviders.google&&y.push({value:"google",label:"Google Drive"}),o.authenticatedProviders.rclone&&y.push({value:"rclone",label:"Rclone"}),y.push({value:"none",label:"None (Local Only)"});const i=r=>r==="none"?"Local Only (No Sync)":r==="google"?"Google Drive":r==="github"?"GitHub":r==="rclone"?"Rclone":r;return e("div",{className:L.sectionCard,children:[e("h3",{children:"Active Sync Provider"}),e("p",{children:'Choose which provider to use for synchronization. "Default" uses the first available provider you are logged into.'}),e("div",{style:{marginBottom:"1.5rem",padding:"0.75rem",background:"rgba(255, 255, 255, 0.03)",borderRadius:"var(--radius-md)",borderLeft:"4px solid var(--accent)",fontSize:"var(--font-size-sm)"},children:["Current Status:"," ",e("strong",{style:{color:"var(--accent-light)",textTransform:"capitalize"},children:i(o.actualActiveProvider)})]}),e("div",{className:L.settingRow,children:[e("label",{htmlFor:"sync-provider-select",children:"Selected Preference"}),e("select",{id:"sync-provider-select",value:o.activeProvider,onChange:k,style:{padding:"0.5rem",borderRadius:"var(--radius-md)",background:"rgba(255, 255, 255, 0.05)",color:"var(--text-primary)",border:"1px solid var(--glass-border)",fontSize:"var(--font-size-sm)",minWidth:"220px",outline:"none",cursor:"pointer"},children:y.map(r=>e("option",{value:r.value,children:r.label},r.value))})]})]})};function ca(){return"javascript:"+encodeURIComponent(`(function(){
2
- if(!/(^|\\.)discord\\.com$/.test(location.hostname)){alert('Dango: use this bookmarklet while on discord.com');return}
3
- var t=null;
4
- try{
5
- window.webpackChunkdiscord_app.push([[Symbol()],{},function(req){
6
- if(!req.c)return;
7
- var ms=Object.values(req.c);
8
- for(var i=0;i<ms.length;i++){var m=ms[i];
9
- try{
10
- if(!m.exports||m.exports===window)continue;
11
- if(typeof m.exports.getToken==='function'){var x=m.exports.getToken();if(x){t=x;return}}
12
- for(var k in m.exports){try{var ex=m.exports[k];if(ex&&typeof ex.getToken==='function'&&ex[Symbol.toStringTag]!=='IntlMessagesProxy'){var y=ex.getToken();if(y){t=y;return}}}catch(e1){}}
13
- }catch(e2){}}
14
- }]);
15
- window.webpackChunkdiscord_app.pop();
16
- }catch(e3){}
17
- if(!t){alert('Dango: could not grab your token. Make sure you are logged in to Discord in this tab, then run the bookmarklet again.');return}
18
- function copyFallback(){var a=document.createElement('textarea');a.value=t;a.style.position='fixed';a.style.opacity='0';document.body.appendChild(a);a.select();try{document.execCommand('copy')}catch(e4){}document.body.removeChild(a)}
19
- var done=function(){window.close();setTimeout(function(){if(!window.closed){alert('Dango: token copied to clipboard! Could not close this tab, so just close it, go back to Dango Settings, paste the token and press Save.')}},250)};
20
- if(navigator.clipboard&&navigator.clipboard.writeText){navigator.clipboard.writeText(t).then(done,function(){copyFallback();done()})}else{copyFallback();done()}
21
- })()`)}const da=()=>{const t=Me(ca,[]);return e("div",{style:{marginTop:"0.9rem",paddingTop:"0.9rem",borderTop:"1px dashed var(--border-color)"},children:[e("h4",{style:{margin:"0 0 0.35rem",fontSize:"0.95rem"},children:"Grab the token automatically (bookmarklet)"}),e("p",{style:{margin:"0 0 0.6rem",fontSize:"0.85rem",color:"var(--text-secondary)"},children:"Set this up once and you never have to dig through DevTools: the bookmarklet copies your Discord token to the clipboard and closes the Discord tab - then you just paste it above and press Save."}),e("ol",{style:{margin:"0 0 0.75rem",paddingLeft:"1.25rem",fontSize:"0.85rem",color:"var(--text-secondary)",display:"grid",gap:"0.3rem"},children:[e("li",{children:["Drag the ",e("strong",{style:{color:"var(--text-primary)"},children:"Dango Token Grabber"})," ","button below onto your bookmarks bar (press ",e("kbd",{children:"Ctrl"}),"+",e("kbd",{children:"Shift"}),"+",e("kbd",{children:"B"})," ","first if the bar is hidden)."]}),e("li",{children:["Click ",e("strong",{style:{color:"var(--text-primary)"},children:"Open Discord"})," and log in (skip this if you are already logged in)."]}),e("li",{children:["On the Discord tab, click the"," ",e("strong",{style:{color:"var(--text-primary)"},children:"Dango Token Grabber"})," bookmark. The token lands in your clipboard and the tab closes on its own - come back here, paste it above and press ",e("strong",{children:"Save"}),"."]})]}),e("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center",flexWrap:"wrap"},children:[e("a",{href:t,onClick:g=>{g.preventDefault(),alert("Drag this button onto your bookmarks bar instead of clicking it, then click it while you are on discord.com.")},title:"Drag me to your bookmarks bar",draggable:!0,style:{display:"inline-flex",alignItems:"center",padding:"0.4rem 0.8rem",borderRadius:"999px",border:"1px dashed var(--accent)",background:"var(--bg-secondary)",color:"var(--text-primary)",fontSize:"0.85rem",textDecoration:"none",cursor:"grab",userSelect:"none"},children:[e(B,{name:"bookmark",style:{marginRight:"0.45rem",color:"var(--accent)"}}),"Dango Token Grabber"]}),e("a",{className:"btn btn-secondary btn-sm",href:"https://discord.com/channels/@me",target:"_blank",rel:"noopener noreferrer",children:"Open Discord"}),e(S,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(t),alert('Bookmarklet code copied. Create a new bookmark on your bookmarks bar, name it "Dango Token" and paste the code as its URL.')}catch{alert(`Could not copy automatically. Right-click the "Dango Token Grabber" button and choose "Copy link address" instead, then paste that into a new bookmark's URL.`)}},children:"Copy code"})]}),e("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",color:"var(--text-tertiary)"},children:`"Copy code" is a fallback for browsers that won't drag bookmarklets: create any bookmark, then paste the copied code as its URL.`})]})},ua="_settingItem_68mz3_1",ha="_field_68mz3_6",ga="_input_68mz3_19",ma="_actions_68mz3_39",pa="_status_68mz3_45",E={settingItem:ua,field:ha,input:ga,actions:ma,status:pa},fa=()=>{const[t,o]=s(!1),[c,g]=s(""),[p,h]=s(""),[k,y]=s(!0),[i,r]=s(!1),[m,f]=s("");G(()=>{(async()=>{try{const T=await(await X("/api/auth/app-status")).json();o(T.hasPassword)}catch{console.error("Failed to fetch LAN auth status")}finally{y(!1)}})()},[]);const d=async()=>{if(f(""),c!==p){f("Passwords do not match");return}if(c.length<4){f("Password must be at least 4 characters");return}r(!0);try{const v=await X("/api/auth/app-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:c})}),_=await v.json();if(!v.ok){f(_.error||"Failed to update password");return}o(_.hasPassword),g(""),h(""),f(_.hasPassword?"Password set successfully":"Password removed")}catch{f("Network error")}finally{r(!1)}},P=async()=>{r(!0);try{const v=await X("/api/auth/app-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:""})}),_=await v.json();if(!v.ok){f(_.error||"Failed to remove password");return}o(!1),g(""),h(""),f("Password removed")}catch{f("Network error")}finally{r(!1)}},l=async()=>{r(!0);try{await X("/api/auth/app-logout",{method:"POST"}),f("Logged out"),window.location.reload()}catch{f("Logout failed")}finally{r(!1)}};return k?e("div",{className:L.sectionCard,children:e("p",{children:"Loading..."})}):e("div",{className:L.sectionCard,children:[e("h3",{children:"LAN Lock"}),e("p",{children:"Require a password to access this instance from any device, including this one. Sessions persist across server restarts until logout or password change."}),e("div",{className:E.settingItem,children:[e("div",{className:E.field,children:[e("label",{htmlFor:"lan-password",children:"New Password"}),e("input",{id:"lan-password",type:"password",value:c,onChange:v=>g(v.currentTarget.value),placeholder:t?"Leave empty to keep current password":"Enter a password...",className:E.input})]}),e("div",{className:E.field,children:[e("label",{htmlFor:"lan-confirm-password",children:"Confirm Password"}),e("input",{id:"lan-confirm-password",type:"password",value:p,onChange:v=>h(v.currentTarget.value),placeholder:"Confirm password...",className:E.input})]}),e("div",{className:E.actions,children:[e(S,{variant:"primary",onClick:d,loading:i,disabled:i,children:t?"Update Password":"Set Password"}),t&&e(S,{variant:"danger",onClick:l,loading:i,disabled:i,children:"Logout"}),t&&e(S,{variant:"secondary",onClick:P,loading:i,disabled:i,children:"Remove Password"})]}),m&&e("p",{className:E.status,children:m})]})]})},ya=()=>{const[t,o]=s(""),[c,g]=s(!0),[p,h]=s(!1),[k,y]=s("");G(()=>{J("/api/auth/app-status").then(r=>o(String(r.port??3e3))).catch(()=>y("Failed to load current port")).finally(()=>g(!1))},[]);const i=async()=>{const r=Number(t);if(!Number.isInteger(r)||r<1||r>65535){y("Enter a port between 1 and 65535");return}h(!0),y("");try{await C.auth.setServerPort.mutate({port:r}),y(`Saved. Restart dango, then open http://localhost:${r} - this overrides the PORT environment variable.`)}catch(m){y(m.message)}finally{h(!1)}};return c?e("div",{className:L.sectionCard,children:e("p",{children:"Loading..."})}):e("div",{className:L.sectionCard,children:[e("h3",{children:"Server Port"}),e("p",{children:"Port the backend listens on. Takes effect after a restart. Google and AniList sign-in need the matching redirect URI registered with the provider."}),e("div",{className:E.settingItem,children:[e("div",{className:E.field,children:[e("label",{htmlFor:"server-port",children:"Port"}),e("input",{id:"server-port",type:"number",min:1,max:65535,value:t,onChange:r=>o(r.currentTarget.value),className:E.input})]}),e("div",{className:E.actions,children:e(S,{variant:"primary",onClick:i,loading:p,disabled:p,children:"Save Port"})}),k&&e("p",{className:E.status,children:k})]})]})},va=()=>{const{theme:t,setTheme:o,loading:c}=Fe();return e("div",{children:[e("h4",{style:{margin:"0 0 0.25rem",fontSize:"1rem"},children:"Palette"}),e("p",{style:{margin:"0 0 0.75rem",fontSize:"0.85rem",color:"var(--text-secondary)"},children:"Taro is the default. Pick a palette that suits you."}),e("div",{role:"radiogroup","aria-label":"Palette",style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(150px, 1fr))",gap:"0.6rem"},children:$e.map(g=>{const p=t===g.id;return e("button",{role:"radio","aria-checked":p,disabled:c,onClick:()=>o(g.id),style:{display:"flex",gap:"0.6rem",alignItems:"center",textAlign:"left",padding:"0.65rem 0.75rem",borderRadius:"10px",cursor:"pointer",background:p?"var(--accent-subtle)":"var(--bg-tertiary)",border:p?"1px solid var(--accent)":"1px solid var(--border-primary)",color:"var(--text-primary)"},children:[e("span",{"aria-hidden":!0,style:{width:26,height:26,borderRadius:"50%",flex:"none",background:g.swatch,border:"1px solid rgba(0,0,0,0.35)"}}),e("span",{style:{minWidth:0},children:[e("span",{style:{display:"block",fontSize:"0.85rem",fontWeight:700},children:g.label}),e("span",{style:{display:"block",fontSize:"0.75rem",color:"var(--text-secondary)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:g.blurb})]})]},g.id)})})]})};function wa({variant:t="info",children:o,className:c=""}){return e("div",{className:`alert alert-${t} ${c}`,children:o})}const ba={anime:"Watchlist",manga:"Reading List",tv:"TV Watchlist",asmr:"Listening List"},Ne=["general","presence","server","sync","watchlist","database"],La=()=>{const{data:t}=pe(ee),[o,c]=qe(),{contentType:g}=Te(),p=o.get("tab"),[h,k]=s(p&&Ne.includes(p)?p:"general"),[y,i]=s(""),r=Z(null),m=Z(null),f=Z(new Map),[d,P]=s({top:0,height:0,left:0,width:0}),{lowEndMode:l,setLowEndMode:v}=We(),{hasConsent:_,grant:T,revoke:O}=He(),[I,a]=s(!1),[N,R]=s(Be),[q,x]=s(!0),{data:A}=le("discordRPCEnabled"),M=_e(),[j,Q]=s(!0),{data:b}=le("dangoGaze"),[Le,fe]=s(!0),{data:ae}=le("discordRPCHideMature"),[ye,ie]=s(""),[ne,oe]=s(null);G(()=>{t?.owner&&C.discord.gatewayStatus.query().then(n=>{oe(n),n.masked&&n.masked!=="none"&&ie(n.masked)}).catch(()=>{})},[t?.owner]),G(()=>{A!==void 0&&x(A==="true"||A===!0||A===null)},[A]),G(()=>{ae!==void 0&&fe(ae==="true"||ae===!0||ae===null)},[ae]);const Pe=n=>{x(n),M.mutate({key:"discordRPCEnabled",value:String(n)})};G(()=>{b!==void 0&&Q(b!=="false"&&b!==!1)},[b]);const Ie=n=>{Q(n),M.mutate({key:"dangoGaze",value:String(n)})},xe=n=>{fe(n),M.mutate({key:"discordRPCHideMature",value:String(n)})},Re=n=>{R(n),je.setItem(Qe,String(n)),window.dispatchEvent(new CustomEvent(Ve))};we.useEffect(()=>{document.title="Settings - dango"},[]),we.useEffect(()=>{const n=o.get("tab");n&&Ne.includes(n)&&k(n)},[o]);const V=n=>{k(n),c(n==="general"?{}:{tab:n})},re=me(()=>{const n=f.current.get(h),z=m.current;if(n&&z){const Y=z.getBoundingClientRect(),F=n.getBoundingClientRect(),se=window.matchMedia("(max-width: 900px)").matches;P(se?{top:F.top-Y.top,height:F.height,left:F.left-Y.left,width:F.width}:{top:F.top-Y.top,height:F.height,left:0,width:0})}},[h]);ze(()=>{re()},[h,re]),G(()=>{const n=()=>re();window.addEventListener("resize",n);let z=!1;return document.fonts?.ready&&document.fonts.ready.then(()=>{z||re()}),()=>{z=!0,window.removeEventListener("resize",n)}},[h,re]);const De=()=>{i("Exporting databases...");const n=window.DangoBridge;if(n?.downloadFile){n.downloadFile("/api/backup-db","dango-backup.json"),setTimeout(()=>{i("Databases exported successfully!")},1500);return}const z=document.createElement("a");z.href="/api/backup-db",z.download="dango-backup.json",document.body.appendChild(z),z.click(),z.remove(),setTimeout(()=>{i("Databases exported successfully!")},1500)},Ae=async n=>{const z=n.currentTarget.files?.[0];if(!z)return;i("Importing databases...");const Y=new FormData;Y.append("dbfile",z);try{const F=await X("/api/restore-db",{method:"POST",body:Y}),se=await F.json();if(F.ok){const ve=Array.isArray(se.restored)?se.restored.join(", "):null;i(ve?`Databases imported successfully (${ve})!`:"Database imported successfully!"),setTimeout(()=>window.location.reload(),2e3)}else i(`Import failed: ${se.error}`)}catch{i("Import failed: An unexpected error occurred.")}finally{n.currentTarget.value=""}},Oe=()=>{r.current?.click()},Ge=()=>{switch(h){case"general":return e("div",{className:u.tabContent,children:[e(et,{}),e("div",{className:L.sectionCard,children:[e("h3",{children:"Appearance & Preferences"}),e("p",{children:"Configure how titles are displayed and other general preferences."}),e("div",{className:u.settingItem,children:e(tt,{})}),e("div",{className:u.settingItem,style:{marginTop:"1.5rem"},children:e(va,{})}),e("div",{className:u.settingItem,style:{marginTop:"1.5rem"},children:e("div",{className:L.settingRow,children:[e("div",{style:{minWidth:0},children:[e("h4",{style:{margin:0,fontSize:"1rem"},children:"Low End Mode"}),e("p",{style:{margin:"0.25rem 0 0",fontSize:"0.85rem",color:"var(--text-secondary)"},children:"Disables animations and heavy visual effects for better performance on older hardware."})]}),e($,{isChecked:l,onChange:n=>v(n.currentTarget.checked),id:"low-end-mode"})]})}),e("div",{className:u.settingItem,style:{marginTop:"1.5rem"},children:e("div",{className:L.settingRow,children:[e("div",{style:{minWidth:0},children:[e("h4",{style:{margin:0,fontSize:"1rem"},children:"Dango Animations"}),e("p",{style:{margin:"0.25rem 0 0",fontSize:"0.85rem",color:"var(--text-secondary)"},children:"Lets the dango logo look around, blink and react when you pet it. Always off in Low End Mode."})]}),e($,{isChecked:j,onChange:n=>Ie(n.currentTarget.checked),id:"dango-gaze"})]})}),e("div",{className:u.settingItem,style:{marginTop:"1.5rem"},children:e("div",{className:L.settingRow,children:[e("div",{style:{minWidth:0},children:[e("h4",{style:{margin:0,fontSize:"1rem"},children:"Virtual Keyboard"}),e("p",{style:{margin:"0.25rem 0 0",fontSize:"0.85rem",color:"var(--text-secondary)"},children:"Shows an on-screen keyboard when text search fields are focused."})]}),e($,{isChecked:N,onChange:n=>Re(n.currentTarget.checked),id:"virtual-keyboard-enabled"})]})})]}),e("section",{className:L.sectionCard,children:[e("h3",{children:"Keyboard Shortcuts"}),e("p",{children:"Use S or Ctrl+K to focus search anywhere, or use player keys while watching."}),e("div",{className:u.shortcutContainer,children:[e("div",{className:u.shortcutGroup,children:[e("h4",{className:u.shortcutGroupTitle,children:"Search"}),e("div",{className:u.shortcutGrid,children:[e("div",{className:u.shortcutCard,children:[e("kbd",{children:"S"}),e("span",{children:"Focus search"})]}),e("div",{className:u.shortcutCard,children:[e("kbd",{children:"Ctrl + K / ⌘ + K"}),e("span",{children:"Focus search"})]})]})]}),e("div",{className:u.shortcutGroup,children:[e("h4",{className:u.shortcutGroupTitle,children:"Player"}),e("div",{className:u.shortcutGrid,children:[e("div",{className:u.shortcutCard,children:[e("kbd",{children:"Space / K"}),e("span",{children:"Play / pause"})]}),e("div",{className:u.shortcutCard,children:[e("kbd",{children:"J / L · ← / →"}),e("span",{children:"Seek back / fwd"})]}),e("div",{className:u.shortcutCard,children:[e("kbd",{children:"↑ / ↓"}),e("span",{children:"Adjust volume"})]}),e("div",{className:u.shortcutCard,children:[e("kbd",{children:"M / F"}),e("span",{children:"Mute / fullscreen"})]}),e("div",{className:u.shortcutCard,children:[e("kbd",{children:"N / P"}),e("span",{children:"Next / prev episode"})]}),e("div",{className:u.shortcutCard,children:[e("kbd",{children:"T"}),e("span",{children:"Theater mode"})]})]})]})]})]})]});case"presence":return e("div",{className:u.tabContent,children:e("div",{className:L.sectionCard,children:[e("h3",{children:"Presence & Content"}),e("p",{children:"Control what Dango shares on Discord and your mature-content preference."}),t?.owner&&e("div",{className:u.settingItem,style:{marginTop:"1.5rem"},children:e("div",{className:L.settingRow,children:[e("div",{style:{minWidth:0},children:[e("h4",{style:{margin:0,fontSize:"1rem"},children:"Discord Rich Presence"}),e("p",{style:{margin:"0.25rem 0 0",fontSize:"0.85rem",color:"var(--text-secondary)"},children:"Show your current anime and watch progress on your Discord profile status."})]}),e($,{isChecked:q,onChange:n=>Pe(n.currentTarget.checked),id:"discord-rpc-enabled"})]})}),t?.owner&&q&&e("div",{className:u.settingItem,style:{marginTop:"1rem"},children:e("div",{className:L.settingRow,children:[e("div",{style:{minWidth:0},children:[e("h4",{style:{margin:0,fontSize:"1rem"},children:"Hide Mature Content"}),e("p",{style:{margin:"0.25rem 0 0",fontSize:"0.85rem",color:"var(--text-secondary)"},children:"Hide mature content (18+) from Discord Rich Presence."})]}),e($,{isChecked:Le,onChange:n=>xe(n.currentTarget.checked),id:"discord-hide-mature"})]})}),t?.owner&&e("div",{className:u.settingItem,style:{marginTop:"1.5rem",background:"var(--bg-tertiary)",padding:"1rem",borderRadius:"8px",border:"1px solid var(--border-color)"},children:[e("div",{className:L.settingRow,children:e("div",{style:{minWidth:0},children:[e("h4",{style:{margin:0,fontSize:"1rem"},children:"Discord Mobile Presence (Gateway)"}),e("p",{style:{margin:"0.25rem 0 0.75rem",fontSize:"0.85rem",color:"var(--text-secondary)"},children:"Paste your Discord authentication token to enable presence on mobile devices. If no token is saved, the default desktop Rich Presence is used. The token is stored locally in your configuration and never shared."})]})}),e(wa,{variant:"warning",style:{marginTop:"1.25rem",paddingTop:"1.25rem"},children:[e("strong",{children:"Use at your own risk."})," This feature uses the Discord Gateway API with your user token, which violates Discord's Terms of Service. Discord may detect this usage and take action against your account, including phone number locks, temporary suspensions, or permanent bans. While the risk is generally low, it is not zero. Only use this if you understand and accept the risks."]}),e("div",{style:{marginTop:"0.75rem",display:"flex",gap:"0.5rem",alignItems:"center",flexWrap:"wrap"},children:[e("input",{type:"password",value:ye,onChange:n=>ie(n.currentTarget.value),placeholder:"Paste Discord token here...",style:{flex:"1 1 200px",padding:"0.5rem",borderRadius:"4px",border:"1px solid var(--border-color)",background:"var(--bg-primary)",color:"var(--text-primary)",fontFamily:"monospace",minWidth:0}}),e(S,{variant:"primary",size:"sm",onClick:async()=>{try{const n=await C.discord.gatewaySave.mutate({token:ye});oe({hasToken:!0,masked:n.masked,enabled:!0}),ie(n.masked)}catch(n){alert(n instanceof Error?n.message:"Failed to save token")}},children:"Save"}),e(S,{variant:"secondary",size:"sm",onClick:async()=>{await C.discord.gatewayRemove.mutate().catch(()=>{}),ie(""),oe({hasToken:!1,masked:null,enabled:!1})},children:"Remove"})]}),ne&&e("p",{style:{marginTop:"0.5rem",fontSize:"0.8rem",color:ne.hasToken?"green":"var(--text-secondary)"},children:["Status:"," ",ne.hasToken?`Token saved (${ne.masked})`:"No token saved",ne.enabled?" - Gateway active":""]}),t?.owner&&e(da,{})]}),e("div",{className:u.settingItem,style:{marginTop:"1.5rem"},children:e("div",{className:L.settingRow,children:[e("div",{style:{minWidth:0},children:[e("h4",{style:{margin:0,fontSize:"1rem"},children:"Mature Content"}),e("p",{style:{margin:"0.25rem 0 0",fontSize:"0.85rem",color:"var(--text-secondary)"},children:"Allow mature content intended for adults 18 and older. Turning this off restores filtering and blur gates."})]}),e($,{isChecked:_,onChange:n=>{n.currentTarget.checked?a(!0):(O(),window.location.reload())},id:"mature-content-enabled"})]})})]})});case"server":return e("div",{className:u.tabContent,children:[t?.owner&&e(fa,{}),t?.owner&&e(ya,{})]});case"sync":return e("div",{className:u.tabContent,children:[e(la,{}),e(Rt,{}),e(Dt,{}),t?.owner&&e(oa,{})]});case"watchlist":return e("div",{className:u.tabContent,children:e(Et,{})});case"database":return e("div",{className:u.tabContent,children:[e("div",{className:L.sectionCard,children:[e("h3",{children:"Database Management"}),e("p",{children:"Download a backup of all databases (anime, manga, TV and ASMR) or restore from a backup file. Legacy single-file anime (.db) backups can still be restored."}),e("div",{className:u.controls,children:[e(S,{onClick:De,children:"Backup Database"}),e(S,{variant:"secondary",onClick:Oe,children:"Restore Database"})]}),e("input",{type:"file",ref:r,onChange:Ae,style:{position:"absolute",width:1,height:1,opacity:0,overflow:"hidden"},accept:".json,.db,application/octet-stream"}),y&&e("p",{className:u.status,children:y})]}),t?.owner&&e(aa,{}),e(ia,{})]});default:return null}};return e("div",{className:"page-container",children:[e("div",{className:u.settingsHeader,children:[e("h1",{className:u.pageTitle,children:"Settings"}),e("p",{className:u.pageSubtitle,children:"Manage your preferences and data synchronization"})]}),e("div",{className:u.settingsLayout,children:[e("aside",{className:u.sidebar,ref:m,children:[e("div",{className:u.sidebarIndicator,style:{top:d.top,height:d.height,left:d.left,...d.width?{width:d.width}:{}}}),e("button",{ref:n=>{n&&f.current.set("general",n)},className:`${u.sidebarItem} ${h==="general"?u.active:""}`,onClick:()=>V("general"),children:[e(B,{name:"cog"})," ",e("span",{children:"General"})]}),e("button",{ref:n=>{n&&f.current.set("presence",n)},className:`${u.sidebarItem} ${h==="presence"?u.active:""}`,onClick:()=>V("presence"),children:[e(B,{name:"discord"})," ",e("span",{children:"Presence"})]}),e("button",{ref:n=>{n&&f.current.set("server",n)},className:`${u.sidebarItem} ${h==="server"?u.active:""}`,onClick:()=>V("server"),children:[e(B,{name:"server"})," ",e("span",{children:"Server"})]}),e("button",{ref:n=>{n&&f.current.set("sync",n)},className:`${u.sidebarItem} ${h==="sync"?u.active:""}`,onClick:()=>V("sync"),children:[e(B,{name:"cloud"})," ",e("span",{children:"Synchronization"})]}),e("button",{ref:n=>{n&&f.current.set("watchlist",n)},className:`${u.sidebarItem} ${h==="watchlist"?u.active:""}`,onClick:()=>V("watchlist"),children:[e(B,{name:"list"})," ",e("span",{children:ba[g]})]}),e("button",{ref:n=>{n&&f.current.set("database",n)},className:`${u.sidebarItem} ${h==="database"?u.active:""}`,onClick:()=>V("database"),children:[e(B,{name:"database"})," ",e("span",{children:"Database"})]})]}),e("main",{className:u.mainContent,children:e("div",{className:u.tabContent,children:Ge()},h)})]}),e(Ye,{isOpen:I,onClose:()=>a(!1),onGrant:()=>{T(),a(!1)},scope:"section"})]})};export{La as default};
@@ -1,4 +0,0 @@
1
- import{u as t,d as y,A as V,h as g,S as Xe,g as ns,q as C,o as rs,p as ss,a as os,T as Se}from"./vendor-core-DfaOB3Rn.js";import{h as Un,p as z,t as pt,ac as as,a6 as is,S as On,e as ls,ak as cs,J as br,a8 as us,B as cn}from"./index-npJ4Ahxa.js";import{P as ds,a as ms,b as bs,F as hs,f as fs,c as vs}from"./PlayerProvider-DzaMVhFX.js";import{u as ps}from"./vendor-query-BBT5_sHx.js";import{I as he}from"./vendor-icons-DrybRNxP.js";import{p as Hn,M as gs,z as pr,f as Wn,c as ys,C as Ss,a as _s,P as Ts,b as un,u as Cs,i as ks,j as Es,n as Ns,h as Is,k as xs,m as As,l as Ls,s as qn,d as ws,e as Bs,g as Ps,r as Ms,o as Ae,A as Rs,t as zs,E as $s,w as Ds,x as Os,v as ie,y as qs,R as Vs,q as Fs}from"./useWatchAlongPlayer-CRf0zHFj.js";import{S as Us,O as Vn,a as Hs,A as Ws,b as Ks}from"./OptionListMenu-ClUReC8J.js";import{M as Qs}from"./MatureConsentModal-BrKd4CBZ.js";import{u as Ys}from"./useProviders-DphwZjpZ.js";import{e as js,f as Gs,g as Xs,d as Js,c as Zs,h as eo,i as to}from"./useTvLibrary-efdd6TIy.js";import{l as no,s as ro,i as dn,h as hr}from"./playbackCompletion-DB_c1lex.js";import{u as so}from"./useIsMobile-Dvx1uJ82.js";import{S as oo}from"./SynopsisText-B3Sa5pRv.js";import{W as ao}from"./WatchAlongPanel-CvUFCFll.js";import"./libraryInvalidation-CHlEJU7b.js";const io="_fullscreenFlat_10bzs_1",lo="_timeDisplay_10bzs_12",co="_bottomControls_10bzs_16",uo="_leftControls_10bzs_20",mo="_rightControls_10bzs_21",bo="_controlBtn_10bzs_25",ho="_controlsOverlay_10bzs_32",fo="_hidden_10bzs_52",vo="_topControls_10bzs_58",po="_backBtn_10bzs_78",go="_videoTitleInfo_10bzs_98",yo="_animeTitle_10bzs_104",So="_episodeLabel_10bzs_112",_o="_speedBoostBadge_10bzs_119",To="_progressBarContainer_10bzs_165",Co="_progressBar_10bzs_165",ko="_thumb_10bzs_184",Eo="_bufferedBar_10bzs_202",No="_watchedBar_10bzs_212",Io="_scrubbing_10bzs_237",xo="_timeBubble_10bzs_241",Ao="_bottomControlsRow_10bzs_255",Lo="_nextEpisodeBtn_10bzs_278",wo="_active_10bzs_340",Bo="_settingsPanel_10bzs_352",Po="_settingsHeader_10bzs_371",Mo="_settingsBackBtn_10bzs_379",Ro="_settingsTitle_10bzs_397",zo="_settingsContent_10bzs_408",$o="_currentValue_10bzs_417",Do="_menuItem_10bzs_423",Oo="_menuNote_10bzs_456",qo="_loadingOverlay_10bzs_465",Vo="_loadingDots_10bzs_476",Fo="_dot_10bzs_481",Uo="_bufferingOverlay_10bzs_510",Ho="_bufferingSpinner_10bzs_519",o={fullscreenFlat:io,timeDisplay:lo,bottomControls:co,leftControls:uo,rightControls:mo,controlBtn:bo,controlsOverlay:ho,hidden:fo,topControls:vo,backBtn:po,videoTitleInfo:go,animeTitle:yo,episodeLabel:So,speedBoostBadge:_o,progressBarContainer:To,progressBar:Co,thumb:ko,bufferedBar:Eo,watchedBar:No,scrubbing:Io,timeBubble:xo,bottomControlsRow:Ao,nextEpisodeBtn:Lo,active:wo,settingsPanel:Bo,settingsHeader:Po,settingsBackBtn:Mo,settingsTitle:Ro,settingsContent:zo,currentValue:$o,menuItem:Do,menuNote:Oo,loadingOverlay:qo,loadingDots:Vo,dot:Fo,bufferingOverlay:Uo,bufferingSpinner:Ho},Wo=({player:s,visible:h,settingsOpen:O,onOpenSettings:w,onCloseSettings:R,hasSubtitles:k,isSubtitleActive:I,subtitles:d,onSubtitleChange:i,showNextEpisodeButton:S,onNextEpisode:r,isTheaterMode:B,onTheaterModeToggle:fe,timeLabelRef:J})=>{const{state:m,actions:ke}=s,Le=()=>{if(I){i(-1);return}let ve=null;try{ve=z.getItem("tvLastSubtitle")}catch{}i(Hn(d,{lastKey:ve,enabled:!0}))};return t("div",{className:`${o.controlsOverlay} ${h?"":o.hidden}`,"data-speed-boost-ignore":"true",style:{pointerEvents:"none",background:"none",justifyContent:"flex-end"},children:t("div",{className:o.bottomControls,onClick:ve=>ve.stopPropagation(),children:[t(ds,{classes:{container:o.progressBarContainer,scrubbing:o.scrubbing,timeBubble:o.timeBubble,bar:o.progressBar,buffered:o.bufferedBar,watched:o.watchedBar,thumb:o.thumb},timeLabelRef:J}),t("div",{className:o.bottomControlsRow,children:[t("div",{className:o.leftControls,children:[t(ms,{className:o.controlBtn}),t(bs,{buttonClassName:o.controlBtn,onExpandedChange:ke.setShowVolumeSlider}),t("span",{className:o.timeDisplay,ref:J,children:[Un(0)," / ",Un(m.duration)]})]}),t("div",{className:o.rightControls,children:[S&&t("button",{className:o.nextEpisodeBtn,onClick:r,title:"Play next episode",children:"Next EP"}),k&&t("button",{className:`${o.controlBtn} ${I?o.active:""}`,onClick:Le,"aria-label":I?"Turn subtitles off":"Turn subtitles on",children:t(he,{name:"closed-captioning"})}),t("button",{className:`${o.controlBtn} ${O?o.active:""}`,onClick:()=>O?R():w(),"aria-label":"Settings",children:t(he,{name:"cog"})}),t("button",{className:`${o.controlBtn} ${B?o.active:""}`,onClick:ve=>{ve.stopPropagation(),fe()},title:B?"Exit Theater Mode":"Theater Mode","aria-label":B?"Exit Theater Mode":"Theater Mode",children:t(he,{name:"tv"})}),t(hs,{className:o.controlBtn})]})]})]})})},mn=-6e4,Fn=6e4,fr=500,Ko=({classes:s,delayMs:h,onDelayChange:O})=>{const[w,R]=y(null),k=w??h,I=V(O);I.current=O;const d=V(h);d.current=h;const i=V(null);i.current=w,g(()=>{R(null)},[h]),g(()=>()=>{const B=i.current;B!==null&&B!==d.current&&I.current(B)},[]);const S=B=>{d.current=B,i.current=null,I.current(B),R(null)},r=B=>{const fe=i.current??d.current,J=Math.max(mn,Math.min(Fn,fe+B));S(J)};return t(Xe,{children:[t("div",{style:{display:"flex",gap:6,padding:"0.5rem 0.75rem 0.25rem"},children:[t("button",{type:"button",className:s.item,onClick:()=>r(-fr),"aria-label":"Show subtitles 0.5 seconds earlier",style:{flex:1,justifyContent:"center"},children:t("span",{children:"-0.5s"})}),t("button",{type:"button",className:s.item,onClick:()=>r(fr),"aria-label":"Show subtitles 0.5 seconds later",style:{flex:1,justifyContent:"center"},children:t("span",{children:"+0.5s"})}),t("button",{type:"button",className:s.item,onClick:()=>S(0),disabled:k===0,"aria-label":"Reset subtitle timing",style:{flex:1,justifyContent:"center"},children:t("span",{children:"Reset"})})]}),t(gs,{label:"Subtitle timing",display:pr(k),min:mn,max:Fn,step:100,value:k,percent:(k-mn)/(Fn-mn)*100,onChange:B=>{const fe=Math.round(B);i.current=fe,R(fe)},onCommit:()=>{const B=i.current;B!==null&&S(B)}}),t("div",{className:s.note,children:"Positive delays subtitles (show later). Negative shows them earlier. 0.0s is default."})]})},Qo=({view:s,onSelectView:h,onClose:O,player:w,onSubtitleStyleChange:R,streams:k,resolutionIdx:I,onResolutionChange:d,hasSubtitles:i,subtitles:S,selectedSubtitle:r,isSubtitleActive:B,onSubtitleChange:fe,audioTracks:J,selectedAudioTrack:m,onAudioTrackChange:ke,videoDelayEnabled:Le,onVideoDelayToggle:ve,videoDelayMs:pe,onVideoDelayChange:T,onCalibrate:gt,subtitleDelayMs:Je,onSubtitleDelayChange:E,ambientSettings:U,onAmbientChange:Q})=>{const{state:le}=w,yt=()=>t(Xe,{children:[k.length>1&&t("button",{className:o.menuItem,onClick:()=>h("resolution"),children:[t("span",{children:"Resolution"}),t("span",{className:o.currentValue,children:k[I]?.quality||"Auto"})]}),i&&t("button",{className:o.menuItem,onClick:()=>h("subtitles"),children:[t("span",{children:"Subtitles"}),t("span",{className:o.currentValue,children:B?S[r]?.label||S[r]?.language:"Off"})]}),i&&t("button",{className:o.menuItem,onClick:()=>h("subtitle-style"),children:[t("span",{children:"Subtitle Style"}),t("span",{className:o.currentValue,children:[le.subtitleFontSize.toFixed(1),"x · ",le.subtitlePosition]})]}),i&&t("button",{className:o.menuItem,onClick:()=>h("subtitle-timing"),children:[t("span",{children:"Subtitle Timing"}),t("span",{className:o.currentValue,children:pr(Je)})]}),J.length>0&&t("button",{className:o.menuItem,onClick:()=>h("audio"),children:[t("span",{children:"Audio Track"}),t("span",{className:o.currentValue,children:J[m]?.label||J[m]?.language})]}),t("button",{className:o.menuItem,onClick:()=>h("av-sync"),children:[t("span",{children:"A/V Sync"}),t("span",{className:o.currentValue,children:Le?`${pe}ms`:"Off"})]}),U&&Q&&t("button",{className:o.menuItem,onClick:()=>h("ambient"),children:[t("span",{children:"Ambient Light"}),t("span",{className:o.currentValue,children:U.enabled?"On":"Off"})]})]}),we=()=>t(Vn,{classes:{item:o.menuItem,active:o.active},options:k.map((x,se)=>({key:String(se),label:x.quality,selected:se===I})),onSelect:x=>d(Number(x))}),Ze=()=>t(Vn,{classes:{item:o.menuItem,active:o.active},options:[{key:"off",label:"Off",selected:!B},...S.map((x,se)=>({key:String(se),label:x.label||x.language,selected:se===r}))],onSelect:x=>fe(x==="off"?-1:Number(x))}),te=()=>t(Hs,{classes:{item:o.menuItem,active:o.active},values:{fontSize:le.subtitleFontSize,position:le.subtitlePosition,bgOpacity:le.subtitleBgOpacity,bgColor:le.subtitleBgColor,textColor:le.subtitleTextColor,edge:le.subtitleEdge,bold:le.subtitleBold},onChange:R}),St=()=>t(Ko,{classes:{item:o.menuItem,active:o.active,note:o.menuNote},delayMs:Je,onDelayChange:x=>E?.(x)}),st=()=>t(Vn,{classes:{item:o.menuItem,active:o.active},options:J.map((x,se)=>({key:String(se),label:x.label||x.language,selected:se===m})),onSelect:x=>ke(Number(x))}),Be=()=>t(Ws,{classes:{item:o.menuItem,active:o.active,note:o.menuNote},enabled:Le,delayMs:pe,onToggle:x=>ve?.(x),onDelayChange:x=>T?.(x),onCalibrate:gt}),j=()=>U&&Q?t(Ks,{classes:{item:o.menuItem,active:o.active,note:o.menuNote},values:U,onChange:Q}):null;return t("div",{"data-speed-boost-ignore":"true",onClick:x=>x.stopPropagation(),children:t(Us,{classes:{panel:o.settingsPanel,header:o.settingsHeader,backBtn:o.settingsBackBtn,title:o.settingsTitle,content:o.settingsContent},title:s==="main"?"Settings":s==="subtitle-style"?"Subtitle Style":s==="subtitle-timing"?"Subtitle Timing":s==="audio"?"Audio Track":s==="resolution"?"Resolution":s==="av-sync"?"A/V Sync":s==="ambient"?"Ambient Light":s.charAt(0).toUpperCase()+s.slice(1),onBack:()=>s==="main"?O():h("main"),children:[s==="main"&&yt(),s==="resolution"&&we(),s==="subtitles"&&Ze(),s==="subtitle-style"&&te(),s==="subtitle-timing"&&St(),s==="audio"&&st(),s==="av-sync"&&Be(),s==="ambient"&&j()]})})},Yo=({player:s,title:h,episodeLabel:O,server:w,audioTracks:R,selectedAudioTrack:k,onAudioTrackChange:I,subtitles:d,selectedSubtitle:i,onSubtitleChange:S,streams:r,resolutionIdx:B,onResolutionChange:fe,onBack:J,children:m,videoDelayEnabled:ke=!1,onVideoDelayToggle:Le,videoDelayMs:ve=0,onVideoDelayChange:pe,onCalibrateAvSync:T,subtitleDelayMs:gt=0,onSubtitleDelayChange:Je,showNextEpisodeButton:E=!1,onNextEpisode:U,isLoading:Q=!1,isTheaterMode:le,onTheaterModeToggle:yt,ambientSettings:we,onAmbientChange:Ze})=>{const{state:te,refs:St,actions:st}=s,Be=St.videoRef,{subtitleFontSize:j,subtitlePosition:x,subtitleBgOpacity:se,subtitleBgColor:ce,subtitleTextColor:Pe,subtitleEdge:Me,subtitleBold:ne}=te,[Ve,et]=y(null),Fe=V(null),[ot,Ee]=y(0);g(()=>{const ae=Be.current;if(!ae)return;const _e=()=>Ee(ae.clientHeight||0);_e();const ge=new ResizeObserver(_e);return ge.observe(ae),()=>ge.disconnect()},[Be]);const _t=st.setSubtitleStyle;g(()=>{const ae="tv-player-subtitle-style";let _e=document.getElementById(ae);_e||(_e=document.createElement("style"),_e.id=ae,document.head.appendChild(_e));const ge={fontSize:j,position:x,bgOpacity:se,bgColor:ce,textColor:Pe,edge:Me,bold:ne},Z=Be.current,Ot=Wn(j,ot||Z?.clientHeight||720);if(_e.textContent=ys({...ge,fontSize:Ot}),Z){const lt=()=>{const L=Number(x);return isNaN(L)?0:Math.max(0,Math.min(100,L))},ct=(L,u)=>{try{const l=L;l.snapToLines=!1,l.line=u}catch{}},kt=()=>{const L=Ot*16,u=Z.videoHeight||Z.clientHeight||720,l=Z.videoWidth||Z.clientWidth||1280;return{step:L*1.3/u*100,chars:Math.max(20,Math.floor(l/(L*.55)))}},ue=L=>{const u=Math.max(0,Math.min(100,100-lt())),l=Array.from(L.activeCues??[]);if(l.length<=1){l.forEach($e=>ct($e,u));return}const{step:de,chars:me}=kt();let At=u;for(let $e=l.length-1;$e>=0;$e--){const Lt=String(l[$e].text??"").replace(/<[^>]*>/g,"").split(`
2
- `).reduce((Vt,fn)=>Vt+Math.max(1,Math.ceil(fn.length/me)),0),qt=At-Lt*de;ct(l[$e],Math.max(0,qt)),At=qt-de*.4}},Et=()=>{const L=Math.max(0,Math.min(100,100-lt()));Array.from(Z.textTracks).forEach(u=>{u.cues&&(Array.from(u.cues).forEach(l=>ct(l,L)),u.mode==="showing"&&ue(u))})};Et();const Te=L=>{const u=L.target;u.mode==="showing"&&ue(u)},Nt=()=>{Array.from(Z.textTracks).forEach(L=>{L.removeEventListener("cuechange",Te),L.addEventListener("cuechange",Te)}),Et()};Array.from(Z.textTracks).forEach(L=>{L.addEventListener("cuechange",Te)}),Z.textTracks.addEventListener("addtrack",Nt);const It=Array.from(Z.querySelectorAll("track")),xt=()=>Et();return It.forEach(L=>L.addEventListener("load",xt)),()=>{Array.from(Z.textTracks).forEach(L=>{L.removeEventListener("cuechange",Te)}),Z.textTracks.removeEventListener("addtrack",Nt),It.forEach(L=>L.removeEventListener("load",xt))}}},[j,x,se,ce,Pe,Me,ne,i,d,Be,ot]);const oe=d.length>0,Re=i>=0,ze=()=>{et("main"),st.setShowControls(!0)},Ue=()=>{et(null)},tt=te.showControls||!!Ve,Tt=fs(s.engine),at=Tt.audioTracks.find(ae=>ae.id===Tt.activeAudioTrack)??R[k],He=i>=0?d[i]??Tt.subtitleTracks.find(ae=>ae.id===i):void 0,bn=t(Ss,{visible:tt,title:h,episode:O,server:Q?void 0:w,audio:Q?void 0:at?.label||at?.language,subtitles:Q?void 0:He?.label||He?.language,onBack:J,classes:{overlay:o.controlsOverlay,hidden:o.hidden,top:o.topControls,backBtn:o.backBtn,titleInfo:o.videoTitleInfo,title:o.animeTitle,episode:o.episodeLabel}}),Ct=!Q&&!te.isBuffering&&te.duration>0?t(_s,{}):null,K=t(Wo,{player:s,visible:tt,settingsOpen:!!Ve,onOpenSettings:ze,onCloseSettings:Ue,hasSubtitles:oe,isSubtitleActive:Re,subtitles:d,onSubtitleChange:S,showNextEpisodeButton:E,onNextEpisode:U,isTheaterMode:le,onTheaterModeToggle:yt,timeLabelRef:Fe}),it=Ve?t(Qo,{view:Ve,onSelectView:et,onClose:Ue,player:s,onSubtitleStyleChange:_t,streams:r,resolutionIdx:B,onResolutionChange:fe,hasSubtitles:oe,subtitles:d,selectedSubtitle:i,isSubtitleActive:Re,onSubtitleChange:S,audioTracks:R,selectedAudioTrack:k,onAudioTrackChange:I,videoDelayEnabled:ke,onVideoDelayToggle:Le,videoDelayMs:ve,onVideoDelayChange:pe,onCalibrate:()=>{et(null),T?.()},subtitleDelayMs:gt,onSubtitleDelayChange:Je,ambientSettings:we,onAmbientChange:Ze}):null,A=t(Xe,{children:[Q&&t("div",{className:o.loadingOverlay,"aria-hidden":"true",children:t("div",{className:o.loadingDots,children:[t("div",{className:o.dot}),t("div",{className:o.dot}),t("div",{className:o.dot})]})}),te.isBuffering&&!Q&&t("div",{className:o.bufferingOverlay,"aria-hidden":"true",children:t("div",{className:o.bufferingSpinner})}),te.isSpeedBoostActive&&t("div",{className:o.speedBoostBadge,"aria-hidden":"true",children:[t("span",{children:"2x"}),t(he,{name:"forward",size:12})]})]});return t(Ts,{engine:s.engine,topBar:bn,centerControls:Ct,bottomBar:!Q&&te.duration>0?K:null,settingsPanel:it,overlays:A,isInteracting:!!Ve||te.showVolumeSlider,nativeControls:te.useNativeControls,onStageClick:Ue,className:te.isFullscreen?o.fullscreenFlat:"",children:m})},jo=({servers:s,selectedServer:h,onServerSelect:O})=>s.length===0?null:t("div",{className:un.sourceSelectionContainer,children:[t("h4",{children:"Source"}),t("div",{className:un.sourceButtons,children:s.map(w=>t("button",{className:`${un.sourceButton} ${h===w?un.active:""}`,onClick:()=>O(w),children:w},w))})]}),Go=ns.memo(jo);function Xo({details:s,isMovie:h,season:O,episode:w,videoRef:R,active:k}){const I=V("");I.current||(I.current=`tv-${Date.now()}-${Math.random().toString(36).slice(2)}`);const d=C(()=>{if(!s)return;const i=R.current,S=h?"":`S${String(O).padStart(2,"0")}E${String(w).padStart(2,"0")}`;pt.discord.tvPresence.mutate({title:s.title,episodeLabel:S,isPlaying:i?!i.paused&&!i.ended:!0,thumbnail:s.poster,currentTime:i?i.currentTime:0,duration:i&&i.duration||0,isAdult:s.adult===!0,sessionId:I.current}).catch(()=>{}),pt.discord.heartbeat.mutate({sessionId:I.current}).catch(()=>{})},[s,h,O,w,R]);return g(()=>{if(!s)return;d();const i=window.setInterval(()=>{const S=R.current;(!S||!S.paused)&&d()},15e3);return()=>window.clearInterval(i)},[d,s,R]),g(()=>{if(!s||!k)return;const i=R.current;if(!i)return;const S=()=>d();return i.addEventListener("play",S),i.addEventListener("pause",S),i.addEventListener("seeked",S),()=>{i.removeEventListener("play",S),i.removeEventListener("pause",S),i.removeEventListener("seeked",S)}},[s,k,d,R]),g(()=>{const i=I.current,S=()=>as(i),r=()=>S();return window.addEventListener("pagehide",r),window.addEventListener("beforeunload",r),()=>{window.removeEventListener("pagehide",r),window.removeEventListener("beforeunload",r),S()}},[]),{sendPresence:d}}function Jo(s,h,O){const w=()=>{const k=Array.isArray(s.audioTracks)?s.audioTracks.length:0,I=O.getWant(),d=k>0?Math.min(Math.max(0,I),k-1):I;s.audioTrack=d,d!==I&&O.onResolve(d)},R=(k,I)=>{const d=O.getWant(),i=Array.isArray(s.audioTracks)?s.audioTracks.length:0;if(I.id!==d&&d>=0&&d<i){s.audioTrack!==d&&(s.audioTrack=d);return}O.onResolve(I.id)};return s.on(h.MANIFEST_PARSED,w),s.on(h.AUDIO_TRACK_SWITCHED,R),()=>{s.off(h.MANIFEST_PARSED,w),s.off(h.AUDIO_TRACK_SWITCHED,R)}}const Zo=/\b(SmartTV|SMART-TV|Tizen|Web0S|webOS|NetCast|HbbTV|AppleTV|CrKey|BRAVIA|AFT[A-Za-z]|Fire\s?TV|GoogleTV|Roku|VIDAA|DTV|PlayStation|Xbox|Opera TV|POV_TV)\b/i;function ea(){try{if(Zo.test(navigator.userAgent||""))return!0;const s=navigator.deviceMemory;if(typeof s=="number"&&s>0&&s<2)return!0}catch{}return!1}const ta="_statusMsg_zqb8u_1",na="_error_zqb8u_7",ra="_spinner_zqb8u_11",sa="_spin_zqb8u_11",oa="_sourceLoader_zqb8u_16",aa="_ringSpinner_zqb8u_22",ia="_meta_zqb8u_40",la="_year_zqb8u_48",ca="_rating_zqb8u_53",ua="_typeBadge_zqb8u_62",da="_tv_zqb8u_70",ma="_movie_zqb8u_75",ba="_controlLabel_zqb8u_80",ha="_select_zqb8u_90",fa="_playerSection_zqb8u_102",va="_video_zqb8u_106",pa="_videoHidden_zqb8u_128",ga="_delayCanvas_zqb8u_133",ya="_delayCanvasActive_zqb8u_146",Sa="_subtitleOverlay_zqb8u_150",_a="_videoIframe_zqb8u_169",Ta="_retryButton_zqb8u_177",Ca="_sidebarSeason_zqb8u_192",ka="_mobileSeasonRow_zqb8u_208",Ea="_providerSelectWrap_zqb8u_222",Na="_genreRow_zqb8u_230",Ia="_genreChip_zqb8u_237",xa="_metaRow_zqb8u_247",Aa="_detailGrid_zqb8u_256",La="_detailItem_zqb8u_264",wa="_imdbLink_zqb8u_286",p={statusMsg:ta,error:na,spinner:ra,spin:sa,sourceLoader:oa,ringSpinner:aa,meta:ia,year:la,rating:ca,typeBadge:ua,tv:da,movie:ma,controlLabel:ba,select:ha,playerSection:fa,video:va,videoHidden:pa,delayCanvas:ga,delayCanvasActive:ya,subtitleOverlay:Sa,videoIframe:_a,retryButton:Ta,sidebarSeason:Ca,mobileSeasonRow:ka,providerSelectWrap:Ea,genreRow:Na,genreChip:Ia,metaRow:xa,detailGrid:Aa,detailItem:La,imdbLink:wa},Ba=[],Pa=[];function vr({error:s,onRetry:h}){return t("div",{className:`${p.statusMsg} ${p.error}`,style:{flexDirection:"column",alignItems:"stretch",gap:8},children:t("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[t("span",{style:{flex:1},children:s}),t("button",{className:p.retryButton,onClick:h,children:"Retry"})]})})}const ja=()=>{const{id:s}=rs(),[h]=ss(),O=V(h);O.current=h;const w=os(),R=ps(),k=h.get("type"),I=is(),d=!!I.session,i=d&&!I.session?.host,S=i&&["tv","movie"].includes(I.room?.selection.kind||"")?I.room?.selection:null,[r,B]=y(null),[fe,J]=y(()=>parseInt(h.get("s")||"1",10)||1),m=S?.season??fe,[ke,Le]=y([]),[ve,pe]=y(()=>parseInt(h.get("e")||"1",10)||1),T=S?Number(S.episode):ve,[gt,Je]=y(()=>{try{return z.getItem("tvProvider")||""}catch{return""}}),E=S?.provider??gt,[U,Q]=y([]),[le,yt]=y(""),[we,Ze]=y(""),{options:te,isFallback:St,isLoading:st}=Ys(),Be=Se(()=>te.filter(e=>(e.kind??"tv")==="tv").map(e=>({id:e.id,label:e.label,tier:e.tier==="embed"?"embed":"direct",servers:e.servers})),[te]),j=St||Be.length===0?Ba:Be,x=j.filter(e=>e.tier==="direct"),se=j.filter(e=>e.tier==="embed"),[ce,Pe]=y(!1),[Me,ne]=y(""),[Ve,et]=y([]),[Fe,ot]=y(0),[Ee,_t]=y([]),[oe,Re]=y(-1),[ze,Ue]=y(0),[tt,Tt]=y(""),[at,He]=y(""),[bn,Ct]=y(()=>{try{return z.getItem("tvServer")||""}catch{return""}}),K=S?.source??bn,it=Se(()=>j.find(e=>e.id===E),[j,E]),A=it?.tier==="embed",[ae,_e]=y([]),[ge,Z]=y(""),[Ot,lt]=y(""),[ct,kt]=y(!1),ue=Se(()=>ae.length>0?ae:it?.servers??[],[ae,it]),Et=Se(()=>ge&&!d?["Embed",...ue]:ue,[ue,ge,d]),Te=ct&&!!ge,Nt=Te?Ot||ge:"";g(()=>{if(!ge){lt("");return}let e=!1;return On(`/api/resolve?url=${encodeURIComponent(ge)}`).then(n=>{!e&&n.finalUrl&&lt(n.finalUrl)}).catch(()=>{}),()=>{e=!0}},[ge]);const It=V([]);g(()=>{It.current=U},[U]);const xt=V(Fe);g(()=>{xt.current=Fe},[Fe]);const L=V(oe);g(()=>{L.current=oe},[oe]);const u=Cs({skipIntervals:Pa}),l=u.refs.videoRef,de=V(null),me=V([]),At=V(null),$e=V(null),{videoDelayMs:hn,videoDelayEnabled:Lt,setDelayEnabled:qt,handleVideoDelayChange:Vt,isCalibrating:fn,testClipActive:Ne,stopCalibration:vn,openAvSyncCalibrator:gr,cancelAvSyncCalibrator:yr,applyAvSyncCalibrator:Sr,toggleTestClip:_r,calibReturnRef:Ft,effectiveVideoDelayMs:pn}=ks(l),[ut,Tr]=y(()=>{try{const e=Number(z.getItem("tvSubtitleDelayMs"));if(Number.isFinite(e)&&e>=-6e4&&e<=6e4)return Math.round(e)}catch{}return 0}),gn=V(ut);gn.current=ut;const Cr=C(e=>{const n=Math.max(-6e4,Math.min(6e4,Math.round(e)));if(gn.current!==n){gn.current=n,Tr(n);try{z.setItem("tvSubtitleDelayMs",String(n))}catch{}}},[]);Es({videoRef:l,canvasRef:At,delayMs:pn,enabled:Lt});const yn=Lt,ye=yn||ut!==0,{settings:Sn,update:kr}=Ns(),_n=V(ye);_n.current=ye;const Tn=C(()=>{if(!_n.current)return;const e=l.current;e&&Array.from(e.textTracks).forEach(n=>{n.mode!=="hidden"&&(n.mode="hidden")})},[l]),{hasConsent:wt,grant:Er}=ls(),f=k==="movie";Xo({details:r,isMovie:f,season:m,episode:T,videoRef:l,active:!A&&!ce&&!Me&&U.length>0});const Ut=s?cs(k||"tv",s):"",ee=Ut,De=`${ee}:${m}:${T}:${E}:${K}`,Ht=Se(()=>!s||!r||A||Te||ce||we!==De||U[ze]?.type!=="hls"?null:{kind:f?"movie":"tv",...f?{}:{season:m},showId:s,episode:String(f?1:T),provider:E,source:K,mode:"sub",title:r.title},[s,r,A,Te,ce,we,De,U,ze,f,m,T,E,K]),Kn=Is(u.engine,Ht,ce||!r),Qn=js(),Wt=Gs(),Kt=Xs(),{toggle:Yn,bookmarkedIds:Nr,pending:Ir}=Js(),{data:jn}=Zs(r?Ut:void 0),Bt=jn?!!jn.inLibrary:Ut?Nr.has(Ut):!1,xr=C(()=>{!r||!s||Yn({tmdbId:Number(s),mediaType:k||"tv",title:r.title,poster:r.poster,year:r.year,adult:r.adult})},[r,s,k,Yn]),{data:dt,isFetched:Gn,isFetching:Cn}=eo(ee||void 0,m,T),Qt=Se(()=>ke.map(e=>e.episode_number).sort((e,n)=>e-n),[ke]),Pt=Qt.indexOf(T),kn=Pt>0?Qt[Pt-1]:null,F=Pt>=0&&Pt<Qt.length-1?Qt[Pt+1]:null,Yt=Se(()=>(r?.seasons??[]).map(e=>e.season_number).filter(e=>Number.isFinite(e)).sort((e,n)=>e-n),[r]),We=Se(()=>{if(f||F!=null)return null;const e=Yt.indexOf(m);return e>=0&&e<Yt.length-1?Yt[e+1]:(r?.number_of_seasons??0)>m?m+1:null},[f,F,Yt,m,r?.number_of_seasons]),Xn=dt?.currentTime??0,jt=V(null),[Ke,Gt]=y(!1),[mt,Jn]=y(0),[Mt,Zn]=y(!1),[bt,ht]=y(!1),[Ar,En]=y(!1),[Lr,wr]=y(""),[Xt,Br]=y(!1),[Pr,Nn]=y(!1),{isTheaterMode:Oe,toggleTheaterMode:In,handleLayoutClick:Mr}=xs();g(()=>{const e=n=>{n.defaultPrevented||n.ctrlKey||n.metaKey||n.altKey||n.repeat||n.target.closest('input, textarea, button, select, a, [role="button"], [contenteditable="true"]')||n.key.toLowerCase()==="t"&&In()};return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[In]),As(u,(U.length>0||at!=="")&&!Oe&&!Ke&&!bt);const Rr=so(),[ft,zr]=y(no),$r=C(e=>{zr(e),ro(e)},[]),Qe=V(!1),qe=V(null),xn=V(0),G=V(null),Jt=V(""),Dr=hr(Xn),Rt=!d&&!Qe.current&&(Ke||bt||Dr),Zt=V(Rt);Zt.current=Rt;const en=V(!1);g(()=>{en.current=Mt},[Mt]);const Ye=C((e,n)=>{if(!ee||!n||n<30)return;const a=dn(e,n);Math.abs(e-xn.current)<10&&!a||(xn.current=e,Qn.mutate({mediaId:ee,season:m,episode:T,currentTime:Math.floor(e),duration:Math.floor(n),completed:a,title:r?.title??null,poster:r?.poster??null,backdrop:r?.backdrop??null,year:r?.year??null,overview:r?.overview??null,tmdbId:r?.id??null,mediaType:k||"tv",adult:r?.adult?1:0}))},[ee,m,T,Qn,r,k]),Ie=C((e,n)=>{vn();const a=new URLSearchParams(h);a.set("type",h.get("type")||"tv"),a.set("s",String(e)),a.set("e",String(n)),w(`${window.location.pathname}?${a.toString()}`)},[h,w,vn]),zt=C(()=>{const e=l.current;if(!e||f||F==null){En(!1);return}const n=e.duration||0,a=e.currentTime||0;En(n>0&&a/n>=.8)},[f,F,l]),tn=C((e,n)=>["tv-sources",E,f?"movie":"tv",s,e,n,K],[E,f,s,K]),nn=C(async(e,n)=>{if(!r||!s||!E)return{valid:!1,sources:[]};const a=f?"movie":"tv",c=await pt.tv.sources.query({provider:E,type:a,tmdbId:String(s),season:e,episode:n,title:r.title||"",year:r.year||"",totalSeasons:String(r.number_of_seasons||1),imdbId:r.imdb_id||"",...K?{server:K}:{}});return{valid:"valid"in c?c.valid:!1,error:"error"in c?c.error:void 0,sources:c.sources,referer:"referer"in c?c.referer:void 0,audioTracks:c.audioTracks,subtitles:"subtitles"in c?c.subtitles:void 0,servers:"servers"in c?c.servers:void 0,server:"server"in c?c.server:void 0,embedUrl:"embedUrl"in c?c.embedUrl:void 0}},[r,s,E,f,K]),er=C(()=>{if(f||!r||!s||!E||A||F==null)return;const e=tn(m,F);R.getQueryState(e)?.status!=="success"&&R.prefetchQuery({queryKey:e,queryFn:()=>nn(m,F),staleTime:300*1e3,gcTime:1800*1e3})},[f,r,s,E,A,F,m,R,tn,nn]),Or=C(()=>{if(Ne)return;zt();const e=l.current;!e||e.paused||e.ended||(e.duration>0&&e.duration-e.currentTime<=60&&er(),!qe.current&&(qe.current=setTimeout(()=>{qe.current=null,Ye(e.currentTime,e.duration||0)},5e3)))},[Ye,l,Ne,zt,er]),qr=C(()=>{const e=l.current;if(!(!e||!r)&&(qe.current&&clearTimeout(qe.current),qe.current=null,Ye(e.currentTime,e.duration||0),!i)){if(F!=null){ft&&(pe(F),Ie(m,F));return}wr(f?r.title:`${r.title} - Season ${m}`),ht(!0),Qe.current=!0}},[f,r,m,F,ft,Ye,Ie,l,i]),{checkEnd:rn,logDuration:tr}=Ls({videoRef:l,sourceType:A?"iframe":void 0,resetKey:`${ee}:${m}:${T}`,onEnd:qr}),Vr=C(()=>{u.actions.onPlay()},[u.actions]),Fr=C(()=>{u.actions.onPause();const e=l.current;e&&!e.ended&&Ye(e.currentTime,e.duration||0)},[u.actions,Ye,l]),Ur=C(()=>{const e=l.current;if(e){try{const n=parseFloat(z.getItem("playerVolume")||"");isNaN(n)||(e.volume=Math.max(0,Math.min(1,n))),e.muted=z.getItem("playerMuted")==="true"}catch{}if(G.current!=null&&G.current>0){try{e.currentTime=G.current}catch{}G.current=null}zt()}},[l,zt]),An=C(()=>{const e=l.current;if(e&&G.current!=null&&G.current>0){try{e.currentTime=G.current}catch{}G.current=null}},[l]),Hr=C(()=>{mt>0&&(G.current=mt);const e=l.current;if(e&&mt>0){try{e.currentTime=mt,G.current=null}catch{}e.play().catch(()=>{})}Gt(!1),Qe.current=!0},[mt,l]),nr=C(()=>{G.current=null;const e=l.current;e&&(e.currentTime=0,e.play().catch(()=>{})),Gt(!1),Qe.current=!0},[l]),Wr=C(()=>{F!=null&&(Qe.current=!0,pe(F),Ie(m,F))},[F,m,Ie]),Kr=C(()=>{We!=null&&(ht(!1),Qe.current=!0,J(We),pe(1),Ie(We,1))},[We,Ie]),Qr=C(async()=>{if(ee)try{Bt?await Wt.mutateAsync({id:ee,status:"Completed"}):r&&s&&(await Kt.mutateAsync({tmdbId:Number(s),mediaType:k||"tv",title:r.title,poster:r.poster,backdrop:r.backdrop,year:r.year,overview:r.overview,adult:r.adult,status:"Completed",silent:!0}),br.success("Moved to Completed")),ht(!1),w("/")}catch{}},[ee,Bt,Wt,Kt,r,s,k,w]);g(()=>{Qe.current=!1,jt.current=null,Gt(!1),En(!1),Jn(0),Zn(!1),en.current=!1,G.current=null,xn.current=0},[ee,m,T]),g(()=>{Jt.current=De},[De]),g(()=>{Gn&&(Zn(!0),en.current=!0)},[Gn,ee,m,T]),g(()=>{if(d||Cn||!dt||Qe.current)return;const e=`${ee}:${m}:${T}`;if(jt.current===e)return;jt.current=e;const n=dt,a=n.currentTime??0;hr(a)&&n.completed!==1&&!dn(a,n.duration??0)&&(Jn(a),Gt(!0))},[dt,Cn,ee,m,T,d]),g(()=>{!d&&Ke&&l.current&&l.current.pause()},[Ke,l,d]),g(()=>{const e=l.current;return()=>{qe.current&&clearTimeout(qe.current),qe.current=null,!e?.ended&&u.engine.getState().duration>0&&Ye(u.engine.getTimeline().currentTime,u.engine.getState().duration)}},[u.engine,Ye,l]);const Ln=C(e=>{let n=null,a=!0;try{n=z.getItem("tvLastSubtitle"),a=z.getItem("tvSubtitlesEnabled")!=="false"}catch{}return Hn(e,{lastKey:n,enabled:a})},[]),wn=C(e=>{if(!(e<0))try{z.setItem("tvSubtitlesEnabled","true"),z.setItem("tvSelectedSubtitle",String(e))}catch{}},[]),rr=C(e=>{if(e.length===0)return 0;let n=null;try{n=z.getItem("tvLastAudio")}catch{}if(n){const a=e.findIndex(P=>qn(P)===n);if(a>=0)return a;const c=n.indexOf("|||"),b=c>=0?n.slice(0,c):n,_=c>=0?n.slice(c+3):n,$=e.findIndex(P=>P.language===b||P.label===_);if($>=0)return $}return Hn(e,{lastKey:null,enabled:!0})},[]),sr=C(e=>{let n=null;try{n=z.getItem("tvLastQuality")}catch{}if(!n||e.length===0)return 0;const a=e.findIndex(P=>(P.quality||"")===n);if(a>=0)return a;const c=P=>{const X=/(\d{3,4})/.exec(P||"");return X?parseInt(X[1],10):0},b=c(n);if(!b)return 0;let _=0,$=1/0;return e.forEach((P,X)=>{const v=c(P.quality),H=Math.abs(v-b);v>0&&H<$&&($=H,_=X)}),_},[]),{data:or}=to(ee||void 0),ar=Se(()=>(or?.progress??[]).filter(n=>n.season===m&&(n.completed===1||dn(n.currentTime,n.duration))).map(n=>String(n.episode)),[or,m]),ir=Se(()=>ke.map(e=>({id:String(e.episode_number),label:`Episode ${e.episode_number}`,sublabel:e.name||void 0,thumbnail:e.still_path?`https://image.tmdb.org/t/p/w185${e.still_path}`:void 0})),[ke]),lr=Se(()=>(r?.genres??[]).map(e=>e.name).slice(0,5),[r]),Bn=Se(()=>[r?.year,r?.status,r?.number_of_seasons?`${r.number_of_seasons} Season${r.number_of_seasons>1?"s":""}`:null,r?.number_of_episodes?`${r.number_of_episodes} Episodes`:null].filter(Boolean),[r]);g(()=>{if(!i&&j.length!==0&&!j.some(e=>e.id===E)){const e=j.find(n=>n.tier==="direct")?.id??j[0].id;Je(e);try{z.setItem("tvProvider",e)}catch{}}},[j,E,i]),g(()=>{_e([]),Z(""),lt(""),kt(!1)},[E]),g(()=>{if(!i&&ue.length!==0&&!ue.includes(K)){Ct(ue[0]);try{z.setItem("tvServer",ue[0])}catch{}}},[ue,K,i]),g(()=>{if(!s){B(null),Q([]),Ze(""),ne(""),He("");return}const e=Number(s),n=k||"tv";B(null),Q([]),Ze(""),ne(""),He("");const a=parseInt(O.current.get("s")||"",10),c=parseInt(O.current.get("e")||"",10);J(isNaN(a)?1:a),pe(isNaN(c)?1:c),Ue(0),pt.tv.details.query({type:n,id:String(e)}).then(b=>{const _={id:b.id,title:b.title||"",overview:b.overview||"",vote_average:b.vote_average,year:b.year,poster:b.poster,backdrop:b.backdrop,imdb_id:b.imdb_id||void 0,adult:b.adult,seasons:b.seasons,number_of_seasons:b.number_of_seasons};B(_),_.seasons&&_.seasons.length>0&&isNaN(a)&&J(_.seasons[0].season_number)}).catch(()=>{})},[s,k]),g(()=>{if(!r||!s)return;if(!(r.seasons!==void 0||r.number_of_seasons!==void 0)){Le([]);return}const n=parseInt(h.get("e")||"",10);pt.tv.episodes.query({id:String(s),season:String(m)}).then(a=>{const c=(a.episodes||[]).map(b=>({episode_number:b.episode_number,name:b.name||"",vote_average:b.vote_average,overview:b.overview||"",still_path:b.still_path||""}));Le(c),c.length!==0&&pe(b=>!isNaN(n)&&c.some(_=>_.episode_number===n)?n:c.some(_=>_.episode_number===b)?b:c[0].episode_number)}).catch(()=>{})},[r,s,m,h]),g(()=>{if(!A||!r||!s)return;On(`/api/tv/embed/${E}/${f?"movie":"tv"}/${s}?season=${m}&episode=${T}`).then(n=>{if(n.url)return He(n.url),On(`/api/resolve?url=${encodeURIComponent(n.url)}`).then(a=>{a.finalUrl&&He(a.finalUrl)})}).catch(()=>{})},[E,r,s,m,T,f,A]);const sn=C(async()=>{if(!r||!s||!E||A||r.adult&&!wt)return;const e=De;Pe(!0),ne(""),It.current.length===0&&(Q([]),Ue(0),et([]),_t([]));try{const n=await R.fetchQuery({queryKey:tn(m,T),queryFn:()=>nn(m,T),staleTime:3e5,gcTime:18e5});if(Jt.current!==e)return;if(Pe(!1),!n.valid||!n.sources?.length){ne(n.error?`${n.error}`:ue.length>0?`No streams from ${K}. Try another server.`:"No streams available.");return}if(d&&K&&n.server&&n.server!==K){Q([]),ne("The host's selected server is unavailable. Automatic source switching is disabled in watch-along rooms.");return}!i&&!K&&n.server&&Ct(n.server);const a=d?n.sources.filter(P=>P.type==="hls"):n.sources;if(d&&a.length===0){Q([]),ne("The room requires a direct HLS source. No compatible stream is available here.");return}Q(a),yt(n.server||K),Ze(e),n.servers?.length&&_e(n.servers),n.embedUrl&&Z(n.embedUrl),Ue(sr(a)),n.referer&&Tt(n.referer);const c=n.audioTracks||[];et(c),ot(c.length>0?rr(c):0);const b=n.subtitles||[];if(_t(b),b.length>0){const P=Ln(b);Re(P),wn(P)}else Re(-1);const _=f?"movie":"tv",$=s;pt.tv.subtitles.query({type:_,tmdbId:String($),season:String(m),episode:String(T)}).then(P=>{if(Jt.current!==e)return;const X=Array.isArray(P.subtitles)?P.subtitles:[];X.length!==0&&_t(v=>{const H=[...v,...X.filter(Y=>!v.some(q=>q.url===Y.url))];if(v.length===0){const Y=Ln(H);Re(Y),wn(Y)}return H})}).catch(()=>{}),ne("")}catch(n){if(Jt.current!==e)return;Pe(!1),ne(n instanceof Error?n.message:"Failed to load streams.")}},[r,s,E,m,T,f,A,wt,ue,K,Ln,wn,rr,sr,R,tn,nn,De,d,i]),Pn=C(()=>{const e=l.current;e&&!isNaN(e.currentTime)&&(G.current=e.currentTime)},[l]),Yr=C(e=>{if(!(i||d&&e==="Embed")){if(e==="Embed"){kt(!0);return}Pn(),kt(!1),Ct(e);try{z.setItem("tvServer",e)}catch{}ne("")}},[Pn,i,d]),jr=C(e=>{Je(e);try{z.setItem("tvProvider",e)}catch{}},[]);g(()=>{E&&r&&!A&&sn()},[E,r,sn,A]),g(()=>{if(!l.current)return;if(de.current=null,A||Te||d&&U[ze]?.type!=="hls"){u.engine.unload();return}if(Ne&&!d)return u.engine.loadSource({url:"/av-sync-test.mp4"},{autoPlay:!Zt.current});if(Ft.current!=null&&(G.current=Ft.current,Ft.current=null),we===De&&G.current==null&&!Zt.current)try{const v=l.current;v&&!v.ended&&v.currentTime>1&&(G.current=v.currentTime)}catch{}const n=G.current??0,a=!ce&&we===De?Te?"":U[ze]?.url||"":"";if(!a){try{l.current?.pause(),l.current?.removeAttribute("src"),l.current?.load()}catch{}return}const c=l.current;c.pause(),c.removeAttribute("src"),c.load(),u.actions.resetMediaState();const b=`/api/tv/stream-proxy?url=${encodeURIComponent(a)}&referer=${encodeURIComponent(tt)}&provider=${encodeURIComponent(E)}`,_=ea()||document.body.classList.contains("low-end"),$=_?60:180,P=u.engine.loadSource({url:b,hls:U[ze]?.type==="hls"},{hlsConfig:{enableWorker:!0,lowLatencyMode:!1,startPosition:n>0?n:-1,maxBufferLength:$,maxMaxBufferLength:$+(_?30:60),backBufferLength:_?30:60,maxBufferSize:(_?120:360)*1e3*1e3,fragLoadPolicy:{default:{maxTimeToFirstByteMs:15e3,maxLoadTimeMs:45e3,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:3,retryDelayMs:800,maxRetryDelayMs:6e3}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:25e3,timeoutRetry:{maxNumRetry:1,retryDelayMs:500,maxRetryDelayMs:2e3},errorRetry:{maxNumRetry:2,retryDelayMs:800,maxRetryDelayMs:4e3}}}},onHls:(v,H)=>{de.current=v;const Y=()=>{let D=!1,M=0;try{D=z.getItem("tvSubtitlesEnabled")==="true";const N=parseInt(z.getItem("tvSelectedSubtitle")||"0",10);!isNaN(N)&&N>=0&&(M=N)}catch{}return{enabled:D,index:M}},q=()=>{if(typeof v.subtitleTrack!="number")return;if(me.current.length>0){v.subtitleTrack=-1;return}const D=Array.isArray(v.subtitleTracks)?v.subtitleTracks:[];if(D.length===0){v.subtitleTrack=-1;return}const M=Y();if(M.enabled){const N=M.index<D.length?M.index:0;v.subtitleTrack=N,Re(N),Tn()}else v.subtitleTrack=-1};Jo(v,H.Events,{getWant:()=>xt.current,onResolve:D=>ot(D)}),v.on(H.Events.MANIFEST_PARSED,q),v.on(H.Events.SUBTITLE_TRACKS_UPDATED,()=>{q()}),v.on(H.Events.SUBTITLE_TRACK_SWITCH,(D,M)=>{if(me.current.length>0){if(M.id!==-1)try{v.subtitleTrack=-1}catch{}return}const N=Array.isArray(v.subtitleTracks)?v.subtitleTracks:[];if(N.length!==0){if(M.id===-1){const Ce=Y();if(Ce.enabled){const re=Ce.index<N.length?Ce.index:0;v.subtitleTrack=re;return}}Re(M.id),Tn()}})},onReady:()=>{(n>0||!Zt.current&&en.current)&&u.engine.play()},onError:v=>{ne(v.message),Pe(!1),de.current=null}}),X=()=>{const Y=c.error?.code===4?"Video source not supported or not found":"Failed to load video stream";ne(`${Y}. The source may be invalid or expired. Try switching source or reloading.`),Pe(!1)};return c.addEventListener("error",X),()=>{P(),de.current=null,c.removeEventListener("error",X)}},[U,we,ce,ze,E,tt,A,Te,l,Ft,Ne,ee,m,T,An,Tn,u.actions,u.engine,De,d]),g(()=>{if(i||!Mt||Ke||bt||Rt||A||Ne)return;const e=l.current;!e||!e.paused||e.ended||e.readyState<1||(An(),u.engine.play())},[Mt,Ke,bt,Rt,A,Ne,An,l,i,u.engine]),g(()=>{const e=de.current;!e||typeof e.audioTrack!="number"||(e.audioTrack=Fe)},[Fe]),g(()=>{const e=de.current;!e||typeof e.subtitleTrack!="number"||!Array.isArray(e.subtitleTracks)||e.subtitleTracks.length===0||me.current.length>0||(oe>=0?e.subtitleTrack=oe:e.subtitleTrack=-1)},[oe]),g(()=>{const e=l.current;if(!(!e||A)&&(e.querySelectorAll("track").forEach(n=>n.remove()),me.current=[],Ee.length!==0&&(Ee.forEach(n=>{const a=document.createElement("track");a.kind="subtitles",a.label=n.label||n.language||"Unknown",a.srclang=n.language||n.label||"en";const c=`/api/subtitle-proxy?url=${encodeURIComponent(n.url)}&referer=${encodeURIComponent(tt)}`;a.src=c,a.addEventListener("load",()=>{const b=me.current.indexOf(a),_=a.track;if(_&&b>=0){const $=b===L.current;_.mode=$&&!_n.current?"showing":"hidden"}}),e.appendChild(a),me.current.push(a)}),Ee.length>0)))try{const n=de.current;n&&typeof n.subtitleTrack=="number"&&n.subtitleTrack!==-1&&(n.subtitleTrack=-1)}catch{}},[Ee,tt,A,E,K,l]),g(()=>{const e=l.current;if(!e||A)return;const n=de.current;me.current.length>0&&n&&typeof n.subtitleTrack=="number"&&Array.isArray(n.subtitleTracks)&&n.subtitleTracks.length>0&&(n.subtitleTrack=-1);const a=()=>{const _=Wn(u.state.subtitleFontSize,e.clientHeight||720),$=Math.max(0,Math.min(100,100-u.state.subtitlePosition)),P=()=>{const q=_*16,D=e.videoHeight||e.clientHeight||720,M=e.videoWidth||e.clientWidth||1280;return{step:q*1.3/D*100,chars:Math.max(20,Math.floor(M/(q*.55)))}},X=(q,D)=>{const M=q;M.snapToLines=!1,M.line=D},v=q=>{if(!q.cues)return;Array.from(q.cues).forEach(re=>X(re,$));const D=Array.from(q.activeCues??[]);if(D.length<=1){D.forEach(re=>X(re,$));return}const{step:M,chars:N}=P();let Ce=$;for(let re=D.length-1;re>=0;re--){const je=String(D[re].text??"").replace(/<[^>]*>/g,"").split(`
3
- `).reduce((an,$t)=>an+Math.max(1,Math.ceil($t.length/N)),0);Ce=Math.max(0,Ce-je*M),X(D[re],Ce),Ce-=M*.4}},H=me.current;if(H.length>0){H.forEach((q,D)=>{const M=q.track;if(!M)return;const N=D===oe;M.mode=N&&!ye?"showing":"hidden",N&&!ye&&v(M)});return}const Y=Array.from(e.textTracks);Y.length!==0&&Y.forEach((q,D)=>{const M=D===oe;q.mode=M&&!ye?"showing":"hidden",M&&!ye&&v(q)})};a();const c=()=>a();e.textTracks.addEventListener("addtrack",c),e.addEventListener("loadedmetadata",a,{once:!0});const b=window.setTimeout(a,600);return()=>{e.textTracks.removeEventListener("addtrack",c),e.removeEventListener("loadedmetadata",a),window.clearTimeout(b)}},[oe,Ee,A,E,l,ye,u.state.subtitleFontSize,u.state.subtitlePosition]),g(()=>{if(!ye)return;const e=l.current,n=$e.current;if(!e||!n)return;const a=ut/1e3,c=pn/1e3,b=new Set;let _=[],$=-1,P=-1,X=-1,v=-1,H=0,Y=0,q=!1;const D=()=>{const W=L.current;if(W<0)return null;const Ge=me.current;return Ge.length>0?Ge[W]?.track??null:Array.from(e.textTracks)[W]??null},M=(W,Ge)=>{const be=W.cues;if(!be||be.length===0)return Array.from(W.activeCues??[]);let nt=0,rt=be.length;for(;nt<rt;){const xe=nt+rt>>>1;be[xe].endTime+a<Ge?nt=xe+1:rt=xe}const Dt=[];for(let xe=nt;xe<be.length;xe++){const ln=be[xe];if(ln.startTime+a>Ge)break;ln.endTime+a>=Ge&&Dt.push(ln)}return Dt},N=()=>{const W=D(),Ge=e.currentTime-c,be=W?M(W,Ge):[],nt=e.clientWidth,rt=e.clientHeight,Dt=e.videoWidth,xe=e.videoHeight;if(be.length===_.length&&be.every((zn,$n)=>zn===_[$n])&&nt===$&&rt===P&&Dt===X&&xe===v||(_=be,$=nt,P=rt,X=Dt,v=xe,n.textContent="",be.length===0))return;const dr={fontSize:Wn(u.state.subtitleFontSize,rt),position:u.state.subtitlePosition,bgOpacity:u.state.subtitleBgOpacity,bgColor:u.state.subtitleBgColor,textColor:u.state.subtitleTextColor,edge:u.state.subtitleEdge,bold:u.state.subtitleBold},Zr=ws(dr),es=Bs(e,dr.position);be.forEach((zn,$n)=>{const mr=String(zn.text??"");if(!Ps(mr).trim())return;const Dn=document.createElement("div"),ts=(be.length-1-$n)*1.7;Dn.style.cssText=`${Zr}
4
- bottom: calc(${es}px + ${ts}em);`,Dn.innerHTML=Ms(mr),n.appendChild(Dn)})},Ce=()=>{Array.from(e.textTracks).forEach(W=>{b.has(W)||(b.add(W),W.addEventListener("cuechange",N))})},re=()=>{Ce(),N()},Rn=()=>{if(q||Y)return;const W=()=>{Y=0,!(q||e.paused||e.ended)&&(N(),Rn())};Y=window.requestAnimationFrame(W)},je=e,an=()=>{H=0,N(),!q&&je.requestVideoFrameCallback&&(H=je.requestVideoFrameCallback(an))},$t=()=>{N(),je.requestVideoFrameCallback?H||(H=je.requestVideoFrameCallback(an)):Rn()};Ce(),e.textTracks.addEventListener("addtrack",re),e.textTracks.addEventListener("removetrack",re),e.addEventListener("timeupdate",N),e.addEventListener("seeked",N),e.addEventListener("loadedmetadata",N),e.addEventListener("play",$t);const cr=Array.from(e.querySelectorAll("track"));cr.forEach(W=>W.addEventListener("load",N));const ur=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>N());return ur?.observe(e),N(),$t(),()=>{q=!0,b.forEach(W=>W.removeEventListener("cuechange",N)),e.textTracks.removeEventListener("addtrack",re),e.textTracks.removeEventListener("removetrack",re),e.removeEventListener("timeupdate",N),e.removeEventListener("seeked",N),e.removeEventListener("loadedmetadata",N),e.removeEventListener("play",$t),cr.forEach(W=>W.removeEventListener("load",N)),ur?.disconnect(),Y&&window.cancelAnimationFrame(Y),H&&je.cancelVideoFrameCallback&&je.cancelVideoFrameCallback(H),n.textContent=""}},[ye,ut,oe,Ee,pn,l,u.state.subtitleFontSize,u.state.subtitlePosition,u.state.subtitleBgOpacity,u.state.subtitleBgColor,u.state.subtitleTextColor,u.state.subtitleEdge,u.state.subtitleBold]);const Mn=()=>{B(null),Q([]),He(""),w(-1)},Gr=C(e=>{i||(J(e),pe(1),Ie(e,1))},[Ie,i]),on=!f&&r?.seasons&&r.seasons.length>1?t("label",{className:p.sidebarSeason,children:[t("span",{children:"Season"}),t("select",{disabled:i,value:m,onChange:e=>Gr(parseInt(e.currentTarget.value,10)||1),className:p.select,children:r.seasons.map(e=>t("option",{value:e.season_number,children:["Season ",e.season_number," (",e.episode_count," ep)"]},e.season_number))})]}):null,vt=C(e=>{if(i)return;const n=parseInt(e,10);if(!isNaN(n)){try{l.current?.pause()}catch{}pe(n),Ie(m,n)}Nn(!1)},[m,Ie,l,i]);g(()=>{if(f)return;const e=n=>{n.target.closest('input, textarea, button, select, a, [role="button"], [contenteditable="true"]')||n.key.toLowerCase()==="n"&&(F!=null?vt(String(F)):br.error("No next episode available"))};return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[f,F,vt]);const Xr=e=>{ot(e);try{const a=Ve[e];a&&z.setItem("tvLastAudio",qn(a))}catch{}const n=de.current;n&&n.audioTrack!==void 0&&(n.audioTrack=e)},Jr=e=>{Re(e);try{if(e===-1)z.setItem("tvSubtitlesEnabled","false");else{z.setItem("tvSubtitlesEnabled","true"),z.setItem("tvSelectedSubtitle",String(e));const b=Ee[e];b&&z.setItem("tvLastSubtitle",qn(b))}}catch{}const n=l.current,a=de.current;if(a&&typeof a.subtitleTrack=="number"&&Array.isArray(a.subtitleTracks)&&a.subtitleTracks.length>0&&(a.subtitleTrack=me.current.length>0||e<0?-1:e),!n)return;const c=me.current;if(c.length>0){c.forEach((b,_)=>{const $=b.track;if(!$)return;const P=_===e;$.mode=P&&!ye?"showing":"hidden"});return}Array.from(n.textTracks).forEach((b,_)=>{const $=_===e;b.mode=$&&!ye?"showing":"hidden"})};return g(()=>{if(!r){document.title="TV & Movies - dango";return}document.title=f?`${r.title} - dango`:`${r.title} - Season ${m} Episode ${T} - dango`},[r,f,m,T]),g(()=>{if(!r||f)return;const e=new URLSearchParams(h),n=e.get("s"),a=e.get("e"),c=String(m),b=String(T);n===c&&a===b||(e.set("type",h.get("type")||"tv"),e.set("s",c),e.set("e",b),w(`${window.location.pathname}?${e.toString()}`,{replace:!0}))},[r,f,m,T,h,w]),t("div",{className:`${Ae.playerPageLayout} ${Oe?Ae.theaterMode:""} ${f?Ae.noSidebar:""}`,onClick:Mr,children:[Oe&&t(Rs,{videoRef:l,active:Sn.enabled&&!A&&U.length>0&&!Me&&!(r?.adult&&!wt),settings:Sn}),!Oe&&!f&&t("aside",{className:Ae.episodeSidebar,children:r?t(zs,{episodes:ir,currentEpisode:String(T),watchedEpisodes:ar,onEpisodeClick:vt,header:on}):t($s,{variant:"sidebar"})}),t("div",{className:Ae.playerMain,children:[r&&t("div",{className:p.playerSection,onContextMenu:e=>e.preventDefault(),style:r.adult&&!wt?{filter:"blur(14px)",pointerEvents:"none",userSelect:"none"}:void 0,children:A&&at&&!d?t("iframe",{src:at,className:p.videoIframe,allow:"autoplay; fullscreen",allowFullScreen:!0}):!A&&Nt&&!d?t("iframe",{src:Nt,className:p.videoIframe,allow:"autoplay; fullscreen",allowFullScreen:!0}):!A&&(U.length>0||ce)?t(Xe,{children:[Me&&t(vr,{error:Me,onRetry:sn}),t(Yo,{player:u,title:r.title,episodeLabel:f?void 0:`S${m} E${T}`,server:le||it?.label||E,audioTracks:Ve,selectedAudioTrack:Fe,onAudioTrackChange:Xr,subtitles:Ee,selectedSubtitle:oe,onSubtitleChange:Jr,streams:U,resolutionIdx:ze,onResolutionChange:e=>{Pn(),Ue(e);try{const n=U[e]?.quality;n&&z.setItem("tvLastQuality",n)}catch{}},onBack:Mn,videoDelayEnabled:Lt,onVideoDelayToggle:qt,videoDelayMs:hn,onVideoDelayChange:Vt,onCalibrateAvSync:d?void 0:gr,subtitleDelayMs:ut,onSubtitleDelayChange:Cr,showNextEpisodeButton:!i&&Ar&&!Ke&&!bt,onNextEpisode:Wr,isLoading:ce,isTheaterMode:Oe,onTheaterModeToggle:In,ambientSettings:Sn,onAmbientChange:kr,children:[t(vs,{autoPlay:!d&&Mt&&!Rt,playsInline:!0,disablePictureInPicture:!0,className:`${p.video} ${yn?p.videoHidden:""}`,onTimeUpdate:()=>{Ne||(Or(),rn())},onEnded:()=>{Ne||rn(!0)},onPlay:Vr,onPause:Fr,onSeeked:()=>{Ne||(zt(),rn())},onLoadedMetadata:()=>{Ur(),tr(),rn()},onDurationChange:()=>{tr()},onContextMenu:e=>e.preventDefault(),onError:()=>{ne("Video failed to load. Try another server or reload."),Pe(!1)}}),t("canvas",{ref:At,className:`${p.delayCanvas} ${yn?p.delayCanvasActive:""}`}),ye&&t("div",{ref:$e,className:p.subtitleOverlay}),t(Ds,{isOpen:fn,ms:hn,onChange:Vt,onApply:Sr,onClose:yr,testClipActive:Ne,onTestClip:_r})]})]}):Me&&!A?t(vr,{error:Me,onRetry:sn}):null}),t(ao,{playback:Ht?{selection:Ht,position:l.current?.currentTime||0,playing:!1,rate:u.engine.getState().playbackRate}:null,onCreate:()=>{vn(),u.engine.pause()},needsPlayback:Kn.needsPlayback,onEnablePlayback:Kn.enablePlayback}),d&&!ce&&r&&!Ht&&t("p",{role:"alert",children:"The host's direct HLS source is unavailable here. Retry or leave the room to use another source."}),!Oe&&r&&t(Os,{}),!Oe&&on&&t("div",{className:p.mobileSeasonRow,children:on}),!Oe&&r&&t("div",{className:ie.streamPanel,children:[t("div",{className:p.providerSelectWrap,children:t("label",{className:p.controlLabel,children:["Provider",t("select",{value:E,onChange:e=>jr(e.currentTarget.value),className:p.select,disabled:i||j.length===0,children:st?t("option",{value:"",children:"Loading..."}):j.length===0?t("option",{value:"",children:"No providers available"}):t(Xe,{children:[x.length>0&&t("optgroup",{label:"Direct HLS",children:x.map(e=>t("option",{value:e.id,children:e.label},e.id))}),se.length>0&&t("optgroup",{label:"Embeds",children:se.map(e=>t("option",{value:e.id,children:e.label},e.id))})]})})]})}),!i&&!A&&(ce?t("div",{className:p.sourceLoader,children:t("div",{className:p.ringSpinner})}):t(Go,{servers:Et,selectedServer:ct?"Embed":K,onServerSelect:Yr}))]}),!Oe&&r&&t("div",{className:Ae.playerInfoContainer,children:[t("div",{className:Ae.playerInfoHeader,children:[t("div",{className:Ae.playerAnimeCard,children:r.poster&&t(us,{src:`https://image.tmdb.org/t/p/w342${r.poster}`,alt:r.title,loading:"lazy",decoding:"async"})}),t("div",{className:Ae.videoTitleSection,children:[t("div",{className:ie.titleContainer,children:[t("h1",{children:r.title}),t("div",{className:p.meta,children:[t("span",{className:p.year,children:r.year}),r.vote_average!=null&&r.vote_average>0&&t("span",{className:p.rating,children:[t(he,{name:"star",size:12}),Number(r.vote_average).toFixed(1)]}),t("span",{className:`${p.typeBadge} ${p[f?"movie":"tv"]}`,children:f?"Movie":"TV Show"})]}),lr.length>0&&t("div",{className:p.genreRow,children:lr.map(e=>t("span",{className:p.genreChip,children:e},e))}),Bn.length>0&&t("div",{className:p.metaRow,children:Bn.map((e,n)=>t("span",{children:[e,n<Bn.length-1?" · ":""]},`${e}-${n}`))})]}),t("div",{className:ie.controls,children:[t("button",{className:`${ie.watchlistBtn} ${Bt?ie.inList:""}`,onClick:xr,disabled:Ir,type:"button",children:[Bt?t(he,{name:"check",size:14}):t(he,{name:"plus",size:14}),Bt?"In Watchlist":"Add to Watchlist"]}),!f&&t(Xe,{children:[t("button",{className:`${ie.watchlistBtn}`,onClick:()=>kn!=null&&vt(String(kn)),disabled:i||kn==null,type:"button",children:[t(he,{name:"chevron-left",size:14}),"Prev EP"]}),t("button",{className:`${ie.watchlistBtn}`,onClick:()=>F!=null&&vt(String(F)),disabled:i||F==null,type:"button",children:["Next EP",t(he,{name:"chevron-right",size:14})]}),!f&&t("button",{className:`${ie.watchlistBtn} ${ie.modeToggleBtn} ${ft?ie.modeToggleActive:""}`,onClick:()=>$r(!ft),type:"button","aria-pressed":ft,children:ft?"AUTOPLAY: ON":"AUTOPLAY: OFF"}),Rr&&t("button",{className:`${ie.watchlistBtn}`,onClick:()=>Nn(!0),type:"button",children:[t(he,{name:"list-ul",size:14}),"Episodes"]})]})]})]})]}),t("div",{className:Ae.infoColumns,children:[t("div",{className:`${ie.descriptionSection} ${ie.synopsisFlat}`,children:[t("h3",{children:"Synopsis"}),t(oo,{text:r.overview,emptyText:"No description available."}),t("button",{className:ie.detailsToggleBtn,onClick:()=>Br(!Xt),type:"button",children:[Xt?t(he,{name:"chevron-up"}):t(he,{name:"chevron-down"}),Xt?"Hide Details":"Show Details"]})]}),Xt&&t("div",{className:p.detailGrid,children:[r.first_air_date&&t("div",{className:p.detailItem,children:[t("strong",{children:f?"Release Date":"First Air Date"}),t("span",{children:r.first_air_date})]}),r.last_air_date&&t("div",{className:p.detailItem,children:[t("strong",{children:"Last Air Date"}),t("span",{children:r.last_air_date})]}),r.networks&&r.networks.length>0&&t("div",{className:p.detailItem,children:[t("strong",{children:"Networks"}),t("span",{children:r.networks.map(e=>e.name).join(", ")})]}),r.created_by&&r.created_by.length>0&&t("div",{className:p.detailItem,children:[t("strong",{children:"Created By"}),t("span",{children:r.created_by.map(e=>e.name).join(", ")})]}),r.episode_run_time&&r.episode_run_time.length>0&&t("div",{className:p.detailItem,children:[t("strong",{children:"Episode Runtime"}),t("span",{children:[r.episode_run_time[0]," min"]})]}),r.imdb_id&&t("div",{className:p.detailItem,children:[t("strong",{children:"IMDb"}),t("a",{href:`https://www.imdb.com/title/${r.imdb_id}`,target:"_blank",rel:"noopener noreferrer",className:p.imdbLink,children:"View on IMDb"})]})]})]})]}),!f&&t(qs,{isOpen:Pr,onClose:()=>Nn(!1),episodes:ir,currentEpisode:String(T),watchedEpisodes:ar,onEpisodeClick:vt,header:on}),r?.adult&&!wt&&t(Qs,{isOpen:!0,onClose:Mn,onGrant:Er}),t(Vs,{isOpen:!d&&Ke&&!Cn&&jt.current===`${ee}:${m}:${T}`&&dt?.completed!==1&&!dn(Xn,dt?.duration??0),onClose:nr,title:"Resume Watching",message:t(Xe,{children:["You were at ",t("strong",{children:Un(mt)})]}),restartLabel:"Start from Beginning",onResume:Hr,onRestart:nr}),t(Fs,{isOpen:bt,onClose:()=>ht(!1),title:f?"Movie Completed!":We!=null?"Season Complete!":"Show Completed!",heading:Lr,message:f?"You finished this movie!":We!=null?`You finished Season ${m}.`:"Congratulations! You finished all available episodes.",children:[t(cn,{variant:"secondary",onClick:()=>ht(!1),children:"Close"}),We!=null?t(cn,{onClick:Kr,children:["Start Season ",We]}):t(Xe,{children:[t(cn,{onClick:()=>{ht(!1),Mn()},children:"Back to Details"}),t(cn,{onClick:Qr,disabled:Wt.isPending||Kt.isPending,children:Wt.isPending||Kt.isPending?"Saving...":"Move to Completed"})]})]}),!r&&t("div",{className:p.statusMsg,children:[t(he,{name:"spinner",className:p.spinner})," Loading..."]})]})]})};export{ja as default};